<commit_before>export function app(props, container) {
  var lock
  var root = (container = container || document.body).children[0]
  var node = vnode(root, [].map)
  var lifecycle = []
  var appState = props.state || {}
  var appActions = {}

  repaint(init(appState, appActions, props.actions, []))

  return appActions

  function vnode(element, map) {
    return (
      element &&
      h(
        element.tagName.toLowerCase(),
        {},
        map.call(element.childNodes, function(element) {
          return element.nodeType === 3
            ? element.nodeValue
            : vnode(element, map)
        })
      )
    )
  }

  function set(to, from) {
    for (var i in from) {
      to[i] = from[i]
    }
    return to
  }

  function merge(to, from) {
    return set(set({}, to), from)
  }

  function setDeep(path, value, from) {
    var to = {}
    return 0 === path.length
      ? value
      : ((to[path[0]] =
          1 < path.length
            ? setDeep(path.slice(1), value, from[path[0]])
            : value),
        merge(from, to))
  }

  function get(path, from) {
    for (var i = 0; i < path.length; i++) {
      from = from[path[i]]
    }
    return from
  }

  function isFunction(any) {
    return "function" === typeof any
  }

  function init(state, actions, from, path) {
    for (var key in from) {
      isFunction(from[key])
        ? (function(key, action) {
            actions[key] = function(data) {
              state = get(path, appState)

              if (
                isFunction((data = action(data))) &&
                isFunction((data = data(state)))
              ) {
                data = data(actions)
              }

              if (data && data !== state && !data.then) {
                repaint(
                  (appState = setDeep(path, merge(state, data), appState))
                )
              }

              return data
            }
          })(key, from[key])
        : init(
            state[key] || (state[key] = {}),
            (actions[key] = {}),
            from[key],
            path.concat(key)
          )
    }
  }

  function getKey(node) {
    if (node && node.props) {
      return node.props.key
    }
  }

  function setElementProp(element, name, value, oldValue) {
    if (name === "key") {
    } else if (name === "style") {
      for (var i in merge(oldValue, (value = value || {}))) {
        element.style[i] = null == value[i] ? "" : value[i]
      }
    } else {
      try {
        element[name] = null == value ? "" : value
      } catch (_) {}

      if (!isFunction(value)) {
        if (null == value || false === value) {
          element.removeAttribute(name)
        } else {
          element.setAttribute(name, value)
        }
      }
    }
  }

  function createElement(node, isSVG) {
    if (typeof node === "string") {
      var element = document.createTextNode(node)
    } else {
      var element = (isSVG = isSVG || node.type === "svg")
        ? document.createElementNS("http://www.w3.org/2000/svg", node.type)
        : document.createElement(node.type)

      if (node.props.oncreate) {
        lifecycle.push(function() {
          node.props.oncreate(element)
        })
      }

      for (var i = 0; i < node.children.length; i++) {
        element.appendChild(createElement(node.children[i], isSVG))
      }

      for (var i in node.props) {
        setElementProp(element, i, node.props[i])
      }
    }
    return element
  }

  function updateElement(element, oldProps, props) {
    for (var i in merge(oldProps, props)) {
      var value = props[i]
      var oldValue = i === "value" || i === "checked" ? element[i] : oldProps[i]

      if (value !== oldValue) {
        setElementProp(element, i, value, oldValue)
      }
    }

    if (props.onupdate) {
      lifecycle.push(function() {
        props.onupdate(element, oldProps)
      })
    }
  }

  function removeElement(parent, element, props) {
    function done() {
      parent.removeChild(element)
    }

    if (props && props.onremove) {
      props.onremove(element, done)
    } else {
      done()
    }
  }

  function patch(parent, element, oldNode, node, isSVG, nextSibling) {
    if (oldNode === node) {
    } else if (null == oldNode) {
      element = parent.insertBefore(createElement(node, isSVG), element)
    } else if (node.type != null && node.type === oldNode.type) {
      updateElement(element, oldNode.props, node.props)

      isSVG = isSVG || node.type === "svg"

      var len = node.children.length
      var oldLen = oldNode.children.length
      var oldKeyed = {}
      var oldElements = []
      var keyed = {}

      for (var i = 0; i < oldLen; i++) {
        var oldElement = (oldElements[i] = element.childNodes[i])
        var oldChild = oldNode.children[i]
        var oldKey = getKey(oldChild)

        if (null != oldKey) {
          oldKeyed[oldKey] = [oldElement, oldChild]
        }
      }

      var i = 0
      var j = 0

      while (j < len) {
        var oldElement = oldElements[i]
        var oldChild = oldNode.children[i]
        var newChild = node.children[j]

        var oldKey = getKey(oldChild)
        if (keyed[oldKey]) {
          i++
          continue
        }

        var newKey = getKey(newChild)
        var keyedNode = oldKeyed[newKey] || []

        if (null == newKey) {
          if (null == oldKey) {
            patch(element, oldElement, oldChild, newChild, isSVG)
            j++
          }
          i++
        } else {
          if (oldKey === newKey) {
            patch(element, keyedNode[0], keyedNode[1], newChild, isSVG)
            i++
          } else if (keyedNode[0]) {
            element.insertBefore(keyedNode[0], oldElement)
            patch(element, keyedNode[0], keyedNode[1], newChild, isSVG)
          } else {
            patch(element, oldElement, null, newChild, isSVG)
          }

          j++
          keyed[newKey] = newChild
        }
      }

      while (i < oldLen) {
        var oldChild = oldNode.children[i]
        var oldKey = getKey(oldChild)
        if (null == oldKey) {
          removeElement(element, oldElements[i], oldChild.props)
        }
        i++
      }

      for (var i in oldKeyed) {
        var keyedNode = oldKeyed[i]
        var reusableNode = keyedNode[1]
        if (!keyed[reusableNode.props.key]) {
          removeElement(element, keyedNode[0], reusableNode.props)
        }
      }
    } else if (element && node !== element.nodeValue) {
      if (typeof node === "string" && typeof oldNode === "string") {
        element.nodeValue = node
      } else {
        element = parent.insertBefore(
          createElement(node, isSVG),
          (nextSibling = element)
        )
        removeElement(parent, nextSibling, oldNode.props)
      }
    }

    return element
  }

  function render(next) {
    lock = !lock

    if (isFunction((next = props.view(appState)))) {
      next = next(appActions)
    }

    if (!lock) {
      root = patch(container, root, node, (node = next))
    }

    while ((next = lifecycle.pop())) next()
  }

  function repaint() {
    if (props.view && !lock) {
      setTimeout(render, (lock = !lock))
    }
  }
}

export function h(type, props) {
  var node
  var stack = []
  var children = []

  for (var i = arguments.length; i-- > 2; ) {
    stack.push(arguments[i])
  }

  while (stack.length) {
    if (Array.isArray((node = stack.pop()))) {
      for (i = node.length; i--; ) {
        stack.push(node[i])
      }
    } else if (null == node || node === true || node === false) {
    } else {
      children.push(typeof node === "number" ? (node = node + "") : node)
    }
  }

  return typeof type === "string"
    ? {
        type: type,
        props: props || {},
        children: children
      }
    : type(props || {}, children)
}
<commit_msg>Declare h before app.<commit_after>export function h(type, props) {
  var node
  var stack = []
  var children = []

  for (var i = arguments.length; i-- > 2; ) {
    stack.push(arguments[i])
  }

  while (stack.length) {
    if (Array.isArray((node = stack.pop()))) {
      for (i = node.length; i--; ) {
        stack.push(node[i])
      }
    } else if (null == node || node === true || node === false) {
    } else {
      children.push(typeof node === "number" ? (node = node + "") : node)
    }
  }

  return typeof type === "string"
    ? {
        type: type,
        props: props || {},
        children: children
      }
    : type(props || {}, children)
}

