<commit_before>(function(exports) {
  'use strict';

  if (exports.EventsManager) {
    return;
  }

  var EventInstance = function(name, namespace) {
    var _isStoppedPropagation = false;

    this.name = name;
    this.namespace = namespace;

    this.stopPropagation = function() {
      _isStoppedPropagation = true;
    };

    this.isStoppedPropagation = function() {
      return _isStoppedPropagation;
    };

    this.resetStopPropagation = function() {
      _isStoppedPropagation = false;
    };
  };

  var EventPriority = function() {
    var _priorities = {
      low: -1,
      normal: 0,
      high: 9999999
    };

    this.formatPriority = function(priority) {
      if (typeof priority == 'undefined' || priority === null) {
        priority = 'normal';
      }

      if (typeof priority == 'string') {
        if (!(priority in _priorities)) {
          priority = 'normal';
        }
        priority = _priorities[priority];
      }

      return priority;
    };

    this.sortByPriority = function(list) {
      list.sort(function(a, b) {
        return b.priority - a.priority;
      });
    };

  };

  exports.EventsManager = function() {

    var _this = this,
        _events = [],
        _eventsAnything = [],
        _priority = new EventPriority(),
        _locks = {};

    function _formatEventNames(eventName) {
      var events = [];

      eventName.split(' ').map(function(name) {
        if (name) {
          events.push(name);
        }
      });

      return events;
    }

    function _namespace(eventName) {
      var namespace = null;
      eventName = eventName.split('.');
      if (eventName.length > 1) {
        namespace = eventName[0];
        eventName = eventName[1];
      }
      else {
        eventName = eventName[0];
      }

      return {
        name: eventName,
        namespace: namespace
      };
    }

    function _checkLock(eventName) {
      if (_locks[eventName]) {
        console.error('EventsManager: Event "' + eventName + '" is locked for use');
      }
    }

    this.eventsName = function() {
      var names = [],
          name = null;

      for (name in _events) {
        names.push(name);
      }

      return names;
    };

    this.eventsStack = function(eventName) {
      return (_events[eventName] || []).concat(_eventsAnything);
    };

    function _fireLoop(eventName, eventArgs, events, callback, i, results) {
      i = i || 0;
      results = results || [];

      if (i === events.length) {
        if (callback) {
          callback(results);
        }

        return;
      }

      var evt = events[i];

      if (evt) {
        var eventInstance = new EventInstance(eventName, evt.namespace);

        if (evt.async) {
          evt.func.call(eventInstance, eventArgs, function(result) {
            results.push(typeof result == 'undefined' ? null : result);

            _fireLoop(eventName, eventArgs, events, callback,
              eventInstance.isStoppedPropagation() ? events.length : i + 1,
              results
            );
          });

          return;
        }

        var result = evt.func.call(eventInstance, eventArgs);

        results.push(typeof result == 'undefined' ? null : result);

        _fireLoop(eventName, eventArgs, events, callback,
          eventInstance.isStoppedPropagation() ? events.length : i + 1,
          results
        );

        return;
      }

      _fireLoop(eventName, eventArgs, events, callback, i + 1, results);
    }

    this.fire = function(eventName, eventArgs, callback) {
      var values = [];

      if (typeof _events[eventName] != 'undefined') {

        _checkLock(eventName);

        _locks[eventName] = true;

        _fireLoop(eventName, eventArgs, _events[eventName], function(results) {
          if (callback) {
            callback(results);
          }
        });

        delete _locks[eventName];
      }

      if (_eventsAnything.length) {
        _fireLoop(eventName, eventArgs, _eventsAnything, function(results) {
          if (callback) {
            callback(results);
          }
        });
      }

      return values;
    };

    function _on(eventName, eventFunc, priority, async) {
      priority = _priority.formatPriority(priority);

      _checkLock(eventName);

      _formatEventNames(eventName).map(function(name) {
        name = _namespace(name);

        _events[name.name] = _events[name.name] || [];
        _events[name.name].push({
          namespace: name.namespace,
          priority: priority,
          func: eventFunc,
          async: async || false
        });

        _priority.sortByPriority(_events[name.name]);
      });
    }

    this.on = function(eventName, eventFunc, priority) {
      _on(eventName, eventFunc, priority);

      return _this;
    };

    this.onSafe = function(eventName, eventFunc, priority) {
      _this.off(eventName, eventFunc);

      return _this.on(eventName, eventFunc, priority);
    };

    this.onAsync = function(eventName, eventFunc, priority) {
      _on(eventName, eventFunc, priority, true);

      return _this;
    };

    this.onAsyncSafe = function(eventName, eventFunc, priority) {
      _this.off(eventName, eventFunc);

      return _this.onAsync(eventName, eventFunc, priority);
    };

    this.onAnything = function(eventNamespace, eventFunc, priority) {
      priority = _priority.formatPriority(priority);

      _eventsAnything.push({
        namespace: eventNamespace,
        priority: priority,
        func: eventFunc
      });

      return _this;
    };

    this.onAnythingSafe = function(eventNamespace, eventFunc, priority) {
      _this.offAnything(eventNamespace, eventFunc);

      return _this.onAnything(eventNamespace, eventFunc, priority);
    };

    this.off = function(eventName, eventFunc) {
      _checkLock(eventName);

      _formatEventNames(eventName).map(function(name) {
        name = _namespace(name);

        if (typeof _events[name.name] != 'undefined') {
          for (var i = 0, len = _events[name.name].length; i < len; i++) {
            if (name.namespace && _events[name.name][i].namespace != name.namespace) {
              continue;
            }

            if (_events[name.name][i].func.toString() == eventFunc.toString()) {
              _events[name.name].splice(i, 1);
              break;
            }
          }
        }
      });

      return _this;
    };

    function _offAnything(eventNamespace, eventFunc, entireNamespace) {
      for (var i = 0, len = _eventsAnything.length; i < len; i++) {
        if (_eventsAnything[i].namespace != eventNamespace) {
          continue;
        }

        if (entireNamespace || _eventsAnything[i].func.toString() == eventFunc.toString()) {
          _eventsAnything.splice(i, 1);

          break;
        }
      }
    }

    this.offAnything = function(eventNamespace, eventFunc) {
      _offAnything(eventNamespace, eventFunc);

      return _this;
    };

    this.offNamespace = function(namespace) {
      var name;

      for (name in _events) {
        var event = _events[name],
            newEvent = [];

        for (var i = event.length - 1; i >= 0; i--) {
          if (event[i].namespace !== namespace) {
            newEvent.push(event[i]);
          }
        }

        if (newEvent.length !== event.length) {
          _checkLock(name);
          _events[name] = newEvent;
        }
      }

      _offAnything(namespace, null, true);

      return _this;
    };

    this.offAll = function() {
      _events = [];
      _eventsAnything = [];
    };

  };

})(typeof exports == 'undefined' ? this : exports);
<commit_msg>fix(events-manager): use warning instead of error for lock checking<commit_after>(function(exports) {
  'use strict';

  if (exports.EventsManager) {
    return;
  }

  var EventInstance = function(name, namespace) {
    var _isStoppedPropagation = false;

    this.name = name;
    this.namespace = namespace;

    this.stopPropagation = function() {
      _isStoppedPropagation = true;
    };

    this.isStoppedPropagation = function() {
      return _isStoppedPropagation;
    };

    this.resetStopPropagation = function() {
      _isStoppedPropagation = false;
    };
  };

  var EventPriority = function() {
    var _priorities = {
      low: -1,
      normal: 0,
      high: 9999999
    };

    this.formatPriority = function(priority) {
      if (typeof priority == 'undefined' || priority === null) {
        priority = 'normal';
      }

      if (typeof priority == 'string') {
        if (!(priority in _priorities)) {
          priority = 'normal';
        }
        priority = _priorities[priority];
      }

      return priority;
    };

    this.sortByPriority = function(list) {
      list.sort(function(a, b) {
        return b.priority - a.priority;
      });
    };

  };

  exports.EventsManager = function() {

    var _this = this,
        _events = [],
        _eventsAnything = [],
        _priority = new EventPriority(),
        _locks = {};

    function _formatEventNames(eventName) {
      var events = [];

      eventName.split(' ').map(function(name) {
        if (name) {
          events.push(name);
        }
      });

      return events;
    }

    function _namespace(eventName) {
      var namespace = null;
      eventName = eventName.split('.');
      if (eventName.length > 1) {
        namespace = eventName[0];
        eventName = eventName[1];
      }
      else {
        eventName = eventName[0];
      }

      return {
        name: eventName,
        namespace: namespace
      };
    }

    function _checkLock(eventName) {
      if (_locks[eventName]) {
        console.warn('EventsManager: Be careful, event "' + eventName + '" is locked for use');
      }
    }

    this.eventsName = function() {
      var names = [],
          name = null;

      for (name in _events) {
        names.push(name);
      }

      return names;
    };

    this.eventsStack = function(eventName) {
      return (_events[eventName] || []).concat(_eventsAnything);
    };

    function _fireLoop(eventName, eventArgs, events, callback, i, results) {
      i = i || 0;
      results = results || [];

      if (i === events.length) {
        if (callback) {
          callback(results);
        }

        return;
      }

      var evt = events[i];

      if (evt) {
        var eventInstance = new EventInstance(eventName, evt.namespace);

        if (evt.async) {
          evt.func.call(eventInstance, eventArgs, function(result) {
            results.push(typeof result == 'undefined' ? null : result);

            _fireLoop(eventName, eventArgs, events, callback,
              eventInstance.isStoppedPropagation() ? events.length : i + 1,
              results
            );
          });

          return;
        }

        var result = evt.func.call(eventInstance, eventArgs);

        results.push(typeof result == 'undefined' ? null : result);

        _fireLoop(eventName, eventArgs, events, callback,
          eventInstance.isStoppedPropagation() ? events.length : i + 1,
          results
        );

        return;
      }

      _fireLoop(eventName, eventArgs, events, callback, i + 1, results);
    }

    this.fire = function(eventName, eventArgs, callback) {
      var values = [];

      if (typeof _events[eventName] != 'undefined') {

        _checkLock(eventName);

        _locks[eventName] = true;

        _fireLoop(eventName, eventArgs, _events[eventName], function(results) {
          if (callback) {
            callback(results);
          }
        });

        delete _locks[eventName];
      }

      if (_eventsAnything.length) {
        _fireLoop(eventName, eventArgs, _eventsAnything, function(results) {
          if (callback) {
            callback(results);
          }
        });
      }

      return values;
    };

    function _on(eventName, eventFunc, priority, async) {
      priority = _priority.formatPriority(priority);

      _checkLock(eventName);

      _formatEventNames(eventName).map(function(name) {
        name = _namespace(name);

        _events[name.name] = _events[name.name] || [];
        _events[name.name].push({
          namespace: name.namespace,
          priority: priority,
          func: eventFunc,
          async: async || false
        });

        _priority.sortByPriority(_events[name.name]);
      });
    }

    this.on = function(eventName, eventFunc, priority) {
      _on(eventName, eventFunc, priority);

      return _this;
    };

    this.onSafe = function(eventName, eventFunc, priority) {
      _this.off(eventName, eventFunc);

      return _this.on(eventName, eventFunc, priority);
    };

    this.onAsync = function(eventName, eventFunc, priority) {
      _on(eventName, eventFunc, priority, true);

      return _this;
    };

    this.onAsyncSafe = function(eventName, eventFunc, priority) {
      _this.off(eventName, eventFunc);

      return _this.onAsync(eventName, eventFunc, priority);
    };

    this.onAnything = function(eventNamespace, eventFunc, priority) {
      priority = _priority.formatPriority(priority);

      _eventsAnything.push({
        namespace: eventNamespace,
        priority: priority,
        func: eventFunc
      });

      return _this;
    };

    this.onAnythingSafe = function(eventNamespace, eventFunc, priority) {
      _this.offAnything(eventNamespace, eventFunc);

      return _this.onAnything(eventNamespace, eventFunc, priority);
    };

    this.off = function(eventName, eventFunc) {
      _checkLock(eventName);

      _formatEventNames(eventName).map(function(name) {
        name = _namespace(name);

        if (typeof _events[name.name] != 'undefined') {
          for (var i = 0, len = _events[name.name].length; i < len; i++) {
            if (name.namespace && _events[name.name][i].namespace != name.namespace) {
              continue;
            }

            if (_events[name.name][i].func.toString() == eventFunc.toString()) {
              _events[name.name].splice(i, 1);
              break;
            }
          }
        }
      });

      return _this;
    };

    function _offAnything(eventNamespace, eventFunc, entireNamespace) {
      for (var i = 0, len = _eventsAnything.length; i < len; i++) {
        if (_eventsAnything[i].namespace != eventNamespace) {
          continue;
        }

        if (entireNamespace || _eventsAnything[i].func.toString() == eventFunc.toString()) {
          _eventsAnything.splice(i, 1);

          break;
        }
      }
    }

    this.offAnything = function(eventNamespace, eventFunc) {
      _offAnything(eventNamespace, eventFunc);

      return _this;
    };

    this.offNamespace = function(namespace) {
      var name;

      for (name in _events) {
        var event = _events[name],
            newEvent = [];

        for (var i = event.length - 1; i >= 0; i--) {
          if (event[i].namespace !== namespace) {
            newEvent.push(event[i]);
          }
        }

        if (newEvent.length !== event.length) {
          _checkLock(name);
          _events[name] = newEvent;
        }
      }

      _offAnything(namespace, null, true);

      return _this;
    };

    this.offAll = function() {
      _events = [];
      _eventsAnything = [];
    };

  };

})(typeof exports == 'undefined' ? this : exports);
<|endoftext|>


