<commit_before>/*
 * L.Evented is a base class that Leaflet classes inherit from to handle custom events.
 */

L.Evented = L.Class.extend({

	on: function (types, fn, context) {

		// types can be a map of types/handlers
		if (typeof types === 'object') {
			for (var type in types) {
				this._on(type, types[type], fn);
			}

		} else {
			// types can be a string of space-separated words
			types = L.Util.splitWords(types);

			for (var i = 0, len = types.length; i < len; i++) {
				this._on(types[i], fn, context);
			}
		}

		return this;
	},

	off: function (types, fn, context) {

		if (!types) {
			// clear all listeners if called without arguments
			delete this._events;

		} else if (typeof types === 'object') {
			for (var type in types) {
				this._off(type, types[type], fn);
			}

		} else {
			types = L.Util.splitWords(types);

			for (var i = 0, len = types.length; i < len; i++) {
				this._off(types[i], fn, context);
			}
		}

		return this;
	},

	// attach listener (without syntactic sugar now)
	_on: function (type, fn, context) {

		var events = this._events = this._events || {},
		    contextId = context && context !== this && L.stamp(context);

		if (contextId) {
			// store listeners of a particular context in a separate hash (if it has an id)
			// gives a major performance boost when removing thousands of map layers

			var fnId = L.stamp(fn),
			    indexKey = type + '_idx',
			    indexLenKey = type + '_len',
			    typeIndex = events[indexKey] = events[indexKey] || {};

			typeIndex[fnId] = typeIndex[fnId] || {};

			if (!typeIndex[fnId][contextId]) {
				typeIndex[fnId][contextId] = {fn: fn, ctx: context};

				// keep track of the number of keys in the index to quickly check if it's empty
				events[indexLenKey] = (events[indexLenKey] || 0) + 1;
			}

		} else {
			events[type] = events[type] || [];
			events[type].push({fn: fn});
		}
	},

	_off: function (type, fn, context) {
		var events = this._events,
		    indexKey = type + '_idx',
		    indexLenKey = type + '_len';

		if (!events) { return; }

		if (!fn) {
			// clear all listeners for a type if function isn't specified
			delete events[type];
			delete events[indexKey];
			delete events[indexLenKey];
			return;
		}

		var contextId = context && context !== this && L.stamp(context),
		    listeners, i, len, listener;

		if (contextId) {
			listeners = events[indexKey] && events[indexKey][L.stamp(fn)];

			if (listeners && listeners[contextId]) {
				// set the old action to a no-op, because it is possible
				// that the listener is being iterated over as part of a dispatch
				listener = listeners[contextId];
				delete listeners[contextId];
				events[indexLenKey]--;
			}

		} else {
			listeners = events[type];

			for (i = 0, len = listeners.length; i < len; i++) {
				if (listeners[i].fn === fn) {
					listener = listeners[i];
					listeners.splice(i, 1);
					break;
				}
			}
		}

		// set the removed listener to noop so that's not called if remove happens in fire
		if (listener) {
			listener.fn = L.Util.falseFn;
		}
	},

	fire: function (type, data, propagate) {
		if (!this.listens(type, propagate)) { return this; }

		var event = L.Util.extend({}, data, {type: type, target: this}),
		    events = this._events;

		if (events) {
		    var typeIndex = events[type + '_idx'],
		        fnId, contextId, i, len, listeners, listener;

			if (events[type]) {
				// make sure adding/removing listeners inside other listeners won't cause infinite loop
				listeners = events[type].slice();

				for (i = 0, len = listeners.length; i < len; i++) {
					listeners[i].fn.call(this, event);
				}
			}

			// fire event for the context-indexed listeners as well
			if (typeIndex) {
				for (fnId in typeIndex) {
					for (contextId in typeIndex[fnId]) {
						listener = typeIndex[fnId][contextId];
						listener.fn.call(listener.ctx, event);
					}
				}
			}
		}

		if (propagate) {
			this._propagateEvent(event);
		}

		return this;
	},

	listens: function (type, propagate) {
		var events = this._events;

		if (events && (events[type] || events[type + '_len'])) { return true; }

		if (propagate) {
			for (var id in this._eventParents) {
				if (this._eventParents[id].listens(type)) { return true; }
			}
		}
		return false;
	},

	once: function (types, fn, context) {

		if (typeof types === 'object') {
			for (var type in types) {
				this.once(type, types[type], fn);
			}
			return this;
		}

		var handler = L.bind(function () {
			this
			    .off(types, fn, context)
			    .off(types, handler, context);
		}, this);

		return this
		    .on(types, fn, context)
		    .on(types, handler, context);
	},

	addEventParent: function (obj) {
		this._eventParents = this._eventParents || {};
		this._eventParents[L.stamp(obj)] = obj;
		return this;
	},

	removeEventParent: function (obj) {
		if (this._eventParents) {
			delete this._eventParents[L.stamp(obj)];
		}
		return this;
	},

	_propagateEvent: function (e) {
		for (var id in this._eventParents) {
			this._eventParents[id].fire(e.type, L.extend({layer: e.target}, e));
		}
	}
});

var proto = L.Evented.prototype;

// aliases
proto.addEventListener = proto.on;
proto.removeEventListener = proto.clearAllEventListeners = proto.off;
proto.addOneTimeEventListener = proto.once;
proto.fireEvent = proto.fire;
proto.hasEventListeners = proto.listens;

L.Mixin = {Events: proto};
<commit_msg>ensure execution order in events, slightly bulkier structure<commit_after>/*
 * L.Evented is a base class that Leaflet classes inherit from to handle custom events.
 */

L.Evented = L.Class.extend({

	on: function (types, fn, context) {

		// types can be a map of types/handlers
		if (typeof types === 'object') {
			for (var type in types) {
				this._on(type, types[type], fn);
			}

		} else {
			// types can be a string of space-separated words
			types = L.Util.splitWords(types);

			for (var i = 0, len = types.length; i < len; i++) {
				this._on(types[i], fn, context);
			}
		}

		return this;
	},

	off: function (types, fn, context) {

		if (!types) {
			// clear all listeners if called without arguments
			delete this._events;

		} else if (typeof types === 'object') {
			for (var type in types) {
				this._off(type, types[type], fn);
			}

		} else {
			types = L.Util.splitWords(types);

			for (var i = 0, len = types.length; i < len; i++) {
				this._off(types[i], fn, context);
			}
		}

		return this;
	},

	// attach listener (without syntactic sugar now)
	_on: function (type, fn, context) {

		var events = this._events = this._events || {},
		    contextId = context && context !== this && L.stamp(context);

		if (contextId) {
			// store listeners of a particular context in a separate hash (if it has an id)
			// gives a major performance boost when removing thousands of map layers

			var indexKey = type + '_idx',
			    indexLenKey = type + '_len',
			    typeIndex = events[indexKey] = events[indexKey] || {},
			    id = L.stamp(fn) + '_' + contextId;

			if (!typeIndex[id]) {
				typeIndex[id] = {fn: fn, ctx: context};

				// keep track of the number of keys in the index to quickly check if it's empty
				events[indexLenKey] = (events[indexLenKey] || 0) + 1;
			}

		} else {
			events[type] = events[type] || [];
			events[type].push({fn: fn});
		}
	},

	_off: function (type, fn, context) {
		var events = this._events,
		    indexKey = type + '_idx',
		    indexLenKey = type + '_len';

		if (!events) { return; }

		if (!fn) {
			// clear all listeners for a type if function isn't specified
			delete events[type];
			delete events[indexKey];
			delete events[indexLenKey];
			return;
		}

		var contextId = context && context !== this && L.stamp(context),
		    listeners, i, len, listener, id;

		if (contextId) {
			id = L.stamp(fn) + '_' + contextId;
			listeners = events[indexKey];

			if (listeners && listeners[id]) {
				// set the old action to a no-op, because it is possible
				// that the listener is being iterated over as part of a dispatch
				listener = listeners[id];
				delete listeners[id];
				events[indexLenKey]--;
			}

		} else {
			listeners = events[type];

			for (i = 0, len = listeners.length; i < len; i++) {
				if (listeners[i].fn === fn) {
					listener = listeners[i];
					listeners.splice(i, 1);
					break;
				}
			}
		}

		// set the removed listener to noop so that's not called if remove happens in fire
		if (listener) {
			listener.fn = L.Util.falseFn;
		}
	},

	fire: function (type, data, propagate) {
		if (!this.listens(type, propagate)) { return this; }

		var event = L.Util.extend({}, data, {type: type, target: this}),
		    events = this._events;

		if (events) {
		    var typeIndex = events[type + '_idx'],
		        i, len, listeners, id;

			if (events[type]) {
				// make sure adding/removing listeners inside other listeners won't cause infinite loop
				listeners = events[type].slice();

				for (i = 0, len = listeners.length; i < len; i++) {
					listeners[i].fn.call(this, event);
				}
			}

			// fire event for the context-indexed listeners as well
			for (id in typeIndex) {
				typeIndex[id].fn.call(typeIndex[id].ctx, event);
			}
		}

		if (propagate) {
			this._propagateEvent(event);
		}

		return this;
	},

	listens: function (type, propagate) {
		var events = this._events;

		if (events && (events[type] || events[type + '_len'])) { return true; }

		if (propagate) {
			for (var id in this._eventParents) {
				if (this._eventParents[id].listens(type)) { return true; }
			}
		}
		return false;
	},

	once: function (types, fn, context) {

		if (typeof types === 'object') {
			for (var type in types) {
				this.once(type, types[type], fn);
			}
			return this;
		}

		var handler = L.bind(function () {
			this
			    .off(types, fn, context)
			    .off(types, handler, context);
		}, this);

		return this
		    .on(types, fn, context)
		    .on(types, handler, context);
	},

	addEventParent: function (obj) {
		this._eventParents = this._eventParents || {};
		this._eventParents[L.stamp(obj)] = obj;
		return this;
	},

	removeEventParent: function (obj) {
		if (this._eventParents) {
			delete this._eventParents[L.stamp(obj)];
		}
		return this;
	},

	_propagateEvent: function (e) {
		for (var id in this._eventParents) {
			this._eventParents[id].fire(e.type, L.extend({layer: e.target}, e));
		}
	}
});

var proto = L.Evented.prototype;

// aliases
proto.addEventListener = proto.on;
proto.removeEventListener = proto.clearAllEventListeners = proto.off;
proto.addOneTimeEventListener = proto.once;
proto.fireEvent = proto.fire;
proto.hasEventListeners = proto.listens;

L.Mixin = {Events: proto};
<|endoftext|>


<commit_before>"use strict";

// ----------------------------------------------------------------------------

exports.title = function (elt) {
  return function () {
    return elt.title;
  };
};

exports.setTitle = function (title) {
  return function (elt) {
    return function () {
      elt.title = title;
      return {};
    };
  };
};

// ----------------------------------------------------------------------------

exports.lang = function (elt) {
  return function () {
    return elt.lang;
  };
};

exports.setLang = function (lang) {
  return function (elt) {
    return function () {
      elt.lang = lang;
      return {};
    };
  };
};

// ----------------------------------------------------------------------------

exports.dir = function (elt) {
  return function () {
    return elt.dir;
  };
};

exports.setDir = function (dir) {
  return function (elt) {
    return function () {
      elt.dir = dir;
      return {};
    };
  };
};

// ----------------------------------------------------------------------------

exports.className = function (elt) {
  return function () {
    return elt.className;
  };
};

exports.setClassName = function (className) {
  return function (elt) {
    return function () {
      elt.className = className;
      return {};
    };
  };
};

exports.classList = function (element) {
  return function () {
    return element.classList;
  };
};

// ----------------------------------------------------------------------------

exports.hidden = function (elt) {
  return function () {
    return elt.hidden;
  };
};

exports.setHidden = function (hidden) {
  return function (elt) {
    return function () {
      elt.hidden = hidden;
      return {};
    };
  };
};

// ----------------------------------------------------------------------------

exports.click = function (elt) {
  return function () {
    return elt.click();
  };
};