export function app(props, container) {
  var lock
  var root = (container = container || document.body).children[0]
  var node = vnode(root, [].map)
  var lifecycle = []
  var appState = props.state || {}
  var appActions = {}

  repaint(init(appState, appActions, props.actions, []))

  return appActions

  function vnode(element, map) {
    return (
      element &&
      h(
        element.tagName.toLowerCase(),
        {},
        map.call(element.childNodes, function(element) {
          return element.nodeType === 3
            ? element.nodeValue
            : vnode(element, map)
        })
      )
    )
  }

  function set(to, from) {
    for (var i in from) {
      to[i] = from[i]
    }
    return to
  }

  function merge(to, from) {
    return set(set({}, to), from)
  }

  function setDeep(path, value, from) {
    var to = {}
    return 0 === path.length
      ? value
      : ((to[path[0]] =
          1 < path.length
            ? setDeep(path.slice(1), value, from[path[0]])
            : value),
        merge(from, to))
  }

  function get(path, from) {
    for (var i = 0; i < path.length; i++) {
      from = from[path[i]]
    }
    return from
  }

  function isFunction(any) {
    return "function" === typeof any
  }

  function init(state, actions, from, path) {
    for (var key in from) {
      isFunction(from[key])
        ? (function(key, action) {
            actions[key] = function(data) {
              state = get(path, appState)

              if (
                isFunction((data = action(data))) &&
                isFunction((data = data(state)))
              ) {
                data = data(actions)
              }

              if (data && data !== state && !data.then) {
                repaint(
                  (appState = setDeep(path, merge(state, data), appState))
                )
              }

              return data
            }
          })(key, from[key])
        : init(
            state[key] || (state[key] = {}),
            (actions[key] = {}),
            from[key],
            path.concat(key)
          )
    }
  }

  function getKey(node) {
    if (node && node.props) {
      return node.props.key
    }
  }

  function setElementProp(element, name, value, oldValue) {
    if (name === "key") {
    } else if (name === "style") {
      for (var i in merge(oldValue, (value = value || {}))) {
        element.style[i] = null == value[i] ? "" : value[i]
      }
    } else {
      try {
        element[name] = null == value ? "" : value
      } catch (_) {}

      if (!isFunction(value)) {
        if (null == value || false === value) {
          element.removeAttribute(name)
        } else {
          element.setAttribute(name, value)
        }
      }
    }
  }

  function createElement(node, isSVG) {
    if (typeof node === "string") {
      var element = document.createTextNode(node)
    } else {
      var element = (isSVG = isSVG || node.type === "svg")
        ? document.createElementNS("http://www.w3.org/2000/svg", node.type)
        : document.createElement(node.type)

      if (node.props.oncreate) {
        lifecycle.push(function() {
          node.props.oncreate(element)
        })
      }

      for (var i = 0; i < node.children.length; i++) {
        element.appendChild(createElement(node.children[i], isSVG))
      }

      for (var i in node.props) {
        setElementProp(element, i, node.props[i])
      }
    }
    return element
  }

  function updateElement(element, oldProps, props) {
    for (var i in merge(oldProps, props)) {
      var value = props[i]
      var oldValue = i === "value" || i === "checked" ? element[i] : oldProps[i]

      if (value !== oldValue) {
        setElementProp(element, i, value, oldValue)
      }
    }

    if (props.onupdate) {
      lifecycle.push(function() {
        props.onupdate(element, oldProps)
      })
    }
  }

  function removeElement(parent, element, props) {
    function done() {
      parent.removeChild(element)
    }

    if (props && props.onremove) {
      props.onremove(element, done)
    } else {
      done()
    }
  }

  function patch(parent, element, oldNode, node, isSVG, nextSibling) {
    if (oldNode === node) {
    } else if (null == oldNode) {
      element = parent.insertBefore(createElement(node, isSVG), element)
    } else if (node.type != null && node.type === oldNode.type) {
      updateElement(element, oldNode.props, node.props)

      isSVG = isSVG || node.type === "svg"

      var len = node.children.length
      var oldLen = oldNode.children.length
      var oldKeyed = {}
      var oldElements = []
      var keyed = {}

      for (var i = 0; i < oldLen; i++) {
        var oldElement = (oldElements[i] = element.childNodes[i])
        var oldChild = oldNode.children[i]
        var oldKey = getKey(oldChild)

        if (null != oldKey) {
          oldKeyed[oldKey] = [oldElement, oldChild]
        }
      }

      var i = 0
      var j = 0

      while (j < len) {
        var oldElement = oldElements[i]
        var oldChild = oldNode.children[i]
        var newChild = node.children[j]

        var oldKey = getKey(oldChild)
        if (keyed[oldKey]) {
          i++
          continue
        }

        var newKey = getKey(newChild)
        var keyedNode = oldKeyed[newKey] || []

        if (null == newKey) {
          if (null == oldKey) {
            patch(element, oldElement, oldChild, newChild, isSVG)
            j++
          }
          i++
        } else {
          if (oldKey === newKey) {
            patch(element, keyedNode[0], keyedNode[1], newChild, isSVG)
            i++
          } else if (keyedNode[0]) {
            element.insertBefore(keyedNode[0], oldElement)
            patch(element, keyedNode[0], keyedNode[1], newChild, isSVG)
          } else {
            patch(element, oldElement, null, newChild, isSVG)
          }

          j++
          keyed[newKey] = newChild
        }
      }

      while (i < oldLen) {
        var oldChild = oldNode.children[i]
        var oldKey = getKey(oldChild)
        if (null == oldKey) {
          removeElement(element, oldElements[i], oldChild.props)
        }
        i++
      }

      for (var i in oldKeyed) {
        var keyedNode = oldKeyed[i]
        var reusableNode = keyedNode[1]
        if (!keyed[reusableNode.props.key]) {
          removeElement(element, keyedNode[0], reusableNode.props)
        }
      }
    } else if (element && node !== element.nodeValue) {
      if (typeof node === "string" && typeof oldNode === "string") {
        element.nodeValue = node
      } else {
        element = parent.insertBefore(
          createElement(node, isSVG),
          (nextSibling = element)
        )
        removeElement(parent, nextSibling, oldNode.props)
      }
    }

    return element
  }

  function render(next) {
    lock = !lock

    if (isFunction((next = props.view(appState)))) {
      next = next(appActions)
    }

    if (!lock) {
      root = patch(container, root, node, (node = next))
    }

    while ((next = lifecycle.pop())) next()
  }

  function repaint() {
    if (props.view && !lock) {
      setTimeout(render, (lock = !lock))
    }
  }
}
<|endoftext|>


<commit_before>var _ = require('lodash');

module.exports = {

    /** @param {Creep} builder **/
    run: function (builder) {

        builder.pickupEnergyInRange();

        if (builder.memory.building && builder.carry.energy === 0) {
            builder.memory.building = false;
        } else if (!builder.memory.building && builder.carry.energy === builder.carryCapacity) {
            builder.memory.building = true;
        }

        if (builder.memory.building) {
            if (builder.room.controller.ticksToDowngrade < 1000) {
                // Controller about to downgrade; this takes priority
                this.upgradeController(builder);
            }

            // Building mode on; build something or upgrade the controller

            var site = Game.getObjectById(builder.memory.constructionSiteId);
            if (!site) {
                // No construction site in memory; find the closest started one,
                // or if none are started, just the closest one
                site = builder.pos.findClosestByRange(FIND_MY_CONSTRUCTION_SITES, {
                            filter: site => site.progress > 0
                        }) || builder.pos.findClosestByRange(FIND_MY_CONSTRUCTION_SITES);
                builder.memory.constructionSiteId = site ? site.id : null;
            }

            if (site) {
                if (!builder.pos.inRangeTo(site, 3)) {
                    builder.moveTo(site);
                } else {
                    builder.build(site);
                }

                return;
            }

            var repairTarget = this.findRepairTarget(builder);
            if (repairTarget) {
                if (!builder.pos.inRangeTo(repairTarget, 3)) {
                    builder.moveTo(repairTarget);
                } else {
                    builder.repair(repairTarget);
                }
            } else {
                this.upgradeController(builder);
            }
        } else {
            // Energy pickup mode

            // TODO: The pickup target ID should probably be cached
            var energyDeficit = builder.carryCapacity - _.sum(builder.carry);
            var pickupTarget = builder.pos.findClosestByRange(FIND_MY_STRUCTURES, {
                filter: structure => {
                    return ((structure.structureType === STRUCTURE_EXTENSION ||
                            structure.structureType === STRUCTURE_SPAWN) &&
                            (structure.energy >= energyDeficit ||
                            structure.energy === structure.energyCapacity)) ||
                            ((structure.structureType === STRUCTURE_STORAGE ||
                            structure.structureType === STRUCTURE_CONTAINER) &&
                            (structure.store.energy >= energyDeficit ||
                            _.sum(structure.store) === structure.storeCapacity));
                }
            });

            if (pickupTarget) {
                if (!builder.pos.isNearTo(pickupTarget)) {
                    builder.moveTo(pickupTarget);
                } else {
                    builder.requestEnergyFrom(pickupTarget);
                }
            }
        }

        builder.pickupEnergyInRange();
    },

    findRepairTarget: function (builder) {
        var closestWeakOwnedStructure = builder.pos.findClosestByRange(FIND_MY_STRUCTURES, {
            filter: structure => structure.hits / structure.hitsMax < 0.5
        });
        if (closestWeakOwnedStructure) {
            return closestWeakOwnedStructure;
        }

        // TODO: Make wall hit point threshold dynamic
        var closestWeakNeutralStructure = builder.pos.findClosestByRange(FIND_STRUCTURES, {
            filter: structure => {
                return (_.includes([STRUCTURE_ROAD, STRUCTURE_CONTAINER], structure.structureType) &&
                        structure.hits / structure.hitsMax < 0.5) ||
                        (structure.structureType === STRUCTURE_WALL && structure.hits < 100000)
            }
        });
        if (closestWeakNeutralStructure) {
            return closestWeakNeutralStructure;
        }

        return null;
    },

    upgradeController: function (builder) {
        var controller = builder.room.controller;
        if (!builder.pos.inRangeTo(controller, 3)) {
            builder.moveTo(controller);
        } else {
            builder.upgradeController(controller);
        }
    },

    getBody: function (energy) {
        if (energy < BODYPART_COST[MOVE] + BODYPART_COST[CARRY] + BODYPART_COST[WORK]) {
            return null;
        }

        var move = [], carry = [], work = [];
        var cheapestPart = _.min([BODYPART_COST[MOVE], BODYPART_COST[CARRY], BODYPART_COST[WORK]]);
        while (energy >= cheapestPart) {
            if (energy >= BODYPART_COST[WORK] && (!work.length || work.length < 2 * carry.length)) {
                energy = this.addPart(energy, work, WORK);
            } else if (energy >= BODYPART_COST[MOVE] && (!move.length || move.length <= work.length)) {
                energy = this.addPart(energy, move, MOVE);
            } else if (energy >= BODYPART_COST[CARRY]) {
                energy = this.addPart(energy, carry, CARRY);
            } else {
                break;
            }
        }

        return work.concat(carry).concat(move);
    },

    addPart: function (energy, parts, part) {
        parts.push(part);
        return energy - BODYPART_COST[part];
    }
};
<commit_msg>Increased the hit point threshold walls are repaired to from 100.000 to 1.000.000<commit_after>var _ = require('lodash');

