<commit_before>/*
 * ImageLoader
 * Visit http://createjs.com/ for documentation, updates and examples.
 *
 *
 * Copyright (c) 2012 gskinner.com, inc.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

// namespace:
this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for image files.
	 * @class ImageLoader
	 * @param {LoadItem|Object} loadItem
	 * @param {Boolean} preferXHR
	 * @extends AbstractLoader
	 * @constructor
	 */
	function ImageLoader (loadItem, preferXHR) {
		this.AbstractLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.IMAGE);

		// public properties
		this.resultFormatter = this._formatResult;

		// protected properties
		this._tagSrcAttribute = "src";

		// Check if the preload item is already a tag.
		if (createjs.DomUtils.isImageTag(loadItem)) {
			this._tag = loadItem;
		} else if (createjs.DomUtils.isImageTag(loadItem.src)) {
			this._tag = loadItem.src;
		} else if (createjs.DomUtils.isImageTag(loadItem.tag)) {
			this._tag = loadItem.tag;
		}

		if (this._tag != null) {
			this._preferXHR = false;
		} else {
			this._tag = createjs.Elements.img();
		}

		this.on("initialize", this._updateXHR, this);
	};

	var p = createjs.extend(ImageLoader, createjs.AbstractLoader);
	var s = ImageLoader;

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/IMAGE:property"}}{{/crossLink}}.
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.IMAGE;
	};

	// public methods
	p.load = function () {
		if (this._tag.src != "" && this._tag.complete) {
			this._sendComplete();
			return;
		}

		var crossOrigin = this._item.crossOrigin;
		if (crossOrigin == true) { crossOrigin = "Anonymous"; }
		if (crossOrigin != null && !createjs.URLUtils.isLocal(this._item)) {
			this._tag.crossOrigin = crossOrigin;
		}

		this.AbstractLoader_load();
	};

	// protected methods
	/**
	 * Before the item loads, set its mimeType and responseType.
	 * @property _updateXHR
	 * @param {Event} event
	 * @private
	 */
	p._updateXHR = function (event) {
		event.loader.mimeType = 'text/plain; charset=x-user-defined-binary';

		// Only exists for XHR
		if (event.loader.setResponseType) {
			event.loader.setResponseType("blob");
		}
	};

	/**
	 * The result formatter for Image files.
	 * @method _formatResult
	 * @param {AbstractLoader} loader
	 * @returns {HTMLImageElement}
	 * @private
	 */
	p._formatResult = function (loader) {
		return this._formatImage;
	};

	/**
	 * The asynchronous image formatter function. This is required because images have
	 * a short delay before they are ready.
	 * @method _formatImage
	 * @param {Function} successCallback The method to call when the result has finished formatting
	 * @param {Function} errorCallback The method to call if an error occurs during formatting
	 * @private
	 */
	p._formatImage = function (successCallback, errorCallback) {
		var tag = this._tag;
		var URL = window.URL || window.webkitURL;

		if (!this._preferXHR) {

			//document.body.removeChild(tag);
		} else if (URL) {
			var objURL = URL.createObjectURL(this.getResult(true));
			tag.src = objURL;

			tag.addEventListener("load", this._cleanUpURL, false);
			tag.addEventListener("error", this._cleanUpURL, false);
		} else {
			tag.src = this._item.src;
		}

		if (tag.complete) {
			successCallback(tag);
		} else {
            tag.onload = createjs.proxy(function() {
                successCallback(this._tag);
            }, this);

            tag.onerror = createjs.proxy(function() {
                errorCallback(this._tag);
            }, this);
		}
	};

	/**
	 * Clean up the ObjectURL, the tag is done with it. Note that this function is run
	 * as an event listener without a proxy/closure, as it doesn't require it - so do not
	 * include any functionality that requires scope without changing it.
	 * @method _cleanUpURL
	 * @param event
	 * @private
	 */
	p._cleanUpURL = function (event) {
		var URL = window.URL || window.webkitURL;
		URL.revokeObjectURL(event.target.src);
	};

	createjs.ImageLoader = createjs.promote(ImageLoader, "AbstractLoader");

}());
<commit_msg>Fixe format error callback arg.<commit_after>/*
 * ImageLoader
 * Visit http://createjs.com/ for documentation, updates and examples.
 *
 *
 * Copyright (c) 2012 gskinner.com, inc.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

// namespace:
this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * A loader for image files.
	 * @class ImageLoader
	 * @param {LoadItem|Object} loadItem
	 * @param {Boolean} preferXHR
	 * @extends AbstractLoader
	 * @constructor
	 */
	function ImageLoader (loadItem, preferXHR) {
		this.AbstractLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.IMAGE);

		// public properties
		this.resultFormatter = this._formatResult;

		// protected properties
		this._tagSrcAttribute = "src";

		// Check if the preload item is already a tag.
		if (createjs.DomUtils.isImageTag(loadItem)) {
			this._tag = loadItem;
		} else if (createjs.DomUtils.isImageTag(loadItem.src)) {
			this._tag = loadItem.src;
		} else if (createjs.DomUtils.isImageTag(loadItem.tag)) {
			this._tag = loadItem.tag;
		}

		if (this._tag != null) {
			this._preferXHR = false;
		} else {
			this._tag = createjs.Elements.img();
		}

		this.on("initialize", this._updateXHR, this);
	};

	var p = createjs.extend(ImageLoader, createjs.AbstractLoader);
	var s = ImageLoader;

	// static methods
	/**
	 * Determines if the loader can load a specific item. This loader can only load items that are of type
	 * {{#crossLink "AbstractLoader/IMAGE:property"}}{{/crossLink}}.
	 * @method canLoadItem
	 * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
	 * @returns {Boolean} Whether the loader can load the item.
	 * @static
	 */
	s.canLoadItem = function (item) {
		return item.type == createjs.AbstractLoader.IMAGE;
	};

	// public methods
	p.load = function () {
		if (this._tag.src != "" && this._tag.complete) {
			this._sendComplete();
			return;
		}

		var crossOrigin = this._item.crossOrigin;
		if (crossOrigin == true) { crossOrigin = "Anonymous"; }
		if (crossOrigin != null && !createjs.URLUtils.isLocal(this._item)) {
			this._tag.crossOrigin = crossOrigin;
		}

		this.AbstractLoader_load();
	};

	// protected methods
	/**
	 * Before the item loads, set its mimeType and responseType.
	 * @property _updateXHR
	 * @param {Event} event
	 * @private
	 */
	p._updateXHR = function (event) {
		event.loader.mimeType = 'text/plain; charset=x-user-defined-binary';

		// Only exists for XHR
		if (event.loader.setResponseType) {
			event.loader.setResponseType("blob");
		}
	};

	/**
	 * The result formatter for Image files.
	 * @method _formatResult
	 * @param {AbstractLoader} loader
	 * @returns {HTMLImageElement}
	 * @private
	 */
	p._formatResult = function (loader) {
		return this._formatImage;
	};

	/**
	 * The asynchronous image formatter function. This is required because images have
	 * a short delay before they are ready.
	 * @method _formatImage
	 * @param {Function} successCallback The method to call when the result has finished formatting
	 * @param {Function} errorCallback The method to call if an error occurs during formatting
	 * @private
	 */
	p._formatImage = function (successCallback, errorCallback) {
		var tag = this._tag;
		var URL = window.URL || window.webkitURL;

		if (!this._preferXHR) {

			//document.body.removeChild(tag);
		} else if (URL) {
			var objURL = URL.createObjectURL(this.getResult(true));
			tag.src = objURL;

			tag.addEventListener("load", this._cleanUpURL, false);
			tag.addEventListener("error", this._cleanUpURL, false);
		} else {
			tag.src = this._item.src;
		}

		if (tag.complete) {
			successCallback(tag);
		} else {
            tag.onload = createjs.proxy(function() {
                successCallback(this._tag);
            }, this);

            tag.onerror = createjs.proxy(function() {
                errorCallback(new createjs.ErrorEvent('IMAGE_FORMAT'));
            }, this);
		}
	};

	/**
	 * Clean up the ObjectURL, the tag is done with it. Note that this function is run
	 * as an event listener without a proxy/closure, as it doesn't require it - so do not
	 * include any functionality that requires scope without changing it.
	 * @method _cleanUpURL
	 * @param event
	 * @private
	 */
	p._cleanUpURL = function (event) {
		var URL = window.URL || window.webkitURL;
		URL.revokeObjectURL(event.target.src);
	};

	createjs.ImageLoader = createjs.promote(ImageLoader, "AbstractLoader");

}());
<|endoftext|>


<commit_before>'use strict';

Creep.execute = function(creep, methods) {
  for (var method of methods) {
    if (method(creep)) {
      return true;
    }
  }
};

Creep.upgradeControllerTask = function(creep) {
  if (creep.carry.energy === 0) {
    return false;
  }

  var range = creep.pos.getRangeTo(creep.room.controller);
  if (range <= 3) {
    let returnCode = creep.upgradeController(creep.room.controller);
    if (returnCode != OK) {
      creep.log('upgradeController: ' + returnCode);
    }
    creep.moveRandom();
    return true;
  }

  if (range > 1) {
    let search = PathFinder.search(
      creep.pos, {
        pos: creep.room.controller.pos,
        range: 3
      }, {
        roomCallback: creep.room.getAvoids(creep.room, {}, true),
        maxRooms: 0
      }
    );

    if (search.incomplete) {
      creep.say('incomplete');
      creep.moveTo(creep.room.controller.pos);
      return true;
    }
    creep.move(creep.pos.getDirectionTo(search.path[0]));
  }
  return true;
};

Creep.constructTask = function(creep) {
  //  creep.say('construct', true);
  return creep.construct();
};

Creep.transferEnergy = function(creep) {
  //  creep.say('transferEnergy', true);
  return creep.transferEnergyMy();
};

Creep.buildRoads = function(creep) {
  let room = Game.rooms[creep.room.name];

  // TODO extract to roomposition
  function checkForRoad(pos) {
    var structures = pos.lookFor('structure');
    for (let structuresIndex in structures) {
      if (structures[structuresIndex].structureType == STRUCTURE_ROAD) {
        return true;
      }
    }
    return false;
  }

  // TODO Redo for all path in room
  var path = room.memory.position.path;
  for (let pathIndex in path) {
    var pos = new RoomPosition(
      path[pathIndex].x,
      path[pathIndex].y,
      creep.room.name
    );
    if (checkForRoad(pos)) {
      continue;
    }

    let returnCode = pos.createConstructionSite(STRUCTURE_ROAD);
    if (returnCode == OK) {
      return true;
    }
    if (returnCode == ERR_FULL) {
      return true;
    }
    if (returnCode == ERR_INVALID_TARGET) {
      // FIXME Creep is standing on constructionSite, need to check why it is not building
      creep.moveRandom();
      continue;
    }
    creep.log('buildRoads: ' + returnCode + ' pos: ' + JSON.stringify(pos));
    return true;
  }
  return false;
};