// ----------------------------------------------------------------------------

exports.tabIndex = function (elt) {
  return function () {
    return elt.tabIndex;
  };
};

exports.setTabIndex = function (tabIndex) {
  return function (elt) {
    return function () {
      elt.tabIndex = tabIndex;
      return {};
    };
  };
};

// ----------------------------------------------------------------------------

exports.hidden = function (elt) {
  return function () {
    return elt.hidden;
  };
};

exports.setHidden = function (hidden) {
  return function (elt) {
    return function () {
      elt.hidden = hidden;
      return {};
    };
  };
};

// ----------------------------------------------------------------------------

exports.focus = function (elt) {
  return function () {
    return elt.focus();
  };
};

// ----------------------------------------------------------------------------

exports.blur = function (elt) {
  return function () {
    return elt.blur();
  };
};

// ----------------------------------------------------------------------------

exports.draggable = function (elt) {
  return function () {
    return elt.draggable;
  };
};

exports.setDraggable = function (draggable) {
  return function (elt) {
    return function () {
      elt.draggable = draggable;
      return {};
    };
  };
};

// ----------------------------------------------------------------------------

exports.contentEditable = function (elt) {
  return function () {
    return elt.contentEditable;
  };
};

exports.setContentEditable = function (contentEditable) {
  return function (elt) {
    return function () {
      elt.contentEditable = contentEditable;
      return {};
    };
  };
};

exports.isContentEditable = function (elt) {
  return function () {
    return elt.isContentEditable;
  };
};

// ----------------------------------------------------------------------------

exports.spellcheck = function (elt) {
  return function () {
    return elt.spellcheck;
  };
};

exports.setSpellcheck = function (spellcheck) {
  return function (elt) {
    return function () {
      elt.spellcheck = spellcheck;
      return {};
    };
  };
};

// - CSSOM ---------------------------------------------------------------------

exports.getBoundingClientRect = function (el) {
  return function () {
    var rect = el.getBoundingClientRect();
    return {
      top: rect.top,
      right: rect.right,
      bottom: rect.bottom,
      left: rect.left,
      width: rect.width,
      height: rect.height
    };
  };
};

exports._offsetParent = function (el) {
  return function () {
    return el.offsetParent;
  };
};

exports.offsetTop = function (el) {
  return function () {
    return el.offsetTop;
  };
};

exports.offsetLeft = function (el) {
  return function () {
    return el.offsetLeft;
  };
};

exports.offsetWidth = function (el) {
  return function () {
    return el.offsetWidth;
  };
};

exports.offsetHeight = function (el) {
  return function () {
    return el.offsetHeight;
  };
};
<commit_msg>Update HTMLElement FFI code to match purs definitions<commit_after>"use strict";

// ----------------------------------------------------------------------------

exports.title = function (elt) {
  return function () {
    return elt.title;
  };
};

exports.setTitle = function (title) {
  return function (elt) {
    return function () {
      elt.title = title;
      return {};
    };
  };
};

// ----------------------------------------------------------------------------

exports.lang = function (elt) {
  return function () {
    return elt.lang;
  };
};

exports.setLang = function (lang) {
  return function (elt) {
    return function () {
      elt.lang = lang;
      return {};
    };
  };
};

// ----------------------------------------------------------------------------

exports.dir = function (elt) {
  return function () {
    return elt.dir;
  };
};

exports.setDir = function (dir) {
  return function (elt) {
    return function () {
      elt.dir = dir;
      return {};
    };
  };
};

// ----------------------------------------------------------------------------

exports.className = function (elt) {
  return function () {
    return elt.className;
  };
};

exports.setClassName = function (className) {
  return function (elt) {
    return function () {
      elt.className = className;
      return {};
    };
  };
};

exports.classList = function (element) {
  return function () {
    return element.classList;
  };
};

// ----------------------------------------------------------------------------

exports.hidden = function (elt) {
  return function () {
    return elt.hidden;
  };
};

exports.setHidden = function (hidden) {
  return function (elt) {
    return function () {
      elt.hidden = hidden;
      return {};
    };
  };
};

// ----------------------------------------------------------------------------

exports.tabIndex = function (elt) {
  return function () {
    return elt.tabIndex;
  };
};

exports.setTabIndex = function (tabIndex) {
  return function (elt) {
    return function () {
      elt.tabIndex = tabIndex;
      return {};
    };
  };
};

// ----------------------------------------------------------------------------

exports.draggable = function (elt) {
  return function () {
    return elt.draggable;
  };
};

exports.setDraggable = function (draggable) {
  return function (elt) {
    return function () {
      elt.draggable = draggable;
      return {};
    };
  };
};

// ----------------------------------------------------------------------------

exports.contentEditable = function (elt) {
  return function () {
    return elt.contentEditable;
  };
};

exports.setContentEditable = function (contentEditable) {
  return function (elt) {
    return function () {
      elt.contentEditable = contentEditable;
      return {};
    };
  };
};

exports.isContentEditable = function (elt) {
  return function () {
    return elt.isContentEditable;
  };
};

// ----------------------------------------------------------------------------

exports.spellcheck = function (elt) {
  return function () {
    return elt.spellcheck;
  };
};

exports.setSpellcheck = function (spellcheck) {
  return function (elt) {
    return function () {
      elt.spellcheck = spellcheck;
      return {};
    };
  };
};

// ----------------------------------------------------------------------------

exports.click = function (elt) {
  return function () {
    return elt.click();
  };
};

exports.focus = function (elt) {
  return function () {
    return elt.focus();
  };
};

exports.blur = function (elt) {
  return function () {
    return elt.blur();
  };
};

// - CSSOM ---------------------------------------------------------------------

exports.getBoundingClientRect = function (el) {
  return function () {
    var rect = el.getBoundingClientRect();
    return {
      top: rect.top,
      right: rect.right,
      bottom: rect.bottom,
      left: rect.left,
      width: rect.width,
      height: rect.height
    };
  };
};

exports._offsetParent = function (el) {
  return function () {
    return el.offsetParent;
  };
};

exports.offsetTop = function (el) {
  return function () {
    return el.offsetTop;
  };
};

exports.offsetLeft = function (el) {
  return function () {
    return el.offsetLeft;
  };
};

exports.offsetWidth = function (el) {
  return function () {
    return el.offsetWidth;
  };
};

exports.offsetHeight = function (el) {
  return function () {
    return el.offsetHeight;
  };
};
<|endoftext|>


<commit_before>'use strict';

const {CompositeDisposable} = require('atom');
const path = require('path');
const Install = require('../../install');
const {logo} =  require('./assets');

class InstallElement extends HTMLElement {
  static initClass() {
    const elementClass = document.registerElement('kite-atom-install', {
      prototype: this.prototype,
    });
    atom.themes.requireStylesheet(path.resolve(__dirname, '..', '..', '..', 'styles', 'install.less'));
    atom.views.addViewProvider(Install, model => {
      const element = new elementClass();
      element.setModel(model);
      return element;
    });
    return elementClass;
  }

  createdCallback() {
    this.classList.add('native-key-bindings');
    this.innerHTML = `

${logo}

        <progress max='100' class="inline-block"></progress>
        Downloading Kite

        Installing Kite

        Starting Kite

        Installing the Kite plugin

`;

    this.logo = this.querySelector('.logo');
    this.content = this.querySelector('.content');
    this.progress = this.querySelector('progress');
    this.downloadKite = this.querySelector('.download-kite');
    this.installKite = this.querySelector('.install-kite');
    this.runKite = this.querySelector('.run-kite');
    this.installPlugin = this.querySelector('.install-plugin');
  }

  detachedCallback() {
    this.subscriptions && this.subscriptions.dispose();
    delete this.install;
    delete this.subscriptions;
  }

  setModel(install) {
    this.subscriptions = new CompositeDisposable();
    this.install = install;

    this.subscriptions.add(this.install.onDidChangeCurrentStep(() => {
      this.updateView();
    }));

    this.subscriptions.add(this.install.observeState(state => {
      this.logo.classList.toggle('hidden', !state.kiteLogoVisible);

      if (state.download) {
        if (state.download.done) {
          this.downloadKite.classList.add('hidden');
        } else {
          this.downloadKite.classList.remove('hidden');
        }

        if (state.download.ratio) {
          this.progress.value = Math.round(state.download.ratio * 100);
        }
      }

      if (state.install) {
        this.installKite.classList.toggle('hidden', state.install.done);
      }

      if (state.running) {
        this.runKite.classList.toggle('hidden', state.running.done);
      }

      if (state.plugin) {
        this.installPlugin.classList.toggle('hidden', state.plugin.done);
      }
    }));
  }

  getModel() {
    return this.install;
  }

  updateView() {
    if (this.currentView) { this.currentView.release(); }

    const view = this.install.getCurrentStepView();
    if (view) {
      if (this.content.children.length) {
        [].slice.call(this.content.children).forEach(n => this.content.removeChild(n));
      }
      this.content.appendChild(view);
      view.init(this.install);
      this.currentView = view;
    }
  }
}

module.exports = InstallElement.initClass();
<commit_msg>Wrap all progress indicators in their own container<commit_after>'use strict';

const {CompositeDisposable} = require('atom');
const path = require('path');
const Install = require('../../install');
const {logo} =  require('./assets');

class InstallElement extends HTMLElement {
  static initClass() {
    const elementClass = document.registerElement('kite-atom-install', {
      prototype: this.prototype,
    });
    atom.themes.requireStylesheet(path.resolve(__dirname, '..', '..', '..', 'styles', 'install.less'));
    atom.views.addViewProvider(Install, model => {
      const element = new elementClass();
      element.setModel(model);
      return element;
    });
    return elementClass;
  }

  createdCallback() {
    this.classList.add('native-key-bindings');
    this.innerHTML = `

${logo}

          <progress max='100' class="inline-block"></progress>
          Downloading Kite

          Installing Kite

          Starting Kite

          Installing the Kite plugin

`;

    this.logo = this.querySelector('.logo');
    this.content = this.querySelector('.content');
    this.progress = this.querySelector('progress');
    this.downloadKite = this.querySelector('.download-kite');
    this.installKite = this.querySelector('.install-kite');
    this.runKite = this.querySelector('.run-kite');
    this.installPlugin = this.querySelector('.install-plugin');
  }

  detachedCallback() {
    this.subscriptions && this.subscriptions.dispose();
    delete this.install;
    delete this.subscriptions;
  }

  setModel(install) {
    this.subscriptions = new CompositeDisposable();
    this.install = install;

    this.subscriptions.add(this.install.onDidChangeCurrentStep(() => {
      this.updateView();
    }));

    this.subscriptions.add(this.install.observeState(state => {
      this.logo.classList.toggle('hidden', !state.kiteLogoVisible);

      if (state.download) {
        if (state.download.done) {
          this.downloadKite.classList.add('hidden');
        } else {
          this.downloadKite.classList.remove('hidden');
        }

        if (state.download.ratio) {
          this.progress.value = Math.round(state.download.ratio * 100);
        }
      }

      if (state.install) {
        this.installKite.classList.toggle('hidden', state.install.done);
      }

      if (state.running) {
        this.runKite.classList.toggle('hidden', state.running.done);
      }

      if (state.plugin) {
        this.installPlugin.classList.toggle('hidden', state.plugin.done);
      }
    }));
  }

  getModel() {
    return this.install;
  }

  updateView() {
    if (this.currentView) { this.currentView.release(); }

    const view = this.install.getCurrentStepView();
    if (view) {
      if (this.content.children.length) {
        [].slice.call(this.content.children).forEach(n => this.content.removeChild(n));
      }
      this.content.appendChild(view);
      view.init(this.install);
      this.currentView = view;
    }
  }
}

module.exports = InstallElement.initClass();
<|endoftext|>