module.exports = {

    /** @param {Creep} builder **/
    run: function (builder) {

        builder.pickupEnergyInRange();

        if (builder.memory.building && builder.carry.energy === 0) {
            builder.memory.building = false;
        } else if (!builder.memory.building && builder.carry.energy === builder.carryCapacity) {
            builder.memory.building = true;
        }

        if (builder.memory.building) {
            if (builder.room.controller.ticksToDowngrade < 1000) {
                // Controller about to downgrade; this takes priority
                this.upgradeController(builder);
            }

            // Building mode on; build something or upgrade the controller

            var site = Game.getObjectById(builder.memory.constructionSiteId);
            if (!site) {
                // No construction site in memory; find the closest started one,
                // or if none are started, just the closest one
                site = builder.pos.findClosestByRange(FIND_MY_CONSTRUCTION_SITES, {
                            filter: site => site.progress > 0
                        }) || builder.pos.findClosestByRange(FIND_MY_CONSTRUCTION_SITES);
                builder.memory.constructionSiteId = site ? site.id : null;
            }

            if (site) {
                if (!builder.pos.inRangeTo(site, 3)) {
                    builder.moveTo(site);
                } else {
                    builder.build(site);
                }

                return;
            }

            var repairTarget = this.findRepairTarget(builder);
            if (repairTarget) {
                if (!builder.pos.inRangeTo(repairTarget, 3)) {
                    builder.moveTo(repairTarget);
                } else {
                    builder.repair(repairTarget);
                }
            } else {
                this.upgradeController(builder);
            }
        } else {
            // Energy pickup mode

            // TODO: The pickup target ID should probably be cached
            var energyDeficit = builder.carryCapacity - _.sum(builder.carry);
            var pickupTarget = builder.pos.findClosestByRange(FIND_MY_STRUCTURES, {
                filter: structure => {
                    return ((structure.structureType === STRUCTURE_EXTENSION ||
                            structure.structureType === STRUCTURE_SPAWN) &&
                            (structure.energy >= energyDeficit ||
                            structure.energy === structure.energyCapacity)) ||
                            ((structure.structureType === STRUCTURE_STORAGE ||
                            structure.structureType === STRUCTURE_CONTAINER) &&
                            (structure.store.energy >= energyDeficit ||
                            _.sum(structure.store) === structure.storeCapacity));
                }
            });

            if (pickupTarget) {
                if (!builder.pos.isNearTo(pickupTarget)) {
                    builder.moveTo(pickupTarget);
                } else {
                    builder.requestEnergyFrom(pickupTarget);
                }
            }
        }

        builder.pickupEnergyInRange();
    },

    findRepairTarget: function (builder) {
        var closestWeakOwnedStructure = builder.pos.findClosestByRange(FIND_MY_STRUCTURES, {
            filter: structure => structure.hits / structure.hitsMax < 0.5
        });
        if (closestWeakOwnedStructure) {
            return closestWeakOwnedStructure;
        }

        // TODO: Make wall hit point threshold dynamic
        var closestWeakNeutralStructure = builder.pos.findClosestByRange(FIND_STRUCTURES, {
            filter: structure => {
                return (_.includes([STRUCTURE_ROAD, STRUCTURE_CONTAINER], structure.structureType) &&
                        structure.hits / structure.hitsMax < 0.5) ||
                        (structure.structureType === STRUCTURE_WALL && structure.hits < 1000000)
            }
        });
        if (closestWeakNeutralStructure) {
            return closestWeakNeutralStructure;
        }

        return null;
    },

    upgradeController: function (builder) {
        var controller = builder.room.controller;
        if (!builder.pos.inRangeTo(controller, 3)) {
            builder.moveTo(controller);
        } else {
            builder.upgradeController(controller);
        }
    },

    getBody: function (energy) {
        if (energy < BODYPART_COST[MOVE] + BODYPART_COST[CARRY] + BODYPART_COST[WORK]) {
            return null;
        }

        var move = [], carry = [], work = [];
        var cheapestPart = _.min([BODYPART_COST[MOVE], BODYPART_COST[CARRY], BODYPART_COST[WORK]]);
        while (energy >= cheapestPart) {
            if (energy >= BODYPART_COST[WORK] && (!work.length || work.length < 2 * carry.length)) {
                energy = this.addPart(energy, work, WORK);
            } else if (energy >= BODYPART_COST[MOVE] && (!move.length || move.length <= work.length)) {
                energy = this.addPart(energy, move, MOVE);
            } else if (energy >= BODYPART_COST[CARRY]) {
                energy = this.addPart(energy, carry, CARRY);
            } else {
                break;
            }
        }

        return work.concat(carry).concat(move);
    },

    addPart: function (energy, parts, part) {
        parts.push(part);
        return energy - BODYPART_COST[part];
    }
};
<|endoftext|>


<commit_before>(function() {
	function Message($firebaseArray) {
		var ref = firebase.database().ref().child('messages').orderByChild('roomId');
		var messages = $firebaseArray(ref);

		var getByRoomId = function(roomId) {
			return $firebaseArray(ref.equalTo(roomId));
		};

		return {
			getByRoomId: getByRoomId
		};
	}

	angular
		.module('blocChat')
		.factory('Message', ['$firebaseArray', Message]);
})();<commit_msg>dist file updated<commit_after>(function() {
	function Message($firebaseArray) {
		var ref = firebase.database().ref().child('messages').orderByChild('roomId');
		var messages = $firebaseArray(ref);

		var getByRoomId = function(roomId) {
			return $firebaseArray(ref.equalTo(roomId));
		};

		return {
			getByRoomId: getByRoomId
			// is this proper naming convention for returning a method like this? What I did here seems stupid and naive
		};
	}

	angular
		.module('blocChat')
		.factory('Message', ['$firebaseArray', Message]);
})();<|endoftext|>