Creep.recycleCreep = function(creep) {
  if (creep.memory.role == 'planer') {
    creep.room.buildStructures();
  }

  let spawn = creep.pos.findClosestByRange(FIND_MY_STRUCTURES, {
    filter: {
      structureType: STRUCTURE_SPAWN
    }
  });
  if (spawn !== null) {
    creep.moveTo(spawn, {
      ignoreCreeps: true
    });
    spawn.recycleCreep(creep);
  }
  // TODO move back
  return true;
};

Creep.getEnergy = function(creep) {
  return creep.getEnergy();
};

Creep.repairStructure = function(creep) {
  return creep.repairStructure();
};

Creep.prototype.getEnergyFromHostileStructures = function() {
  if (this.carry.energy) {
    return false;
  }
  this.say('hostile');
  let hostileStructures = this.room.find(FIND_HOSTILE_STRUCTURES, {
    filter: function(object) {
      let table = {
        [STRUCTURE_CONTROLLER]: true,
        [STRUCTURE_RAMPART]: true,
        [STRUCTURE_EXTRACTOR]: true
      };
      return !table[object.structureType];
    }
  });
  if (!hostileStructures.length) {
    return false;
  }

  hostileStructures = _.sortBy(hostileStructures, function(object) {
    if (object.structureType == STRUCTURE_STORAGE) {
      return 1;
    }
    return 2;
  });

  let structure = _.max(hostileStructures, s => s.structureType === STRUCTURE_STORAGE);
  this.log(JSON.stringify(structure));
  if (structure.structureType === STRUCTURE_STORAGE) {
    if (structure.store.energy === 0) {
      structure.destroy();
      return true;
    }
  } else if (!structure.energy) {
    structure.destroy();
    return true;
  }

  let range = this.pos.getRangeTo(structure);
  this.say('hostile');
  this.moveTo(structure);
  this.withdraw(structure, RESOURCE_ENERGY);
  return true;
};

Creep.prototype.getEnergyFromStorage = function() {
  if (!this.room.storage || this.room.storage.store.energy < config.creep.energyFromStorageThreshold) {
    return false;
  }

  if (this.carry.energy) {
    return false;
  }

  var range = this.pos.getRangeTo(this.room.storage);
  if (range == 1) {
    this.withdraw(this.room.storage, RESOURCE_ENERGY);
  } else {
    let search = PathFinder.search(
      this.pos, {
        pos: this.room.storage.pos,
        range: 1
      }, {
        roomCallback: this.room.getAvoids(this.room, {}, true),
      }
    );
    if (search.incomplete) {
      this.say('incomplete', true);
      this.moveTo(this.room.storage.pos, {
        ignoreCreeps: true
      });
      return true;
    }
    let returnCode = this.move(this.pos.getDirectionTo(search.path[0]));
    if (returnCode != OK) {
      this.log(`getEnergyFromStorage: ${returnCode}`);
    }
  }
  return true;
};

Creep.prototype.repairStructure = function() {
  var structure = null;
  var range = null;
  var i = null;
  var structures = null;

  if (this.memory.target) {
    var to_repair = Game.getObjectById(this.memory.target);
    if (!to_repair || to_repair === null) {
      delete this.memory.target;
      return false;
    }

    if (to_repair instanceof ConstructionSite) {
      this.build(to_repair);

      let search = PathFinder.search(
        this.pos, {
          pos: to_repair.pos,
          range: 3
        }, {
          roomCallback: this.room.getAvoids(this.room, {}, true),
          maxRooms: 0
        }
      );

      if (search.incomplete) {
        this.moveTo(to_repair);
        return true;
      }

      if (!this.pos.getDirectionTo(search.path[0])) {
        this.moveRandom();
        return true;
      }

      let returnCode = this.move(this.pos.getDirectionTo(search.path[0]));
      return true;
    } else if (to_repair.hits < 10000 || to_repair.hits < this.memory.step + 10000) {
      this.repair(to_repair);
      if (this.fatigue === 0) {
        range = this.pos.getRangeTo(to_repair);
        if (range <= 3) {
          this.moveRandom();
        } else {
          let search = PathFinder.search(
            this.pos, {
              pos: to_repair.pos,
              range: 3
            }, {
              roomCallback: this.room.getAvoids(this.room, {}, true),
              maxRooms: 0
            }
          );

          if (!this.pos.getDirectionTo(search.path[0])) {
            this.moveRandom();
            return true;
          }

          if (search.incomplete) {
            this.moveTo(to_repair.pos);
            return true;
          }

          let returnCode = this.move(this.pos.getDirectionTo(search.path[0]));
          this.memory.lastPosition = this.pos;
          if (returnCode == OK) {
            return true;
          }
          if (returnCode == ERR_NO_PATH) {
            this.memory.move_wait = 0;
            this.log('No path : ' + JSON.stringify(search));
            returnCode = this.moveTo(to_repair, {
              ignoreCreeps: true,
              costCallback: this.room.getAvoids(this.room, {
                power: true
              })
            });
          }
          this.log('config_creep_resources.repairStructure moveByPath.returnCode: ' + returnCode + ' search: ' + JSON.stringify(search) + ' start: ' + JSON.stringify(this.pos) + ' end: ' + JSON.stringify(to_repair.pos));
          return true;
        }
      }
    } else {
      delete this.memory.target;
    }
  }

  let nukes = this.room.find(FIND_NUKES);
  if (nukes.length > 0) {
    let spawns = this.room.find(FIND_MY_STRUCTURES, {
      filter: function(object) {
        if (object.structureType != STRUCTURE_SPAWN) {
          return false;
        }
        return true;
      }
    });
    if (spawns.length > 0) {
      for (let spawn of spawns) {
        let found = false;
        let rampart;
        structures = spawn.pos.lookFor(LOOK_STRUCTURES);
        for (structure of structures) {
          if (structure.structureType == STRUCTURE_RAMPART) {
            if (structure.hits < 1100000) {
              found = true;
              rampart = structure;
              break;
            }
          }
        }
        if (found) {
          this.memory.target = rampart.id;
          this.memory.step = 1200000;
          return true;
        }
      }
    }
  }

  // Repair low ramparts
  let lowRamparts = this.pos.findInRange(FIND_STRUCTURES, 4, {
    filter: function(object) {
      if (object.structureType == STRUCTURE_RAMPART && object.hits < 10000) {
        return true;
      }
      return false;
    }
  });

  if (lowRamparts.length > 0) {
    let search = PathFinder.search(
      this.pos, {
        pos: lowRamparts[0].pos,
        range: 3
      }, {
        roomCallback: this.room.getAvoids(this.room, {}, true),
        maxRooms: 0
      }
    );
    //     this.log('LowRampart: ' + lowRamparts[0].pos + ' search: ' + JSON.stringify(search));
    let returnCode = this.move(this.pos.getDirectionTo(search.path[0]));
    this.repair(lowRamparts[0]);
    this.moveRandom();
    return true;
  }

  // Build construction sites
  var target = this.pos.findClosestByRange(FIND_CONSTRUCTION_SITES, {
    filter: function(object) {
      if (object.structureType == 'constructedWall') {
        return true;
      }
      if (object.structureType == 'rampart') {
        return true;
      }
      return false;
    }
  });

  if (target !== null) {
    range = this.pos.getRangeTo(target);

    if (range <= 3) {
      this.build(target);
      this.memory.step = 0;
      var targetNew = this.pos.findClosestByRange(FIND_CONSTRUCTION_SITES, {
        filter: function(object) {
          if (object.id == target.id) {
            return false;
          }
          if (object.structureType == 'constructedWall') {
            return true;
          }
          if (object.structureType == 'rampart') {
            return true;
          }
          return false;
        }
      });
      if (targetNew !== null) {
        target = targetNew;
      }
    }
    let ignoreCreepsSwitch = true;
    let last_pos = this.memory.lastPosition;
    if (this.memory.lastPosition && this.pos.isEqualTo(new RoomPosition(last_pos.x, last_pos.y, this.room.name))) {
      this.memory.move_wait++;
      if (this.memory.move_wait > 5) {
        ignoreCreepsSwitch = false;
      }
    } else {
      this.memory.move_wait = 0;
    }

    let search = PathFinder.search(
      this.pos, {
        pos: target.pos,
        range: 3
      }, {
        roomCallback: this.room.getAvoids(this.room, {}, true),
        maxRooms: 0
      }
    );
    //    this.log('ConstructionSite: ' + target.pos + ' search: ' + JSON.stringify(search));
    // for (let x = 19; x < 31; x++) {
    // for (let y = 2; y < 7; y++) {
    // let costmatrix = this.room.getAvoids(this.room, {}, true)(this.room.name);
    // this.log(x + ',' + y + ' ' + costmatrix.get(x, y));
    // }
    // }
    let returnCode = this.move(this.pos.getDirectionTo(search.path[0]));
    this.memory.lastPosition = this.pos;
    this.memory.target = target.id;
    return true;
  }

  var creep = this;
  structure = this.pos.findClosestByRange(FIND_STRUCTURES, {
    filter: function(object) {

      // Newbie zone walls have no hits
      if (!object.hits) {
        return false;
      }

      if (object.hits >= Math.min(creep.memory.step, object.hitsMax)) {
        return false;
      }

      if (object.structureType == 'constructedWall') {
        return true;
      }

      if (object.structureType == 'rampart') {
        return true;
      }
      return false;
    }
  });
  if (structure && structure !== null) {
    this.memory.target = structure.id;
    return true;
  }

  if (this.memory.step === 0) {
    this.memory.step = this.room.controller.level * 10000;
  }
  this.memory.step = (this.memory.step * 1.1) + 1;

  //   this.log('Nothing found: ' + this.memory.step);
  return false;
};

Creep.prototype.getDroppedEnergy = function() {
  let target = this.pos.findClosestByRange(FIND_DROPPED_ENERGY, {
    filter: function(object) {
      return 0 < object.energy;
    }
  });
  if (target !== null) {
    var energyRange = this.pos.getRangeTo(target.pos);
    if (energyRange <= 1) {
      this.pickup(target);
      return true;
    }
    if (target.energy > (energyRange * 10) * (this.carry.energy + 1)) {
      let search = PathFinder.search(
        this.pos, {
          pos: target.pos,
          range: 1
        }, {
          roomCallback: this.room.getAvoids(this.room, {}, true),
          maxRooms: 0
        }
      );
      if (search.path.length === 0 || search.incomplete) {
        this.say('deir');
        this.moveRandom();
        return true;
      }
      let returnCode = this.move(this.pos.getDirectionTo(search.path[0]));
      return true;
    }
  }
  return false;
};
<commit_msg>Remove redundant hostile message<commit_after>'use strict';