<commit_before>var Aquaplane = {};

Aquaplane.Preloader = function () {};

Aquaplane.Preloader.prototype = {

    init: function () {

        this.input.maxPointers = 1;

        this.scale.pageAlignHorizontally = true;

    },

    preload: function () {

        this.load.path = 'assets/';

        this.load.bitmapFont('fat-and-tiny');
        this.load.bitmapFont('interfont');

        this.load.images('Blank', 'pole', 'rock', 'shark', 'background', 'low-rez-corgi']);
        this.load.spritesheet('waves', 'waves.png', 16, 6);
       // var sea = this.load.image('background', 'background.png');
      //  background.height = game.height
      //  background.width = game.width

    },

    create: function () {

        this.state.start('Aquaplane.MainMenu');

    }

};

Aquaplane.MainMenu = function () {};

Aquaplane.MainMenu.prototype = {

    create: function () {

        this.add.image(0, 0, 'sea');

        var logo = this.add.image(this.world.centerX, 200, 'logo');
        logo.anchor.x = 0.5;

        var start = this.add.bitmapText(this.world.centerX, 460, 'fat-and-tiny', 'CLICK TO PLAY', 64);
        start.anchor.x = 0.5;
        start.smoothed = false;
        start.tint = 0xff0000;

        this.input.onDown.addOnce(this.start, this);

    },

    start: function () {

        this.state.start('Aquaplane.Game');

    }

};

Aquaplane.Game = function (game) {

    this.score = 0;
    this.scoreText = null;

    this.lives = 3;
    this.livesText = null;

    this.speed = 420;
    this.lastKey = 0;
    this.ready = false;

    this.layer = null;
    this.itemDist = ['pole', 'pole', 'pole', 'rock', 'rock', 'rock', 'shark'];

    this.boat = null;
    this.skier = null;
    this.rope = null;

    this.timer = null;
    this.itemInterval = { count: 0, min: 500, max: 1500 };

    this.pauseKey = null;
    this.debugKey = null;
    this.showDebug = false;

};