<commit_before>define(['momentDurationFormat'], function(moment) {

    'use strict';

    // Service to edit an absence,
    // shared by account/request/absence-edit and admin/request/absence-edit

    return {

        /**
         * Set scope delfault values
         * @param {Object} $scope
         */
        initScope: function initScope($scope) {
            // default values
            $scope.periodSelection = true;
            $scope.assignments = false;
            $scope.newRequest = false;
            $scope.editRequest = false;

            // list of beneficiaries objects, populated once period set
            $scope.accountRights = [];

            $scope.selection = {
                begin: undefined,
                end: undefined,
                isValid: false,
                duration: undefined,
                days: undefined,
                hours: undefined
            };
        },

        getNextButtonJob: function getNextButtonJob($scope, accountCollection, accountRights) {
            return function() {

                // hide the period selection
                $scope.periodSelection = false;

                // show the right assignement
                $scope.assignments = true;

                if ($scope.user) {

                    /**
                     * Load collection
                     * The collection available on the selected period
                     */

                    $scope.collection = accountCollection.get({
                        user: $scope.user.id,
                        dtstart: $scope.selection.begin,
                        dtend: $scope.selection.end
                    });

                    /**
                     * Load accountRights
                     * the list of rights accessible on the selected period
                     */

                    $scope.accountRights = accountRights.query({
                        user: $scope.user.id,
                        dtstart: $scope.selection.begin,
                        dtend: $scope.selection.end
                    });

                }
            };
        },

        /**
         * Process scope once the user document is available
         * @param   {Object}   $scope
         * @param   {Object}   user           user document as object
         * @param   {Resource} calendarEvents
         *
         */
        onceUserLoaded: function onceUserLoaded($scope, user, calendarEvents)
        {
            /**
             * get the onUpdateInterval function
             * @param   {Object}   $scope
             * @param   {Object}   account        object from the Account schema (vacation account)
             * @param   {Resource} calendarEvents Resource for the REST service (user and admin will have differents resources)
             * @returns {function}
             */
            function getOnUpdateInterval($scope, account, calendarEvents) {

                /**
                 * Set a duration visible to the final user
                 *
                 * @param {Int} duration        Number of miliseconds
                 * @param {Number} businessDays Number of days
                 */
                function setDuration(duration, businessDays)
                {
                    var momentMs = moment.duration(duration, "milliseconds");
                    var momentDays = moment.duration(businessDays, "days");

                    $scope.selection.duration = duration;
                    $scope.selection.days = momentDays.format("d [days]", 1);
                    $scope.selection.hours = momentMs.format("h [hours]", 2);

                    $scope.selection.isValid = duration > 0;
                }

                /**
                 * Get notified if interval is modified
                 * @param {Date} begin
                 * @param {Date} end
                 */
                return function onUpdateInterval(begin, end)
                {
                    if (!begin || !end) {
                        return setDuration(0, 0);
                    }

                    if (begin >= end) {
                        return setDuration(0, 0);
                    }

                    calendarEvents.query({
                        calendar: account.currentScheduleCalendar._id,
                        dtstart: begin,
                        dtend: end
                    }).$promise.then(function(periods) {
                        var duration = 0;
                        var businessDays = 0;
                        var p;

                        for(var i=0; i<periods.length; i++) {

                            p = {
                                dtstart: new Date(periods[i].dtstart),
                                dtend: new Date(periods[i].dtend)
                            };

                            duration += p.dtend.getTime() - p.dtstart.getTime();

                            businessDays += periods[i].businessDays;
                        }

                        return setDuration(duration, businessDays);
                    });
                };
            }

            if (!user.roles.account) {
                throw new Error('the user must have a vacation account');
            }

            var onUpdateInterval = getOnUpdateInterval($scope, user.roles.account, calendarEvents);

            $scope.$watch(function() { return $scope.selection.begin; }, function(begin) {
                onUpdateInterval(begin, $scope.selection.end);
            });

            $scope.$watch(function() { return $scope.selection.end; }, function(end) {
                onUpdateInterval($scope.selection.begin, end);
            });

            $scope.$watch('distribution', function(distribution) {
                if (distribution === undefined) {
                    $scope.distribution = {
                        right: {},
                        total: 0
                    };

                    console.log($scope.accountRights);
                } else {

                    distribution.total = 0;
                    for(var rightId in distribution.right) {
                        if (distribution.right.hasOwnProperty(rightId) && distribution.right[rightId]) {
                            distribution.total += parseFloat(distribution.right[rightId]);
                        }
                    }
                }
            }, true);

        }
    };
});
<commit_msg>Remove debug<commit_after>define(['momentDurationFormat'], function(moment) {

    'use strict';

    // Service to edit an absence,
    // shared by account/request/absence-edit and admin/request/absence-edit

    return {

        /**
         * Set scope delfault values
         * @param {Object} $scope
         */
        initScope: function initScope($scope) {
            // default values
            $scope.periodSelection = true;
            $scope.assignments = false;
            $scope.newRequest = false;
            $scope.editRequest = false;

            // list of beneficiaries objects, populated once period set
            $scope.accountRights = [];

            $scope.selection = {
                begin: undefined,
                end: undefined,
                isValid: false,
                duration: undefined,
                days: undefined,
                hours: undefined
            };
        },

        getNextButtonJob: function getNextButtonJob($scope, accountCollection, accountRights) {
            return function() {

                // hide the period selection
                $scope.periodSelection = false;

                // show the right assignement
                $scope.assignments = true;

                if ($scope.user) {

                    /**
                     * Load collection
                     * The collection available on the selected period
                     */

                    $scope.collection = accountCollection.get({
                        user: $scope.user.id,
                        dtstart: $scope.selection.begin,
                        dtend: $scope.selection.end
                    });

                    /**
                     * Load accountRights
                     * the list of rights accessible on the selected period
                     */

                    $scope.accountRights = accountRights.query({
                        user: $scope.user.id,
                        dtstart: $scope.selection.begin,
                        dtend: $scope.selection.end
                    });

                }
            };
        },

        /**
         * Process scope once the user document is available
         * @param   {Object}   $scope
         * @param   {Object}   user           user document as object
         * @param   {Resource} calendarEvents
         *
         */
        onceUserLoaded: function onceUserLoaded($scope, user, calendarEvents)
        {
            /**
             * get the onUpdateInterval function
             * @param   {Object}   $scope
             * @param   {Object}   account        object from the Account schema (vacation account)
             * @param   {Resource} calendarEvents Resource for the REST service (user and admin will have differents resources)
             * @returns {function}
             */
            function getOnUpdateInterval($scope, account, calendarEvents) {

                /**
                 * Set a duration visible to the final user
                 *
                 * @param {Int} duration        Number of miliseconds
                 * @param {Number} businessDays Number of days
                 */
                function setDuration(duration, businessDays)
                {
                    var momentMs = moment.duration(duration, "milliseconds");
                    var momentDays = moment.duration(businessDays, "days");

                    $scope.selection.duration = duration;
                    $scope.selection.days = momentDays.format("d [days]", 1);
                    $scope.selection.hours = momentMs.format("h [hours]", 2);

                    $scope.selection.isValid = duration > 0;
                }

                /**
                 * Get notified if interval is modified
                 * @param {Date} begin
                 * @param {Date} end
                 */
                return function onUpdateInterval(begin, end)
                {
                    if (!begin || !end) {
                        return setDuration(0, 0);
                    }

                    if (begin >= end) {
                        return setDuration(0, 0);
                    }

                    calendarEvents.query({
                        calendar: account.currentScheduleCalendar._id,
                        dtstart: begin,
                        dtend: end
                    }).$promise.then(function(periods) {
                        var duration = 0;
                        var businessDays = 0;
                        var p;

                        for(var i=0; i<periods.length; i++) {

                            p = {
                                dtstart: new Date(periods[i].dtstart),
                                dtend: new Date(periods[i].dtend)
                            };

                            duration += p.dtend.getTime() - p.dtstart.getTime();

                            businessDays += periods[i].businessDays;
                        }

                        return setDuration(duration, businessDays);
                    });
                };
            }

            if (!user.roles.account) {
                throw new Error('the user must have a vacation account');
            }

            var onUpdateInterval = getOnUpdateInterval($scope, user.roles.account, calendarEvents);

            $scope.$watch(function() { return $scope.selection.begin; }, function(begin) {
                onUpdateInterval(begin, $scope.selection.end);
            });

            $scope.$watch(function() { return $scope.selection.end; }, function(end) {
                onUpdateInterval($scope.selection.begin, end);
            });

            $scope.$watch('distribution', function(distribution) {
                if (distribution === undefined) {
                    $scope.distribution = {
                        right: {},
                        total: 0
                    };
                } else {

                    distribution.total = 0;
                    for(var rightId in distribution.right) {
                        if (distribution.right.hasOwnProperty(rightId) && distribution.right[rightId]) {
                            distribution.total += parseFloat(distribution.right[rightId]);
                        }
                    }
                }
            }, true);

        }
    };
});
<|endoftext|>


<commit_before>const fs = require("fs").promises;
const getTheme = require("./theme");
const getClassicTheme = require("./classic/theme");

const lightDefaultTheme = getTheme({
  theme: "light",
  name: "GitHub Light Default",
});

const lightHighContrastTheme = getTheme({
  theme: "hc",
  name: "GitHub Light High Contrast"
})

const lightColorblindTheme = getTheme({
  theme: "light_colorblind",
  name: "GitHub Light Colorblind",
});

const darkDefaultTheme = getTheme({
  theme: "dark",
  name: "GitHub Dark Default",
});

const darkHighContrastTheme = getTheme({
  theme: "hc",
  name: "GitHub Dark High Contrast"
})

const darkColorblindTheme = getTheme({
  theme: "dark_colorblind",
  name: "GitHub Dark Colorblind"
})

const darkDimmedTheme = getTheme({
  theme: "dimmed",
  name: "GitHub Dark Dimmed"
})

// Classic

const lightTheme = getClassicTheme({
  style: "light",
  name: "GitHub Light",
});

const darkTheme = getClassicTheme({
  style: "dark",
  name: "GitHub Dark",
});

// Write themes