<commit_before>// SELECT S.foto, S.nombre,S.cum,(P.nombre) as patrulla,Pr.porcentaje FROM scouts S, patrullas P, users U,progresionespersonales  Pr WHERE S.patrulla=P.idpatrullas AND P.usuario=U.id AND S.cum=Pr.scout AND U.username=:username
var app = angular.module('Uhlu', ['ngRoute', 'ngMaterial','ngMessages','ngImgCrop', 'oitozero.ngSweetAlert']);
app.config(function($routeProvider, $mdThemingProvider) {
	$routeProvider
	  .when("/", {
	    templateUrl : "scouts.html",
	    controller: "scoutsCtrl"
	  })
	  .when("/scout/:cum/:tab", {
	    templateUrl : "scout.html",
	    controller: "scoutCtrl"
	  })
	  .when("/scout/:cum", {
	    templateUrl : "scout.html",
	    controller: "scoutCtrl"
	  })
	  .when("/patrullas", {
	    templateUrl : "patrullas.html",
	    controller: "patrullasCtrl"
	  })
	  .when("/patrulla/:id/:nombre", {
	    templateUrl : "patrulla.html",
	    controller: "patrullaCtrl"
	  })
	  .when("/fichasreme", {
	    templateUrl : "fichasreme.html",
	    controller: "fichasCtrl"
	  })
	  .when("/fichareme/:id", {
	    templateUrl : "fichareme.html",
	    controller: "fichaCtrl"
	  })
	  .when("/editarperfil", {
	    templateUrl : "editarperfil.html",
	    controller: "editarPerfilCtrl"
	  });

	  $mdThemingProvider.theme('default')
	      .primaryPalette('purple', {'default': '800'})
				.accentPalette('purple', {'default': '800'})
});

app.filter('capitalize', function() {
    return function(input) {
      return (!!input) ? input.charAt(0).toUpperCase() + input.substr(1).toLowerCase() : '';
    }
});
<commit_msg>Update app.js<commit_after>var app = angular.module('Uhlu', ['ngRoute', 'ngMaterial','ngMessages','ngImgCrop', 'oitozero.ngSweetAlert']);
app.config(function($routeProvider, $mdThemingProvider) {
	$routeProvider
	  .when("/", {
	    templateUrl : "scouts.html",
	    controller: "scoutsCtrl"
	  })
	  .when("/scout/:cum/:tab", {
	    templateUrl : "scout.html",
	    controller: "scoutCtrl"
	  })
	  .when("/scout/:cum", {
	    templateUrl : "scout.html",
	    controller: "scoutCtrl"
	  })
	  .when("/patrullas", {
	    templateUrl : "patrullas.html",
	    controller: "patrullasCtrl"
	  })
	  .when("/patrulla/:id/:nombre", {
	    templateUrl : "patrulla.html",
	    controller: "patrullaCtrl"
	  })
	  .when("/fichasreme", {
	    templateUrl : "fichasreme.html",
	    controller: "fichasCtrl"
	  })
	  .when("/fichareme/:id", {
	    templateUrl : "fichareme.html",
	    controller: "fichaCtrl"
	  })
	  .when("/editarperfil", {
	    templateUrl : "editarperfil.html",
	    controller: "editarPerfilCtrl"
	  });

	  $mdThemingProvider.theme('default')
	      .primaryPalette('purple', {'default': '800'})
				.accentPalette('purple', {'default': '800'})
});

app.filter('capitalize', function() {
    return function(input) {
      return (!!input) ? input.charAt(0).toUpperCase() + input.substr(1).toLowerCase() : '';
    }
});
<|endoftext|>


<commit_before>import {
  isFunction,
  isArray,
  isNumber,
  bind,
  assign
} from 'min-dash';

var FN_REF = '__fn';

var DEFAULT_PRIORITY = 1000;

var slice = Array.prototype.slice;

/**
 * A general purpose event bus.
 *
 * This component is used to communicate across a diagram instance.
 * Other parts of a diagram can use it to listen to and broadcast events.
 *
 *
 * ## Registering for Events
 *
 * The event bus provides the {@link EventBus#on} and {@link EventBus#once}
 * methods to register for events. {@link EventBus#off} can be used to
 * remove event registrations. Listeners receive an instance of {@link Event}
 * as the first argument. It allows them to hook into the event execution.
 *
 * ```javascript
 *
 * // listen for event
 * eventBus.on('foo', function(event) {
 *
 *   // access event type
 *   event.type; // 'foo'
 *
 *   // stop propagation to other listeners
 *   event.stopPropagation();
 *
 *   // prevent event default
 *   event.preventDefault();
 * });
 *
 * // listen for event with custom payload
 * eventBus.on('bar', function(event, payload) {
 *   console.log(payload);
 * });
 *
 * // listen for event returning value
 * eventBus.on('foobar', function(event) {
 *
 *   // stop event propagation + prevent default
 *   return false;
 *
 *   // stop event propagation + return custom result
 *   return {
 *     complex: 'listening result'
 *   };
 * });
 *
 *
 * // listen with custom priority (default=1000, higher is better)
 * eventBus.on('priorityfoo', 1500, function(event) {
 *   console.log('invoked first!');
 * });
 *
 *
 * // listen for event and pass the context (`this`)
 * eventBus.on('foobar', function(event) {
 *   this.foo();
 * }, this);
 * ```
 *
 *
 * ## Emitting Events
 *
 * Events can be emitted via the event bus using {@link EventBus#fire}.
 *
 * ```javascript
 *
 * // false indicates that the default action
 * // was prevented by listeners
 * if (eventBus.fire('foo') === false) {
 *   console.log('default has been prevented!');
 * };
 *
 *
 * // custom args + return value listener
 * eventBus.on('sum', function(event, a, b) {
 *   return a + b;
 * });
 *
 * // you can pass custom arguments + retrieve result values.
 * var sum = eventBus.fire('sum', 1, 2);
 * console.log(sum); // 3
 * ```
 */
export default function EventBus() {
  this._listeners = {};

  // cleanup on destroy on lowest priority to allow
  // message passing until the bitter end
  this.on('diagram.destroy', 1, this._destroy, this);
}

/**
 * Register an event listener for events with the given name.
 *
 * The callback will be invoked with `event, ...additionalArguments`
 * that have been passed to {@link EventBus#fire}.
 *
 * Returning false from a listener will prevent the events default action
 * (if any is specified). To stop an event from being processed further in
 * other listeners execute {@link Event#stopPropagation}.
 *
 * Returning anything but `undefined` from a listener will stop the listener propagation.
 *
 * @param {string|Array<string>} events
 * @param {number} [priority=1000] the priority in which this listener is called, larger is higher
 * @param {Function} callback
 * @param {Object} [that] Pass context (`this`) to the callback
 */
EventBus.prototype.on = function(events, priority, callback, that) {

  events = isArray(events) ? events : [ events ];

  if (isFunction(priority)) {
    that = callback;
    callback = priority;
    priority = DEFAULT_PRIORITY;
  }

  if (!isNumber(priority)) {
    throw new Error('priority must be a number');
  }

  var actualCallback = callback;

  if (that) {
    actualCallback = bind(callback, that);

    // make sure we remember and are able to remove
    // bound callbacks via {@link #off} using the original
    // callback
    actualCallback[FN_REF] = callback[FN_REF] || callback;
  }

  var self = this;

  events.forEach(function(e) {
    self._addListener(e, {
      priority: priority,
      callback: actualCallback,
      next: null
    });
  });
};

/**
 * Register an event listener that is executed only once.
 *
 * @param {string} event the event name to register for
 * @param {number} [priority=1000] the priority in which this listener is called, larger is higher
 * @param {Function} callback the callback to execute
 * @param {Object} [that] Pass context (`this`) to the callback
 */
EventBus.prototype.once = function(event, priority, callback, that) {
  var self = this;

  if (isFunction(priority)) {
    that = callback;
    callback = priority;
    priority = DEFAULT_PRIORITY;
  }

  if (!isNumber(priority)) {
    throw new Error('priority must be a number');
  }

  function wrappedCallback() {
    wrappedCallback.__isTomb = true;

    var result = callback.apply(that, arguments);

    self.off(event, wrappedCallback);

    return result;
  }

  // make sure we remember and are able to remove
  // bound callbacks via {@link #off} using the original
  // callback
  wrappedCallback[FN_REF] = callback;

  this.on(event, priority, wrappedCallback);
};

/**
 * Removes event listeners by event and callback.
 *
 * If no callback is given, all listeners for a given event name are being removed.
 *
 * @param {string|Array<string>} events
 * @param {Function} [callback]
 */
EventBus.prototype.off = function(events, callback) {

  events = isArray(events) ? events : [ events ];

  var self = this;

  events.forEach(function(event) {
    self._removeListener(event, callback);
  });

};

/**
 * Create an EventBus event.
 *
 * @param {Object} data
 *
 * @return {Object} event, recognized by the eventBus
 */
EventBus.prototype.createEvent = function(data) {
  var event = new InternalEvent();

  event.init(data);

  return event;
};

/**
 * Fires a named event.
 *
 * @example
 *
 * // fire event by name
 * events.fire('foo');
 *
 * // fire event object with nested type
 * var event = { type: 'foo' };
 * events.fire(event);
 *
 * // fire event with explicit type
 * var event = { x: 10, y: 20 };
 * events.fire('element.moved', event);
 *
 * // pass additional arguments to the event
 * events.on('foo', function(event, bar) {
 *   alert(bar);
 * });
 *
 * events.fire({ type: 'foo' }, 'I am bar!');
 *
 * @param {string} [name] the optional event name
 * @param {Object} [event] the event object
 * @param {...Object} additional arguments to be passed to the callback functions
 *
 * @return {boolean} the events return value, if specified or false if the
 *                   default action was prevented by listeners
 */
EventBus.prototype.fire = function(type, data) {
  var event,
      firstListener,
      returnValue,
      args;

  args = slice.call(arguments);

  if (typeof type === 'object') {
    data = type;
    type = data.type;
  }

  if (!type) {
    throw new Error('no event type specified');
  }

  firstListener = this._listeners[type];

  if (!firstListener) {
    return;
  }

  // we make sure we fire instances of our home made
  // events here. We wrap them only once, though
  if (data instanceof InternalEvent) {

    // we are fine, we alread have an event
    event = data;
  } else {
    event = this.createEvent(data);
  }

  // ensure we pass the event as the first parameter
  args[0] = event;

  // original event type (in case we delegate)
  var originalType = event.type;

  // update event type before delegation
  if (type !== originalType) {
    event.type = type;
  }

  try {
    returnValue = this._invokeListeners(event, args, firstListener);
  } finally {

    // reset event type after delegation
    if (type !== originalType) {
      event.type = originalType;
    }
  }

  // set the return value to false if the event default
  // got prevented and no other return value exists
  if (returnValue === undefined && event.defaultPrevented) {
    returnValue = false;
  }

  return returnValue;
};

EventBus.prototype.handleError = function(error) {
  return this.fire('error', { error: error }) === false;
};

EventBus.prototype._destroy = function() {
  this._listeners = {};
};

EventBus.prototype._invokeListeners = function(event, args, listener) {

  var returnValue;

  while (listener) {

    // handle stopped propagation
    if (event.cancelBubble) {
      break;
    }

    returnValue = this._invokeListener(event, args, listener);

    listener = listener.next;
  }

  return returnValue;
};

EventBus.prototype._invokeListener = function(event, args, listener) {

  var returnValue;

  if (listener.callback.__isTomb) {
    return returnValue;
  }

  try {

    // returning false prevents the default action
    returnValue = invokeFunction(listener.callback, args);

    // stop propagation on return value
    if (returnValue !== undefined) {
      event.returnValue = returnValue;
      event.stopPropagation();
    }

    // prevent default on return false
    if (returnValue === false) {
      event.preventDefault();
    }
  } catch (e) {
    if (!this.handleError(e)) {
      console.error('unhandled error in event listener');
      console.error(e.stack);

      throw e;
    }
  }

  return returnValue;
};

/*
 * Add new listener with a certain priority to the list
 * of listeners (for the given event).
 *
 * The semantics of listener registration / listener execution are
 * first register, first serve: New listeners will always be inserted
 * after existing listeners with the same priority.
 *
 * Example: Inserting two listeners with priority 1000 and 1300
 *
 *    * before: [ 1500, 1500, 1000, 1000 ]
 *    * after: [ 1500, 1500, (new=1300), 1000, 1000, (new=1000) ]
 *
 * @param {string} event
 * @param {Object} listener { priority, callback }
 */