Aquaplane.Game.prototype = {

    init: function () {

        this.score = 0;
        this.lives = 3;
        this.speed = 420;

        this.ready = false;
        this.lastKey = 0;

        this.timer = this.time.create(false);
        this.itemInterval = { count: 0, min: 500, max: 1500 };

        this.physics.startSystem(Phaser.Physics.P2JS);
        this.physics.p2.gravity.y = 0;

        this.showDebug = false;

    },

    create: function () {

        this.add.image(0, 0, 'sea');
         sea.height = game.height
         sea.width = game.width

        this.waterParticle = this.make.bitmapData(2, 2);
        this.waterParticle.rect(0, 0, 2, 2, '#ffffff');
        this.waterParticle.update();

        this.emitter = this.add.emitter(0, 0, 128);
        this.emitter.makeParticles(this.waterParticle);

        this.emitter.gravity = 0;
        this.emitter.setXSpeed(-100, -250);
        this.emitter.setYSpeed(-100, 100);

        this.emitter.setAlpha(1, 0.2, 500);

        this.emitter.flow(500, 20, 2, -1, true);

        this.layer = this.add.group();

        this.boat = this.layer.create(0, 0, 'low-rez-corgi');

        this.physics.p2.enable(this.boat, false);

        this.boat.body.mass = 1;
        this.boat.body.damping = 0.5;
        this.boat.body.fixedRotation = true;
        this.boat.body.collideWorldBounds = false;

        this.skier = this.layer.create(0, 0, 'skier');

        this.physics.p2.enable(this.skier, false);

        this.skier.body.mass = 0.05;
        this.skier.body.damping = 0.5;
        this.skier.body.fixedRotation = true;
        this.skier.body.collideWorldBounds = false;

        this.boatBounds = new Phaser.Rectangle(0, 0, 60, 10);
        //this.skierBounds = new Phaser.Rectangle(0, 0, 30, 8);
        this.skierBounds = new Phaser.Rectangle(0, 0, 0, 0);

        var rev = new p2.RevoluteConstraint(this.boat.body.data, this.skier.body.data, {
                localPivotA: [9, 0],
                localPivotB: [2, 0],
                collideConnected: false
            });

        this.physics.p2.world.addConstraint(rev);

        rev.setLimits(this.math.degToRad(-40), this.math.degToRad(40));

        rev.setStiffness(2.0);

        //  Let's create some waves (harmless eye candy)
        //
        //  Divide screen vertically into 520px / 8 layers = 65px per layer
        //  Place 8 waves per layer (8*8 total)

        var area = new Phaser.Rectangle(0, 80, this.game.width, 65);

        for (var i = 1; i <= 8; i++)
        {
            for (var w = 0; w < 8; w++)
            {
                var wave = this.layer.create(area.randomX, area.randomY, 'waves', this.rnd.between(0, 2));
                wave.anchor.y = -1.5;
                this.physics.arcade.enable(wave);
                wave.body.velocity.x = -120 + (i * -30);
            }

            area.y += 65;
        }

        this.line = new Phaser.Line(this.boat.x - 28, this.boat.y, this.skier.x + 6, this.skier.y - 1);

        //  The rope that attaches the water skier to the boat
        this.rope = this.add.graphics(0, 0);

        this.scoreText = this.add.bitmapText(16, 0, 'fat-and-tiny', 'SCORE: 0', 32);
        this.scoreText.smoothed = false;

        this.livesText = this.add.bitmapText(680, 0, 'fat-and-tiny', 'LIVES: ' + this.lives, 32);
        this.livesText.smoothed = false;

        this.cursors = this.input.keyboard.createCursorKeys();

        //  Press P to pause and resume the game
        this.pauseKey = this.input.keyboard.addKey(Phaser.Keyboard.P);
        this.pauseKey.onDown.add(this.togglePause, this);

        //  Press D to toggle the debug display
        this.debugKey = this.input.keyboard.addKey(Phaser.Keyboard.D);
        this.debugKey.onDown.add(this.toggleDebug, this);

        this.bringBoatOn();

    },

    togglePause: function () {

        this.game.paused = (this.game.paused) ? false : true;

    },

    toggleDebug: function () {

        this.showDebug = (this.showDebug) ? false : true;

    },

    bringBoatOn: function () {

        this.ready = false;

        this.boat.body.x = -64;
        this.boat.body.y = 300;

        this.skier.visible = true;
        this.skier.body.x = -264;
        this.skier.body.y = 300;

        this.boat.body.velocity.x = 300;

    },

    boatReady: function () {

        this.ready = true;

        this.boat.body.setZeroVelocity();

        this.timer.add(this.itemInterval.max, this.releaseItem, this);
        this.timer.start();

    },

    releaseItem: function (x, y) {

        if (x === undefined) { x = 800; }
        if (y === undefined) { y = this.rnd.between(80, 487); }

        var frame = this.rnd.pick(this.itemDist);

        var item = this.layer.getFirstDead(true, x, y, frame);

        this.physics.arcade.enable(item);

        if (frame === 'shark')
        {
            item.body.setSize(32, 14, 0, 16);
        }
        else
        {
            item.body.setSize(16, 8, 0, 24);
        }

        var i = this.math.snapToFloor(y, 65) / 65;

        item.body.velocity.x = -120 + (i * -30);

        this.itemInterval.count++;

        //  Every 10 new items we'll speed things up a bit
        if (this.itemInterval.min > 100 && this.itemInterval.count % 10 === 0)
        {
            this.itemInterval.min -= 10;
            this.itemInterval.max -= 10;
        }

        //  Is the player idle? Then release another item directly towards them
        if ((this.time.time - this.lastKey) > 200)
        {
            this.lastKey = this.time.time;
            this.releaseItem(800, this.skier.y - 16);
        }
        else
        {
            this.timer.add(this.rnd.between(this.itemInterval.min, this.itemInterval.max), this.releaseItem, this);
        }

    },

    update: function () {

        this.layer.sort('y', Phaser.Group.SORT_ASCENDING);

        if (this.ready)
        {
            this.updateBoat();

            //  Score based on their position on the screen
            this.score += (this.math.snapToFloor(this.skier.y, 65) / 65);
            this.scoreText.text = "SCORE: " + this.score;
        }
        else
        {
            if (this.skier.visible)
            {
                if (this.boat.x >= 250)
                {
                    this.boatReady();
                }
            }
            else
            {
                if (this.boat.x >= 832)
                {
                    this.bringBoatOn();
                }
            }
        }

        this.boatBounds.centerOn(this.boat.x + 4, this.boat.y + 8);
        this.skierBounds.centerOn(this.skier.x + 2, this.skier.y + 10);

        this.emitter.emitX = this.boat.x - 16;
        this.emitter.emitY = this.boat.y + 10;

        //  Let's sort and collide
        this.layer.forEachAlive(this.checkItem, this);

    },

    updateBoat: function () {

        if (this.boat.x < 200)
        {
            this.boat.body.setZeroForce();
            this.boat.body.x = 200;
        }
        else if (this.boat.x > 750)
        {
            this.boat.body.setZeroForce();
            this.boat.body.x = 750;
        }

        if (this.boat.y < 100)
        {
            this.boat.body.setZeroForce();
            this.boat.body.y = 100;
        }
        else if (this.boat.y > 550)
        {
            this.boat.body.setZeroForce();
            this.boat.body.y = 550;
        }

        if (this.cursors.left.isDown)
        {
            this.boat.body.force.x = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.right.isDown)
        {
            this.boat.body.force.x = this.speed;
            this.lastKey = this.time.time;
        }

        if (this.cursors.up.isDown)
        {
            this.boat.body.force.y = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.down.isDown)
        {
            this.boat.body.force.y = this.speed;
            this.lastKey = this.time.time;
        }

    },

    checkItem: function (item) {

        if (item === this.boat || item === this.skier)
        {
            return;
        }

        if (item.x < -32)
        {
            if (item.key === 'waves')
            {
                item.x = this.rnd.between(800, 864);
            }
            else
            {
                item.kill();
            }
        }
        else
        {
            //   Check for collision
           //if (this.ready && item.key !== 'waves' && this.skierBounds.intersects(item.body))
             if (this.ready && item.key !== 'waves' && this.boatBounds.intersects(item.body))
            {
                this.loseLife();
            }
        }

    },

    loseLife: function () {

        if (this.lives === 0)
        {
            this.gameOver();
        }
        else
        {
            this.lives--;

            this.livesText.text = "LIVES: " + this.lives;

            this.ready = false;

            //  Kill the surfer!
            this.boat.visible = false;

            //  Hide the rope
            this.rope.clear();

            //  Speed the boat away
            this.boat.body.setZeroVelocity();
            this.boat.body.velocity.x = 600;

            this.itemInterval.min += 200;
            this.itemInterval.max += 200;
        }

    },

    gameOver: function () {

        this.state.start('Aquaplane.MainMenu');

    },

    preRender: function () {

        this.line.setTo(this.boat.x - 28, this.boat.y, this.skier.x + 6, this.skier.y - 1);

        if (this.skier.visible)
        {
            this.rope.clear();
            this.rope.lineStyle(1, 0xffffff, 0);
            this.rope.moveTo(this.line.start.x, this.line.start.y);
            this.rope.lineTo(this.line.end.x, this.line.end.y);
            this.rope.endFill();
        }

    },

    render: function () {

        if (this.showDebug)
        {
            this.game.debug.geom(this.boatBounds);
            this.game.debug.geom(this.skierBounds);
            this.layer.forEachAlive(this.renderBody, this);
            this.game.debug.geom(this.skier.position, 'rgba(255,255,0,1)');
        }

    },

    renderBody: function (sprite) {

        if (sprite === this.boat || sprite === this.skier || sprite.key === 'waves')
        {
            return;
        }

        this.game.debug.body(sprite);

    }

};

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'game');

game.state.add('Aquaplane.Preloader', Aquaplane.Preloader);
game.state.add('Aquaplane.MainMenu', Aquaplane.MainMenu);
game.state.add('Aquaplane.Game', Aquaplane.Game);

game.state.start('Aquaplane.Preloader');
<commit_msg>Create game.js<commit_after>var Aquaplane = {};

Aquaplane.Preloader = function () {};

Aquaplane.Preloader.prototype = {

    init: function () {

        this.input.maxPointers = 1;

        this.scale.pageAlignHorizontally = true;

    },

    preload: function () {

        this.load.path = 'assets/';

        this.load.bitmapFont('fat-and-tiny');
        this.load.bitmapFont('interfont');

        this.load.images('Blank', 'pole', 'rock', 'shark', 'background', 'low-rez-corgi']);
        this.load.spritesheet('waves', 'waves.png', 16, 6);
       // var sea = this.load.image('background', 'background.png');
      //  background.height = game.height
      //  background.width = game.width

    },

    create: function () {

        this.state.start('Aquaplane.MainMenu');

    }

};

Aquaplane.MainMenu = function () {};

Aquaplane.MainMenu.prototype = {

    create: function () {

        this.add.image(0, 0, 'sea');

        var logo = this.add.image(this.world.centerX, 200, 'logo');
        logo.anchor.x = 0.5;

        var start = this.add.bitmapText(this.world.centerX, 460, 'fat-and-tiny', 'CLICK TO PLAY', 64);
        start.anchor.x = 0.5;
        start.smoothed = false;
        start.tint = 0xff0000;

        this.input.onDown.addOnce(this.start, this);

    },

    start: function () {

        this.state.start('Aquaplane.Game');

    }

};

Aquaplane.Game = function (game) {

    this.score = 0;
    this.scoreText = null;

    this.lives = 3;
    this.livesText = null;

    this.speed = 420;
    this.lastKey = 0;
    this.ready = false;

    this.layer = null;
    this.itemDist = ['pole', 'pole', 'pole', 'rock', 'rock', 'rock', 'shark'];

    this.boat = null;
    this.skier = null;
    this.rope = null;

    this.timer = null;
    this.itemInterval = { count: 0, min: 500, max: 1500 };

    this.pauseKey = null;
    this.debugKey = null;
    this.showDebug = false;

};