fs.mkdir("./themes", { recursive: true })
  .then(() => Promise.all([
    fs.writeFile("./themes/light-default.json", JSON.stringify(lightDefaultTheme, null, 2)),
    fs.writeFile("./themes/light-high-contrast.json", JSON.stringify(lightHighContrastTheme, null, 2)),
    fs.writeFile("./themes/light-colorblind.json", JSON.stringify(lightColorblindTheme, null, 2)),
    fs.writeFile("./themes/dark-default.json", JSON.stringify(darkDefaultTheme, null, 2)),
    fs.writeFile("./themes/dark-high-contrast.json", JSON.stringify(darkHighContrastTheme, null, 2)),
    fs.writeFile("./themes/dark-colorblind.json", JSON.stringify(darkColorblindTheme, null, 2)),
    fs.writeFile("./themes/dark-dimmed.json", JSON.stringify(darkDimmedTheme, null, 2)),
    fs.writeFile("./themes/light.json", JSON.stringify(lightTheme, null, 2)),
    fs.writeFile("./themes/dark.json", JSON.stringify(darkTheme, null, 2)),
  ]))
  .catch(() => process.exit(1))
<commit_msg>Update wrong values<commit_after>const fs = require("fs").promises;
const getTheme = require("./theme");
const getClassicTheme = require("./classic/theme");

const lightDefaultTheme = getTheme({
  theme: "light",
  name: "GitHub Light Default",
});

const lightHighContrastTheme = getTheme({
  theme: "light_high_contrast",
  name: "GitHub Light High Contrast"
})

const lightColorblindTheme = getTheme({
  theme: "light_colorblind",
  name: "GitHub Light Colorblind",
});

const darkDefaultTheme = getTheme({
  theme: "dark",
  name: "GitHub Dark Default",
});

const darkHighContrastTheme = getTheme({
  theme: "dark_high_contrast",
  name: "GitHub Dark High Contrast"
})

const darkColorblindTheme = getTheme({
  theme: "dark_colorblind",
  name: "GitHub Dark Colorblind"
})

const darkDimmedTheme = getTheme({
  theme: "dark_dimmed",
  name: "GitHub Dark Dimmed"
})

// Classic

const lightTheme = getClassicTheme({
  style: "light",
  name: "GitHub Light",
});

const darkTheme = getClassicTheme({
  style: "dark",
  name: "GitHub Dark",
});

// Write themes

fs.mkdir("./themes", { recursive: true })
  .then(() => Promise.all([
    fs.writeFile("./themes/light-default.json", JSON.stringify(lightDefaultTheme, null, 2)),
    fs.writeFile("./themes/light-high-contrast.json", JSON.stringify(lightHighContrastTheme, null, 2)),
    fs.writeFile("./themes/light-colorblind.json", JSON.stringify(lightColorblindTheme, null, 2)),
    fs.writeFile("./themes/dark-default.json", JSON.stringify(darkDefaultTheme, null, 2)),
    fs.writeFile("./themes/dark-high-contrast.json", JSON.stringify(darkHighContrastTheme, null, 2)),
    fs.writeFile("./themes/dark-colorblind.json", JSON.stringify(darkColorblindTheme, null, 2)),
    fs.writeFile("./themes/dark-dimmed.json", JSON.stringify(darkDimmedTheme, null, 2)),
    fs.writeFile("./themes/light.json", JSON.stringify(lightTheme, null, 2)),
    fs.writeFile("./themes/dark.json", JSON.stringify(darkTheme, null, 2)),
  ]))
  .catch(() => process.exit(1))
<|endoftext|>


<commit_before>import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  path: __dirname,
  routes: [
    {
      path: '/',
      name: 'front',
      meta: {
        front: true,
      },
    },
    {
      path: 'ideas',
      name: 'ideas',
      meta: {
        pageTitle: 'Ideas',
      },
    },
    {
      path: 'prototypes',
      name: 'prototypes',
      meta: {
        pageTitle: 'Prototypes',
      },
    },
    {
      path: 'code',
      name: 'code',
      meta: {
        pageTitle: 'Code',
      },
    },
  ],
})

router.afterEach((to) => {
  Vue.nextTick(() => {
    router.app.$store.commit('setTitle', {
      title: to.meta.pageTitle,
    })
  })
})

export default router
<commit_msg>Fix routing bug by making sure `/` always is part of route path<commit_after>import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  path: __dirname,
  routes: [
    {
      path: '/',
      children: [
        {
          path: '',
          name: 'front',
          meta: {
            front: true,
          },
        },
        {
          path: '/ideas',
          name: 'ideas',
          meta: {
            pageTitle: 'Ideas',
          },
        },
        {
          path: '/prototypes',
          name: 'prototypes',
          meta: {
            pageTitle: 'Prototypes',
          },
        },
        {
          path: '/code',
          name: 'code',
          meta: {
            pageTitle: 'Code',
          },
        },
      ],
    },
  ],
})

router.afterEach((to) => {
  Vue.nextTick(() => {
    router.app.$store.commit('setTitle', {
      title: to.meta.pageTitle,
    })
  })
})

export default router
<|endoftext|>


<commit_before>
var kg = window.kg || {};

/**
 * Simulator is the central component to control the simulation and all of
 * its components.
 */