Creep.execute = function(creep, methods) {
  for (var method of methods) {
    if (method(creep)) {
      return true;
    }
  }
};

Creep.upgradeControllerTask = function(creep) {
  if (creep.carry.energy === 0) {
    return false;
  }

  var range = creep.pos.getRangeTo(creep.room.controller);
  if (range <= 3) {
    let returnCode = creep.upgradeController(creep.room.controller);
    if (returnCode != OK) {
      creep.log('upgradeController: ' + returnCode);
    }
    creep.moveRandom();
    return true;
  }

  if (range > 1) {
    let search = PathFinder.search(
      creep.pos, {
        pos: creep.room.controller.pos,
        range: 3
      }, {
        roomCallback: creep.room.getAvoids(creep.room, {}, true),
        maxRooms: 0
      }
    );

    if (search.incomplete) {
      creep.say('incomplete');
      creep.moveTo(creep.room.controller.pos);
      return true;
    }
    creep.move(creep.pos.getDirectionTo(search.path[0]));
  }
  return true;
};

Creep.constructTask = function(creep) {
  //  creep.say('construct', true);
  return creep.construct();
};

Creep.transferEnergy = function(creep) {
  //  creep.say('transferEnergy', true);
  return creep.transferEnergyMy();
};

Creep.buildRoads = function(creep) {
  let room = Game.rooms[creep.room.name];

  // TODO extract to roomposition
  function checkForRoad(pos) {
    var structures = pos.lookFor('structure');
    for (let structuresIndex in structures) {
      if (structures[structuresIndex].structureType == STRUCTURE_ROAD) {
        return true;
      }
    }
    return false;
  }

  // TODO Redo for all path in room
  var path = room.memory.position.path;
  for (let pathIndex in path) {
    var pos = new RoomPosition(
      path[pathIndex].x,
      path[pathIndex].y,
      creep.room.name
    );
    if (checkForRoad(pos)) {
      continue;
    }

    let returnCode = pos.createConstructionSite(STRUCTURE_ROAD);
    if (returnCode == OK) {
      return true;
    }
    if (returnCode == ERR_FULL) {
      return true;
    }
    if (returnCode == ERR_INVALID_TARGET) {
      // FIXME Creep is standing on constructionSite, need to check why it is not building
      creep.moveRandom();
      continue;
    }
    creep.log('buildRoads: ' + returnCode + ' pos: ' + JSON.stringify(pos));
    return true;
  }
  return false;
};

Creep.recycleCreep = function(creep) {
  if (creep.memory.role == 'planer') {
    creep.room.buildStructures();
  }

  let spawn = creep.pos.findClosestByRange(FIND_MY_STRUCTURES, {
    filter: {
      structureType: STRUCTURE_SPAWN
    }
  });
  if (spawn !== null) {
    creep.moveTo(spawn, {
      ignoreCreeps: true
    });
    spawn.recycleCreep(creep);
  }
  // TODO move back
  return true;
};

Creep.getEnergy = function(creep) {
  return creep.getEnergy();
};

Creep.repairStructure = function(creep) {
  return creep.repairStructure();
};

Creep.prototype.getEnergyFromHostileStructures = function() {
  if (this.carry.energy) {
    return false;
  }
  let hostileStructures = this.room.find(FIND_HOSTILE_STRUCTURES, {
    filter: function(object) {
      let table = {
        [STRUCTURE_CONTROLLER]: true,
        [STRUCTURE_RAMPART]: true,
        [STRUCTURE_EXTRACTOR]: true
      };
      return !table[object.structureType];
    }
  });
  if (!hostileStructures.length) {
    return false;
  }

  this.say('hostile');
  hostileStructures = _.sortBy(hostileStructures, function(object) {
    if (object.structureType == STRUCTURE_STORAGE) {
      return 1;
    }
    return 2;
  });

  let structure = _.max(hostileStructures, s => s.structureType === STRUCTURE_STORAGE);
  this.log(JSON.stringify(structure));
  if (structure.structureType === STRUCTURE_STORAGE) {
    if (structure.store.energy === 0) {
      structure.destroy();
      return true;
    }
  } else if (!structure.energy) {
    structure.destroy();
    return true;
  }

  let range = this.pos.getRangeTo(structure);
  this.moveTo(structure);
  this.withdraw(structure, RESOURCE_ENERGY);
  return true;
};

Creep.prototype.getEnergyFromStorage = function() {
  if (!this.room.storage || this.room.storage.store.energy < config.creep.energyFromStorageThreshold) {
    return false;
  }

  if (this.carry.energy) {
    return false;
  }

  var range = this.pos.getRangeTo(this.room.storage);
  if (range == 1) {
    this.withdraw(this.room.storage, RESOURCE_ENERGY);
  } else {
    let search = PathFinder.search(
      this.pos, {
        pos: this.room.storage.pos,
        range: 1
      }, {
        roomCallback: this.room.getAvoids(this.room, {}, true),
      }
    );
    if (search.incomplete) {
      this.say('incomplete', true);
      this.moveTo(this.room.storage.pos, {
        ignoreCreeps: true
      });
      return true;
    }
    let returnCode = this.move(this.pos.getDirectionTo(search.path[0]));
    if (returnCode != OK) {
      this.log(`getEnergyFromStorage: ${returnCode}`);
    }
  }
  return true;
};

Creep.prototype.repairStructure = function() {
  var structure = null;
  var range = null;
  var i = null;
  var structures = null;

  if (this.memory.target) {
    var to_repair = Game.getObjectById(this.memory.target);
    if (!to_repair || to_repair === null) {
      delete this.memory.target;
      return false;
    }

    if (to_repair instanceof ConstructionSite) {
      this.build(to_repair);

      let search = PathFinder.search(
        this.pos, {
          pos: to_repair.pos,
          range: 3
        }, {
          roomCallback: this.room.getAvoids(this.room, {}, true),
          maxRooms: 0
        }
      );

      if (search.incomplete) {
        this.moveTo(to_repair);
        return true;
      }

      if (!this.pos.getDirectionTo(search.path[0])) {
        this.moveRandom();
        return true;
      }

      let returnCode = this.move(this.pos.getDirectionTo(search.path[0]));
      return true;
    } else if (to_repair.hits < 10000 || to_repair.hits < this.memory.step + 10000) {
      this.repair(to_repair);
      if (this.fatigue === 0) {
        range = this.pos.getRangeTo(to_repair);
        if (range <= 3) {
          this.moveRandom();
        } else {
          let search = PathFinder.search(
            this.pos, {
              pos: to_repair.pos,
              range: 3
            }, {
              roomCallback: this.room.getAvoids(this.room, {}, true),
              maxRooms: 0
            }
          );

          if (!this.pos.getDirectionTo(search.path[0])) {
            this.moveRandom();
            return true;
          }

          if (search.incomplete) {
            this.moveTo(to_repair.pos);
            return true;
          }

          let returnCode = this.move(this.pos.getDirectionTo(search.path[0]));
          this.memory.lastPosition = this.pos;
          if (returnCode == OK) {
            return true;
          }
          if (returnCode == ERR_NO_PATH) {
            this.memory.move_wait = 0;
            this.log('No path : ' + JSON.stringify(search));
            returnCode = this.moveTo(to_repair, {
              ignoreCreeps: true,
              costCallback: this.room.getAvoids(this.room, {
                power: true
              })
            });
          }
          this.log('config_creep_resources.repairStructure moveByPath.returnCode: ' + returnCode + ' search: ' + JSON.stringify(search) + ' start: ' + JSON.stringify(this.pos) + ' end: ' + JSON.stringify(to_repair.pos));
          return true;
        }
      }
    } else {
      delete this.memory.target;
    }
  }

  let nukes = this.room.find(FIND_NUKES);
  if (nukes.length > 0) {
    let spawns = this.room.find(FIND_MY_STRUCTURES, {
      filter: function(object) {
        if (object.structureType != STRUCTURE_SPAWN) {
          return false;
        }
        return true;
      }
    });
    if (spawns.length > 0) {
      for (let spawn of spawns) {
        let found = false;
        let rampart;
        structures = spawn.pos.lookFor(LOOK_STRUCTURES);
        for (structure of structures) {
          if (structure.structureType == STRUCTURE_RAMPART) {
            if (structure.hits < 1100000) {
              found = true;
              rampart = structure;
              break;
            }
          }
        }
        if (found) {
          this.memory.target = rampart.id;
          this.memory.step = 1200000;
          return true;
        }
      }
    }
  }

  // Repair low ramparts
  let lowRamparts = this.pos.findInRange(FIND_STRUCTURES, 4, {
    filter: function(object) {
      if (object.structureType == STRUCTURE_RAMPART && object.hits < 10000) {
        return true;
      }
      return false;
    }
  });

  if (lowRamparts.length > 0) {
    let search = PathFinder.search(
      this.pos, {
        pos: lowRamparts[0].pos,
        range: 3
      }, {
        roomCallback: this.room.getAvoids(this.room, {}, true),
        maxRooms: 0
      }
    );
    //     this.log('LowRampart: ' + lowRamparts[0].pos + ' search: ' + JSON.stringify(search));
    let returnCode = this.move(this.pos.getDirectionTo(search.path[0]));
    this.repair(lowRamparts[0]);
    this.moveRandom();
    return true;
  }

  // Build construction sites
  var target = this.pos.findClosestByRange(FIND_CONSTRUCTION_SITES, {
    filter: function(object) {
      if (object.structureType == 'constructedWall') {
        return true;
      }
      if (object.structureType == 'rampart') {
        return true;
      }
      return false;
    }
  });

  if (target !== null) {
    range = this.pos.getRangeTo(target);

    if (range <= 3) {
      this.build(target);
      this.memory.step = 0;
      var targetNew = this.pos.findClosestByRange(FIND_CONSTRUCTION_SITES, {
        filter: function(object) {
          if (object.id == target.id) {
            return false;
          }
          if (object.structureType == 'constructedWall') {
            return true;
          }
          if (object.structureType == 'rampart') {
            return true;
          }
          return false;
        }
      });
      if (targetNew !== null) {
        target = targetNew;
      }
    }
    let ignoreCreepsSwitch = true;
    let last_pos = this.memory.lastPosition;
    if (this.memory.lastPosition && this.pos.isEqualTo(new RoomPosition(last_pos.x, last_pos.y, this.room.name))) {
      this.memory.move_wait++;
      if (this.memory.move_wait > 5) {
        ignoreCreepsSwitch = false;
      }
    } else {
      this.memory.move_wait = 0;
    }

    let search = PathFinder.search(
      this.pos, {
        pos: target.pos,
        range: 3
      }, {
        roomCallback: this.room.getAvoids(this.room, {}, true),
        maxRooms: 0
      }
    );
    //    this.log('ConstructionSite: ' + target.pos + ' search: ' + JSON.stringify(search));
    // for (let x = 19; x < 31; x++) {
    // for (let y = 2; y < 7; y++) {
    // let costmatrix = this.room.getAvoids(this.room, {}, true)(this.room.name);
    // this.log(x + ',' + y + ' ' + costmatrix.get(x, y));
    // }
    // }
    let returnCode = this.move(this.pos.getDirectionTo(search.path[0]));
    this.memory.lastPosition = this.pos;
    this.memory.target = target.id;
    return true;
  }

  var creep = this;
  structure = this.pos.findClosestByRange(FIND_STRUCTURES, {
    filter: function(object) {

      // Newbie zone walls have no hits
      if (!object.hits) {
        return false;
      }

      if (object.hits >= Math.min(creep.memory.step, object.hitsMax)) {
        return false;
      }

      if (object.structureType == 'constructedWall') {
        return true;
      }

      if (object.structureType == 'rampart') {
        return true;
      }
      return false;
    }
  });
  if (structure && structure !== null) {
    this.memory.target = structure.id;
    return true;
  }

  if (this.memory.step === 0) {
    this.memory.step = this.room.controller.level * 10000;
  }
  this.memory.step = (this.memory.step * 1.1) + 1;

  //   this.log('Nothing found: ' + this.memory.step);
  return false;
};