Aquaplane.Game.prototype = {

    init: function () {

        this.score = 0;
        this.lives = 3;
        this.speed = 420;

        this.ready = false;
        this.lastKey = 0;

        this.timer = this.time.create(false);
        this.itemInterval = { count: 0, min: 500, max: 1500 };

        this.physics.startSystem(Phaser.Physics.P2JS);
        this.physics.p2.gravity.y = 0;

        this.showDebug = false;

    },

    create: function () {

        this.add.image(0, 0, 'sea');
         sea.height = game.height
         sea.width = game.width

        this.waterParticle = this.make.bitmapData(2, 2);
        this.waterParticle.rect(0, 0, 2, 2, '#ffffff');
        this.waterParticle.update();

        this.emitter = this.add.emitter(0, 0, 128);
        this.emitter.makeParticles(this.waterParticle);

        this.emitter.gravity = 0;
        this.emitter.setXSpeed(-100, -250);
        this.emitter.setYSpeed(-100, 100);

        this.emitter.setAlpha(1, 0.2, 500);

        this.emitter.flow(500, 20, 2, -1, true);

        this.layer = this.add.group();

        this.boat = this.layer.create(0, 0, 'low-rez-corgi');

        this.physics.p2.enable(this.boat, false);

        this.boat.body.mass = 1;
        this.boat.body.damping = 0.5;
        this.boat.body.fixedRotation = true;
        this.boat.body.collideWorldBounds = false;

        this.skier = this.layer.create(0, 0, 'skier');

        this.physics.p2.enable(this.skier, false);

        this.skier.body.mass = 0.05;
        this.skier.body.damping = 0.5;
        this.skier.body.fixedRotation = true;
        this.skier.body.collideWorldBounds = false;

        this.boatBounds = new Phaser.Rectangle(0, 0, 60, 10);
        //this.skierBounds = new Phaser.Rectangle(0, 0, 30, 8);
        this.skierBounds = new Phaser.Rectangle(0, 0, 0, 0);

        var rev = new p2.RevoluteConstraint(this.boat.body.data, this.skier.body.data, {
                localPivotA: [9, 0],
                localPivotB: [2, 0],
                collideConnected: false
            });

        this.physics.p2.world.addConstraint(rev);

        rev.setLimits(this.math.degToRad(-40), this.math.degToRad(40));

        rev.setStiffness(2.0);

        //  Let's create some waves (harmless eye candy)
        //
        //  Divide screen vertically into 520px / 8 layers = 65px per layer
        //  Place 8 waves per layer (8*8 total)

        var area = new Phaser.Rectangle(0, 80, this.game.width, 65);

        for (var i = 1; i <= 8; i++)
        {
            for (var w = 0; w < 8; w++)
            {
                var wave = this.layer.create(area.randomX, area.randomY, 'waves', this.rnd.between(0, 2));
                wave.anchor.y = -1.5;
                this.physics.arcade.enable(wave);
                wave.body.velocity.x = -120 + (i * -30);
            }

            area.y += 65;
        }

        this.line = new Phaser.Line(this.boat.x - 28, this.boat.y, this.skier.x + 6, this.skier.y - 1);

        //  The rope that attaches the water skier to the boat
        this.rope = this.add.graphics(0, 0);

        this.scoreText = this.add.bitmapText(16, 0, 'fat-and-tiny', 'SCORE: 0', 32);
        this.scoreText.smoothed = false;

        this.livesText = this.add.bitmapText(680, 0, 'fat-and-tiny', 'LIVES: ' + this.lives, 32);
        this.livesText.smoothed = false;

        this.cursors = this.input.keyboard.createCursorKeys();

        //  Press P to pause and resume the game
        this.pauseKey = this.input.keyboard.addKey(Phaser.Keyboard.P);
        this.pauseKey.onDown.add(this.togglePause, this);

        //  Press D to toggle the debug display
        this.debugKey = this.input.keyboard.addKey(Phaser.Keyboard.D);
        this.debugKey.onDown.add(this.toggleDebug, this);

        this.bringBoatOn();

    },

    togglePause: function () {

        this.game.paused = (this.game.paused) ? false : true;

    },

    toggleDebug: function () {

        this.showDebug = (this.showDebug) ? false : true;

    },

    bringBoatOn: function () {

        this.ready = false;

        this.boat.body.x = -64;
        this.boat.body.y = 300;

        this.skier.visible = true;
        this.skier.body.x = -264;
        this.skier.body.y = 300;

        this.boat.body.velocity.x = 300;

    },

    boatReady: function () {

        this.ready = true;

        this.boat.body.setZeroVelocity();

        this.timer.add(this.itemInterval.max, this.releaseItem, this);
        this.timer.start();

    },

    releaseItem: function (x, y) {

        if (x === undefined) { x = 800; }
        if (y === undefined) { y = this.rnd.between(80, 487); }

        var frame = this.rnd.pick(this.itemDist);

        var item = this.layer.getFirstDead(true, x, y, frame);

        this.physics.arcade.enable(item);

        if (frame === 'shark')
        {
            item.body.setSize(32, 14, 0, 16);
        }
        else
        {
            item.body.setSize(16, 8, 0, 24);
        }

        var i = this.math.snapToFloor(y, 65) / 65;

        item.body.velocity.x = -120 + (i * -30);

        this.itemInterval.count++;

        //  Every 10 new items we'll speed things up a bit
        if (this.itemInterval.min > 100 && this.itemInterval.count % 10 === 0)
        {
            this.itemInterval.min -= 10;
            this.itemInterval.max -= 10;
        }

        //  Is the player idle? Then release another item directly towards them
        if ((this.time.time - this.lastKey) > 200)
        {
            this.lastKey = this.time.time;
            this.releaseItem(800, this.skier.y - 16);
        }
        else
        {
            this.timer.add(this.rnd.between(this.itemInterval.min, this.itemInterval.max), this.releaseItem, this);
        }

    },

    update: function () {

        this.layer.sort('y', Phaser.Group.SORT_ASCENDING);

        if (this.ready)
        {
            this.updateBoat();

            //  Score based on their position on the screen
            this.score += (this.math.snapToFloor(this.skier.y, 65) / 65);
            this.scoreText.text = "SCORE: " + this.score;
        }
        else
        {
            if (this.skier.visible)
            {
                if (this.boat.x >= 250)
                {
                    this.boatReady();
                }
            }
            else
            {
                if (this.boat.x >= 832)
                {
                    this.bringBoatOn();
                }
            }
        }

        this.boatBounds.centerOn(this.boat.x + 4, this.boat.y + 8);
        this.skierBounds.centerOn(this.skier.x + 2, this.skier.y + 10);

        this.emitter.emitX = this.boat.x - 16;
        this.emitter.emitY = this.boat.y + 10;

        //  Let's sort and collide
        this.layer.forEachAlive(this.checkItem, this);

    },

    updateBoat: function () {

        if (this.boat.x < 200)
        {
            this.boat.body.setZeroForce();
            this.boat.body.x = 200;
        }
        else if (this.boat.x > 750)
        {
            this.boat.body.setZeroForce();
            this.boat.body.x = 750;
        }

        if (this.boat.y < 100)
        {
            this.boat.body.setZeroForce();
            this.boat.body.y = 100;
        }
        else if (this.boat.y > 550)
        {
            this.boat.body.setZeroForce();
            this.boat.body.y = 550;
        }

        if (this.cursors.left.isDown)
        {
            this.boat.body.force.x = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.right.isDown)
        {
            this.boat.body.force.x = this.speed;
            this.lastKey = this.time.time;
        }

        if (this.cursors.up.isDown)
        {
            this.boat.body.force.y = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.down.isDown)
        {
            this.boat.body.force.y = this.speed;
            this.lastKey = this.time.time;
        }

    },

    checkItem: function (item) {

        if (item === this.boat || item === this.skier)
        {
            return;
        }

        if (item.x < -32)
        {
            if (item.key === 'waves')
            {
                item.x = this.rnd.between(800, 864);
            }
            else
            {
                item.kill();
            }
        }
        else
        {
            //   Check for collision
           //if (this.ready && item.key !== 'waves' && this.skierBounds.intersects(item.body))
             if (this.ready && item.key !== 'waves' && this.boatBounds.intersects(item.body))
            {
                this.loseLife();
            }
        }

    },

    loseLife: function () {

        if (this.lives === 0)
        {
            this.gameOver();
        }
        else
        {
            this.lives--;

            this.livesText.text = "LIVES: " + this.lives;

            this.ready = false;

            //  Kill the surfer!
            this.boat.visible = false;

            //  Hide the rope
            this.rope.clear();

            //  Speed the boat away
            this.boat.body.setZeroVelocity();
            this.boat.body.velocity.x = 600;

            this.itemInterval.min += 200;
            this.itemInterval.max += 200;
        }

    },

    gameOver: function () {

        this.state.start('Aquaplane.MainMenu');

    },

    preRender: function () {

        this.line.setTo(this.boat.x - 28, this.boat.y, this.skier.x + 6, this.skier.y - 1);

        if (this.skier.visible)
        {
            this.rope.clear();
            this.rope.lineStyle(1, 0xffffff, 0);
            this.rope.moveTo(this.line.start.x, this.line.start.y);
            this.rope.lineTo(this.line.end.x, this.line.end.y);
            this.rope.endFill();
        }

    },

    render: function () {

        if (this.showDebug)
        {
            this.game.debug.geom(this.boatBounds);
            this.game.debug.geom(this.skierBounds);
            this.layer.forEachAlive(this.renderBody, this);
            this.game.debug.geom(this.skier.position, 'rgba(255,255,0,1)');
        }

    },

    renderBody: function (sprite) {

        if (sprite === this.boat || sprite === this.skier || sprite.key === 'waves')
        {
            return;
        }

        this.game.debug.body(sprite);

    }

};

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'game');

game.state.add('Aquaplane.Preloader', Aquaplane.Preloader);
game.state.add('Aquaplane.MainMenu', Aquaplane.MainMenu);
game.state.add('Aquaplane.Game', Aquaplane.Game);

game.state.start('Aquaplane.Preloader');

<|endoftext|>


<commit_before>/*
    A small plugin made for especially for UORPG chat server
*/

var core = undefined;

var UORPG_Server = "177730395352072192";

var Chan_RUS = "203294045689217024";
var Chan_ENG = "199908461549584384";

function isRussian(chan)
{
    return (chan.id == Chan_RUS);
}

function getChaos(guild)
{
    return guild.roles.find('name', 'Chaos');
}

function getOrder(guild)
{
    return guild.roles.find('name', 'Order');
}

var joinOrder = function(bot, message, args)
{
    var chaos = getChaos(message.guild);
    var order = getOrder(message.guild);
    var member = message.guild.members.get(message.author.id);
    member.removeRole(chaos);
    member.addRole(order);
    message.reply("Welcome to Order!", core.msgSendError);
}

var joinChaos = function(bot, message, args)
{
    var chaos = getChaos(message.guild);
    var order = getOrder(message.guild);
    var member = message.guild.members.get(message.author.id);
    member.removeRole(order);
    member.addRole(chaos);
    message.reply("Welcome to Chaos!", core.msgSendError);
}

var crystalPhase = function(bot, message, args)
{
    var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
    var firstDate = new Date(2017,11,1);//Точка отсчёта чётности
    var secondDate = new Date();

    var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

    var ru = bot.channels.get(Chan_RUS);
    //var en = bot.channels.get(Chan_ENG);

    var crystal_peace;
    var crystal_war;

    if(message.channel.id == ru.id)
    {
        crystal_peace = "# Кристал в мирной проекции мира.";
        crystal_war = "# Кристал в боевой проекции мира.";
    }
    else
    {
        crystal_peace = "# The Crystal is in the world projection of the peace.";
        crystal_war = "# The Crystal is in the world projection of the war.";
    }

    if((diffDays % 2) == 0)
        message.channel.send(crystal_peace).catch(core.msgSendError);
    else
        message.channel.send(crystal_war).catch(core.msgSendError);
}

function registerCommands(foxyCore)
{
    core = foxyCore;
    core.addCMD(["order",      joinOrder,           "Join The Order Alliance - Holy Empire and Insurgents!!!", [], true, [UORPG_Server] ]);
    core.addCMD(["chaos",      joinChaos,           "Join The Chaos Alliance - Army of Darkness and The Shadows!!!", [], true, [UORPG_Server] ]);
    core.addCMD(["crystal",    crystalPhase,        "Show projection where crystal is located", [], true, [UORPG_Server] ]);
}