(function (kg, $) {
    'use strict';

    if (kg.simulator) {
        return;
    }

    var defaults,
        simulator;

    defaults = {
        deviceNames: ['apollo', 'hermes', 'pluto', 'vesta', 'minerva'],
        deviceClass: '.device',
        btnPause: '.btn-pause-active, .btn-pause-inactive',
        btnPauseActive: 'btn-pause-active',
        btnPauseInactive: 'btn-pause-inactive',
        btnSpeedIncrease: '.btn-speed-increase',
        btnSpeedDecrease: '.btn-speed-decrease',
        txtFps: '.txt-fps',
        cableClass: '.cbl',
        tickRate: 4,
        tlgLength: 100
    };

    simulator = function createSimulator(options) {
        var settings = $.extend({}, defaults, options),
            $devices = $(settings.deviceClass, kg.context),
            $cables = $(settings.cableClass, kg.context),
            simulator = this;

        this._settings = settings;

        // Device setup.
        $devices.each(function addDevicesToSimulator() {
            var $element = $(this),
                $numpad = $('#numpad-' + $element.attr('id'), kg.context);

            simulator.addDevice(new kg.device($element, $numpad));
        });

        // Cable setup.
        $cables.each(function addCablesToSimulator() {
            simulator.addCable(new kg.cable($(this)));
        });

        // Hook up devices and cables.
        connectComponents(simulator);

        // Event handler for (un)pausing the simulation.
        $(this._settings.btnPause, kg.context).on('click', function callToggle(e) {
            simulator.toggle();
        });

        // Event handler for increasing the simulation speed.
        $(this._settings.btnSpeedIncrease, kg.context).on('click', function callIncreaseSpeed(e) {
            simulator.increaseSpeed(e);
        });

        // Event handler for decreasing the simulation speed.
        $(this._settings.btnSpeedDecrease, kg.context).on('click', function callDecreaseSpeed(e) {
            simulator.decreaseSpeed(e);
        });

        simulator.updateFpsTxt(this._settings.tickRate);

        // Start the simulation.
        simulator.play();
    };

    /**
     * Starts the simulation.
     */
    simulator.prototype.play = function play() {
        this._intervalId = setInterval(function callTickHandler(simulator) {
            simulator.tickHandler.call(simulator);
        }, 1000 / this._settings.tickRate, this);

        $(this._settings.btnPause, kg.context)
            .removeClass(this._settings.btnPauseActive)
            .addClass(this._settings.btnPauseInactive)
        ;
    };

    /**
     * Stops the simulation.
     */
    simulator.prototype.pause = function pause() {
        if (this._intervalId !== null) {
            clearInterval(this._intervalId);

            this._intervalId = null;
        }

        $(this._settings.btnPause, kg.context)
            .removeClass(this._settings.btnPauseInactive)
            .addClass(this._settings.btnPauseActive)
        ;
    };

    /**
     * Toggles the simulation (paused vs playing).
     */
    simulator.prototype.toggle = function toggle() {
        if (this._intervalId) {
            this.pause();
        } else {
            this.play();
        }
    };

    /**
     * Updates the display with the new tickrate.
     *
     * @param newTickRate
     */
    simulator.prototype.updateFpsTxt = function updateFpsTxt(newTickRate) {
        $(this._settings.txtFps, kg.context).text(newTickRate + ' fps');
    };

    /**
     * Changes the tickrate by the given delta.
     *
     * @param {Number} delta
     */
    simulator.prototype.changeTickRate = function changeTickRate(delta) {
        var newTickRate = this._settings.tickRate + delta;

        if (newTickRate < 1 || 32 < newTickRate) {
            return;
        }

        console.log('setting tickrate to ' + newTickRate);

        this._settings.tickRate = newTickRate;

        $(this._settings.txtFps, kg.context).text(newTickRate + ' fps');

        // Restarts only if it's already running as to not unintentionally unpause.
        if (this._intervalId) {
            this.pause();
            this.play();
        }
    };

    /**
     * @returns {Number} The tickrate
     */
    simulator.prototype.getTickRate = function getTickRate() {
        return this._settings.tickRate;
    };

    /**
     * Increases the simulation speed by doubling the tickrate.
     *
     * @param e
     */
    simulator.prototype.increaseSpeed = function increaseSpeed(e) {
        this.changeTickRate(this.getTickRate());
    };

    /**
     * Decreases the simulation speed by cutting the tickrate in half.
     *
     * @param e
     */
    simulator.prototype.decreaseSpeed = function decreaseSpeed(e) {
        this.changeTickRate(-0.5 * this.getTickRate());
    };

    simulator.prototype.tickHandler = function tickHandler() {
        var components = this.getComponents(),
            cables = this.getCables(),
            id = null;

        for (id in cables) cables[id].preTick();
        for (id in components) components[id].tick();

        this.handleCollision();
    };

    /**
     * Goes into conflict handling mode, if there is a need.
     *
     * http://en.wikipedia.org/wiki/Exponential_backoff
     * http://en.wikipedia.org/wiki/Carrier_sense_multiple_access_with_collision_avoidance
     */
    simulator.prototype.handleCollision = function handleCollision() {
        var devices = this.getDevices(),
            cables  = this.getCables(),
            i;

        // First of all, each device must be aware that there has been a conflict.
        for (i = 0; i < devices.length; i++) {
            if (!devices[i].isCollision()) {
                return;
            }
        }

        for (i in cables) {
            cables[i].clear();
        }

        for (i in devices) {
            devices[i].handleCollision();
        }
    };

    /**
     * Gets all components (both devices and cables) mapped by their
     * respective DOM element IDs.
     *
     * @returns {Object}
     */
    simulator.prototype.getComponents = function getComponents() {
        this._components = this._components || {};

        return this._components;
    };

    /**
     * Gets all devices participating in the simulation.
     *
     * @returns {Array}
     */
    simulator.prototype.getDevices = function getDevices() {
        if (!this._devices) {
            this._devices = [];
        }

        return this._devices;
    };

    /**
     * Adds a new device to the simulator.
     *
     * @param {kg.device}
     */
    simulator.prototype.addDevice = function addDevice(device) {
        var me = this;

        me.getDevices().push(device);
        me.getComponents()[device._$element.attr('id')] = device;

        device._$element.on('click', function (e) {

            me.clickHandler.call(me, e);

        });

        return me;
    };

    simulator.prototype.clickHandler = function clickHandler(e) {
        var device = this.getComponents()[$(e.currentTarget).attr('id')];

        if (!this._from) {
            this._from = device;

            return;
        }

        this._from.sendTlg(device, this._settings.tlgLength);
        this._from = null;
    };

    /**
     * Gets all cables participating in the simulation.
     *
     * @returns {Array}
     */
    simulator.prototype.getCables = function getCables() {
        if (!this._cables) {
            this._cables = [];
        }

        return this._cables;
    };

    /**
     * Adds a new cable to the simulator.
     *
     * @param {kg.cable}
     */
    simulator.prototype.addCable = function addCable(cable) {
        this.getCables().push(cable);
        this.getComponents()[cable._$element.attr('id')] = cable;

        return this;
    };

    /**
     * Connects all of the components of a simulator.
     *
     * @param {kg.simulator}
     */
    function connectComponents(simulator) {
        var components = simulator.getComponents(),
            id = null,
            i,
            relatedIds;

        for (id in components) {

            if (!components.hasOwnProperty(id)) {
                continue;
            }

            relatedIds = findRelatedIds(components[id]._$element);

            for (i = 0; i < relatedIds.length; i++) {

                if (!(relatedIds[i] in components)) {
                    throw 'trying to connect a component with nonexisting id `' + relatedIds[i] + '` to component `' + id + '`';
                }

                components[id].addConnection(components[relatedIds[i]]);
            }
        }
    }

    /**
     * Finds element ids related to the given element. It basically looks
     * for classes starting with `rel-` and breaks up anything that comes
     * after it from the hyphens. For example the class `foo rel-bah-baz rel-gah`
     * would yeld ['bah', 'baz', 'gah'].
     *
     * @param {jQuery} $element
     *
     * @return {Array}
     */
    function findRelatedIds($element) {
        var classNames = $element.attr('class'),
            classParts = [],
            relatedIds = [];

        classNames = classNames.split(' ');

        for (var i in classNames) {

            if (!classNames[i].match(/^rel-/)) {
                continue;
            }

            classParts = classNames[i].split('-');
            classParts.shift();

            relatedIds = relatedIds.concat(classParts);

        }

        return relatedIds;
    }

    kg.simulator = simulator;

})(kg, jQuery);
<commit_msg>Pause the simulation, when a collision happens<commit_after>
var kg = window.kg || {};

/**
 * Simulator is the central component to control the simulation and all of
 * its components.
 */