Creep.prototype.getDroppedEnergy = function() {
  let target = this.pos.findClosestByRange(FIND_DROPPED_ENERGY, {
    filter: function(object) {
      return 0 < object.energy;
    }
  });
  if (target !== null) {
    var energyRange = this.pos.getRangeTo(target.pos);
    if (energyRange <= 1) {
      this.pickup(target);
      return true;
    }
    if (target.energy > (energyRange * 10) * (this.carry.energy + 1)) {
      let search = PathFinder.search(
        this.pos, {
          pos: target.pos,
          range: 1
        }, {
          roomCallback: this.room.getAvoids(this.room, {}, true),
          maxRooms: 0
        }
      );
      if (search.path.length === 0 || search.incomplete) {
        this.say('deir');
        this.moveRandom();
        return true;
      }
      let returnCode = this.move(this.pos.getDirectionTo(search.path[0]));
      return true;
    }
  }
  return false;
};
<|endoftext|>


<commit_before><commit_msg>Update dendro js<commit_after><|endoftext|>


<commit_before>$( document ).ready(function() {

$( ".lobbysearch" ).focus(function() {
    $( ".overlay" ).fadeOut( "slow" );
});

$( "#networkviz" ).draggable();

$( ".logo-name" ).click(function() {
    $( ".result-list" ).slideUp( "slow" );
    $( ".overlay" ).fadeIn( "slow" );
});

  $('.lobbysearch').keypress(function (e) {
  if (e.which === 13) {
    // $( ".result-list" ).slideToggle( "slow" );
    $( ".result-list" ).slideDown( "slow" );
    return false;
  }
});

// http://stackoverflow.com/questions/16437182/issue-with-a-scrollable-div-on-ipad
$('body').on('touchmove','.scrollable',function(e) {
  var tot = 0;
  $(this).children('li:visible').each(function() { tot += $(this).height(); });
  if(tot > $(this).innerHeight()) {
    e.stopPropagation();
  }
});

//uses body because jquery on events are called off of the element they are
//added to, so bubbling would not work if we used document instead.
$('body').on('touchstart','.scrollable',function(e) {
    if (e.currentTarget.scrollTop === 0) {
        e.currentTarget.scrollTop = 1;
    } else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
        e.currentTarget.scrollTop -= 1;
    }
});

//prevents preventDefault from being called on document if it sees a scrollable div
$('body').on('touchmove','.scrollable',function(e) {
    e.stopPropagation();
});

//    $("#joschka").click(function () {
//           // $(".result-list").hide("slide", { direction: "left" }, 1000);
//           $(".result-list").animate({height:"toggle",opacity:"toggle", easing: "easeOutQuint"},500);
//           $(".result-single").animate({height:"toggle",opacity:"toggle", easing: "easeOutQuint"},1000);

//           return false;
//     });

//       $("#back").click(function () {
//           // $(".result-list").hide("slide", { direction: "left" }, 1000);
//                     $(".result-single").animate({height:"toggle",opacity:"toggle", easing: "easeOutQuint"},500);

//           $(".result-list").animate({height:"toggle",opacity:"toggle", easing: "easeOutQuint"},1000);

//           return false;
//     });

// $("#change-visual").click(function () {
//           // $(".result-list").hide("slide", { direction: "left" }, 1000);
//           $("#map").animate({opacity:"toggle", easing: "easeOutQuint"},500);
//           $("svg").animate({opacity:"toggle", easing: "easeOutQuint"},1000);
//           $('.fullscreen').css({
//   'width': winWidth,
//   'height': winHeight,
// });
//           return false;
//     });

  // global vars
var winWidth = $(window).width();
var winHeight = $(window).height();

// set initial div height / width
$('.fullscreen').css({
  'width': winWidth,
  'height': winHeight,
});

// make sure div stays full width/height on resize

  $(window).resize(function(){
    $('.fullscreen').css({
      'width': winWidth,
      'height': winHeight,
    });
  });

// var w = winWidth,
//     h = winHeight,
//     node,
//     link,
//     root;

// var force = d3.layout.force()
//     .on("tick", tick)
//     .charge(function(d) { return d._children ? -d.size / 1 : -300; })
//     .linkDistance(function(d) { return d.target._children ? 20 : 30; })
//     .size([w-400, h - 60]);

// var vis = d3.select(".fullscreen").append("svg:svg")
//     .attr("width", w)
//     .attr("height", h);

// d3.json("flare.json", function(json) {
//   root = json;
//   root.fixed = true;
//   root.x = w / 2;
//   root.y = h / 2 - 80;
//   update();
// });

// function update() {
//   var nodes = flatten(root),
//       links = d3.layout.tree().links(nodes);

//   // Restart the force layout.
//   force
//       .nodes(nodes)
//       .links(links)
//       .start();

//   // Update the links…
//   link = vis.selectAll("line.link")
//       .data(links, function(d) { return d.target.id; });

//   // Enter any new links.
//   link.enter().insert("svg:line", ".node")
//       .attr("class", "link")
//       .attr("x1", function(d) { return d.source.x; })
//       .attr("y1", function(d) { return d.source.y; })
//       .attr("x2", function(d) { return d.target.x; })
//       .attr("y2", function(d) { return d.target.y; });

//   // Exit any old links.
//   link.exit().remove();

//   // Update the nodes…
//   node = vis.selectAll("circle.node")
//       .data(nodes, function(d) { return d.id; })
//       .style("fill", color);

//   node.transition()
//       .attr("r", function(d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; });

//   // Enter any new nodes.
//   node.enter().append("svg:circle")
//       .attr("class", "node")
//       .attr("cx", function(d) { return d.x; })
//       .attr("cy", function(d) { return d.y; })
//       .attr("r", function(d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; })
//       .style("fill", color)
//       .on("click", click)
//       .call(force.drag);

//   // Exit any old nodes.
//   node.exit().remove();
// }

// function tick() {
//   link.attr("x1", function(d) { return d.source.x; })
//       .attr("y1", function(d) { return d.source.y; })
//       .attr("x2", function(d) { return d.target.x; })
//       .attr("y2", function(d) { return d.target.y; });

//   node.attr("cx", function(d) { return d.x; })
//       .attr("cy", function(d) { return d.y; });
// }

// // Color leaf nodes orange, and packages white or blue.
// function color(d) {
//   return d._children ? "#062b3e" : d.children ? "#c6dbef" : "#fd8d3c";
// }

// // Toggle children on click.
// function click(d) {
//   if (d.children) {
//     d._children = d.children;
//     d.children = null;
//   } else {
//     d.children = d._children;
//     d._children = null;
//   }
//   update();
// }

// // Returns a list of all nodes under the root.
// function flatten(root) {
//   var nodes = [], i = 0;

//   function recurse(node) {
//     if (node.children) node.size = node.children.reduce(function(p, v) { return p + recurse(v); }, 0);
//     if (!node.id) node.id = ++i;
//     nodes.push(node);
//     return node.size;
//   }

//   root.size = recurse(root);
//   return nodes;
// }

});<commit_msg>cleanup, more interface show<commit_after>$( document ).ready(function() {

  $( ".lobbysearch" ).focus(function() {
    $( ".overlay" ).fadeOut( "slow" );
  });

  $( "#networkviz" ).draggable();

  $( ".logo-name" ).click(function() {
    $( ".result-list" ).slideUp( "slow" );
    $( ".result-single" ).slideUp( "slow" );

    $( ".overlay" ).fadeIn( "slow" );
  });

  $('.lobbysearch').keypress(function (e) {

    if (e.which === 13) {
      // $( ".result-list" ).slideToggle( "slow" );
      $( ".result-list" ).slideDown( "slow" );
      return false;
    }

  });

  // http://stackoverflow.com/questions/16437182/issue-with-a-scrollable-div-on-ipad
  $('body').on('touchmove','.scrollable',function(e) {
    var tot = 0;
    $(this).children('li:visible').each(function() { tot += $(this).height(); }); // this is not quite right
    if(tot > $(this).innerHeight()) {
      e.stopPropagation();
    }
  });

  //uses body because jquery on events are called off of the element they are
  //added to, so bubbling would not work if we used document instead.
  $('body').on('touchstart','.scrollable',function(e) {
    if (e.currentTarget.scrollTop === 0) {
      e.currentTarget.scrollTop = 1;
    } else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
      e.currentTarget.scrollTop -= 1;
    }
  });

  //prevents preventDefault from being called on document if it sees a scrollable div
  $('body').on('touchmove','.scrollable',function(e) {
    e.stopPropagation();
  });

   $("tr a").click(function () {
          // $(".result-list").hide("slide", { direction: "left" }, 1000);
          $(".result-list").animate({height:"toggle",opacity:"toggle", easing: "easeOutQuint"},500);
          $(".result-single").animate({height:"toggle",opacity:"toggle", easing: "easeOutQuint"},1000);

          return false;
    });

      $("#back").click(function () {
          // $(".result-list").hide("slide", { direction: "left" }, 1000);
                    $(".result-single").animate({height:"toggle",opacity:"toggle", easing: "easeOutQuint"},500);

          $(".result-list").animate({height:"toggle",opacity:"toggle", easing: "easeOutQuint"},1000);

          return false;
    });

  // global vars
  var winWidth = $(window).width();
  var winHeight = $(window).height();

  // set initial div height / width
  $('.fullscreen').css({
    'width': winWidth,
    'height': winHeight,
  });

  // make sure div stays full width/height on resize

  $(window).resize(function(){
    $('.fullscreen').css({
      'width': winWidth,
      'height': winHeight,
    });
  });

});<|endoftext|>