EventBus.prototype._addListener = function(event, newListener) {

  var listener = this._getListeners(event),
      previousListener;

  // no prior listeners
  if (!listener) {
    this._setListeners(event, newListener);

    return;
  }

  // ensure we order listeners by priority from
  // 0 (high) to n > 0 (low)
  while (listener) {

    if (listener.priority < newListener.priority) {

      newListener.next = listener;

      if (previousListener) {
        previousListener.next = newListener;
      } else {
        this._setListeners(event, newListener);
      }

      return;
    }

    previousListener = listener;
    listener = listener.next;
  }

  // add new listener to back
  previousListener.next = newListener;
};

EventBus.prototype._getListeners = function(name) {
  return this._listeners[name];
};

EventBus.prototype._setListeners = function(name, listener) {
  this._listeners[name] = listener;
};

EventBus.prototype._removeListener = function(event, callback) {

  var listener = this._getListeners(event),
      nextListener,
      previousListener,
      listenerCallback;

  if (!callback) {

    // clear listeners
    this._setListeners(event, null);

    return;
  }

  while (listener) {

    nextListener = listener.next;

    listenerCallback = listener.callback;

    if (listenerCallback === callback || listenerCallback[FN_REF] === callback) {
      if (previousListener) {
        previousListener.next = nextListener;
      } else {

        // new first listener
        this._setListeners(event, nextListener);
      }
    }

    previousListener = listener;
    listener = nextListener;
  }
};

/**
 * A event that is emitted via the event bus.
 */
function InternalEvent() { }

InternalEvent.prototype.stopPropagation = function() {
  this.cancelBubble = true;
};

InternalEvent.prototype.preventDefault = function() {
  this.defaultPrevented = true;
};

InternalEvent.prototype.init = function(data) {
  assign(this, data || {});
};

/**
 * Invoke function. Be fast...
 *
 * @param {Function} fn
 * @param {Array<Object>} args
 *
 * @return {Any}
 */
function invokeFunction(fn, args) {
  return fn.apply(null, args);
}
<commit_msg>chore: log EventBus error and message on the same line<commit_after>import {
  isFunction,
  isArray,
  isNumber,
  bind,
  assign
} from 'min-dash';

var FN_REF = '__fn';

var DEFAULT_PRIORITY = 1000;

var slice = Array.prototype.slice;

/**
 * A general purpose event bus.
 *
 * This component is used to communicate across a diagram instance.
 * Other parts of a diagram can use it to listen to and broadcast events.
 *
 *
 * ## Registering for Events
 *
 * The event bus provides the {@link EventBus#on} and {@link EventBus#once}
 * methods to register for events. {@link EventBus#off} can be used to
 * remove event registrations. Listeners receive an instance of {@link Event}
 * as the first argument. It allows them to hook into the event execution.
 *
 * ```javascript
 *
 * // listen for event
 * eventBus.on('foo', function(event) {
 *
 *   // access event type
 *   event.type; // 'foo'
 *
 *   // stop propagation to other listeners
 *   event.stopPropagation();
 *
 *   // prevent event default
 *   event.preventDefault();
 * });
 *
 * // listen for event with custom payload
 * eventBus.on('bar', function(event, payload) {
 *   console.log(payload);
 * });
 *
 * // listen for event returning value
 * eventBus.on('foobar', function(event) {
 *
 *   // stop event propagation + prevent default
 *   return false;
 *
 *   // stop event propagation + return custom result
 *   return {
 *     complex: 'listening result'
 *   };
 * });
 *
 *
 * // listen with custom priority (default=1000, higher is better)
 * eventBus.on('priorityfoo', 1500, function(event) {
 *   console.log('invoked first!');
 * });
 *
 *
 * // listen for event and pass the context (`this`)
 * eventBus.on('foobar', function(event) {
 *   this.foo();
 * }, this);
 * ```
 *
 *
 * ## Emitting Events
 *
 * Events can be emitted via the event bus using {@link EventBus#fire}.
 *
 * ```javascript
 *
 * // false indicates that the default action
 * // was prevented by listeners
 * if (eventBus.fire('foo') === false) {
 *   console.log('default has been prevented!');
 * };
 *
 *
 * // custom args + return value listener
 * eventBus.on('sum', function(event, a, b) {
 *   return a + b;
 * });
 *
 * // you can pass custom arguments + retrieve result values.
 * var sum = eventBus.fire('sum', 1, 2);
 * console.log(sum); // 3
 * ```
 */
export default function EventBus() {
  this._listeners = {};

  // cleanup on destroy on lowest priority to allow
  // message passing until the bitter end
  this.on('diagram.destroy', 1, this._destroy, this);
}

/**
 * Register an event listener for events with the given name.
 *
 * The callback will be invoked with `event, ...additionalArguments`
 * that have been passed to {@link EventBus#fire}.
 *
 * Returning false from a listener will prevent the events default action
 * (if any is specified). To stop an event from being processed further in
 * other listeners execute {@link Event#stopPropagation}.
 *
 * Returning anything but `undefined` from a listener will stop the listener propagation.
 *
 * @param {string|Array<string>} events
 * @param {number} [priority=1000] the priority in which this listener is called, larger is higher
 * @param {Function} callback
 * @param {Object} [that] Pass context (`this`) to the callback
 */
EventBus.prototype.on = function(events, priority, callback, that) {

  events = isArray(events) ? events : [ events ];

  if (isFunction(priority)) {
    that = callback;
    callback = priority;
    priority = DEFAULT_PRIORITY;
  }

  if (!isNumber(priority)) {
    throw new Error('priority must be a number');
  }

  var actualCallback = callback;

  if (that) {
    actualCallback = bind(callback, that);

    // make sure we remember and are able to remove
    // bound callbacks via {@link #off} using the original
    // callback
    actualCallback[FN_REF] = callback[FN_REF] || callback;
  }

  var self = this;

  events.forEach(function(e) {
    self._addListener(e, {
      priority: priority,
      callback: actualCallback,
      next: null
    });
  });
};

/**
 * Register an event listener that is executed only once.
 *
 * @param {string} event the event name to register for
 * @param {number} [priority=1000] the priority in which this listener is called, larger is higher
 * @param {Function} callback the callback to execute
 * @param {Object} [that] Pass context (`this`) to the callback
 */
EventBus.prototype.once = function(event, priority, callback, that) {
  var self = this;

  if (isFunction(priority)) {
    that = callback;
    callback = priority;
    priority = DEFAULT_PRIORITY;
  }

  if (!isNumber(priority)) {
    throw new Error('priority must be a number');
  }

  function wrappedCallback() {
    wrappedCallback.__isTomb = true;

    var result = callback.apply(that, arguments);

    self.off(event, wrappedCallback);

    return result;
  }

  // make sure we remember and are able to remove
  // bound callbacks via {@link #off} using the original
  // callback
  wrappedCallback[FN_REF] = callback;

  this.on(event, priority, wrappedCallback);
};

/**
 * Removes event listeners by event and callback.
 *
 * If no callback is given, all listeners for a given event name are being removed.
 *
 * @param {string|Array<string>} events
 * @param {Function} [callback]
 */
EventBus.prototype.off = function(events, callback) {

  events = isArray(events) ? events : [ events ];

  var self = this;

  events.forEach(function(event) {
    self._removeListener(event, callback);
  });

};

/**
 * Create an EventBus event.
 *
 * @param {Object} data
 *
 * @return {Object} event, recognized by the eventBus
 */
EventBus.prototype.createEvent = function(data) {
  var event = new InternalEvent();

  event.init(data);

  return event;
};

/**
 * Fires a named event.
 *
 * @example
 *
 * // fire event by name
 * events.fire('foo');
 *
 * // fire event object with nested type
 * var event = { type: 'foo' };
 * events.fire(event);
 *
 * // fire event with explicit type
 * var event = { x: 10, y: 20 };
 * events.fire('element.moved', event);
 *
 * // pass additional arguments to the event
 * events.on('foo', function(event, bar) {
 *   alert(bar);
 * });
 *
 * events.fire({ type: 'foo' }, 'I am bar!');
 *
 * @param {string} [name] the optional event name
 * @param {Object} [event] the event object
 * @param {...Object} additional arguments to be passed to the callback functions
 *
 * @return {boolean} the events return value, if specified or false if the
 *                   default action was prevented by listeners
 */
EventBus.prototype.fire = function(type, data) {
  var event,
      firstListener,
      returnValue,
      args;

  args = slice.call(arguments);

  if (typeof type === 'object') {
    data = type;
    type = data.type;
  }

  if (!type) {
    throw new Error('no event type specified');
  }

  firstListener = this._listeners[type];

  if (!firstListener) {
    return;
  }

  // we make sure we fire instances of our home made
  // events here. We wrap them only once, though
  if (data instanceof InternalEvent) {

    // we are fine, we alread have an event
    event = data;
  } else {
    event = this.createEvent(data);
  }

  // ensure we pass the event as the first parameter
  args[0] = event;

  // original event type (in case we delegate)
  var originalType = event.type;

  // update event type before delegation
  if (type !== originalType) {
    event.type = type;
  }

  try {
    returnValue = this._invokeListeners(event, args, firstListener);
  } finally {

    // reset event type after delegation
    if (type !== originalType) {
      event.type = originalType;
    }
  }

  // set the return value to false if the event default
  // got prevented and no other return value exists
  if (returnValue === undefined && event.defaultPrevented) {
    returnValue = false;
  }

  return returnValue;
};

EventBus.prototype.handleError = function(error) {
  return this.fire('error', { error: error }) === false;
};

EventBus.prototype._destroy = function() {
  this._listeners = {};
};

EventBus.prototype._invokeListeners = function(event, args, listener) {

  var returnValue;

  while (listener) {

    // handle stopped propagation
    if (event.cancelBubble) {
      break;
    }

    returnValue = this._invokeListener(event, args, listener);

    listener = listener.next;
  }

  return returnValue;
};

EventBus.prototype._invokeListener = function(event, args, listener) {

  var returnValue;

  if (listener.callback.__isTomb) {
    return returnValue;
  }

  try {

    // returning false prevents the default action
    returnValue = invokeFunction(listener.callback, args);

    // stop propagation on return value
    if (returnValue !== undefined) {
      event.returnValue = returnValue;
      event.stopPropagation();
    }

    // prevent default on return false
    if (returnValue === false) {
      event.preventDefault();
    }
  } catch (error) {
    if (!this.handleError(error)) {
      console.error('unhandled error in event listener', error);

      throw error;
    }
  }

  return returnValue;
};

/*
 * Add new listener with a certain priority to the list
 * of listeners (for the given event).
 *
 * The semantics of listener registration / listener execution are
 * first register, first serve: New listeners will always be inserted
 * after existing listeners with the same priority.
 *
 * Example: Inserting two listeners with priority 1000 and 1300
 *
 *    * before: [ 1500, 1500, 1000, 1000 ]
 *    * after: [ 1500, 1500, (new=1300), 1000, 1000, (new=1000) ]
 *
 * @param {string} event
 * @param {Object} listener { priority, callback }
 */
EventBus.prototype._addListener = function(event, newListener) {

  var listener = this._getListeners(event),
      previousListener;

  // no prior listeners
  if (!listener) {
    this._setListeners(event, newListener);

    return;
  }

  // ensure we order listeners by priority from
  // 0 (high) to n > 0 (low)
  while (listener) {

    if (listener.priority < newListener.priority) {

      newListener.next = listener;

      if (previousListener) {
        previousListener.next = newListener;
      } else {
        this._setListeners(event, newListener);
      }

      return;
    }

    previousListener = listener;
    listener = listener.next;
  }

  // add new listener to back
  previousListener.next = newListener;
};

EventBus.prototype._getListeners = function(name) {
  return this._listeners[name];
};