(function (kg, $) {
    'use strict';

    if (kg.simulator) {
        return;
    }

    var defaults,
        simulator;

    defaults = {
        deviceNames: ['apollo', 'hermes', 'pluto', 'vesta', 'minerva'],
        deviceClass: '.device',
        btnPause: '.btn-pause-active, .btn-pause-inactive',
        btnPauseActive: 'btn-pause-active',
        btnPauseInactive: 'btn-pause-inactive',
        btnSpeedIncrease: '.btn-speed-increase',
        btnSpeedDecrease: '.btn-speed-decrease',
        txtFps: '.txt-fps',
        cableClass: '.cbl',
        tickRate: 4,
        tlgLength: 100
    };

    simulator = function createSimulator(options) {
        var settings = $.extend({}, defaults, options),
            $devices = $(settings.deviceClass, kg.context),
            $cables = $(settings.cableClass, kg.context),
            simulator = this;

        this._settings = settings;

        // Whether all the devices are in collision mode. In that case the
        // system should pause to let the user decide whether he would like
        // to manually choose slot times or let the simulator take care of it.
        this._collisionFound = false;

        // Device setup.
        $devices.each(function addDevicesToSimulator() {
            var $element = $(this),
                $numpad = $('#numpad-' + $element.attr('id'), kg.context);

            simulator.addDevice(new kg.device($element, $numpad));
        });

        // Cable setup.
        $cables.each(function addCablesToSimulator() {
            simulator.addCable(new kg.cable($(this)));
        });

        // Hook up devices and cables.
        connectComponents(simulator);

        // Event handler for (un)pausing the simulation.
        $(this._settings.btnPause, kg.context).on('click', function callToggle(e) {
            simulator.toggle();
        });

        // Event handler for increasing the simulation speed.
        $(this._settings.btnSpeedIncrease, kg.context).on('click', function callIncreaseSpeed(e) {
            simulator.increaseSpeed(e);
        });

        // Event handler for decreasing the simulation speed.
        $(this._settings.btnSpeedDecrease, kg.context).on('click', function callDecreaseSpeed(e) {
            simulator.decreaseSpeed(e);
        });

        simulator.updateFpsTxt(this._settings.tickRate);

        // Start the simulation.
        simulator.play();
    };

    /**
     * Starts the simulation.
     */
    simulator.prototype.play = function play() {
        this._intervalId = setInterval(function callTickHandler(simulator) {
            simulator.tickHandler.call(simulator);
        }, 1000 / this._settings.tickRate, this);

        $(this._settings.btnPause, kg.context)
            .removeClass(this._settings.btnPauseActive)
            .addClass(this._settings.btnPauseInactive)
        ;
    };

    /**
     * Stops the simulation.
     */
    simulator.prototype.pause = function pause() {
        if (this._intervalId !== null) {
            clearInterval(this._intervalId);

            this._intervalId = null;
        }

        $(this._settings.btnPause, kg.context)
            .removeClass(this._settings.btnPauseInactive)
            .addClass(this._settings.btnPauseActive)
        ;
    };

    /**
     * Toggles the simulation (paused vs playing).
     */
    simulator.prototype.toggle = function toggle() {
        if (this._intervalId) {
            this.pause();
        } else {
            this.play();
        }
    };

    /**
     * Updates the display with the new tickrate.
     *
     * @param newTickRate
     */
    simulator.prototype.updateFpsTxt = function updateFpsTxt(newTickRate) {
        $(this._settings.txtFps, kg.context).text(newTickRate + ' fps');
    };

    /**
     * Changes the tickrate by the given delta.
     *
     * @param {Number} delta
     */
    simulator.prototype.changeTickRate = function changeTickRate(delta) {
        var newTickRate = this._settings.tickRate + delta;

        if (newTickRate < 1 || 32 < newTickRate) {
            return;
        }

        console.log('setting tickrate to ' + newTickRate);

        this._settings.tickRate = newTickRate;

        $(this._settings.txtFps, kg.context).text(newTickRate + ' fps');

        // Restarts only if it's already running as to not unintentionally unpause.
        if (this._intervalId) {
            this.pause();
            this.play();
        }
    };

    /**
     * @returns {Number} The tickrate
     */
    simulator.prototype.getTickRate = function getTickRate() {
        return this._settings.tickRate;
    };

    /**
     * Increases the simulation speed by doubling the tickrate.
     *
     * @param e
     */
    simulator.prototype.increaseSpeed = function increaseSpeed(e) {
        this.changeTickRate(this.getTickRate());
    };

    /**
     * Decreases the simulation speed by cutting the tickrate in half.
     *
     * @param e
     */
    simulator.prototype.decreaseSpeed = function decreaseSpeed(e) {
        this.changeTickRate(-0.5 * this.getTickRate());
    };

    simulator.prototype.tickHandler = function tickHandler() {
        var components = this.getComponents(),
            cables = this.getCables(),
            id = null;

        for (id in cables) cables[id].preTick();
        for (id in components) components[id].tick();

        this.handleCollision();
    };

    /**
     * Goes into conflict handling mode, if there is a need.
     *
     * http://en.wikipedia.org/wiki/Exponential_backoff
     * http://en.wikipedia.org/wiki/Carrier_sense_multiple_access_with_collision_avoidance
     */
    simulator.prototype.handleCollision = function handleCollision() {
        var devices = this.getDevices(),
            cables  = this.getCables(),
            i;

        // First of all, each device must be aware that there has been a conflict.
        for (i = 0; i < devices.length; i++) {
            if (!devices[i].isCollision()) {
                return;
            }
        }

        // Pause the simulation right after the collision has reached to all
        // of the devices. This way the user can decide what to do.
        if (!this._collisionFound) {
            this._collisionFound = true;

            this.pause();

            return;
        }

        for (i in cables) {
            cables[i].clear();
        }

        for (i in devices) {
            devices[i].handleCollision();
        }

        this._collisionFound = false;
    };

    /**
     * Gets all components (both devices and cables) mapped by their
     * respective DOM element IDs.
     *
     * @returns {Object}
     */
    simulator.prototype.getComponents = function getComponents() {
        this._components = this._components || {};

        return this._components;
    };

    /**
     * Gets all devices participating in the simulation.
     *
     * @returns {Array}
     */
    simulator.prototype.getDevices = function getDevices() {
        if (!this._devices) {
            this._devices = [];
        }

        return this._devices;
    };

    /**
     * Adds a new device to the simulator.
     *
     * @param {kg.device}
     */
    simulator.prototype.addDevice = function addDevice(device) {
        var me = this;

        me.getDevices().push(device);
        me.getComponents()[device._$element.attr('id')] = device;

        device._$element.on('click', function (e) {

            me.clickHandler.call(me, e);

        });

        return me;
    };

    simulator.prototype.clickHandler = function clickHandler(e) {
        var device = this.getComponents()[$(e.currentTarget).attr('id')];

        if (!this._from) {
            this._from = device;

            return;
        }

        this._from.sendTlg(device, this._settings.tlgLength);
        this._from = null;
    };

    /**
     * Gets all cables participating in the simulation.
     *
     * @returns {Array}
     */
    simulator.prototype.getCables = function getCables() {
        if (!this._cables) {
            this._cables = [];
        }

        return this._cables;
    };

    /**
     * Adds a new cable to the simulator.
     *
     * @param {kg.cable}
     */
    simulator.prototype.addCable = function addCable(cable) {
        this.getCables().push(cable);
        this.getComponents()[cable._$element.attr('id')] = cable;

        return this;
    };

    /**
     * Connects all of the components of a simulator.
     *
     * @param {kg.simulator}
     */
    function connectComponents(simulator) {
        var components = simulator.getComponents(),
            id = null,
            i,
            relatedIds;

        for (id in components) {

            if (!components.hasOwnProperty(id)) {
                continue;
            }

            relatedIds = findRelatedIds(components[id]._$element);

            for (i = 0; i < relatedIds.length; i++) {

                if (!(relatedIds[i] in components)) {
                    throw 'trying to connect a component with nonexisting id `' + relatedIds[i] + '` to component `' + id + '`';
                }

                components[id].addConnection(components[relatedIds[i]]);
            }
        }
    }

    /**
     * Finds element ids related to the given element. It basically looks
     * for classes starting with `rel-` and breaks up anything that comes
     * after it from the hyphens. For example the class `foo rel-bah-baz rel-gah`
     * would yeld ['bah', 'baz', 'gah'].
     *
     * @param {jQuery} $element
     *
     * @return {Array}
     */
    function findRelatedIds($element) {
        var classNames = $element.attr('class'),
            classParts = [],
            relatedIds = [];

        classNames = classNames.split(' ');

        for (var i in classNames) {

            if (!classNames[i].match(/^rel-/)) {
                continue;
            }

            classParts = classNames[i].split('-');
            classParts.shift();

            relatedIds = relatedIds.concat(classParts);

        }

        return relatedIds;
    }

    kg.simulator = simulator;

})(kg, jQuery);
<|endoftext|>


<commit_before>import {
  Skip,
  Match,
  Fault,
  capture,
  wrap,
  parse,
  any,
  permuteObject,
  builtins as $
} from "chimpanzee";

import { collection } from "./";

import { source, composite } from "isotropy-analyzer-utils";

import { canParse } from "isotropy-analyzer-errors";

export default function(state, analysisState) {
  return composite({
    type: "AssignmentExpression",
    operator: "=",
    left: source([collection])(state, analysisState),
    right: {
      type: "CallExpression",
      callee: {
        type: "MemberExpression",
        object: source([collection])(state, analysisState),
        property: {
          type: "Identifier",
          name: "filter"
        }
      }
    }
  }).then(({ object: _object }) =>
    composite(
      {
        right: {
          arguments: [
            wrap({
              type: "ArrowFunctionExpression",
              params: capture(),
              body: {
                type: "UnaryExpression",
                operator: "!"
              }
            }).then(({ params }) => ({
              body: {
                argument: any(
                  permuteObject(["left", "right"], {
                    type: "BinaryExpression",
                    left: {
                      type: "MemberExpression",
                      object: { type: "Identifier", name: params[0].name }
                    },
                    operator: "===",
                    right: capture("key")
                  })
                )
              }
            }))
          ]
        }
      },
      {
        build: obj => () => result =>
          result instanceof Match
            ? {
                ..._object,
                operation: "del",
                key: result.value.arguments[0].argument.key
              }
            : new Fault(
                `Invalid database expression. Should look like: myDb.todos = myDb.todos.filter(todo => !(todo.key === "Task"))`
              )
      }
    )
  );
}
<commit_msg>Remove unused import<commit_after>import {
  Skip,
  Match,
  Fault,
  capture,
  wrap,
  parse,
  any,
  permuteObject,
  builtins as $
} from "chimpanzee";
import { collection } from "./";
import { source, composite } from "isotropy-analyzer-utils";

export default function(state, analysisState) {
  return composite({
    type: "AssignmentExpression",
    operator: "=",
    left: source([collection])(state, analysisState),
    right: {
      type: "CallExpression",
      callee: {
        type: "MemberExpression",
        object: source([collection])(state, analysisState),
        property: {
          type: "Identifier",
          name: "filter"
        }
      }
    }
  }).then(({ object: _object }) =>
    composite(
      {
        right: {
          arguments: [
            wrap({
              type: "ArrowFunctionExpression",
              params: capture(),
              body: {
                type: "UnaryExpression",
                operator: "!"
              }
            }).then(({ params }) => ({
              body: {
                argument: any(
                  permuteObject(["left", "right"], {
                    type: "BinaryExpression",
                    left: {
                      type: "MemberExpression",
                      object: { type: "Identifier", name: params[0].name }
                    },
                    operator: "===",
                    right: capture("key")
                  })
                )
              }
            }))
          ]
        }
      },
      {
        build: obj => () => result =>
          result instanceof Match
            ? {
                ..._object,
                operation: "del",
                key: result.value.arguments[0].argument.key
              }
            : new Fault(
                `Invalid database expression. Should look like: myDb.todos = myDb.todos.filter(todo => !(todo.key === "Task"))`
              )
      }
    )
  );
}
<|endoftext|>


<commit_before>import React from 'react';
import BlobStream from 'blob-stream';
import PDFRenderer from './renderer';
import StyleSheet from './stylesheet';
import { createInstance } from './elements';
import Font from './font';
import { version } from '../package.json';

const View = 'VIEW';
const Text = 'TEXT';
const Link = 'LINK';
const Page = 'PAGE';
const Note = 'NOTE';
const Image = 'IMAGE';
const Document = 'DOCUMENT';