function guildMemberAdd(bot, guildMember)
{
    // console.log("Кто-то новенький! " + guildMember.user.id +
    // " на серваке " + guildMember.guild.id + " == " + UORPG_Server);
    if(guildMember.guild.id == UORPG_Server)
    {
        var ru = bot.channels.get(Chan_RUS);
        var en = bot.channels.get(Chan_ENG);

        var message_ru =
            "<@" + guildMember.user.id +">, Приветствуем вас на сервере Ultima Online - UORPG.net!\n\n" +
            "Выберите вашу фракцию:\n" +
            "Альянс Порядок - Священная Империя и Повстанцы\n" +
            "Альянс Хаос - Армия Тьмы и Тени\n\n" +
            "Для того, чтобы выбрать вашу сторону в войне напишите в чате: /foxy order или /foxy chaos";
        var message_en =
            "<@" + guildMember.user.id +">, Hi, welcome to Ultima Online server - UORPG.net!\n\n" +
            "Assign your faction please:\n" +
            "The Order Alliance - Holy Empire and Insurgents\n" +
            "The Chaos Alliance - Army of Darkness and The Shadows\n\n"+
            "In order to confirm your war force, type: /foxy order ;  /foxy chaos";

        ru.send(message_ru).catch(core.msgSendError);
        en.send(message_en).catch(core.msgSendError);
    }
}

module.exports =
{
    registerCommands:   registerCommands,
    guildMemberAdd:     guildMemberAdd
};
<commit_msg>UORGP Things: Fixed English Crystal notify and added Latvian translate of it<commit_after>/*
    A small plugin made for especially for UORPG chat server
*/

var core = undefined;

var UORPG_Server = "177730395352072192";

var Chan_RUS = "203294045689217024";
var Chan_ENG = "199908461549584384";
var Chan_LAT = "369616743200456715";

function isRussian(chan)
{
    return (chan.id == Chan_RUS);
}

function getChaos(guild)
{
    return guild.roles.find('name', 'Chaos');
}

function getOrder(guild)
{
    return guild.roles.find('name', 'Order');
}

var joinOrder = function(bot, message, args)
{
    var chaos = getChaos(message.guild);
    var order = getOrder(message.guild);
    var member = message.guild.members.get(message.author.id);
    member.removeRole(chaos);
    member.addRole(order);
    message.reply("Welcome to Order!", core.msgSendError);
}

var joinChaos = function(bot, message, args)
{
    var chaos = getChaos(message.guild);
    var order = getOrder(message.guild);
    var member = message.guild.members.get(message.author.id);
    member.removeRole(order);
    member.addRole(chaos);
    message.reply("Welcome to Chaos!", core.msgSendError);
}

var crystalPhase = function(bot, message, args)
{
    var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
    var firstDate = new Date(2017,11,1);//Точка отсчёта чётности
    var secondDate = new Date();

    var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

    var rus = bot.channels.get(Chan_RUS);
    var lat = bot.channels.get(Chan_LAT);
    //var eng = bot.channels.get(Chan_ENG);

    var crystal_peace;
    var crystal_war;

    if(message.channel.id == rus.id)
    {
        crystal_peace = "# Кристал в мирной проекции мира.";
        crystal_war = "# Кристал в боевой проекции мира.";
    }
    else if(message.channel.id == lat.id)
    {
        crystal_peace = "# Crystal mierīgā projekcijas pasaulē.";
        crystal_war = "# Crystal kaujas projekcijas pasaulē.";
    }
    else
    {
        crystal_peace = "# The Crystal is in the peace projection of the world.";
        crystal_war = "# The Crystal is in the war projection of the world.";
    }

    if((diffDays % 2) == 0)
        message.channel.send(crystal_peace).catch(core.msgSendError);
    else
        message.channel.send(crystal_war).catch(core.msgSendError);
}

function registerCommands(foxyCore)
{
    core = foxyCore;
    core.addCMD(["order",      joinOrder,           "Join The Order Alliance - Holy Empire and Insurgents!!!", [], true, [UORPG_Server] ]);
    core.addCMD(["chaos",      joinChaos,           "Join The Chaos Alliance - Army of Darkness and The Shadows!!!", [], true, [UORPG_Server] ]);
    core.addCMD(["crystal",    crystalPhase,        "Show projection where crystal is located", [], true, [UORPG_Server] ]);
}

function guildMemberAdd(bot, guildMember)
{
    // console.log("Кто-то новенький! " + guildMember.user.id +
    // " на серваке " + guildMember.guild.id + " == " + UORPG_Server);
    if(guildMember.guild.id == UORPG_Server)
    {
        var ru = bot.channels.get(Chan_RUS);
        var en = bot.channels.get(Chan_ENG);

        var message_ru =
            "<@" + guildMember.user.id +">, Приветствуем вас на сервере Ultima Online - UORPG.net!\n\n" +
            "Выберите вашу фракцию:\n" +
            "Альянс Порядок - Священная Империя и Повстанцы\n" +
            "Альянс Хаос - Армия Тьмы и Тени\n\n" +
            "Для того, чтобы выбрать вашу сторону в войне напишите в чате: /foxy order или /foxy chaos";
        var message_en =
            "<@" + guildMember.user.id +">, Hi, welcome to Ultima Online server - UORPG.net!\n\n" +
            "Assign your faction please:\n" +
            "The Order Alliance - Holy Empire and Insurgents\n" +
            "The Chaos Alliance - Army of Darkness and The Shadows\n\n"+
            "In order to confirm your war force, type: /foxy order ;  /foxy chaos";

        ru.send(message_ru).catch(core.msgSendError);
        en.send(message_en).catch(core.msgSendError);
    }
}

module.exports =
{
    registerCommands:   registerCommands,
    guildMemberAdd:     guildMemberAdd
};
<|endoftext|>


<commit_before>import { expect } from 'chai';
import * as babel from 'babel-core';
import fs from 'fs';
import polyglotPlugin from 'src/plugin';
import { rmDirSync } from 'src/utils';

describe('Resolve default', () => {
    before(() => {
        rmDirSync('debug');
    });

    it('should strip polyglot tags in any case (without resolve config)', () => {
        const expectedPath = 'tests/fixtures/expected_strip_polyglot_tags.js.src';
        const input = 'console.log(gt`simple string literal`);';
        const customOpts = {
            presets: ['es2015'],
            plugins: [[polyglotPlugin, {}]],
        };
        const result = babel.transform(input, customOpts).code;
        const expected = fs.readFileSync(expectedPath).toString();
        expect(result).to.eql(expected);
    });

});
<commit_msg>fix lint<commit_after>import { expect } from 'chai';
import * as babel from 'babel-core';
import fs from 'fs';
import polyglotPlugin from 'src/plugin';
import { rmDirSync } from 'src/utils';

describe('Resolve default', () => {
    before(() => {
        rmDirSync('debug');
    });

    it('should strip polyglot tags in any case (without resolve config)', () => {
        const expectedPath = 'tests/fixtures/expected_strip_polyglot_tags.js.src';
        const input = 'console.log(gt`simple string literal`);';
        const customOpts = {
            presets: ['es2015'],
            plugins: [[polyglotPlugin, {}]],
        };
        const result = babel.transform(input, customOpts).code;
        const expected = fs.readFileSync(expectedPath).toString();
        expect(result).to.eql(expected);
    });
});
<|endoftext|>


<commit_before>const _ = require('underscore');

module.exports = function (addPrice, addShares, addObj = {}) {
    return new Promise(function (resolve, reject) {
        getPrice()
            .then(price => {
                price.current_price += addPrice;
                price.shares += addShares;

                _.extend(price, addObj);

                setPrice(price)
                    .then(resolve)
                    .catch(reject);
            })
            .catch(reject);
    });
};<commit_msg>Added missing dependencies<commit_after>const _ = require('underscore');
const getPrice = require('./getPrice');
const setPrice = require('./setPrice');

module.exports = function (addPrice, addShares, addObj = {}) {
    return new Promise(function (resolve, reject) {
        getPrice()
            .then(price => {
                price.current_price += addPrice;
                price.shares += addShares;

                _.extend(price, addObj);

                setPrice(price)
                    .then(resolve)
                    .catch(reject);
            })
            .catch(reject);
    });
};<|endoftext|>