EventBus.prototype._setListeners = function(name, listener) {
  this._listeners[name] = listener;
};

EventBus.prototype._removeListener = function(event, callback) {

  var listener = this._getListeners(event),
      nextListener,
      previousListener,
      listenerCallback;

  if (!callback) {

    // clear listeners
    this._setListeners(event, null);

    return;
  }

  while (listener) {

    nextListener = listener.next;

    listenerCallback = listener.callback;

    if (listenerCallback === callback || listenerCallback[FN_REF] === callback) {
      if (previousListener) {
        previousListener.next = nextListener;
      } else {

        // new first listener
        this._setListeners(event, nextListener);
      }
    }

    previousListener = listener;
    listener = nextListener;
  }
};

/**
 * A event that is emitted via the event bus.
 */
function InternalEvent() { }

InternalEvent.prototype.stopPropagation = function() {
  this.cancelBubble = true;
};

InternalEvent.prototype.preventDefault = function() {
  this.defaultPrevented = true;
};

InternalEvent.prototype.init = function(data) {
  assign(this, data || {});
};

/**
 * Invoke function. Be fast...
 *
 * @param {Function} fn
 * @param {Array<Object>} args
 *
 * @return {Any}
 */
function invokeFunction(fn, args) {
  return fn.apply(null, args);
}
<|endoftext|>


<commit_before>const TelegrafContext = require('./context')

class Composer {
  constructor (...fns) {
    this.handler = Composer.compose(fns)
  }

  use (...fns) {
    this.handler = Composer.compose([this.handler, ...fns])
    return this
  }

  on (updateTypes, ...fns) {
    return this.use(Composer.mount(updateTypes, ...fns))
  }

  hears (triggers, ...fns) {
    return this.use(Composer.hears(triggers, ...fns))
  }

  command (commands, ...fns) {
    return this.use(Composer.command(commands, ...fns))
  }

  action (triggers, ...fns) {
    return this.use(Composer.action(triggers, ...fns))
  }

  gameQuery (...fns) {
    return this.use(Composer.gameQuery(...fns))
  }

  drop (predicate) {
    return this.use(Composer.drop(predicate))
  }

  filter (predicate) {
    return this.use(Composer.filter(predicate))
  }

  entity (...args) {
    return this.use(Composer.entity(...args))
  }

  mention (...args) {
    return this.use(Composer.mention(...args))
  }

  hashtag (...args) {
    return this.use(Composer.hashtag(...args))
  }

  middleware () {
    return this.handler
  }

  static reply (...args) {
    return (ctx) => ctx.reply(...args)
  }

  static fork (middleware) {
    return (ctx, next) => {
      setImmediate(Composer.unwrap(middleware), ctx, Composer.safePassThru())
      return next(ctx)
    }
  }

  static passThru () {
    return (ctx, next) => next(ctx)
  }

  static safePassThru () {
    return (ctx, next) => typeof next === 'function' ? next(ctx) : Promise.resolve()
  }

  static lazy (factoryFn) {
    if (typeof factoryFn !== 'function') {
      throw new Error('Argument must be a function')
    }
    return (ctx, next) => Promise.resolve(factoryFn(ctx))
      .then((middleware) => Composer.unwrap(middleware)(ctx, next))
  }

  static log (logFn = console.log) {
    return Composer.fork((ctx) => logFn(JSON.stringify(ctx.update, null, 2)))
  }

  static branch (predicate, trueMiddleware, falseMiddleware) {
    if (typeof predicate !== 'function') {
      return predicate ? trueMiddleware : falseMiddleware
    }
    return Composer.lazy((ctx) => Promise.resolve(predicate(ctx))
      .then((value) => value ? trueMiddleware : falseMiddleware))
  }

  static optional (predicate, ...fns) {
    return Composer.branch(predicate, Composer.compose(fns), Composer.safePassThru())
  }

  static filter (predicate) {
    return Composer.branch(predicate, Composer.safePassThru(), () => { })
  }

  static drop (predicate) {
    return Composer.branch(predicate, () => { }, Composer.safePassThru())
  }

  static dispatch (routeFn, handlers) {
    return typeof routeFn === 'function'
      ? Composer.lazy((ctx) => Promise.resolve(routeFn(ctx)).then((value) => handlers[value]))
      : handlers[routeFn]
  }

  static mount (updateType, ...fns) {
    const updateTypes = normalizeTextArguments(updateType)
    const predicate = (ctx) => updateTypes.includes(ctx.updateType) || updateTypes.some((type) => ctx.updateSubTypes.includes(type))
    return Composer.optional(predicate, ...fns)
  }

  static hears (triggers, ...fns) {
    return Composer.mount('text', Composer.match(normalizeTriggers(triggers), ...fns))
  }

  static entity (predicate, ...fns) {
    if (typeof predicate !== 'function') {
      const entityTypes = normalizeTextArguments(predicate)
      return Composer.entity(({ type }) => entityTypes.includes(type), ...fns)
    }
    return Composer.optional(({ message }) => {
      return message && message.entities && message.entities.some((entity) => predicate(entity, message.text.substring(entity.offset, entity.offset + entity.length)))
    }, ...fns)
  }

  static mention (username, ...fns) {
    if (fns.length === 0) {
      return Composer.entity(['mention'], username)
    }
    const usernames = normalizeTextArguments(username, '@')
    return Composer.entity(({ type }, value) => type === 'mention' && usernames.includes(value), ...fns)
  }

  static hashtag (hashtag, ...fns) {
    if (fns.length === 0) {
      return Composer.entity(['hashtag'], hashtag)
    }
    const hashtags = normalizeTextArguments(hashtag, '#')
    return Composer.entity(({ type }, value) => type === 'hashtag' && hashtags.includes(value), ...fns)
  }

  static command (command, ...fns) {
    if (fns.length === 0) {
      return Composer.entity(['bot_command'], command)
    }
    const commands = normalizeTextArguments(command, '/')
    return Composer.mount('text', Composer.lazy((ctx) => {
      const groupCommands = ctx.me && (ctx.chat.type === 'group' || ctx.chat.type === 'supergroup')
        ? commands.map((command) => `${command}@${ctx.me}`)
        : []
      return Composer.entity(({ offset, type }, value) =>
        offset === 0 &&
        type === 'bot_command' &&
        (commands.includes(value) || groupCommands.includes(value))
        , ...fns)
    }))
  }

  static action (triggers, ...fns) {
    return Composer.mount('callback_query', Composer.match(normalizeTriggers(triggers), ...fns))
  }

  static match (triggers, ...fns) {
    return Composer.lazy((ctx) => {
      const text = (
        (ctx.message && (ctx.message.caption || ctx.message.text)) ||
        (ctx.callbackQuery && ctx.callbackQuery.data)
      )
      for (let trigger of triggers) {
        ctx.match = trigger(text, ctx)
        if (ctx.match) {
          return Composer.compose(fns)
        }
      }
      return Composer.safePassThru()
    })
  }

  static acl (userId, ...fns) {
    if (typeof userId === 'function') {
      return Composer.optional(userId, ...fns)
    }
    const allowed = Array.isArray(userId) ? userId : [userId]
    return Composer.optional((ctx) => !ctx.from || allowed.includes(ctx.from.id), ...fns)
  }

  static gameQuery (...fns) {
    return Composer.mount('callback_query', Composer.optional((ctx) => ctx.callbackQuery.game_short_name, ...fns))
  }

  static unwrap (handler) {
    return handler && typeof handler.middleware === 'function'
      ? handler.middleware()
      : handler
  }

  static compose (middlewares) {
    if (!Array.isArray(middlewares)) {
      throw new Error('Middlewares must be an array')
    }
    if (middlewares.length === 0) {
      return Composer.safePassThru()
    }
    if (middlewares.length === 1) {
      return Composer.unwrap(middlewares[0])
    }
    return (ctx, next) => {
      let index = -1
      return execute(0, ctx)
      function execute (i, context) {
        if (!(context instanceof TelegrafContext)) {
          return Promise.reject(new Error('next(ctx) called with invalid context'))
        }
        if (i <= index) {
          return Promise.reject(new Error('next() called multiple times'))
        }
        index = i
        const handler = Composer.unwrap(middlewares[i]) || next
        if (!handler) {
          return Promise.resolve()
        }
        try {
          return Promise.resolve(
            handler(context, (ctx = context) => execute(i + 1, ctx))
          )
        } catch (err) {
          return Promise.reject(err)
        }
      }
    }
  }
}

function normalizeTriggers (triggers) {
  if (!Array.isArray(triggers)) {
    triggers = [triggers]
  }
  return triggers.map((trigger) => {
    if (!trigger) {
      throw new Error('Invalid trigger')
    }
    if (typeof trigger === 'function') {
      return trigger
    }
    if (trigger instanceof RegExp) {
      return (value) => {
        trigger.lastIndex = 0
        return trigger.exec(value || '')
      }
    }
    return (value) => trigger === value ? value : null
  })
}

function normalizeTextArguments (argument, prefix) {
  const args = Array.isArray(argument) ? argument : [argument]
  return args
    .filter((item) => item)
    .map((arg) => arg && prefix && !arg.startsWith(prefix) ? `${prefix}${arg}` : arg)
}

module.exports = Composer
<commit_msg>format code<commit_after>const TelegrafContext = require('./context')

class Composer {
  constructor (...fns) {
    this.handler = Composer.compose(fns)
  }

  use (...fns) {
    this.handler = Composer.compose([this.handler, ...fns])
    return this
  }

  on (updateTypes, ...fns) {
    return this.use(Composer.mount(updateTypes, ...fns))
  }

  hears (triggers, ...fns) {
    return this.use(Composer.hears(triggers, ...fns))
  }

  command (commands, ...fns) {
    return this.use(Composer.command(commands, ...fns))
  }

  action (triggers, ...fns) {
    return this.use(Composer.action(triggers, ...fns))
  }

  gameQuery (...fns) {
    return this.use(Composer.gameQuery(...fns))
  }

  drop (predicate) {
    return this.use(Composer.drop(predicate))
  }

  filter (predicate) {
    return this.use(Composer.filter(predicate))
  }

  entity (...args) {
    return this.use(Composer.entity(...args))
  }

  mention (...args) {
    return this.use(Composer.mention(...args))
  }

  hashtag (...args) {
    return this.use(Composer.hashtag(...args))
  }

  middleware () {
    return this.handler
  }

  static reply (...args) {
    return (ctx) => ctx.reply(...args)
  }

  static fork (middleware) {
    return (ctx, next) => {
      setImmediate(Composer.unwrap(middleware), ctx, Composer.safePassThru())
      return next(ctx)
    }
  }

  static passThru () {
    return (ctx, next) => next(ctx)
  }

  static safePassThru () {
    return (ctx, next) => typeof next === 'function' ? next(ctx) : Promise.resolve()
  }

  static lazy (factoryFn) {
    if (typeof factoryFn !== 'function') {
      throw new Error('Argument must be a function')
    }
    return (ctx, next) => Promise.resolve(factoryFn(ctx))
      .then((middleware) => Composer.unwrap(middleware)(ctx, next))
  }

  static log (logFn = console.log) {
    return Composer.fork((ctx) => logFn(JSON.stringify(ctx.update, null, 2)))
  }

  static branch (predicate, trueMiddleware, falseMiddleware) {
    if (typeof predicate !== 'function') {
      return predicate ? trueMiddleware : falseMiddleware
    }
    return Composer.lazy((ctx) => Promise.resolve(predicate(ctx))
      .then((value) => value ? trueMiddleware : falseMiddleware))
  }

  static optional (predicate, ...fns) {
    return Composer.branch(predicate, Composer.compose(fns), Composer.safePassThru())
  }

  static filter (predicate) {
    return Composer.branch(predicate, Composer.safePassThru(), () => { })
  }

  static drop (predicate) {
    return Composer.branch(predicate, () => { }, Composer.safePassThru())
  }

  static dispatch (routeFn, handlers) {
    return typeof routeFn === 'function'
      ? Composer.lazy((ctx) => Promise.resolve(routeFn(ctx)).then((value) => handlers[value]))
      : handlers[routeFn]
  }