<commit_before>uwdoem.pagination = (function() {

    var getPaginationContainer = function(handle) {
        return $("div.pagination-container[data-handle-for=" + handle +"]");
    };

    var getAjaxSectionName = function(handle) {
        return $("")
    };

    var getMaxPages = function(handle) {
        return parseInt(getPaginationContainer(handle).find("option").last().html());
    };

    var setArrows = function(handle, page) {
        var paginationContainer, maxPages;

        paginationContainer = getPaginationContainer(handle);
        maxPages = getMaxPages(handle);

        paginationContainer.find("a.pagination-arrow").css("display", "inline");

        if (page === 1) {
            paginationContainer.find("a.pagination-arrow.back").css("display", "none");
        } else {
            paginationContainer.find("a.pagination-arrow.previous").attr("data-page-for", page - 1);
        }

        if (page === maxPages) {
            paginationContainer.find("a.pagination-arrow.forward").css("display", "none");
        } else {
            paginationContainer.find("a.pagination-arrow.next").attr("data-page-for", page + 1);
        }
    };

    var setSelect = function(handle, page) {
        getPaginationContainer(handle).find("select").val(page);
    };

    var setControls = function(handle, page) {
        setArrows(handle, page);
        setSelect(handle, page);
    };

    var registerPage = function(ajaxSectionName, handle, page) {
        var getVar;

        getVar = uwdoem.ajax_section.getVar(ajaxSectionName, handle, "page", page);

        uwdoem.ajax_section.registerGetVar(getVar);
    };

    var getPage = function(ajaxSectionName, handle) {
        var getVar = uwdoem.ajax_section.getGetVarValue(ajaxSectionName, handle, 'page');

        return parseInt(getVar ? getVar: 1);
    };

    var getActiveControls = function(handle) {
        return $("div.section-label div.pagination-container[data-handle-for=" + handle + "]");
    };

    var getInactiveControls = function(handle) {
        return $("div.table-container div.filter-controls div.pagination-container[data-handle-for='" + handle + "']");
    };

    var setupPaginationFilter = function(handle) {
        // If we have already created this filter, return.
        $(function() {
            var page, ajaxSectionName, inactiveControls, activeControls;

            inactiveControls = getInactiveControls(handle);
            activeControls = getActiveControls(handle);

            ajaxSectionName = inactiveControls.closest("div.ajax-loaded-section").attr("id");

            // If this filter is already active...
            if (activeControls.length) {
                // replace the active controls with the new, inactive controls
                activeControls.replaceWith(inactiveControls);
            } else {
                // else just append the new controls to the label.
                inactiveControls.appendTo(inactiveControls.closest("div.section-container").find("div.section-label"));
            }

            activeControls = inactiveControls;

            page = getPage(ajaxSectionName, handle);

            setControls(handle, page);

            activeControls.find("a.pagination-arrow").click(function() {
                var targetPage = parseInt($(this).attr('data-page-for'));

                uwdoem.ajax_section.registerGetVar(uwdoem.ajax_section.getVar(ajaxSectionName, handle, 'page', targetPage));
                uwdoem.ajax_section.loadSection(ajaxSectionName);

                registerPage(ajaxSectionName, handle, targetPage);

                return false;
            });

            activeControls.find("select.pagination-filter." + handle).change(function() {
                var targetPage = parseInt($("select.pagination-filter." + handle + " option:selected").val());

                uwdoem.ajax_section.registerGetVar(uwdoem.ajax_section.getVar(ajaxSectionName, handle, 'page', targetPage));
                uwdoem.ajax_section.loadSection(ajaxSectionName);

                registerPage(ajaxSectionName, handle, targetPage);
            });
        });
    };

    return {
        setupPaginationFilter: setupPaginationFilter
    };
}());<commit_msg>Remove cruft.<commit_after>uwdoem.pagination = (function() {

    var getPaginationContainer = function(handle) {
        return $("div.pagination-container[data-handle-for=" + handle +"]");
    };

    var getAjaxSectionName = function(handle) {
        return $("")
    };

    var getMaxPages = function(handle) {
        return parseInt(getPaginationContainer(handle).find("option").last().html());
    };

    var setArrows = function(handle, page) {
        var paginationContainer, maxPages;

        paginationContainer = getPaginationContainer(handle);
        maxPages = getMaxPages(handle);

        paginationContainer.find("a.pagination-arrow").css("display", "inline");

        if (page === 1) {
            paginationContainer.find("a.pagination-arrow.back").css("display", "none");
        } else {
            paginationContainer.find("a.pagination-arrow.previous").attr("data-page-for", page - 1);
        }

        if (page === maxPages) {
            paginationContainer.find("a.pagination-arrow.forward").css("display", "none");
        } else {
            paginationContainer.find("a.pagination-arrow.next").attr("data-page-for", page + 1);
        }
    };

    var setSelect = function(handle, page) {
        var maxPages = getMaxPages(handle);
        var paginationContainer = getPaginationContainer(handle);

        if (maxPages === 1) {
            paginationContainer.find("select").css("display", "none");
        } else {
            paginationContainer.find("select").css("display", "inline");
            paginationContainer.find("select").val(page);
        }
    };

    var setControls = function(handle, page) {
        setArrows(handle, page);
        setSelect(handle, page);
    };

    var registerPage = function(ajaxSectionName, handle, page) {
        var getVar;

        getVar = uwdoem.ajax_section.getVar(ajaxSectionName, handle, "page", page);

        uwdoem.ajax_section.registerGetVar(getVar);
    };

    var getPage = function(ajaxSectionName, handle) {
        var getVar = uwdoem.ajax_section.getGetVarValue(ajaxSectionName, handle, 'page');

        return parseInt(getVar ? getVar: 1);
    };

    var getActiveControls = function(handle) {
        return $("div.section-label div.pagination-container[data-handle-for=" + handle + "]");
    };

    var getInactiveControls = function(handle) {
        return $("div.table-container div.filter-controls div.pagination-container[data-handle-for='" + handle + "']");
    };

    var setupPaginationFilter = function(handle) {
        // If we have already created this filter, return.
        $(function() {
            var page, ajaxSectionName, inactiveControls, activeControls;

            inactiveControls = getInactiveControls(handle);
            activeControls = getActiveControls(handle);

            ajaxSectionName = inactiveControls.closest("div.ajax-loaded-section").attr("id");

            // If this filter is already active...
            if (activeControls.length) {
                // replace the active controls with the new, inactive controls
                activeControls.replaceWith(inactiveControls);
            } else {
                // else just append the new controls to the label.
                inactiveControls.appendTo(inactiveControls.closest("div.section-container").find("div.section-label"));
            }

            activeControls = inactiveControls;

            page = getPage(ajaxSectionName, handle);

            setControls(handle, page);

            activeControls.find("a.pagination-arrow").click(function() {
                var targetPage = parseInt($(this).attr('data-page-for'));

                uwdoem.ajax_section.registerGetVar(uwdoem.ajax_section.getVar(ajaxSectionName, handle, 'page', targetPage));
                uwdoem.ajax_section.loadSection(ajaxSectionName);

                registerPage(ajaxSectionName, handle, targetPage);

                return false;
            });

            activeControls.find("select.pagination-filter." + handle).change(function() {
                var targetPage = parseInt($("select.pagination-filter." + handle + " option:selected").val());

                uwdoem.ajax_section.registerGetVar(uwdoem.ajax_section.getVar(ajaxSectionName, handle, 'page', targetPage));
                uwdoem.ajax_section.loadSection(ajaxSectionName);

                registerPage(ajaxSectionName, handle, targetPage);
            });
        });
    };

    return {
        setupPaginationFilter: setupPaginationFilter
    };
}());<|endoftext|>


<commit_before>"use strict";

$(function() {
    var $searchField = $("#search-field"),
        $popularTags = $("#popular-tags"),
        showTags,
        hideTags;

    showTags = function() {
        return $popularTags.show();
    };

    hideTags = function() {
        return $popularTags.hide();
    };

    return $searchField.ghostHunter({
        results: "#search-results",
        //rss: "http://biothings.io:9000/tag/mygene-info/rss/",
        zeroResultsInfo: false,
        onKeyUp: true,
        displaySearchInfo: true,
        result_template: "\n
{{title}}
\n
{{pubDate}}
\n",
        onComplete: function(query) {
            if (query.length > 0) {
                return hideTags();
            } else {
                return showTags();
            }

        }
    });
});
<commit_msg>test search rss<commit_after>"use strict";

$(function() {
    var $searchField = $("#search-field"),
        $popularTags = $("#popular-tags"),
        showTags,
        hideTags;

    showTags = function() {
        return $popularTags.show();
    };

    hideTags = function() {
        return $popularTags.hide();
    };

    return $searchField.ghostHunter({
        results: "#search-results",
        rss: "http://mygene.info/rss/",
        zeroResultsInfo: false,
        onKeyUp: true,
        displaySearchInfo: true,
        result_template: "\n
{{title}}
\n
{{pubDate}}
\n",
        onComplete: function(query) {
            if (query.length > 0) {
                return hideTags();
            } else {
                return showTags();
            }

        }
    });
});
<|endoftext|>


<commit_before>import {containerless} from 'aurelia-framework';
import {Parentfield} from './abstract/parentfield';
import {Field} from './abstract/field';

/**
 * Arrayfield is a {@link Parentfield} that has a variable number of the same kind of child.
 */
@containerless
export class Arrayfield extends Parentfield {
  /**
   * The base object that is cloned whenever a new child is added.
   * @type {Field}
   */
  item;
  /**
   * The text that is displayed in the new item -button rather than the label of
   * the child.
   * @type {String}
   */
  newItemText;
  /**
   * The field that is used as the key if {@link #format} is {@linkplain map}
   * @type {String}
   */
  keyField = '_key';
  /**
   * The field that is used as the value if {@link #format} is {@linkplain map}
   * This field is optional. By default, the whole value will be used as-is.
   * @type {String}
   */
  valueField = undefined;
  /**
   * Whether or not to add {@linkplain #<index>} to the end of the labels of
   * children.
   * @type {Boolean}
   */
  addIndexToChildLabel = true;
  /**
   * Whether or not to automatically collapse other fields when uncollapsing a
   * field.
   * @type {Boolean}
   */
  collapseManagement = false;
  /** @inheritdoc */
  _children = [];

  /**
   * @inheritdoc
   * @param {Field}   [args.item]        The base object that is cloned to create
   *                                     new children.
   * @param {String}  [args.newItemText] The text that is displayed in the new
   *                                     item -button rather than the label of
   *                                     the child.
   * @param {String}  [args.keyField]    The field that is used as the key if
   *                                     {@link #format} is {@linkplain map}
   * @param {String}  [args.valueField]  The field that is used as the value if
   *                                     {@link #format} is {@linkplain map}.
   *                                     This field is optional. By default, the
   *                                     whole value will be used as-is.
   * @param {Boolean} [args.collapsed]   Whether or not the UI element should be
   *                                     collapsed.
   */
  init(id = '', args = {}) {
    args = Object.assign({
      format: 'array',
      newItemText: undefined,
      keyField: '_key',
      valueField: undefined,
      addIndexToChildLabel: true,
      collapseManagement: false,
      collapsed: false
    }, args);
    this.item = args.item;
    this.newItemText = args.newItemText;
    this.keyField = args.keyField;
    this.valueField = args.valueField;
    this.addIndexToChildLabel = args.addIndexToChildLabel;
    this.collapseManagement = args.collapseManagement;
    this.collapsed = args.collapsed;
    return super.init(id, args);
  }