<commit_before>(function(Hammer) {
    /**
     * enable multitouch on the desktop by pressing the shiftkey
     * the other touch goes in the opposite direction so the center keeps at its place
     * it's recommended to enable Hammer.debug.showTouches for this one
     */
    Hammer.plugins.fakeMultitouch = function() {
        // keeps the start position to keep it centered
        var start_pos = false;

        /**
         * overwrites Hammer.event.getTouchList.
         * @param   {Event}     ev
         * @param   TOUCHTYPE   type
         * @return  {Array}     Touches
         */
        Hammer.event.getTouchList = function(ev, eventType) {
            // Android, iOS etc
            if(Hammer.HAS_POINTEREVENTS) {
                return Hammer.PointerEvent.getPointers();
            }
            else if(Hammer.HAS_TOUCHEVENTS) {
                return ev.touches;
            }

            // reset on start of a new touch
            if(eventType == Hammer.EVENT_START) {
                start_pos = false;
            }

            // when the shift key is pressed, multitouch is possible on desktop
            // why shift? because ctrl and alt are taken by osx and linux
            if(ev.shiftKey) {
                // on touchstart we store the position of the mouse for multitouch
                if(!start_pos) {
                    start_pos = {
                        pageX: ev.pageX,
                        pageY: ev.pageY
                    };
                }

                // small misplacement to fix NaN/Infinity issues
                var distance_x = start_pos.pageX - ev.pageX;
                var distance_y = start_pos.pageY - ev.pageY;

                // fake second touch in the opposite direction
                return [{
                    identifier: 1,
                    pageX: start_pos.pageX - distance_x - 50,
                    pageY: start_pos.pageY - distance_y - -50,
                    target: ev.target
                },{
                    identifier: 2,
                    pageX: start_pos.pageX + distance_x - -50,
                    pageY: start_pos.pageY + distance_y - 50,
                    target: ev.target
                }];

                // normal single touch
            } else {
                start_pos = false;
                return [{
                    identifier: 1,
                    pageX: ev.pageX,
                    pageY: ev.pageY,
                    target: ev.target
                }];
            }
        };
    };

})(window.Hammer);<commit_msg>removed old comment<commit_after>(function(Hammer) {
    /**
     * enable multitouch on the desktop by pressing the shiftkey
     * the other touch goes in the opposite direction so the center keeps at its place
     * it's recommended to enable Hammer.debug.showTouches for this one
     */
    Hammer.plugins.fakeMultitouch = function() {
        // keeps the start position to keep it centered
        var start_pos = false;

        /**
         * overwrites Hammer.event.getTouchList.
         * @param   {Event}     ev
         * @param   TOUCHTYPE   type
         * @return  {Array}     Touches
         */
        Hammer.event.getTouchList = function(ev, eventType) {
            // Android, iOS etc
            if(Hammer.HAS_POINTEREVENTS) {
                return Hammer.PointerEvent.getPointers();
            }
            else if(Hammer.HAS_TOUCHEVENTS) {
                return ev.touches;
            }

            // reset on start of a new touch
            if(eventType == Hammer.EVENT_START) {
                start_pos = false;
            }

            // when the shift key is pressed, multitouch is possible on desktop
            // why shift? because ctrl and alt are taken by osx and linux
            if(ev.shiftKey) {
                // on touchstart we store the position of the mouse for multitouch
                if(!start_pos) {
                    start_pos = {
                        pageX: ev.pageX,
                        pageY: ev.pageY
                    };
                }

                var distance_x = start_pos.pageX - ev.pageX;
                var distance_y = start_pos.pageY - ev.pageY;

                // fake second touch in the opposite direction
                return [{
                    identifier: 1,
                    pageX: start_pos.pageX - distance_x - 50,
                    pageY: start_pos.pageY - distance_y - -50,
                    target: ev.target
                },{
                    identifier: 2,
                    pageX: start_pos.pageX + distance_x - -50,
                    pageY: start_pos.pageY + distance_y - 50,
                    target: ev.target
                }];

                // normal single touch
            } else {
                start_pos = false;
                return [{
                    identifier: 1,
                    pageX: ev.pageX,
                    pageY: ev.pageY,
                    target: ev.target
                }];
            }
        };
    };

})(window.Hammer);<|endoftext|>


<commit_before>var prefix = "/"
const version = require('../package.json').version;
module.exports = message => {
	if (!message.content.startsWith(prefix)) return;
  if (message.author.bot) return;
	var n = new Date().toLocaleString();
	const client = message.client;
	let args = message.content.split(' ');
	const command = args.shift().slice(prefix.length);
	const guild = client.guilds.find("name", "個人的現實");
if (!command) {
	return;
}

console.log(`
    >Message Event<
Command (${command}) Trigger.
At : ${n}
By : ${message.author.username}
From : ${message.guild.name}`);

//if (client.user.presence['status'] == 'dnd' && message.author.id !== '179443176279375872') return;
// if (message.channel.name !== 'game-center' && message.content == ("/coin")) {
// 	message.delete();
// 	message.channel.send('Please Go To <#351250503306444800> And Try Again').then(response => response.delete(5000));
// 	return;
// };

	try {
		guild.channels.find('name', 'aiw-log').send(`Command : ( ${command} ) Trigger \n${n}, ${message.author.username}`);
		let cmdFile = require(`../commands/${command}`);
		cmdFile.run(client, message, args);
	} catch (error) {
			console.log(`\n${error}`);
			message.channel.send('⚠Error : ' + error.message).then(response => response.delete(5000));
			 client.channels.get('347618456335548427').send({embed: {
			 	color: 10158080,
			 	description: '\`' + '------ 御坂網絡  ' + version + ' ------' + '\`\n' + 'Failed Execute Command : ' + command + `\nInput By : ` + message.author.username + '\nAt : ' + n + '\nFrom : ' + message.guild  + '\n\`\`\`js\n' + error.stack + '\`\`\`'
			 }});
		}

};
<commit_msg>Update message.js<commit_after>var prefix = "/"
const version = require('../package.json').version;
module.exports = message => {
	if (!message.content.startsWith(prefix)) return;
  if (message.author.bot) return;
	var n = new Date().toLocaleString();
	const client = message.client;
	let args = message.content.split(' ');
	const command = args.shift().slice(prefix.length);
	const guild = client.guilds.find("name", "個人的現實");
if (!command) {
	return;
}

console.log(`
    >Message Event<
Command (${command}) Trigger.
At : ${n} US TIME
By : ${message.author.username}
From : ${message.guild.name}`);

//if (client.user.presence['status'] == 'dnd' && message.author.id !== '179443176279375872') return;
// if (message.channel.name !== 'game-center' && message.content == ("/coin")) {
// 	message.delete();
// 	message.channel.send('Please Go To <#351250503306444800> And Try Again').then(response => response.delete(5000));
// 	return;
// };

	try {
		guild.channels.find('name', 'aiw-log').send(`Command : ( ${command} ) Trigger \n${n} US TIME,\n${message.author.username}`);
		let cmdFile = require(`../commands/${command}`);
		cmdFile.run(client, message, args);
	} catch (error) {
			console.log(`\n${error}`);
			message.channel.send('⚠Error : ' + error.message).then(response => response.delete(5000));
			 client.channels.get('347618456335548427').send({embed: {
			 	color: 10158080,
			 	description: '\`' + '------ 御坂網絡  ' + version + ' ------' + '\`\n' + 'Failed Execute Command : ' + command + `\nInput By : ` + message.author.username + '\nAt : ' + n + '\nFrom : ' + message.guild  + '\n\`\`\`js\n' + error.stack + '\`\`\`'
			 }});
		}

};
<|endoftext|>