  static mount (updateType, ...fns) {
    const updateTypes = normalizeTextArguments(updateType)
    const predicate = (ctx) => updateTypes.includes(ctx.updateType) || updateTypes.some((type) => ctx.updateSubTypes.includes(type))
    return Composer.optional(predicate, ...fns)
  }

  static hears (triggers, ...fns) {
    return Composer.mount('text', Composer.match(normalizeTriggers(triggers), ...fns))
  }

  static entity (predicate, ...fns) {
    if (typeof predicate !== 'function') {
      const entityTypes = normalizeTextArguments(predicate)
      return Composer.entity(({ type }) => entityTypes.includes(type), ...fns)
    }
    return Composer.optional(({ message }) =>
      message &&
      message.entities &&
      message.entities.some((entity) => predicate(entity, message.text.substring(entity.offset, entity.offset + entity.length)))
      , ...fns)
  }

  static mention (username, ...fns) {
    if (fns.length === 0) {
      return Composer.entity(['mention'], username)
    }
    const usernames = normalizeTextArguments(username, '@')
    return Composer.entity(({ type }, value) => type === 'mention' && usernames.includes(value), ...fns)
  }

  static hashtag (hashtag, ...fns) {
    if (fns.length === 0) {
      return Composer.entity(['hashtag'], hashtag)
    }
    const hashtags = normalizeTextArguments(hashtag, '#')
    return Composer.entity(({ type }, value) => type === 'hashtag' && hashtags.includes(value), ...fns)
  }

  static command (command, ...fns) {
    if (fns.length === 0) {
      return Composer.entity(['bot_command'], command)
    }
    const commands = normalizeTextArguments(command, '/')
    return Composer.mount('text', Composer.lazy((ctx) => {
      const groupCommands = ctx.me && (ctx.chat.type === 'group' || ctx.chat.type === 'supergroup')
        ? commands.map((command) => `${command}@${ctx.me}`)
        : []
      return Composer.entity(({ offset, type }, value) =>
        offset === 0 &&
        type === 'bot_command' &&
        (commands.includes(value) || groupCommands.includes(value))
        , ...fns)
    }))
  }

  static action (triggers, ...fns) {
    return Composer.mount('callback_query', Composer.match(normalizeTriggers(triggers), ...fns))
  }

  static match (triggers, ...fns) {
    return Composer.lazy((ctx) => {
      const text = (
        (ctx.message && (ctx.message.caption || ctx.message.text)) ||
        (ctx.callbackQuery && ctx.callbackQuery.data)
      )
      for (let trigger of triggers) {
        ctx.match = trigger(text, ctx)
        if (ctx.match) {
          return Composer.compose(fns)
        }
      }
      return Composer.safePassThru()
    })
  }

  static acl (userId, ...fns) {
    if (typeof userId === 'function') {
      return Composer.optional(userId, ...fns)
    }
    const allowed = Array.isArray(userId) ? userId : [userId]
    return Composer.optional((ctx) => !ctx.from || allowed.includes(ctx.from.id), ...fns)
  }

  static gameQuery (...fns) {
    return Composer.mount('callback_query', Composer.optional((ctx) => ctx.callbackQuery.game_short_name, ...fns))
  }

  static unwrap (handler) {
    return handler && typeof handler.middleware === 'function'
      ? handler.middleware()
      : handler
  }

  static compose (middlewares) {
    if (!Array.isArray(middlewares)) {
      throw new Error('Middlewares must be an array')
    }
    if (middlewares.length === 0) {
      return Composer.safePassThru()
    }
    if (middlewares.length === 1) {
      return Composer.unwrap(middlewares[0])
    }
    return (ctx, next) => {
      let index = -1
      return execute(0, ctx)
      function execute (i, context) {
        if (!(context instanceof TelegrafContext)) {
          return Promise.reject(new Error('next(ctx) called with invalid context'))
        }
        if (i <= index) {
          return Promise.reject(new Error('next() called multiple times'))
        }
        index = i
        const handler = Composer.unwrap(middlewares[i]) || next
        if (!handler) {
          return Promise.resolve()
        }
        try {
          return Promise.resolve(
            handler(context, (ctx = context) => execute(i + 1, ctx))
          )
        } catch (err) {
          return Promise.reject(err)
        }
      }
    }
  }
}

function normalizeTriggers (triggers) {
  if (!Array.isArray(triggers)) {
    triggers = [triggers]
  }
  return triggers.map((trigger) => {
    if (!trigger) {
      throw new Error('Invalid trigger')
    }
    if (typeof trigger === 'function') {
      return trigger
    }
    if (trigger instanceof RegExp) {
      return (value) => {
        trigger.lastIndex = 0
        return trigger.exec(value || '')
      }
    }
    return (value) => trigger === value ? value : null
  })
}

function normalizeTextArguments (argument, prefix) {
  const args = Array.isArray(argument) ? argument : [argument]
  return args
    .filter((item) => item)
    .map((arg) => arg && prefix && !arg.startsWith(prefix) ? `${prefix}${arg}` : arg)
}

module.exports = Composer
<|endoftext|>


<commit_before>goog.provide('lime.ui.Scroller');

goog.require('lime.Sprite');
goog.require('lime.animation.MoveTo');

lime.ui.Scroller = function(){

    goog.base(this);

    //need default size for autoresize
    this.setSize(100,100);

    this.clipper = new lime.Sprite().setFill('#c00').setSize(100,100).setAutoResize(lime.AutoResize.ALL);
	this.appendChild(this.clipper);
	this.setMask(this.clipper);

	this.moving_ = new lime.Layer();
	lime.Node.prototype.appendChild.call(this,this.moving_);

	goog.events.listen(this,['mousedown','touchstart'],this.downHandler_,false,this);

  	this.setDirection(lime.ui.Scroller.Direction.HORIZONTAL);

}
goog.inherits(lime.ui.Scroller, lime.Sprite);

/**
 * Offset that can be dragged over the edge
 * @const
 * @type {number}
 */
lime.ui.Scroller.OFFSET = 250;

/**
 * Factor to slow down if over the edge
 * @const
 * @type {number}
 */
lime.ui.Scroller.OFFSET_LAG = .4;

/**
 * How fast to slow down
 * @const
 * @type {number}
 */
lime.ui.Scroller.FRICTION = .95;

/**
 * Direction of the scroller.
 * @enum {number}
 */
lime.ui.Scroller.Direction = {
  HORIZONTAL : 0,
  VERTICAL : 1
};

lime.ui.Scroller.prototype.getDirection = function(){
    return this.direction_;
}

lime.ui.Scroller.prototype.setDirection = function(direction){
    this.direction_ = direction;
    return this;
};

/** @inheritDoc */
lime.ui.Scroller.prototype.setAnchorPoint = function(){
    if(this.clipper){
        this.clipper.setAnchorPoint.apply(this.clipper,arguments);
    }
    return lime.Node.prototype.setAnchorPoint.apply(this,arguments);
}

/** @inheritDoc */

lime.ui.Scroller.prototype.appendChild = function(){
    if(this.moving_) return this.moving_.appendChild.apply(this.moving_,arguments);
    return lime.Node.prototype.appendChild.apply(this,arguments);
}

/** @inheritDoc */
lime.ui.Scroller.prototype.removeChild = function(){
    //if(this.moving_) return this.moving_.removeChild.apply(this.moving_,arguments);
    return lime.Node.prototype.removeChild.apply(this,arguments);
}

lime.ui.Scroller.prototype.measureLimits = function(){

    var measure = this.moving_.measureContents();
    if(this.getDirection()==lime.ui.Scroller.Direction.HORIZONTAL){
        this.downy=this.moving_.getPosition().y;
        var max = this.getSize().width;

        this.LOW = -measure.left;
        this.HIGH =Math.min(max-measure.right,-measure.left);
        var diff = (measure.right-measure.left)-max;
    }
    else {
        this.downx=this.moving_.getPosition().x;
        max = this.getSize().height;

        this.LOW = -measure.top;
        this.HIGH =Math.min(max-measure.bottom,-measure.top);
        diff = (measure.bottom-measure.top)-max;
    }

    if(diff>0){
        this.LOW-=diff;
        this.HIGH+=diff;
    }
}

lime.ui.Scroller.prototype.scrollTo = function(offset,opt_duration){
    var pos = this.moving_.getPosition().clone();
    var duration = opt_duration || 0;

    this.measureLimits();

    if(offset<0) offset = 0;

    if(this.getDirection()==lime.ui.Scroller.Direction.HORIZONTAL){
        pos.x = this.HIGH - offset;
        if(pos.x<this.LOW) pos.x = this.LOW;
    }
    else {
        pos.y = this.HIGH - offset;
        if(pos.y<this.LOW) pos.y = this.LOW;
    }

    if(duration){
        this.moving_.runAction(new lime.animation.MoveTo(pos.x,pos.y).setDuration(duration)
            .setEasing(lime.animation.getEasingFunction(.19,.6,.35,.97)).enableOptimizations());
    }
    else this.moving_.setPosition(pos);
}

lime.ui.Scroller.prototype.downHandler_ = function(e){
    e.position = this.localToNode(e.position,this.moving_);
  	this.downx = e.position.x;
    this.downy = e.position.y;

    this.v = 0;
    this.ismove = 1;

    if(this.getDirection()==lime.ui.Scroller.Direction.HORIZONTAL){
        this.oldvalue = this.posvalue = this.moving_.getPosition().x;
    }
    else {
        this.oldvalue = this.posvalue = this.moving_.getPosition().y;
    }

    this.measureLimits();

    lime.animation.actionManager.stopAll(this.moving_);
    //this.moving_.setPosition(p);

    lime.scheduleManager.schedule(this.captureVelocity_,this);

    e.swallow(['touchmove', 'mousemove'], this.moveHandler_);

    e.swallow(['touchend','mouseup','touchend'], this.upHandler_);

}

lime.ui.Scroller.prototype.captureVelocity_ = function(){
    if(this.ismove){
        this.v = (this.posvalue-this.oldvalue)*1.05;
        this.oldvalue = this.posvalue;
    }
    this.v*=lime.ui.Scroller.FRICTION;
}

lime.ui.Scroller.prototype.cancelEvents = function(){
    this.event.release();
}

lime.ui.Scroller.prototype.moveHandler_ = function(e) {
    var pos = e.position.clone(),dir = this.getDirection(),activeval;

    if(dir==lime.ui.Scroller.Direction.HORIZONTAL){
        pos.x -= this.downx;
        pos.y = this.downy;
        activeval = pos.x;
    }
    else {
        pos.x = this.downx;
        pos.y -= this.downy;
        activeval = pos.y;
    }

    if(activeval<this.LOW){
        var diff = this.LOW-activeval;

        if(diff>lime.ui.Scroller.OFFSET) diff=lime.ui.Scroller.OFFSET;
        activeval = this.LOW-diff*lime.ui.Scroller.OFFSET_LAG;
    }
    if(activeval>this.HIGH) {
        diff = activeval-this.HIGH;

        if(diff>lime.ui.Scroller.OFFSET) diff=lime.ui.Scroller.OFFSET;
        activeval = this.HIGH+diff*lime.ui.Scroller.OFFSET_LAG;
    }

    this.posvalue = activeval;

    if(dir==lime.ui.Scroller.Direction.HORIZONTAL){
        pos.x = activeval;
    }
    else {
        pos.y = activeval;
    }

    this.moving_.setPosition(pos);

    this.event = e.clone();

}