  /**
   * Check if this array is empty. If all children are empty, then this field is
   * also considered to be empty.
   */
  isEmpty() {
    for (const child of this._children) {
      if (!child.isEmpty()) {
        // This field is not empty if any of the children is not empty.
        return false;
      }
    }
    return true;
  }

  /**
   * @inheritdoc
   * @return {Object[]|Object} The values of the children of this array in the
   *                           format specified by {@link #format}.
   */
  getValue() {
    let value = undefined;
    if (this.format === 'map') {
      value = {};
      for (const item of this._children) {
        if (!item.showValueInParent || !item.display) {
          continue;
        } else if (item.isEmpty() && item.hideValueIfEmpty) {
          continue;
        }
        const data = item.getValue();
        const key = data[this.keyField];
        if (this.valueField) {
          value[key] = data[this.valueField];
        } else {
          delete data[this.keyField];
          value[key] = data;
        }
      }
    } else if (this.format === 'array') {
      value = [];
      for (const [index, item] of Object.entries(this._children)) {
        if (!item.showValueInParent || !item.display) {
          continue;
        } else if (item.isEmpty() && item.hideValueIfEmpty) {
          continue;
        }
        value[index] = item.getValue();
      }
    }
    return value;
  }

  childCollapseChanged(field, isNowCollapsed) {
    if (!isNowCollapsed && this.collapseManagement) {
      for (const child of this._children) {
        if (child !== field) {
          child.setCollapsed(true);
        }
      }
    }
  }

  /**
   * @inheritdoc
   * @param {Object|Object[]} value The new value in the format specified by
   *                                {@link #format}.
   */
  setValue(value) {
    this._children = [];
    for (const [key, item] of Object.entries(value)) {
      const index = this.addChild();
      if (this.format === 'map') {
        item[this.keyField] = key;
      }
      this._children[index].setValue(item);
    }
  }

  /**
   * Add a new blank child to this array.
   */
  addChild() {
    if (!(this.item instanceof Field)) {
      return;
    }

    const field = this.item.clone(this);
    field.index = this._children.length;
    field.id = `${this.item.id}-${field.index}`;
    if (this.addIndexToChildLabel) {
      field.labelFormat = `${field.labelFormat} #$index`;
    }
    this._children.push(field);
    if (this.collapseManagement) {
      field.setCollapsed(false);
    }
    this.onChange(field);
    return field.index;
  }

  /**
   * Delete the child with the given index from this field.
   *
   * @override
   * @param  {Number} index The index of the child.
   */
  deleteChild(index) {
    if (this._children.length === 0) {
      return;
    }

    this._children.splice(index, 1);
    for (let i = index; i < this._children.length; i++) {
      const item = this._children[i];
      item.index = i;
    }
    this.onChange();
  }

  /** @inheritdoc */
  clone(parent) {
    const clone = new Arrayfield();
    clone.init(this.id, this);
    if (parent) {
      clone.parent = parent;
    }
    if (this.item instanceof Field) {
      clone.item = this.item.clone();
    }
    return clone;
  }

  resolvePath(path) {
    const superResolv = super.resolvePath(path);
    if (superResolv) {
      return superResolv;
    }

    if (path[0] === ':item') {
      return this.item;
    }
    return undefined;
  }
}
<commit_msg>Allow resolving array children by child field value<commit_after>import {containerless} from 'aurelia-framework';
import {Parentfield} from './abstract/parentfield';
import {Field} from './abstract/field';

/**
 * Arrayfield is a {@link Parentfield} that has a variable number of the same kind of child.
 */
@containerless
export class Arrayfield extends Parentfield {
  /**
   * The base object that is cloned whenever a new child is added.
   * @type {Field}
   */
  item;
  /**
   * The text that is displayed in the new item -button rather than the label of
   * the child.
   * @type {String}
   */
  newItemText;
  /**
   * The field that is used as the key if {@link #format} is {@linkplain map}
   * @type {String}
   */
  keyField = '_key';
  /**
   * The field that is used as the value if {@link #format} is {@linkplain map}
   * This field is optional. By default, the whole value will be used as-is.
   * @type {String}
   */
  valueField = undefined;
  /**
   * Whether or not to add {@linkplain #<index>} to the end of the labels of
   * children.
   * @type {Boolean}
   */
  addIndexToChildLabel = true;
  /**
   * Whether or not to automatically collapse other fields when uncollapsing a
   * field.
   * @type {Boolean}
   */
  collapseManagement = false;
  /** @inheritdoc */
  _children = [];

  /**
   * @inheritdoc
   * @param {Field}   [args.item]        The base object that is cloned to create
   *                                     new children.
   * @param {String}  [args.newItemText] The text that is displayed in the new
   *                                     item -button rather than the label of
   *                                     the child.
   * @param {String}  [args.keyField]    The field that is used as the key if
   *                                     {@link #format} is {@linkplain map}
   * @param {String}  [args.valueField]  The field that is used as the value if
   *                                     {@link #format} is {@linkplain map}.
   *                                     This field is optional. By default, the
   *                                     whole value will be used as-is.
   * @param {Boolean} [args.collapsed]   Whether or not the UI element should be
   *                                     collapsed.
   */
  init(id = '', args = {}) {
    args = Object.assign({
      format: 'array',
      newItemText: undefined,
      keyField: '_key',
      valueField: undefined,
      addIndexToChildLabel: true,
      collapseManagement: false,
      collapsed: false
    }, args);
    this.item = args.item;
    this.newItemText = args.newItemText;
    this.keyField = args.keyField;
    this.valueField = args.valueField;
    this.addIndexToChildLabel = args.addIndexToChildLabel;
    this.collapseManagement = args.collapseManagement;
    this.collapsed = args.collapsed;
    return super.init(id, args);
  }

  /**
   * Check if this array is empty. If all children are empty, then this field is
   * also considered to be empty.
   */
  isEmpty() {
    for (const child of this._children) {
      if (!child.isEmpty()) {
        // This field is not empty if any of the children is not empty.
        return false;
      }
    }
    return true;
  }

  /**
   * @inheritdoc
   * @return {Object[]|Object} The values of the children of this array in the
   *                           format specified by {@link #format}.
   */
  getValue() {
    let value = undefined;
    if (this.format === 'map') {
      value = {};
      for (const item of this._children) {
        if (!item.showValueInParent || !item.display) {
          continue;
        } else if (item.isEmpty() && item.hideValueIfEmpty) {
          continue;
        }
        const data = item.getValue();
        const key = data[this.keyField];
        if (this.valueField) {
          value[key] = data[this.valueField];
        } else {
          delete data[this.keyField];
          value[key] = data;
        }
      }
    } else if (this.format === 'array') {
      value = [];
      for (const [index, item] of Object.entries(this._children)) {
        if (!item.showValueInParent || !item.display) {
          continue;
        } else if (item.isEmpty() && item.hideValueIfEmpty) {
          continue;
        }
        value[index] = item.getValue();
      }
    }
    return value;
  }

  childCollapseChanged(field, isNowCollapsed) {
    if (!isNowCollapsed && this.collapseManagement) {
      for (const child of this._children) {
        if (child !== field) {
          child.setCollapsed(true);
        }
      }
    }
  }

  /**
   * @inheritdoc
   * @param {Object|Object[]} value The new value in the format specified by
   *                                {@link #format}.
   */
  setValue(value) {
    this._children = [];
    for (const [key, item] of Object.entries(value)) {
      const index = this.addChild();
      if (this.format === 'map') {
        item[this.keyField] = key;
      }
      this._children[index].setValue(item);
    }
  }

  /**
   * Add a new blank child to this array.
   */
  addChild() {
    if (!(this.item instanceof Field)) {
      return;
    }

    const field = this.item.clone(this);
    field.index = this._children.length;
    field.id = `${this.item.id}-${field.index}`;
    if (this.addIndexToChildLabel) {
      field.labelFormat = `${field.labelFormat} #$index`;
    }
    this._children.push(field);
    if (this.collapseManagement) {
      field.setCollapsed(false);
    }
    this.onChange(field);
    return field.index;
  }

  /**
   * Delete the child with the given index from this field.
   *
   * @override
   * @param  {Number} index The index of the child.
   */
  deleteChild(index) {
    if (this._children.length === 0) {
      return;
    }

    this._children.splice(index, 1);
    for (let i = index; i < this._children.length; i++) {
      const item = this._children[i];
      item.index = i;
    }
    this.onChange();
  }

  /** @inheritdoc */
  clone(parent) {
    const clone = new Arrayfield();
    clone.init(this.id, this);
    if (parent) {
      clone.parent = parent;
    }
    if (this.item instanceof Field) {
      clone.item = this.item.clone();
    }
    return clone;
  }

  resolvePath(path) {
    const superResolv = super.resolvePath(path);
    if (superResolv) {
      return superResolv;
    }

    if (this.format === 'map') {
      // Matches `fieldName(expectedValue)`
      const match = (/([a-zA-Z0-9]+)\((.+?)\)/g).exec(path[0]);
      if (match) {
        const [, fieldName, value] = match;
        for (const child of this._children) {
          if (child.getValue()[fieldName] === value) {
            return child;
          }
        }
      }
    }

    if (path[0] === ':item') {
      return this.item;
    }
    return undefined;
  }
}
<|endoftext|>


<commit_before>/**
 * Module definition and dependencies
 */
angular.module('ngGo.Board.Directive', [
  'ngGo.Board.Service'
])

/**
 * Directive definition
 */