<commit_before>
//{namespace name=backend/plugin_manager/translation}
Ext.define('Shopware.apps.PluginManager.view.list.LocalPluginListingPage', {
    extend: 'Shopware.grid.Panel',
    alias: 'widget.plugin-manager-local-plugin-listing',
    cls: 'plugin-manager-local-plugin-listing',

    mixins: {
        events: 'Shopware.apps.PluginManager.view.PluginHelper'
    },
    viewConfig: {
        markDirty: false
    },

    configure: function() {
        return {
            addButton: false,
            pageSizeCombo: false,
            deleteButton: false,
            deleteColumn: false,
            editColumn: false,
            columns: {
                label: {
                    flex: 2,
                    header: '{s name="plugin_name"}Plugin name{/s}',
                    groupable: false,
                    renderer: this.nameRenderer,
                    editor: null
                },
                version: {
                    width: 30,
                    header: '{s name="version"}Version{/s}',
                    groupable: false,
                    editor: null
                },
                installationDate: {
                    header: '{s name="installed_on"}Installed on{/s}',
                    groupable: false,
                    renderer: this.dateRenderer,
                    editor: null
                },
                updateDate: {
                    header: '{s name="updated_on"}Updated on{/s}',
                    groupable: false,
                    renderer: this.dateRenderer,
                    editor: null
                },
                licenceCheck: {
                    flex: 2,
                    sortable: false,
                    groupable: false,
                    cls: 'licence-column',
                    header: '{s name="licence"}License{/s}',
                    renderer: this.licenceRenderer,
                    editor: null
                },
                active: this.createActiveColumn,
                author: {
                    header: '{s name="from_producer"}Developed by{/s}',
                    groupable: false,
                    renderer: this.authorRenderer,
                    editor: null
                }
            }
        };
    },

    initComponent: function() {
        var me = this;

        me.callParent(arguments);

        Shopware.app.Application.on('plugin-reloaded', function(plugin) {
            me.store.each(function(record, index) {
                if (record && record.get('technicalName') == plugin.get('technicalName')) {
                    me.store.remove(record);
                }
            });

            if (plugin.get('id') > 0) {
                plugin.set('groupingState', null);
                plugin.dirty = false;
                try {
                    me.store.add(plugin);
                } catch (e) {
                    me.store.load();
                }
            }

            me.store.sort();
            me.store.group();
            me.reconfigure(me.store);
            me.hideLoadingMask();
        });
    },

    createActionColumn: function () {
        var me = this;

        var actionColumn = me.callParent(arguments);

        actionColumn.width = 120;
        return actionColumn;
    },

    createSelectionModel: function() { },

    createActiveColumn: function() {
        var me = this,
            items = [];

        items.push({
            tooltip: '{s name="activate_deactivate"}Activate / Deactivate{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                if (record.allowActivate()) {
                    me.activatePluginEvent(record);

                } else if (record.allowDeactivate()) {
                    me.deactivatePluginEvent(record);
                }
            },
            getClass: function(value, metaData, record) {
                if (!record.allowActivate() && !record.allowDeactivate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }

                if (record.allowActivate()) {
                    return 'sprite-ui-check-box-uncheck';
                } else {
                    return 'sprite-ui-check-box';
                }
            }
        });

        return {
            xtype: 'actioncolumn',
            width: 60,
            align: 'center',
            header: '{s name="active"}Active{/s}',
            groupable: false,
            items: items
        };
    },

    searchEvent: function(field, value) {
        var me = this;

        me.store.clearFilter();

        value = value.toLowerCase();

        me.store.filterBy(function(record, id) {
            var description = record.get('description') + '';
            var name = record.get('label') + '';
            var technicalName = record.get('technicalName') + '';
            var producer = '';

            if (record['getProducerStore']) {
                producer = record['getProducerStore'].first().get('name') + '';
            }

            name = name.toLowerCase();
            technicalName = technicalName.toLowerCase();
            producer = producer.toLowerCase();
            description = description.toLowerCase();

            return (
                name.indexOf(value) > -1
                || description.indexOf(value) > -1
                || producer.indexOf(value) > -1
                || technicalName.indexOf(value) > -1
            );
        });
    },

    createFeatures: function() {
        var me = this,
            items = me.callParent(arguments);

        me.groupingFeature = Ext.create('Ext.grid.feature.Grouping', {
            groupHeaderTpl: new Ext.XTemplate(
                '{literal}{name:this.formatName} ({rows.length} Plugins){/literal}',
                {
                    formatName: function(name) {
                        switch(name) {
                            case 2:
                                return '{s name="group_headline_installed"}Installed{/s}';
                            case 1:
                                return '{s name="group_headline_deactivated"}Inactive{/s}';
                            case 0:
                                return '{s name="group_headline_uninstalled"}Uninstalled{/s}';
                        }
                    }
                }
            )
        });

        items.push(me.groupingFeature);
        return items;
    },

    nameRenderer: function(value, metaData, record) {
        var name = record.get('label');

        if (!record.get('localIcon') || record.get('localIcon') == 'false') {
            return name;
        }

        return '

' + name;
    },

    authorRenderer: function(value, metaData, record) {
        if (!record || !record['getProducerStore']) {
            return value;
        }

        var producer = record['getProducerStore'].first();
        var website = producer.get('website');

        if (producer.get('name') == 'shopware AG' && !website) {
            website = 'http://www.shopware.com';
        }

        if (website && website.length > 0) {
            return ''+producer.get('name')+''
        } else {
            return producer.get('name');
        }
    },

    dateRenderer: function(value) {
        if (!value || !value.hasOwnProperty('date')) {
            return value;
        }
        var date = this.formatDate(value.date);
        return Ext.util.Format.date(date);
    },

    licenceRenderer: function(value, metaData, record) {
        if (!record || !record['getLicenceStore']) {
            return;
        }

        try {
            var licence = record['getLicenceStore'].first();
            var price = licence['getPriceStore'].first();
            var type = this.getTextForPriceType(price.get('type'));
            var expiration = licence.get('expirationDate');
            var result = type;
        } catch (e) {
            return result;
        }

        if (!expiration) {
            return result;
        }

        if (expiration) {
            result += '
{s name="till"}until{/s}: ' + Ext.util.Format.date(expiration.date) + '';
        }

        return result;
    },

    createToolbarItems: function() {
        var me = this,
            items = me.callParent(arguments);

        Ext.Array.insert(items, 0, [
            me.createUploadButton()
        ]);

        return items;
    },

    createUploadButton: function() {
        var me = this;

        me.uploadButton = Ext.create('Ext.button.Button', {
            text: '{s name="upload_plugin"}Upload plugin{/s}',
            iconCls: 'sprite-plus-circle',
            handler: function() {
                me.fireEvent('open-plugin-upload');
            }
        });

        return me.uploadButton;
    },

    createActionColumnItems: function() {
        var me = this, items = [];

        items.push({
            iconCls: 'sprite-pencil',
            tooltip: '{s name="open"}Open{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.displayPluginEvent(record);
            }
        });

        items.push({
            iconCls: 'sprite-plus-circle',
            tooltip: '{s name="install"}Install{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.updateDummyPluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowDummyUpdate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        items.push({
            iconCls: 'sprite-minus-circle',
            tooltip: '{s name="install_uninstall"}Install / Uninstall{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                if (record.allowInstall()) {
                    me.registerConfigRequiredEvent(record);

                    me.installPluginEvent(record);
                } else {
                    me.uninstallPluginEvent(record);
                }
            },
            getClass: function(value, metaData, record) {
                if (record.allowDummyUpdate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }

                if (record.allowInstall()) {
                    return 'sprite-plus-circle';
                }
            }
        });

        items.push({
            iconCls: 'sprite-arrow-continue',
            tooltip: '{s name="reinstall"}Reinstall{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.reinstallPluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowReinstall()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        items.push({
            iconCls: 'sprite-arrow-circle-135',
            tooltip: '{s name="update_plugin"}Update{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.updatePluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowUpdate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
                this.items[4].tooltip = '{s name="install_update"}Install update{/s} (v ' + record.get('availableVersion') + ')';
            }
        });

        items.push({
            iconCls: 'sprite-bin-metal-full',
            tooltip: '{s name="delete"}Delete{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.deletePluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowDelete()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        items.push({
            iconCls: 'sprite-arrow-circle-225-left',
            tooltip: '{s name="local_update"}Update{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.executePluginUpdateEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowLocalUpdate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        return items;
    }
});<commit_msg>SW-11564 - Reload plugin listing after plugin changed<commit_after>
//{namespace name=backend/plugin_manager/translation}
Ext.define('Shopware.apps.PluginManager.view.list.LocalPluginListingPage', {
    extend: 'Shopware.grid.Panel',
    alias: 'widget.plugin-manager-local-plugin-listing',
    cls: 'plugin-manager-local-plugin-listing',

    mixins: {
        events: 'Shopware.apps.PluginManager.view.PluginHelper'
    },
    viewConfig: {
        markDirty: false
    },

    configure: function() {
        return {
            addButton: false,
            pageSizeCombo: false,
            deleteButton: false,
            deleteColumn: false,
            editColumn: false,
            columns: {
                label: {
                    flex: 2,
                    header: '{s name="plugin_name"}Plugin name{/s}',
                    groupable: false,
                    renderer: this.nameRenderer,
                    editor: null
                },
                version: {
                    width: 30,
                    header: '{s name="version"}Version{/s}',
                    groupable: false,
                    editor: null
                },
                installationDate: {
                    header: '{s name="installed_on"}Installed on{/s}',
                    groupable: false,
                    renderer: this.dateRenderer,
                    editor: null
                },
                updateDate: {
                    header: '{s name="updated_on"}Updated on{/s}',
                    groupable: false,
                    renderer: this.dateRenderer,
                    editor: null
                },
                licenceCheck: {
                    flex: 2,
                    sortable: false,
                    groupable: false,
                    cls: 'licence-column',
                    header: '{s name="licence"}License{/s}',
                    renderer: this.licenceRenderer,
                    editor: null
                },
                active: this.createActiveColumn,
                author: {
                    header: '{s name="from_producer"}Developed by{/s}',
                    groupable: false,
                    renderer: this.authorRenderer,
                    editor: null
                }
            }
        };
    },

    initComponent: function() {
        var me = this;

        me.callParent(arguments);

        Shopware.app.Application.on('plugin-reloaded', function(plugin) {
            me.store.load();
            me.hideLoadingMask();
        });
    },

    createActionColumn: function () {
        var me = this;

        var actionColumn = me.callParent(arguments);

        actionColumn.width = 120;
        return actionColumn;
    },

    createSelectionModel: function() { },

    createActiveColumn: function() {
        var me = this,
            items = [];

        items.push({
            tooltip: '{s name="activate_deactivate"}Activate / Deactivate{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                if (record.allowActivate()) {
                    me.activatePluginEvent(record);

                } else if (record.allowDeactivate()) {
                    me.deactivatePluginEvent(record);
                }
            },
            getClass: function(value, metaData, record) {
                if (!record.allowActivate() && !record.allowDeactivate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }

                if (record.allowActivate()) {
                    return 'sprite-ui-check-box-uncheck';
                } else {
                    return 'sprite-ui-check-box';
                }
            }
        });

        return {
            xtype: 'actioncolumn',
            width: 60,
            align: 'center',
            header: '{s name="active"}Active{/s}',
            groupable: false,
            items: items
        };
    },

    searchEvent: function(field, value) {
        var me = this;

        me.store.clearFilter();

        value = value.toLowerCase();

        me.store.filterBy(function(record, id) {
            var description = record.get('description') + '';
            var name = record.get('label') + '';
            var technicalName = record.get('technicalName') + '';
            var producer = '';

            if (record['getProducerStore']) {
                producer = record['getProducerStore'].first().get('name') + '';
            }

            name = name.toLowerCase();
            technicalName = technicalName.toLowerCase();
            producer = producer.toLowerCase();
            description = description.toLowerCase();

            return (
                name.indexOf(value) > -1
                || description.indexOf(value) > -1
                || producer.indexOf(value) > -1
                || technicalName.indexOf(value) > -1
            );
        });
    },

    createFeatures: function() {
        var me = this,
            items = me.callParent(arguments);

        me.groupingFeature = Ext.create('Ext.grid.feature.Grouping', {
            groupHeaderTpl: new Ext.XTemplate(
                '{literal}{name:this.formatName} ({rows.length} Plugins){/literal}',
                {
                    formatName: function(name) {
                        switch(name) {
                            case 2:
                                return '{s name="group_headline_installed"}Installed{/s}';
                            case 1:
                                return '{s name="group_headline_deactivated"}Inactive{/s}';
                            case 0:
                                return '{s name="group_headline_uninstalled"}Uninstalled{/s}';
                        }
                    }
                }
            )
        });

        items.push(me.groupingFeature);
        return items;
    },

    nameRenderer: function(value, metaData, record) {
        var name = record.get('label');

        if (!record.get('localIcon') || record.get('localIcon') == 'false') {
            return name;
        }

        return '

' + name;
    },

    authorRenderer: function(value, metaData, record) {
        if (!record || !record['getProducerStore']) {
            return value;
        }

        var producer = record['getProducerStore'].first();
        var website = producer.get('website');

        if (producer.get('name') == 'shopware AG' && !website) {
            website = 'http://www.shopware.com';
        }

        if (website && website.length > 0) {
            return ''+producer.get('name')+''
        } else {
            return producer.get('name');
        }
    },

    dateRenderer: function(value) {
        if (!value || !value.hasOwnProperty('date')) {
            return value;
        }
        var date = this.formatDate(value.date);
        return Ext.util.Format.date(date);
    },

    licenceRenderer: function(value, metaData, record) {
        if (!record || !record['getLicenceStore']) {
            return;
        }

        try {
            var licence = record['getLicenceStore'].first();
            var price = licence['getPriceStore'].first();
            var type = this.getTextForPriceType(price.get('type'));
            var expiration = licence.get('expirationDate');
            var result = type;
        } catch (e) {
            return result;
        }

        if (!expiration) {
            return result;
        }

        if (expiration) {
            result += '
{s name="till"}until{/s}: ' + Ext.util.Format.date(expiration.date) + '';
        }

        return result;
    },

    createToolbarItems: function() {
        var me = this,
            items = me.callParent(arguments);

        Ext.Array.insert(items, 0, [
            me.createUploadButton()
        ]);

        return items;
    },

    createUploadButton: function() {
        var me = this;

        me.uploadButton = Ext.create('Ext.button.Button', {
            text: '{s name="upload_plugin"}Upload plugin{/s}',
            iconCls: 'sprite-plus-circle',
            handler: function() {
                me.fireEvent('open-plugin-upload');
            }
        });

        return me.uploadButton;
    },

    createActionColumnItems: function() {
        var me = this, items = [];

        items.push({
            iconCls: 'sprite-pencil',
            tooltip: '{s name="open"}Open{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.displayPluginEvent(record);
            }
        });

        items.push({
            iconCls: 'sprite-plus-circle',
            tooltip: '{s name="install"}Install{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.updateDummyPluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowDummyUpdate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        items.push({
            iconCls: 'sprite-minus-circle',
            tooltip: '{s name="install_uninstall"}Install / Uninstall{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                if (record.allowInstall()) {
                    me.registerConfigRequiredEvent(record);

                    me.installPluginEvent(record);
                } else {
                    me.uninstallPluginEvent(record);
                }
            },
            getClass: function(value, metaData, record) {
                if (record.allowDummyUpdate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }

                if (record.allowInstall()) {
                    return 'sprite-plus-circle';
                }
            }
        });

        items.push({
            iconCls: 'sprite-arrow-continue',
            tooltip: '{s name="reinstall"}Reinstall{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.reinstallPluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowReinstall()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        items.push({
            iconCls: 'sprite-arrow-circle-135',
            tooltip: '{s name="update_plugin"}Update{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.updatePluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowUpdate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
                this.items[4].tooltip = '{s name="install_update"}Install update{/s} (v ' + record.get('availableVersion') + ')';
            }
        });

        items.push({
            iconCls: 'sprite-bin-metal-full',
            tooltip: '{s name="delete"}Delete{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.deletePluginEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowDelete()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        items.push({
            iconCls: 'sprite-arrow-circle-225-left',
            tooltip: '{s name="local_update"}Update{/s}',
            handler: function(grid, rowIndex, colIndex, item, eOpts, record) {
                me.executePluginUpdateEvent(record);
            },
            getClass: function(value, metaData, record) {
                if (!record.allowLocalUpdate()) {
                    return Ext.baseCSSPrefix + 'hidden';
                }
            }
        });

        return items;
    }
});<|endoftext|>