lime.ui.Scroller.prototype.upHandler_ = function(e){
    var pos = e.position.clone(),dir = this.getDirection(),activeval;

    if(dir==lime.ui.Scroller.Direction.HORIZONTAL){
        pos.x -= this.downx;
        pos.y = this.downy;
        activeval = pos.x;
    }
    else {
        pos.x = this.downx;
        pos.y -= this.downy;
        activeval = pos.y;
    }

    lime.scheduleManager.unschedule(this.captureVelocity_,this);
    var k = Math.log(0.5/Math.abs(this.v))/Math.log(lime.ui.Scroller.FRICTION),
        duration = k/30,
        endpos = (Math.abs(this.v)*(Math.pow(lime.ui.Scroller.FRICTION,k)-1))/(lime.ui.Scroller.FRICTION-1)*(this.v>0?1:-1);

    activeval+=endpos;
    this.ismove = 0;

    if(this.v!=0){

        var diff = endpos;

        if(activeval<this.LOW){
            diff = this.LOW-(activeval-endpos);
            activeval = this.LOW;
        }
        if(activeval>this.HIGH) {
            diff = this.HIGH-(activeval-endpos);
            activeval = this.HIGH;
        }
        //console.log(diff,endpos);
        duration*=(diff/endpos);

    }

    if(this.oldvalue<this.LOW){
        activeval = this.LOW;
        duration=.3;
    }
    if(this.oldvalue>this.HIGH) {
        activeval = this.HIGH;
        duration=.3;
    }

    if(dir==lime.ui.Scroller.Direction.HORIZONTAL){
        pos.x = activeval;
    }
    else {
        pos.y = activeval;
    }

    if(Math.abs(duration)<10){
         this.moving_.runAction(new lime.animation.MoveTo(pos.x,pos.y).setDuration(duration)
            .setEasing(lime.animation.getEasingFunction(.19,.6,.35,.97)).enableOptimizations());
    }

}<commit_msg>Fix second touch while scrolling<commit_after>goog.provide('lime.ui.Scroller');

goog.require('lime.Sprite');
goog.require('lime.animation.MoveTo');

lime.ui.Scroller = function(){

    goog.base(this);

    //need default size for autoresize
    this.setSize(100,100);

    this.clipper = new lime.Sprite().setFill('#c00').setSize(100,100).setAutoResize(lime.AutoResize.ALL);
	this.appendChild(this.clipper);
	this.setMask(this.clipper);

	this.moving_ = new lime.Layer();
	lime.Node.prototype.appendChild.call(this,this.moving_);

	goog.events.listen(this,['mousedown','touchstart'],this.downHandler_,false,this);

  	this.setDirection(lime.ui.Scroller.Direction.HORIZONTAL);

}
goog.inherits(lime.ui.Scroller, lime.Sprite);

/**
 * Offset that can be dragged over the edge
 * @const
 * @type {number}
 */
lime.ui.Scroller.OFFSET = 250;

/**
 * Factor to slow down if over the edge
 * @const
 * @type {number}
 */
lime.ui.Scroller.OFFSET_LAG = .4;

/**
 * How fast to slow down
 * @const
 * @type {number}
 */
lime.ui.Scroller.FRICTION = .95;

/**
 * Direction of the scroller.
 * @enum {number}
 */
lime.ui.Scroller.Direction = {
  HORIZONTAL : 0,
  VERTICAL : 1
};

lime.ui.Scroller.prototype.getDirection = function(){
    return this.direction_;
}

lime.ui.Scroller.prototype.setDirection = function(direction){
    this.direction_ = direction;
    return this;
};

/** @inheritDoc */
lime.ui.Scroller.prototype.setAnchorPoint = function(){
    if(this.clipper){
        this.clipper.setAnchorPoint.apply(this.clipper,arguments);
    }
    return lime.Node.prototype.setAnchorPoint.apply(this,arguments);
}

/** @inheritDoc */

lime.ui.Scroller.prototype.appendChild = function(){
    if(this.moving_) return this.moving_.appendChild.apply(this.moving_,arguments);
    return lime.Node.prototype.appendChild.apply(this,arguments);
}

/** @inheritDoc */
lime.ui.Scroller.prototype.removeChild = function(){
    //if(this.moving_) return this.moving_.removeChild.apply(this.moving_,arguments);
    return lime.Node.prototype.removeChild.apply(this,arguments);
}

lime.ui.Scroller.prototype.measureLimits = function(){

    var measure = this.moving_.measureContents();
    if(this.getDirection()==lime.ui.Scroller.Direction.HORIZONTAL){
        this.downy=this.moving_.getPosition().y;
        var max = this.getSize().width;

        this.LOW = -measure.left;
        this.HIGH =Math.min(max-measure.right,-measure.left);
        var diff = (measure.right-measure.left)-max;
    }
    else {
        this.downx=this.moving_.getPosition().x;
        max = this.getSize().height;

        this.LOW = -measure.top;
        this.HIGH =Math.min(max-measure.bottom,-measure.top);
        diff = (measure.bottom-measure.top)-max;
    }

    if(diff>0){
        this.LOW-=diff;
        this.HIGH+=diff;
    }
}

lime.ui.Scroller.prototype.scrollTo = function(offset,opt_duration){
    var pos = this.moving_.getPosition().clone();
    var duration = opt_duration || 0;

    this.measureLimits();

    if(offset<0) offset = 0;

    if(this.getDirection()==lime.ui.Scroller.Direction.HORIZONTAL){
        pos.x = this.HIGH - offset;
        if(pos.x<this.LOW) pos.x = this.LOW;
    }
    else {
        pos.y = this.HIGH - offset;
        if(pos.y<this.LOW) pos.y = this.LOW;
    }

    if(duration){
        this.moving_.runAction(new lime.animation.MoveTo(pos.x,pos.y).setDuration(duration)
            .setEasing(lime.animation.getEasingFunction(.19,.6,.35,.97)).enableOptimizations());
    }
    else this.moving_.setPosition(pos);
}

lime.ui.Scroller.prototype.downHandler_ = function(e){
    if(this.ismove) return;

    e.position = this.localToNode(e.position,this.moving_);
  	this.downx = e.position.x;
    this.downy = e.position.y;

    this.v = 0;
    this.ismove = 1;

    if(this.getDirection()==lime.ui.Scroller.Direction.HORIZONTAL){
        this.oldvalue = this.posvalue = this.moving_.getPosition().x;
    }
    else {
        this.oldvalue = this.posvalue = this.moving_.getPosition().y;
    }

    this.measureLimits();

    lime.animation.actionManager.stopAll(this.moving_);
    //this.moving_.setPosition(p);

    lime.scheduleManager.schedule(this.captureVelocity_,this);

    e.swallow(['touchmove', 'mousemove'], this.moveHandler_);

    e.swallow(['touchend','mouseup','touchcancel'], this.upHandler_);

}

lime.ui.Scroller.prototype.captureVelocity_ = function(){
    if(this.ismove){
        this.v = (this.posvalue-this.oldvalue)*1.05;
        this.oldvalue = this.posvalue;
    }
    this.v*=lime.ui.Scroller.FRICTION;
}

lime.ui.Scroller.prototype.cancelEvents = function(){
    this.event.release();
    this.ismove = 0;
}

lime.ui.Scroller.prototype.moveHandler_ = function(e) {
    var pos = e.position.clone(),dir = this.getDirection(),activeval;
    if(dir==lime.ui.Scroller.Direction.HORIZONTAL){
        pos.x -= this.downx;
        pos.y = this.downy;
        activeval = pos.x;
    }
    else {
        pos.x = this.downx;
        pos.y -= this.downy;
        activeval = pos.y;
    }

    if(activeval<this.LOW){
        var diff = this.LOW-activeval;

        if(diff>lime.ui.Scroller.OFFSET) diff=lime.ui.Scroller.OFFSET;
        activeval = this.LOW-diff*lime.ui.Scroller.OFFSET_LAG;
    }
    if(activeval>this.HIGH) {
        diff = activeval-this.HIGH;

        if(diff>lime.ui.Scroller.OFFSET) diff=lime.ui.Scroller.OFFSET;
        activeval = this.HIGH+diff*lime.ui.Scroller.OFFSET_LAG;
    }

    this.posvalue = activeval;

    if(dir==lime.ui.Scroller.Direction.HORIZONTAL){
        pos.x = activeval;
    }
    else {
        pos.y = activeval;
    }

    this.moving_.setPosition(pos);

    this.event = e.clone();

}

lime.ui.Scroller.prototype.upHandler_ = function(e){
    var pos = e.position.clone(),dir = this.getDirection(),activeval;

    if(dir==lime.ui.Scroller.Direction.HORIZONTAL){
        pos.x -= this.downx;
        pos.y = this.downy;
        activeval = pos.x;
    }
    else {
        pos.x = this.downx;
        pos.y -= this.downy;
        activeval = pos.y;
    }

    lime.scheduleManager.unschedule(this.captureVelocity_,this);
    var k = Math.log(0.5/Math.abs(this.v))/Math.log(lime.ui.Scroller.FRICTION),
        duration = k/30,
        endpos = (Math.abs(this.v)*(Math.pow(lime.ui.Scroller.FRICTION,k)-1))/(lime.ui.Scroller.FRICTION-1)*(this.v>0?1:-1);

    activeval+=endpos;
    this.ismove = 0;

    if(this.v!=0){

        var diff = endpos;

        if(activeval<this.LOW){
            diff = this.LOW-(activeval-endpos);
            activeval = this.LOW;
        }
        if(activeval>this.HIGH) {
            diff = this.HIGH-(activeval-endpos);
            activeval = this.HIGH;
        }
        //console.log(diff,endpos);
        duration*=(diff/endpos);

    }

    if(this.oldvalue<this.LOW){
        activeval = this.LOW;
        duration=.3;
    }
    if(this.oldvalue>this.HIGH) {
        activeval = this.HIGH;
        duration=.3;
    }

    if(dir==lime.ui.Scroller.Direction.HORIZONTAL){
        pos.x = activeval;
    }
    else {
        pos.y = activeval;
    }

    if(Math.abs(duration)<10){
         this.moving_.runAction(new lime.animation.MoveTo(pos.x,pos.y).setDuration(duration)
            .setEasing(lime.animation.getEasingFunction(.19,.6,.35,.97)).enableOptimizations());
    }

}<|endoftext|>


<commit_before>'use strict'

const fs = require('fs')
const path = require('path')
const {parse: parseURL} = require('url')
const handlebars = require('handlebars')

const {assets} = require('../assets')

// -------------------------------------------------------------
// Module.
// -------------------------------------------------------------

// Create a template object from a template of the assets folder.
// Use the type to determine which template must be selected.
function createTemplate (type) {
  const templatePath = getTemplatePath(assets, type)

  if (!templatePath) {
    throw new Error('Missing template! Make sure your presskit has a "type" field (product/company)')
  }

  registerPartials(assets)
  registerHelpers()

  const template = fs.readFileSync(templatePath, 'utf-8')
  return handlebars.compile(template)
}

// Get the path to the corresponding template in the assets folder.
function getTemplatePath (folder, type) {
  switch (type) {
    case 'product':
      return path.join(folder, 'product.html')
    case 'company':
      return path.join(folder, 'company.html')
  }
}

// Add all the required partials.
function registerPartials (folder) {
  const partialsFolder = path.join(folder, '_includes')

  const partials = fs.readdirSync(partialsFolder)
    .filter(isValidPartial)
    .reduce((result, partial) => {
      const ext = path.extname(partial)
      const fileFullPath = path.join(partialsFolder, partial)
      const data = fs.readFileSync(fileFullPath, 'utf-8')

      // Store as `"filename without extension": content`.
      result[path.basename(partial, ext)] = data
      return result
    }, {})

  handlebars.registerPartial(partials)
}

function registerHelpers () {
  handlebars.registerHelper({
    prettyURL: function (link) {
      const url = parseURL(link)
      if (!url.hostname) return link

      const path = url.pathname === '/' ? '' : url.pathname
      return url.hostname + path
    },

    domainURL: function (link) {
      const url = parseURL(link)
      if (!url.hostname) return link

      return url.hostname
    },

    permalink: function (link) {
      if (link.endsWith('index.html')) {
        return path.dirname(link) + '/'
      }

      return link
    },

    basename: function (name) {
      const ext = path.extname(name)
      return path.basename(name, ext)
    }
  })
}

// Is the file an HTML file?
function isValidPartial (file) {
  const ext = path.extname(file)
  return ext === '.html'
}