.directive('board', function($window, Board) {

  //Get pixel ratio
  var pixelRatio = window.pixelRatio || 1;

  /**
   * Helper to create a layer canvas
   */
  function createLayerCanvas(name) {

    //Create canvas element and get context
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');

    //Scale context depending on pixel ratio
    if (pixelRatio > 1) {
      context.scale(pixelRatio, pixelRatio);
    }

    //Set class
    canvas.className = name;

    //Set initial canvas width/height based on our own size
    canvas.width = this.clientWidth * pixelRatio;
    canvas.height = this.clientHeight * pixelRatio;

    //Append to element now and return context
    this.appendChild(canvas);
    return context;
  }

  /**
   * Helper to determine draw size
   */
  function determineDrawSize(scope, availableWidth, availableHeight) {

    //Init vars
    var drawWidth, drawHeight, cellSize;

    //Stretch available height to width if zero
    if (availableHeight === 0 && availableWidth > 0) {
      availableHeight = availableWidth;
    }

    //Grid size known?
    if (scope.Board.width && scope.Board.height) {

      //Determine smallest cell size
      cellSize = Math.min(availableWidth / scope.Board.width, availableHeight / scope.Board.height);

      //Set draw size
      drawWidth = Math.floor(cellSize * scope.Board.width);
      drawHeight = Math.floor(cellSize * scope.Board.height);
    }

    //Otherwise, use the lesser of the available width/height
    else {
      drawWidth = drawHeight = Math.min(availableWidth, availableHeight);
    }

    //Broadcast new size if changed
    if (scope.lastDrawWidth !== drawWidth || scope.lastDrawHeight !== drawHeight) {
      scope.lastDrawWidth = drawWidth;
      scope.lastDrawHeight = drawHeight;
      scope.$broadcast('ngGo.board.drawSizeChanged', drawWidth, drawHeight);
      return true;
    }

    //No change
    return false;
  }

  /**
   * Directive
   */
  return {
    restrict: 'E',
    scope: {
      instance: '&'
    },

    /**
     * Linking function
     */
    link: function(scope, element, attrs) {

      //Init vars
      var i, context, layer, playerElement;
      var parent = element.parent();
      var sizingElement = element[0];
      var existingInstance = true;

      //Remember last draw width/height
      scope.lastDrawWidth = 0;
      scope.lastDrawHeight = 0;

      //Get board instance
      scope.Board = scope.instance();

      //Function given?
      if (typeof scope.Board === 'function') {
        scope.Board = scope.Board();
      }

      //Instantiate board if not present in scope
      if (!scope.Board) {
        existingInstance = false;
        scope.Board = new Board();
      }

      //Link element
      scope.Board.linkElement(element);

      //Find player element
      if (parent[0].tagName === 'PLAYER') {
        playerElement = parent;
        sizingElement = parent.parent()[0];
      }

      //Listen for board drawsize events
      scope.$on('ngGo.board.drawSizeChanged', function(event, width, height) {

        //First set the new dimensions on the canvas elements
        var canvas = element.find('canvas');
        for (i = 0; i < canvas.length; i++) {
          canvas[i].width = width * pixelRatio;
          canvas[i].height = height * pixelRatio;
        }

        //Set on the element if we're using a player element and if there is a size
        if (playerElement || attrs.forceSize === 'true') {
          element.css({width: width + 'px', height: height + 'px'});
        }

        //Next set it on the board itself
        scope.Board.setDrawSize(width * pixelRatio, height * pixelRatio);
      });

      //Determine initial draw size
      determineDrawSize(scope, sizingElement.clientWidth, sizingElement.clientHeight);

      //On window resize, determine the draw size again
      angular.element($window).on('resize', function() {
        determineDrawSize(scope, sizingElement.clientWidth, sizingElement.clientHeight);
      });

      //On manual resize, determine draw size again
      scope.$on('ngGo.board.determineDrawSize', function() {
        determineDrawSize(scope, sizingElement.clientWidth, sizingElement.clientHeight);
      });

      //On board grid resize, determine the draw size again
      scope.$on('ngGo.board.resize', function(event, board) {

        //Only relevent if this was our own board
        if (board !== scope.Board) {
          return;
        }

        //If the draw size didn't change, the draw size event won't be triggered.
        //However, that means we should call the resized() method now manually because
        //it won't be called with the setDrawSize() call.
        //This may seem a bit "off", but it's the best way to prevent redundant redraws.
        if (!determineDrawSize(scope, sizingElement.clientWidth, sizingElement.clientHeight)) {
          scope.Board.resized();
        }
      });

      //Static board
      if (attrs.static && attrs.static === 'true') {

        //Add static class and make the board static
        element.addClass('static');
        scope.Board.makeStatic();

        //Create single canvas and link to all relevant layer service classes
        context = createLayerCanvas.call(element[0], 'static');
        for (i = 0; i < scope.Board.layerOrder.length; i++) {
          layer = scope.Board.layerOrder[i];
          scope.Board.layers[layer].setContext(context);
        }
      }

      //Dynamic board
      else {

        //Create individual layer canvasses and link the canvas context to the layer service class
        for (i = 0; i < scope.Board.layerOrder.length; i++) {
          layer = scope.Board.layerOrder[i];
          context = createLayerCanvas.call(element[0], layer);
          scope.Board.layers[layer].setContext(context);
        }
      }

      //Observe the board size attribute
      attrs.$observe('size', function(size) {
        if (typeof size === 'string' && size.toLowerCase().indexOf('x') !== -1) {
          size = size.split('x');
          scope.Board.setSize(size[0], size[1]);
        }
        else {
          scope.Board.setSize(size, size);
        }
      });

      //Observe the coordinates attribute
      attrs.$observe('coordinates', function(attr) {
        scope.Board.toggleCoordinates(attr === 'true');
      });

      //Observe the cutoff attribute
      attrs.$observe('cutoff', function(attr) {
        if (angular.isDefined(attr)) {
          scope.Board.setCutoff(attr.split(','));
        }
      });

      //Observe color multiplier
      attrs.$observe('colorMultiplier', function(attr) {
        if (angular.isDefined(attr)) {
          scope.Board.swapColors(attr);
        }
      });

      //Link board to player if present in parent scope
      if (scope.$parent.Player) {
        scope.$parent.Player.setBoard(scope.Board);
      }

      //Redraw board if we had an existing instance (it might contain data)
      if (existingInstance) {
        scope.Board.redraw();
      }
    }
  };
});
<commit_msg>modify for retina display<commit_after>/**
 * Module definition and dependencies
 */
angular.module('ngGo.Board.Directive', [
  'ngGo.Board.Service'
])

/**
 * Directive definition
 */
.directive('board', function($window, Board) {

  //Get pixel ratio
  var pixelRatio = window.devicePixelRatio || 1;

  /**
   * Helper to create a layer canvas
   */
  function createLayerCanvas(name) {

    //Create canvas element and get context
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');

    //Scale context depending on pixel ratio
    if (pixelRatio > 1) {
      context.scale(pixelRatio, pixelRatio);
    }

    //Set class
    canvas.className = name;

    //Set initial canvas width/height based on our own size
    canvas.width = this.clientWidth * pixelRatio;
    canvas.height = this.clientHeight * pixelRatio;

    //Append to element now and return context
    this.appendChild(canvas);
    return context;
  }

  /**
   * Helper to determine draw size
   */
  function determineDrawSize(scope, availableWidth, availableHeight) {

    //Init vars
    var drawWidth, drawHeight, cellSize;

    //Stretch available height to width if zero
    if (availableHeight === 0 && availableWidth > 0) {
      availableHeight = availableWidth;
    }

    //Grid size known?
    if (scope.Board.width && scope.Board.height) {

      //Determine smallest cell size
      cellSize = Math.min(availableWidth / scope.Board.width, availableHeight / scope.Board.height);

      //Set draw size
      drawWidth = Math.floor(cellSize * scope.Board.width);
      drawHeight = Math.floor(cellSize * scope.Board.height);
    }

    //Otherwise, use the lesser of the available width/height
    else {
      drawWidth = drawHeight = Math.min(availableWidth, availableHeight);
    }

    //Broadcast new size if changed
    if (scope.lastDrawWidth !== drawWidth || scope.lastDrawHeight !== drawHeight) {
      scope.lastDrawWidth = drawWidth;
      scope.lastDrawHeight = drawHeight;
      scope.$broadcast('ngGo.board.drawSizeChanged', drawWidth, drawHeight);
      return true;
    }

    //No change
    return false;
  }

  /**
   * Directive
   */
  return {
    restrict: 'E',
    scope: {
      instance: '&'
    },

    /**
     * Linking function
     */
    link: function(scope, element, attrs) {

      //Init vars
      var i, context, layer, playerElement;
      var parent = element.parent();
      var sizingElement = element[0];
      var existingInstance = true;

      //Remember last draw width/height
      scope.lastDrawWidth = 0;
      scope.lastDrawHeight = 0;

      //Get board instance
      scope.Board = scope.instance();

      //Function given?
      if (typeof scope.Board === 'function') {
        scope.Board = scope.Board();
      }

      //Instantiate board if not present in scope
      if (!scope.Board) {
        existingInstance = false;
        scope.Board = new Board();
      }

      //Link element
      scope.Board.linkElement(element);

      //Find player element
      if (parent[0].tagName === 'PLAYER') {
        playerElement = parent;
        sizingElement = parent.parent()[0];
      }

      //Listen for board drawsize events
      scope.$on('ngGo.board.drawSizeChanged', function(event, width, height) {

        //First set the new dimensions on the canvas elements
        var canvas = element.find('canvas');
        for (i = 0; i < canvas.length; i++) {
          canvas[i].width = width * pixelRatio;
          canvas[i].height = height * pixelRatio;
        }

        //Set on the element if we're using a player element and if there is a size
        if (playerElement || attrs.forceSize === 'true') {
          element.css({width: width + 'px', height: height + 'px'});
        }

        //Next set it on the board itself
        scope.Board.setDrawSize(width * pixelRatio, height * pixelRatio);
      });

      //Determine initial draw size
      determineDrawSize(scope, sizingElement.clientWidth, sizingElement.clientHeight);

      //On window resize, determine the draw size again
      angular.element($window).on('resize', function() {
        determineDrawSize(scope, sizingElement.clientWidth, sizingElement.clientHeight);
      });

      //On manual resize, determine draw size again
      scope.$on('ngGo.board.determineDrawSize', function() {
        determineDrawSize(scope, sizingElement.clientWidth, sizingElement.clientHeight);
      });

      //On board grid resize, determine the draw size again
      scope.$on('ngGo.board.resize', function(event, board) {

        //Only relevent if this was our own board
        if (board !== scope.Board) {
          return;
        }

        //If the draw size didn't change, the draw size event won't be triggered.
        //However, that means we should call the resized() method now manually because
        //it won't be called with the setDrawSize() call.
        //This may seem a bit "off", but it's the best way to prevent redundant redraws.
        if (!determineDrawSize(scope, sizingElement.clientWidth, sizingElement.clientHeight)) {
          scope.Board.resized();
        }
      });

      //Static board
      if (attrs.static && attrs.static === 'true') {

        //Add static class and make the board static
        element.addClass('static');
        scope.Board.makeStatic();

        //Create single canvas and link to all relevant layer service classes
        context = createLayerCanvas.call(element[0], 'static');
        for (i = 0; i < scope.Board.layerOrder.length; i++) {
          layer = scope.Board.layerOrder[i];
          scope.Board.layers[layer].setContext(context);
        }
      }

      //Dynamic board
      else {

        //Create individual layer canvasses and link the canvas context to the layer service class
        for (i = 0; i < scope.Board.layerOrder.length; i++) {
          layer = scope.Board.layerOrder[i];
          context = createLayerCanvas.call(element[0], layer);
          scope.Board.layers[layer].setContext(context);
        }
      }

      //Observe the board size attribute
      attrs.$observe('size', function(size) {
        if (typeof size === 'string' && size.toLowerCase().indexOf('x') !== -1) {
          size = size.split('x');
          scope.Board.setSize(size[0], size[1]);
        }
        else {
          scope.Board.setSize(size, size);
        }
      });

      //Observe the coordinates attribute
      attrs.$observe('coordinates', function(attr) {
        scope.Board.toggleCoordinates(attr === 'true');
      });

      //Observe the cutoff attribute
      attrs.$observe('cutoff', function(attr) {
        if (angular.isDefined(attr)) {
          scope.Board.setCutoff(attr.split(','));
        }
      });

      //Observe color multiplier
      attrs.$observe('colorMultiplier', function(attr) {
        if (angular.isDefined(attr)) {
          scope.Board.swapColors(attr);
        }
      });

      //Link board to player if present in parent scope
      if (scope.$parent.Player) {
        scope.$parent.Player.setBoard(scope.Board);
      }

      //Redraw board if we had an existing instance (it might contain data)
      if (existingInstance) {
        scope.Board.redraw();
      }
    }
  };
});
<|endoftext|>