<commit_before>/*
 * brozzler/behaviors.d/pm-ca.js - behavior for http://www.pm.gc.ca/
 *
 * Copyright (C) 2014-2017 Internet Archive
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var umbraBehavior = {
	IDLE_TIMEOUT_SEC : 10,
	idleSince : null,
    itemsText : "",

	// https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js
	// n.b. returns true for elements with visibility:hidden, which occupy
	// screen real estate but are not visible, or clickable with the ui
	isVisible : function(elem) {
		return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
	},

	intervalFunc : function() {
		var clickedSomething = false;
		var somethingLeftBelow = false;
		var somethingLeftAbove = false;
		var cssSelector = "div.teaser, li.pager__item a";
		var clickUntilTimeout = 10;

		var iframes = document.querySelectorAll("iframe");
		var documents = Array(iframes.length + 1);
		documents[0] = document;

		for (var i = 0; i < iframes.length; i++) {
			documents[i+1] = iframes[i].contentWindow.document;
		}

		for (var j = 0; j < documents.length; j++) {
			var clickTargets = documents[j].querySelectorAll(cssSelector);
			for (var i = 0; i < clickTargets.length; i++) {
				if (!this.isVisible(clickTargets[i])) {
					continue;
				}
				if (this.itemsText.indexOf(clickTargets[i].innerText) > -1) {
					continue;
				}

				var where = this.aboveBelowOrOnScreen(clickTargets[i]);

				if (where == 0) {
					// console.log("clicking on " + clickTargets[i].outerHTML);
					// do mouse over event on click target
					// since some urls are requsted only on
					// this event - see
					// https://webarchive.jira.com/browse/AITFIVE-451
					var mouseOverEvent = document.createEvent('Events');
					mouseOverEvent.initEvent("mouseover",true, false);
					clickTargets[i].dispatchEvent(mouseOverEvent);
					clickTargets[i].click();
					clickedSomething = true;
					this.idleSince = null;
					this.itemsText += clickTargets[i].innerText;

					break; //break from clickTargets loop, but not from iframe loop
				} else if (where > 0) {
					somethingLeftBelow = true;
				} else if (where < 0) {
					somethingLeftAbove = true;
				}
			}
		}

		if (!clickedSomething) {
			if (somethingLeftAbove) {
				// console.log("scrolling UP because everything on this screen has been clicked but we missed something above");
				window.scrollBy(0, -500);
				this.idleSince = null;
			} else if (somethingLeftBelow) {
				// console.log("scrolling because everything on this screen has been clicked but there's more below document.body.clientHeight="
				//				+ document.body.clientHeight);
				window.scrollBy(0, 200);
				this.idleSince = null;
			} else if (window.scrollY + window.innerHeight < document.documentElement.scrollHeight) {
				// console.log("scrolling because we're not to the bottom yet document.body.clientHeight="
				//				+ document.body.clientHeight);
				window.scrollBy(0, 200);
				this.idleSince = null;
			} else if (this.idleSince == null) {
				this.idleSince = Date.now();
			}
		}

		if (!this.idleSince) {
			this.idleSince = Date.now();
		}
	},

	start : function() {
		var that = this;
		this.intervalId = setInterval(function() {
			that.intervalFunc()
		}, 500);
	},

	isFinished : function() {
		if (this.idleSince != null) {
			var idleTimeMs = Date.now() - this.idleSince;
			if (idleTimeMs / 1000 > this.IDLE_TIMEOUT_SEC) {
				clearInterval(this.intervalId);
				return true;
			}
		}
		return false;
	},

	aboveBelowOrOnScreen : function(e) {
		var eTop = e.getBoundingClientRect().top;
		if (eTop < window.scrollY) {
			return -1; // above
		} else if (eTop > window.scrollY + window.innerHeight) {
			return 1; // below
		} else {
			return 0; // on screen
		}
	},
};

// Called from outside of this script.
var umbraBehaviorFinished = function() {
	return umbraBehavior.isFinished()
};

umbraBehavior.start();
<commit_msg>only div.teaser, for *pm.gc.ca*<commit_after>/*
 * brozzler/behaviors.d/pm-ca.js - behavior for http://www.pm.gc.ca/
 *
 * Copyright (C) 2014-2017 Internet Archive
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var umbraBehavior = {
	IDLE_TIMEOUT_SEC : 10,
	idleSince : null,
    itemsText : "",

	// https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js
	// n.b. returns true for elements with visibility:hidden, which occupy
	// screen real estate but are not visible, or clickable with the ui
	isVisible : function(elem) {
		return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
	},

	intervalFunc : function() {
		var clickedSomething = false;
		var somethingLeftBelow = false;
		var somethingLeftAbove = false;
		var cssSelector = "div.teaser";
		var clickUntilTimeout = 10;

		var iframes = document.querySelectorAll("iframe");
		var documents = Array(iframes.length + 1);
		documents[0] = document;

		for (var i = 0; i < iframes.length; i++) {
			documents[i+1] = iframes[i].contentWindow.document;
		}

		for (var j = 0; j < documents.length; j++) {
			var clickTargets = documents[j].querySelectorAll(cssSelector);
			for (var i = 0; i < clickTargets.length; i++) {
				if (!this.isVisible(clickTargets[i])) {
					continue;
				}
				if (this.itemsText.indexOf(clickTargets[i].innerText) > -1) {
					continue;
				}

				var where = this.aboveBelowOrOnScreen(clickTargets[i]);

				if (where == 0) {
					// console.log("clicking on " + clickTargets[i].outerHTML);
					// do mouse over event on click target
					// since some urls are requsted only on
					// this event - see
					// https://webarchive.jira.com/browse/AITFIVE-451
					var mouseOverEvent = document.createEvent('Events');
					mouseOverEvent.initEvent("mouseover",true, false);
					clickTargets[i].dispatchEvent(mouseOverEvent);
					clickTargets[i].click();
					clickedSomething = true;
					this.idleSince = null;
					this.itemsText += clickTargets[i].innerText;

					break; //break from clickTargets loop, but not from iframe loop
				} else if (where > 0) {
					somethingLeftBelow = true;
				} else if (where < 0) {
					somethingLeftAbove = true;
				}
			}
		}

		if (!clickedSomething) {
			if (somethingLeftAbove) {
				// console.log("scrolling UP because everything on this screen has been clicked but we missed something above");
				window.scrollBy(0, -500);
				this.idleSince = null;
			} else if (somethingLeftBelow) {
				// console.log("scrolling because everything on this screen has been clicked but there's more below document.body.clientHeight="
				//				+ document.body.clientHeight);
				window.scrollBy(0, 200);
				this.idleSince = null;
			} else if (window.scrollY + window.innerHeight < document.documentElement.scrollHeight) {
				// console.log("scrolling because we're not to the bottom yet document.body.clientHeight="
				//				+ document.body.clientHeight);
				window.scrollBy(0, 200);
				this.idleSince = null;
			} else if (this.idleSince == null) {
				this.idleSince = Date.now();
			}
		}

		if (!this.idleSince) {
			this.idleSince = Date.now();
		}
	},

	start : function() {
		var that = this;
		this.intervalId = setInterval(function() {
			that.intervalFunc()
		}, 500);
	},

	isFinished : function() {
		if (this.idleSince != null) {
			var idleTimeMs = Date.now() - this.idleSince;
			if (idleTimeMs / 1000 > this.IDLE_TIMEOUT_SEC) {
				clearInterval(this.intervalId);
				return true;
			}
		}
		return false;
	},

	aboveBelowOrOnScreen : function(e) {
		var eTop = e.getBoundingClientRect().top;
		if (eTop < window.scrollY) {
			return -1; // above
		} else if (eTop > window.scrollY + window.innerHeight) {
			return 1; // below
		} else {
			return 0; // on screen
		}
	},
};

// Called from outside of this script.
var umbraBehaviorFinished = function() {
	return umbraBehavior.isFinished()
};

umbraBehavior.start();
<|endoftext|>


<commit_before>export const ConfigException = (message) => {
  this.message = message;
  this.name = 'ConfigException';
};
<commit_msg>Delete exceptions.js<commit_after><|endoftext|>