const pdf = input => {
  const container = createInstance({ type: 'ROOT' });
  const mountNode = PDFRenderer.createContainer(container);

  if (input) {
    updateContainer(React.cloneElement(input, { insideViewer: true }));
  }

  function isDirty() {
    return container.isDirty;
  }

  function updateContainer(doc) {
    PDFRenderer.updateContainer(doc, mountNode, null);
  }

  async function toBlob() {
    await container.render();

    const stream = container.instance.pipe(BlobStream());

    return new Promise((resolve, reject) => {
      stream.on('finish', () => {
        const blob = stream.toBlob('application/pdf');

        if (container.document.props.onRender) {
          container.document.props.onRender({ blob });
        }

        resolve(blob);
      });

      stream.on('error', reject);
    });
  }

  function toBuffer() {
    if (container.document.props.onRender) {
      container.document.props.onRender();
    }

    container.render();

    return container.instance;
  }

  function toString() {
    let result = '';
    container.render();

    return new Promise(resolve => {
      container.instance.on('data', function(buffer) {
        result += buffer;
      });

      container.instance.on('end', function() {
        if (container.document.props.onRender) {
          container.document.props.onRender({ string: result });
        }

        resolve(result);
      });
    });
  }

  return {
    isDirty,
    updateContainer,
    toBuffer,
    toBlob,
    toString,
  };
};

export {
  version,
  PDFRenderer,
  View,
  Text,
  Link,
  Page,
  Font,
  Note,
  Image,
  Document,
  StyleSheet,
  createInstance,
  pdf,
};
<commit_msg>Reject promises on toBlob and toString<commit_after>import React from 'react';
import BlobStream from 'blob-stream';
import PDFRenderer from './renderer';
import StyleSheet from './stylesheet';
import { createInstance } from './elements';
import Font from './font';
import { version } from '../package.json';

const View = 'VIEW';
const Text = 'TEXT';
const Link = 'LINK';
const Page = 'PAGE';
const Note = 'NOTE';
const Image = 'IMAGE';
const Document = 'DOCUMENT';

const pdf = input => {
  const container = createInstance({ type: 'ROOT' });
  const mountNode = PDFRenderer.createContainer(container);

  if (input) {
    updateContainer(React.cloneElement(input, { insideViewer: true }));
  }

  function isDirty() {
    return container.isDirty;
  }

  function updateContainer(doc) {
    PDFRenderer.updateContainer(doc, mountNode, null);
  }

  async function toBlob() {
    await container.render();

    const stream = container.instance.pipe(BlobStream());

    return new Promise((resolve, reject) => {
      stream.on('finish', () => {
        try {
          const blob = stream.toBlob('application/pdf');

          if (container.document.props.onRender) {
            container.document.props.onRender({ blob });
          }

          resolve(blob);
        } catch (error) {
          reject(error);
        }
      });

      stream.on('error', reject);
    });
  }

  function toBuffer() {
    if (container.document.props.onRender) {
      container.document.props.onRender();
    }

    container.render();

    return container.instance;
  }

  function toString() {
    let result = '';
    container.render();

    return new Promise((resolve, reject) => {
      try {
        container.instance.on('data', function(buffer) {
          result += buffer;
        });

        container.instance.on('end', function() {
          if (container.document.props.onRender) {
            container.document.props.onRender({ string: result });
          }

          resolve(result);
        });
      } catch (error) {
        reject(error);
      }
    });
  }

  return {
    isDirty,
    updateContainer,
    toBuffer,
    toBlob,
    toString,
  };
};

export {
  version,
  PDFRenderer,
  View,
  Text,
  Link,
  Page,
  Font,
  Note,
  Image,
  Document,
  StyleSheet,
  createInstance,
  pdf,
};
<|endoftext|>


<commit_before>import { pipe, isTimer, makeArray, $devWarnOn } from './utils'
import { normalizePath } from './utils-path'
import { prefixSpec } from './spec'

const off = () => false
const turnOff = o => Object.assign(o, { match: off, resolve: off, reject: off })

export function toggle(match, newKey, newMatch) {
  let { off, key } = match
  let on = off ? newMatch || off : turnOff({ off: newMatch || match })
  on.key = newKey || key
  let hasAll = (o, ...props) => props.every(Object.prototype.hasOwnProperty.bind(o))
  $devWarnOn(() => !hasAll(on, 'match', 'resolve', 'reject'), `Match not well formed: ${on.key}`)
  return on
}

export function toggleSelected(matchers, key, replacements) {
  if (key === undefined) return matchers
  replacements = makeArray(replacements)
  let replaced = 0
  let result = matchers.map(m => (m.key === key ? toggle(m, key, replacements[replaced++]) : m))
  $devWarnOn(
    () => replaced === 0 || replaced !== replacements.length,
    `${replaced} replacements issued for toggle key: ${key}`
  )
  return result
}

function matcher(specs, checks, msg) {
  let spec, result, { path } = msg
  spec = specs.find(s => !!(result = s.match(checks, path)))
  let success = spec && spec.success(result)
  result = Object.assign({}, msg, result)
  return { result, success, spec }
}

function resolveSpec({ result, success, spec }) {
  let timer = isTimer(spec.resolve(result, success))
  return timer ? { result, timer } : { result }
}

function resolve(msg) {
  return msg.spec ? Object.assign({}, msg, resolveSpec(msg)) : false
}

function reject(specs, msg) {
  let { result, spec } = msg
  specs.forEach(s => s !== spec && s.reject(result))
}

function matchPrefix(prefixKey, matcher) {
  let { match, checks } = matcher
  let pspec = prefixSpec(prefixKey, match)
  return Object.assign({}, matcher, { prefixKey, match: pspec.match.bind(pspec, checks) })
}

function prematch(matchCheck, msg) {
  let { prefix, href, path, qs = '', hash = '' } = msg
  if (prefix) path = normalizePath(prefix)(path)
  if (matchCheck) path = matchCheck({ prefix, href, path, qs, hash })
  return path === msg.path ? msg : Object.assign({}, msg, { path })
}

export function match(specs, checks = {}, matchCheck) {
  if (!Array.isArray(specs)) specs = [].concat(specs)
  let match = pipe(prematch.bind(null, matchCheck), matcher.bind(null, specs, checks))
  return { match, resolve, specs, checks, reject: reject.bind(null, specs) }
}

export function prefixMatch(prefixKey, matcher, prematchCheck) {
  let prefixed = matchPrefix(prefixKey, matcher)
  if (prematchCheck) {
    let { match } = prefixed
    prefixed.match = pipe(prematch.bind(null, prematchCheck), match)
  }
  return prefixed
}
<commit_msg>fix parameter names<commit_after>import { pipe, isTimer, makeArray, $devWarnOn } from './utils'
import { normalizePath } from './utils-path'
import { prefixSpec } from './spec'

const off = () => false
const turnOff = o => Object.assign(o, { match: off, resolve: off, reject: off })

export function toggle(matcher, newKey, replacement) {
  let { off, key } = matcher
  let on = off ? replacement || off : turnOff({ off: replacement || matcher })
  on.key = newKey || key
  let hasAll = (o, ...props) => props.every(Object.prototype.hasOwnProperty.bind(o))
  $devWarnOn(() => !hasAll(on, 'match', 'resolve', 'reject'), `Match not well formed: ${on.key}`)
  return on
}

export function toggleSelected(matchers, key, replacements) {
  if (key === undefined) return matchers
  replacements = makeArray(replacements)
  let replaced = 0
  let result = matchers.map(m => (m.key === key ? toggle(m, key, replacements[replaced++]) : m))
  $devWarnOn(
    () => replaced === 0 || replaced !== replacements.length,
    `${replaced} replacements issued for toggle key: ${key}`
  )
  return result
}

function matcher(specs, checks, msg) {
  let spec, result, { path } = msg
  spec = specs.find(s => !!(result = s.match(checks, path)))
  let success = spec && spec.success(result)
  result = Object.assign({}, msg, result)
  return { result, success, spec }
}

function resolveSpec({ result, success, spec }) {
  let timer = isTimer(spec.resolve(result, success))
  return timer ? { result, timer } : { result }
}

function resolve(msg) {
  return msg.spec ? Object.assign({}, msg, resolveSpec(msg)) : false
}

function reject(specs, msg) {
  let { result, spec } = msg
  specs.forEach(s => s !== spec && s.reject(result))
}

function matchPrefix(prefixKey, matcher) {
  let { match, checks } = matcher
  let pspec = prefixSpec(prefixKey, match)
  return Object.assign({}, matcher, { prefixKey, match: pspec.match.bind(pspec, checks) })
}

function prematch(matchCheck, msg) {
  let { prefix, href, path, qs = '', hash = '' } = msg
  if (prefix) path = normalizePath(prefix)(path)
  if (matchCheck) path = matchCheck({ prefix, href, path, qs, hash })
  return path === msg.path ? msg : Object.assign({}, msg, { path })
}

export function match(specs, checks = {}, matchCheck) {
  if (!Array.isArray(specs)) specs = [].concat(specs)
  let match = pipe(prematch.bind(null, matchCheck), matcher.bind(null, specs, checks))
  return { match, resolve, specs, checks, reject: reject.bind(null, specs) }
}

export function prefixMatch(prefixKey, matcher, prematchCheck) {
  let prefixed = matchPrefix(prefixKey, matcher)
  if (prematchCheck) {
    let { match } = prefixed
    prefixed.match = pipe(prematch.bind(null, prematchCheck), match)
  }
  return prefixed
}
<|endoftext|>