// -------------------------------------------------------------
// Exports.
// -------------------------------------------------------------

module.exports = {
  createTemplate
}
<commit_msg>Remove www. from links in prettyURL and domainURL<commit_after>'use strict'

const fs = require('fs')
const path = require('path')
const {parse: parseURL} = require('url')
const handlebars = require('handlebars')

const {assets} = require('../assets')

// -------------------------------------------------------------
// Module.
// -------------------------------------------------------------

// Create a template object from a template of the assets folder.
// Use the type to determine which template must be selected.
function createTemplate (type) {
  const templatePath = getTemplatePath(assets, type)

  if (!templatePath) {
    throw new Error('Missing template! Make sure your presskit has a "type" field (product/company)')
  }

  registerPartials(assets)
  registerHelpers()

  const template = fs.readFileSync(templatePath, 'utf-8')
  return handlebars.compile(template)
}

// Get the path to the corresponding template in the assets folder.
function getTemplatePath (folder, type) {
  switch (type) {
    case 'product':
      return path.join(folder, 'product.html')
    case 'company':
      return path.join(folder, 'company.html')
  }
}

// Add all the required partials.
function registerPartials (folder) {
  const partialsFolder = path.join(folder, '_includes')

  const partials = fs.readdirSync(partialsFolder)
    .filter(isValidPartial)
    .reduce((result, partial) => {
      const ext = path.extname(partial)
      const fileFullPath = path.join(partialsFolder, partial)
      const data = fs.readFileSync(fileFullPath, 'utf-8')

      // Store as `"filename without extension": content`.
      result[path.basename(partial, ext)] = data
      return result
    }, {})

  handlebars.registerPartial(partials)
}

function registerHelpers () {
  handlebars.registerHelper({
    prettyURL: function (link) {
      const url = parseURL(link)
      if (!url.hostname) return link

      const path = url.pathname === '/' ? '' : url.pathname
      return url.hostname.replace('www.', '') + path
    },

    domainURL: function (link) {
      const url = parseURL(link)
      if (!url.hostname) return link

      return url.hostname.replace('www.', '')
    },

    permalink: function (link) {
      if (link.endsWith('index.html')) {
        return path.dirname(link) + '/'
      }

      return link
    },

    basename: function (name) {
      const ext = path.extname(name)
      return path.basename(name, ext)
    }
  })
}

// Is the file an HTML file?
function isValidPartial (file) {
  const ext = path.extname(file)
  return ext === '.html'
}

// -------------------------------------------------------------
// Exports.
// -------------------------------------------------------------

module.exports = {
  createTemplate
}
<|endoftext|>


<commit_before>'use strict'

var request = require('request')

var tracker = require('../')

var trackingInfo = function (numbers) {
  var trackingInfoList = []
  if (numbers instanceof Array === false) {
    numbers = [numbers]
  }
  for (var i = 0; i < numbers.length; i++) {
    trackingInfoList.push({
      trackNumberInfo: {
        trackingNumber: numbers[i]
      }
    })
  }
  return {
    method: 'POST',
    url: 'https://www.fedex.com/trackingCal/track',
    data: {
      data: JSON.stringify({
        TrackPackagesRequest: {
          trackingInfoList: trackingInfoList
        }
      }),
      action: 'trackpackages'
    }
  }
}

var normalize = function (item) {
  var courier = {
    code: tracker.COURIER.FEDEX.CODE,
    name: tracker.COURIER.FEDEX.NAME
  }
  var result = {
    courier: courier,
    number: item.displayTrackingNbr,
    status: tracker.STATUS.PENDING,
    checkpoints: []
  }

  if (item.isSuccessful) {
    var eventList = item.scanEventList

    for (var i = 0, len = eventList.length; i < len; i++) {
      var message = [eventList[i].status]
      eventList[i].scanDetails && message.push(eventList[i].scanDetails)

      var checkpoint = {
        courier: courier,
        location: eventList[i].scanLocation,
        message: message.join(' - '),
        status: tracker.STATUS.IN_TRANSIT,
        time: [eventList[i].date, eventList[i].time].join('T') + eventList[i].gmtOffset
      }

      // https://www.fedex.com/us/developer/WebHelp/ws/2014/dvg/WS_DVG_WebHelp/Appendix_Q_Track_Service_Scan_Codes.htm
      eventList[i].statusCD === 'OC' && (checkpoint.status = tracker.STATUS.INFO_RECEIVED)
      eventList[i].isException && (checkpoint.status = tracker.STATUS.EXCEPTION)
      eventList[i].isDelivered && (checkpoint.status = tracker.STATUS.DELIVERED)

      result.checkpoints.push(checkpoint)
    }
  }

  result.status = tracker.normalizeStatus(result.checkpoints)

  return result
}

var parser = {
  trace: function (packageList) {
    var results = []

    for (var i = 0, len = packageList.length; i < len; i++) {
      results.push(normalize(packageList[i]))
    }

    return results
  }
}

module.exports = function (opts) {
  return {
    trackingInfo: trackingInfo,
    trace: function (number, cb) {
      var tracking = trackingInfo(number)

      request.post({
        url: tracking.url,
        form: tracking.data,
        json: true
      }, function (err, res, body) {
        if (err) {
          return cb(err)
        }

        try {
          var results = parser.trace(body.TrackPackagesResponse.packageList)
          cb(null, results[0])
        } catch (e) {
          cb(tracker.error(e.message))
        }
      })
    }
  }
}
<commit_msg>Added "eta" to fedex results.<commit_after>'use strict'

var request = require('request')

var tracker = require('../')

var trackingInfo = function (numbers) {
  var trackingInfoList = []
  if (numbers instanceof Array === false) {
    numbers = [numbers]
  }
  for (var i = 0; i < numbers.length; i++) {
    trackingInfoList.push({
      trackNumberInfo: {
        trackingNumber: numbers[i]
      }
    })
  }
  return {
    method: 'POST',
    url: 'https://www.fedex.com/trackingCal/track',
    data: {
      data: JSON.stringify({
        TrackPackagesRequest: {
          trackingInfoList: trackingInfoList
        }
      }),
      action: 'trackpackages'
    }
  }
}

var normalize = function (item) {
  var courier = {
    code: tracker.COURIER.FEDEX.CODE,
    name: tracker.COURIER.FEDEX.NAME
  }
  var result = {
    courier: courier,
    number: item.displayTrackingNbr,
    status: tracker.STATUS.PENDING,
    eta: item.estDeliveryDt,
    checkpoints: []
  }

  if (item.isSuccessful) {
    var eventList = item.scanEventList

    for (var i = 0, len = eventList.length; i < len; i++) {
      var message = [eventList[i].status]
      eventList[i].scanDetails && message.push(eventList[i].scanDetails)

      var checkpoint = {
        courier: courier,
        location: eventList[i].scanLocation,
        message: message.join(' - '),
        status: tracker.STATUS.IN_TRANSIT,
        time: [eventList[i].date, eventList[i].time].join('T') + eventList[i].gmtOffset
      }

      // https://www.fedex.com/us/developer/WebHelp/ws/2014/dvg/WS_DVG_WebHelp/Appendix_Q_Track_Service_Scan_Codes.htm
      eventList[i].statusCD === 'OC' && (checkpoint.status = tracker.STATUS.INFO_RECEIVED)
      eventList[i].isException && (checkpoint.status = tracker.STATUS.EXCEPTION)
      eventList[i].isDelivered && (checkpoint.status = tracker.STATUS.DELIVERED)

      result.checkpoints.push(checkpoint)
    }
  }

  result.status = tracker.normalizeStatus(result.checkpoints)

  return result
}

var parser = {
  trace: function (packageList) {
    var results = []

    for (var i = 0, len = packageList.length; i < len; i++) {
      results.push(normalize(packageList[i]))
    }

    return results
  }
}

module.exports = function (opts) {
  return {
    trackingInfo: trackingInfo,
    trace: function (number, cb) {
      var tracking = trackingInfo(number)

      request.post({
        url: tracking.url,
        form: tracking.data,
        json: true
      }, function (err, res, body) {
        if (err) {
          return cb(err)
        }

        try {
          var results = parser.trace(body.TrackPackagesResponse.packageList)
          cb(null, results[0])
        } catch (e) {
          cb(tracker.error(e.message))
        }
      })
    }
  }
}
<|endoftext|>


<commit_before>/* @flow */
/* eslint no-redeclare: "off", import/no-mutable-exports: "off" */

import type {
  CustomEventHandler,
  DelegateEventHandler,
  EventType
} from "./types";

import on from "./on";

declare function once(
  element: Element,
  eventType: MouseEventTypes,
  handler: MouseEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  element: Element,
  eventType: FocusEventTypes,
  handler: FocusEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  element: Element,
  eventType: KeyboardEventTypes,
  handler: KeyboardEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  element: Element,
  eventType: TouchEventTypes,
  handler: TouchEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  element: Element,
  eventType: WheelEventTypes,
  handler: WheelEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  element: Element,
  eventType: ProgressEventTypes,
  ler: ProgressEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  element: Element,
  eventType: DragEventTypes,
  handler: DragEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  element: Element,
  eventType: AnimationEventTypes,
  handler: AnimationEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  element: Element,
  eventType: EventType,
  handler: CustomEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  element: Element,
  eventType: EventType,
  handler: DelegateEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  element: Element,
  eventType: EventType,
  handler: EventHandler,
  useCapture?: boolean
): () => void;

function once(element, eventType, handler, useCapture = false) {
  function wrappedHandler(event) {
    element.removeEventListener(eventType, wrappedHandler, useCapture);

    handler(event);
  }

  return on(element, eventType, wrappedHandler, useCapture);
}

export default once;
<commit_msg>Update types for `once` function<commit_after>/* @flow */
/* eslint no-redeclare: "off", import/no-mutable-exports: "off" */

import type {
  CustomEventHandler,
  DelegateEventHandler,
  EventType
} from "./types";

import on from "./on";

declare function once(
  target: EventTarget,
  eventType: MouseEventTypes,
  handler: MouseEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  target: EventTarget,
  eventType: FocusEventTypes,
  handler: FocusEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  target: EventTarget,
  eventType: KeyboardEventTypes,
  handler: KeyboardEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  target: EventTarget,
  eventType: TouchEventTypes,
  handler: TouchEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  target: EventTarget,
  eventType: WheelEventTypes,
  handler: WheelEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  target: EventTarget,
  eventType: ProgressEventTypes,
  ler: ProgressEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  target: EventTarget,
  eventType: DragEventTypes,
  handler: DragEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  target: EventTarget,
  eventType: AnimationEventTypes,
  handler: AnimationEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  target: EventTarget,
  eventType: EventType,
  handler: CustomEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  target: EventTarget,
  eventType: EventType,
  handler: DelegateEventHandler,
  useCapture?: boolean
): () => void;

declare function once(
  target: EventTarget,
  eventType: EventType,
  handler: EventHandler,
  useCapture?: boolean
): () => void;

function once(target, eventType, handler, useCapture = false) {
  function wrappedHandler(event) {
    target.removeEventListener(eventType, wrappedHandler, useCapture);

    handler(event);
  }

  return on(target, eventType, wrappedHandler, useCapture);
}

export default once;
<|endoftext|>


<commit_before>'use strict';

var http = require('http');

module.exports = function (ip) {
  var server = http.createServer(function (_, res) {
    res.writeHead(204, {'Cache-Control': 'max-age=31556926'});
    res.end();
  });

  server.listen(80, ip || undefined);

  return server;
};
<commit_msg>log HTTP request<commit_after>'use strict';

var http = require('http');

function createRequestLogEntry(req) {
  return {
    method: req.method,
    host: req.headers.host,
    path: req.url,
    client: req.ip || (req.connection && req.connection.remoteAddress),
    userAgent: req.headers['user-agent']
  };
}

module.exports = function (ip) {
  var server = http.createServer(function (req, res) {
    console.log(createRequestLogEntry(req));
    res.writeHead(204);
    res.end();
  });

  server.listen(80, ip || undefined);

  return server;
};
<|endoftext|>