<commit_before>#ifndef __browser_html_DomWindow__
#define __browser_html_DomWindow__

#include "DomElement.js"

////////////////////////////////////////////////////////////////////////////////
// DomWindow

// Let Window point to DomWindow for now, so new Window(...) can be called.
// This makese for nicer code, but might have to change in the future.
Window = DomWindow = DomElement.extend({
	_BEANS
	_type: 'window',
	// Don't automatically call this.base in overridden initialize methods
	_initialize: false,
	_methods: ['close', 'alert', 'prompt', 'confirm', 'blur', 'focus', 'reload'],

	getDocument: function() {
		return DomElement.wrap(this.$.document);
	},

	getWindow: function() {
		return this;
	},

	// TODO: add get/setStatus, get/setLocation, and find way to deal with
	// referencing of native fields at the end of initialize.

	/**
	 * A constructor for DomWindow that is based on window.open and extends it
	 * to allow more options in the third parameter.
	 *
	 * If param is a string, the standard window.open is executed.
	 * If param is an object, additional parameters maybe be defined, such as
	 * param.confirm, param.focus, etc. Also, if param.width & height are
	 * defined, The window is centered on screen.
	 */
	initialize: function(param) {
		var win;
		// Are we wrapping a window?
		if (param.location && param.frames && param.history) {
			// Do not return yet as we need to add some properties further down
			win = this.base(param);
		} else {
			// If param a string, convert to param object, using its value for url.
			if (typeof param == 'string')
				param = { url: param };
			// Convert boolean values to 0 / 1:
			(['toolbar','menubar','location','status','resizable','scrollbars']).each(function(key) {
				param[key] = param[key] ? 1 : 0;
			});
			// Center window if left / top is not defined, but dimensions are:
			if (param.width && param.height) {
				if (param.left == null) param.left = Math.round(
					Math.max(0, (screen.width - param.width) / 2));
				if (param.top == null) param.top = Math.round(
					Math.max(0, (screen.height - param.height) / 2 - 40));
			}
			// Now convert paramets to string.
			var str = Base.each(param, function(val, key) {
				// Filter out non-standard param names and convert boolean values to 0 / 1 simply by adding 0 to it
				if (!/^(focus|confirm|url|name)$/.test(key))
					this.push(key + '=' + (val + 0));
			}, []).join();
			win = this.base(window.open(param.url, param.name.replace(/\s+|\.+|-+/gi, ''), str));
			if (win && param.focus)
				win.focus();
		}
		// Copy over default windows properties before returning
		return ['location', 'frames', 'history'].each(function(key) {
			this[key] = this.$[key];
		}, win);
	}
});

#endif // __browser_html_DomWindow__<commit_msg>The previous change broke this code, the new way of calling base in initialize and relying on a value is to use var obj = this.base() || this.<commit_after>#ifndef __browser_html_DomWindow__
#define __browser_html_DomWindow__

#include "DomElement.js"

////////////////////////////////////////////////////////////////////////////////
// DomWindow

// Let Window point to DomWindow for now, so new Window(...) can be called.
// This makese for nicer code, but might have to change in the future.
Window = DomWindow = DomElement.extend({
	_BEANS
	_type: 'window',
	// Don't automatically call this.base in overridden initialize methods
	_initialize: false,
	_methods: ['close', 'alert', 'prompt', 'confirm', 'blur', 'focus', 'reload'],

	getDocument: function() {
		return DomElement.wrap(this.$.document);
	},

	getWindow: function() {
		return this;
	},

	// TODO: add get/setStatus, get/setLocation, and find way to deal with
	// referencing of native fields at the end of initialize.

	/**
	 * A constructor for DomWindow that is based on window.open and extends it
	 * to allow more options in the third parameter.
	 *
	 * If param is a string, the standard window.open is executed.
	 * If param is an object, additional parameters maybe be defined, such as
	 * param.confirm, param.focus, etc. Also, if param.width & height are
	 * defined, The window is centered on screen.
	 */
	initialize: function(param) {
		var win;
		// Are we wrapping a window?
		if (param.location && param.frames && param.history) {
			// Do not return yet as we need to add some properties further down
			win = this.base(param) || this;
		} else {
			// If param a string, convert to param object, using its value for url.
			if (typeof param == 'string')
				param = { url: param };
			// Convert boolean values to 0 / 1:
			(['toolbar','menubar','location','status','resizable','scrollbars']).each(function(key) {
				param[key] = param[key] ? 1 : 0;
			});
			// Center window if left / top is not defined, but dimensions are:
			if (param.width && param.height) {
				if (param.left == null) param.left = Math.round(
					Math.max(0, (screen.width - param.width) / 2));
				if (param.top == null) param.top = Math.round(
					Math.max(0, (screen.height - param.height) / 2 - 40));
			}
			// Now convert paramets to string.
			var str = Base.each(param, function(val, key) {
				// Filter out non-standard param names and convert boolean values to 0 / 1 simply by adding 0 to it
				if (!/^(focus|confirm|url|name)$/.test(key))
					this.push(key + '=' + (val + 0));
			}, []).join();
			win = this.base(window.open(param.url, param.name.replace(/\s+|\.+|-+/gi, ''), str)) || this;
			if (win && param.focus)
				win.focus();
		}
		// Copy over default windows properties before returning
		return ['location', 'frames', 'history'].each(function(key) {
			this[key] = this.$[key];
		}, win);
	}
});

#endif // __browser_html_DomWindow__<|endoftext|>


<commit_before>// External
import isFinite from '../../../node_modules/lodash-es/isFinite';

// Internal
import { collectInclClones } from './utils';

export function up (node, callback, depth, includeClones, child) {
  const nodesInclClones = includeClones ? collectInclClones(node) : [node];

  for (let i = nodesInclClones.length; i--;) {
    if (child) {
      callback(nodesInclClones[i], child);
    }

    if (!isFinite(depth) || depth > 0) {
      const parentsId = Object.keys(nodesInclClones[i].parents);
      for (let j = parentsId.length; j--;) {
        up(
          nodesInclClones[i].parents[parentsId[j]],
          callback,
          depth - 1,
          includeClones,
          nodesInclClones[i]
        );
      }
    }
  }
}

export function down (node, callback, depth, includeClones) {
  const nodesInclClones = includeClones ? collectInclClones(node) : [node];

  for (let i = nodesInclClones.length; i--;) {
    callback(nodesInclClones[i]);

    if (!isFinite(depth) || depth > 0) {
      for (let j = nodesInclClones[i].childRefs.length; j--;) {
        down(
          nodesInclClones[i].childRefs[j], callback, depth - 1, includeClones
        );
      }
    }
  }
}

export function upAndDown (
  node, callbackUp, callbackDown, depth, includeClones
) {
  if (callbackDown) {
    up(node, callbackUp, depth, includeClones);
    down(node, callbackDown, depth, includeClones);
  } else {
    up(node, callbackUp, depth, includeClones);
    down(node, callbackUp, depth, includeClones);
  }
}

export function siblings (node, callback) {
  const parentsId = Object.keys(node.parents);
  for (let i = parentsId.length; i--;) {
    for (let j = node.parents[parentsId[i]].childRefs.length; j--;) {
      callback(node.parents[parentsId[i]].childRefs[j]);
    }
  }
  // The root node doesn't have a `parents` property but might have `siblings`.
  if (node.siblings) {
    const siblingsId = Object.keys(node.siblings);
    for (let i = siblingsId.length; i--;) {
      callback(node.siblings[siblingsId[i]]);
    }
  }
}
<commit_msg>Rename to make semantics more clear.<commit_after>// External
import isFinite from '../../../node_modules/lodash-es/isFinite';

// Internal
import { collectInclClones } from './utils';

export function up (node, callback, depth, includeClones, child) {
  const nodes = includeClones ? collectInclClones(node) : [node];

  for (let i = nodes.length; i--;) {
    if (child) {
      callback(nodes[i], child);
    }

    if (!isFinite(depth) || depth > 0) {
      const parentsId = Object.keys(nodes[i].parents);
      for (let j = parentsId.length; j--;) {
        up(
          nodes[i].parents[parentsId[j]],
          callback,
          depth - 1,
          includeClones,
          nodes[i]
        );
      }
    }
  }
}

export function down (node, callback, depth, includeClones) {
  const nodes = includeClones ? collectInclClones(node) : [node];

  for (let i = nodes.length; i--;) {
    callback(nodes[i]);

    if (!isFinite(depth) || depth > 0) {
      for (let j = nodes[i].childRefs.length; j--;) {
        down(
          nodes[i].childRefs[j], callback, depth - 1, includeClones
        );
      }
    }
  }
}

export function upAndDown (
  node, callbackUp, callbackDown, depth, includeClones
) {
  if (callbackDown) {
    up(node, callbackUp, depth, includeClones);
    down(node, callbackDown, depth, includeClones);
  } else {
    up(node, callbackUp, depth, includeClones);
    down(node, callbackUp, depth, includeClones);
  }
}

export function siblings (node, callback) {
  const parentsId = Object.keys(node.parents);
  for (let i = parentsId.length; i--;) {
    for (let j = node.parents[parentsId[i]].childRefs.length; j--;) {
      callback(node.parents[parentsId[i]].childRefs[j]);
    }
  }
  // The root node doesn't have a `parents` property but might have `siblings`.
  if (node.siblings) {
    const siblingsId = Object.keys(node.siblings);
    for (let i = siblingsId.length; i--;) {
      callback(node.siblings[siblingsId[i]]);
    }
  }
}
<|endoftext|>