<commit_before>/**
* @preserve HTML5 Shiv 3.7.3 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
;(function(window, document) {
/*jshint evil:true */
  /** version */
  var version = '3.7.3';

  /** Preset options */
  var options = window.html5 || {};

  /** Used to skip problem elements */
  var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;

  /** Not all elements can be cloned in IE **/
  var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;

  /** Detect whether the browser supports default html5 styles */
  var supportsHtml5Styles;

  /** Name of the expando, to work with multiple documents or to re-shiv one document */
  var expando = '_html5shiv';

  /** The id for the the documents expando */
  var expanID = 0;

  /** Cached data for each document */
  var expandoData = {};

  /** Detect whether the browser supports unknown elements */
  var supportsUnknownElements;

  (function() {
    try {
        var a = document.createElement('a');
        a.innerHTML = '<xyz></xyz>';
        //if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles
        supportsHtml5Styles = ('hidden' in a);

        supportsUnknownElements = a.childNodes.length == 1 || (function() {
          // assign a false positive if unable to shiv
          (document.createElement)('a');
          var frag = document.createDocumentFragment();
          return (
            typeof frag.cloneNode == 'undefined' ||
            typeof frag.createDocumentFragment == 'undefined' ||
            typeof frag.createElement == 'undefined'
          );
        }());
    } catch(e) {
      // assign a false positive if detection fails => unable to shiv
      supportsHtml5Styles = true;
      supportsUnknownElements = true;
    }

  }());

  /*--------------------------------------------------------------------------*/

  /**
   * Creates a style sheet with the given CSS text and adds it to the document.
   * @private
   * @param {Document} ownerDocument The document.
   * @param {String} cssText The CSS text.
   * @returns {StyleSheet} The style element.
   */
  function addStyleSheet(ownerDocument, cssText) {
    var p = ownerDocument.createElement('p'),
        parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;

    p.innerHTML = 'x<style>' + cssText + '</style>';
    return parent.insertBefore(p.lastChild, parent.firstChild);
  }

  /**
   * Returns the value of `html5.elements` as an array.
   * @private
   * @returns {Array} An array of shived element node names.
   */
  function getElements() {
    var elements = html5.elements;
    return typeof elements == 'string' ? elements.split(' ') : elements;
  }

  /**
   * Extends the built-in list of html5 elements
   * @memberOf html5
   * @param {String|Array} newElements whitespace separated list or array of new element names to shiv
   * @param {Document} ownerDocument The context document.
   */
  function addElements(newElements, ownerDocument) {
    var elements = html5.elements;
    if(typeof elements != 'string'){
      elements = elements.join(' ');
    }
    if(typeof newElements != 'string'){
      newElements = newElements.join(' ');
    }
    html5.elements = elements +' '+ newElements;
    shivDocument(ownerDocument);
  }

   /**
   * Returns the data associated to the given document
   * @private
   * @param {Document} ownerDocument The document.
   * @returns {Object} An object of data.
   */
  function getExpandoData(ownerDocument) {
    var data = expandoData[ownerDocument[expando]];
    if (!data) {
        data = {};
        expanID++;
        ownerDocument[expando] = expanID;
        expandoData[expanID] = data;
    }
    return data;
  }

  /**
   * returns a shived element for the given nodeName and document
   * @memberOf html5
   * @param {String} nodeName name of the element
   * @param {Document|DocumentFragment} ownerDocument The context document.
   * @returns {Object} The shived element.
   */
  function createElement(nodeName, ownerDocument, data){
    if (!ownerDocument) {
        ownerDocument = document;
    }
    if(supportsUnknownElements){
        return ownerDocument.createElement(nodeName);
    }
    if (!data) {
        data = getExpandoData(ownerDocument);
    }
    var node;

    if (data.cache[nodeName]) {
        node = data.cache[nodeName].cloneNode();
    } else if (saveClones.test(nodeName)) {
        node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
    } else {
        node = data.createElem(nodeName);
    }

    // Avoid adding some elements to fragments in IE < 9 because
    // * Attributes like `name` or `type` cannot be set/changed once an element
    //   is inserted into a document/fragment
    // * Link elements with `src` attributes that are inaccessible, as with
    //   a 403 response, will cause the tab/window to crash
    // * Script elements appended to fragments will execute when their `src`
    //   or `text` property is set
    return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node;
  }

  /**
   * returns a shived DocumentFragment for the given document
   * @memberOf html5
   * @param {Document} ownerDocument The context document.
   * @returns {Object} The shived DocumentFragment.
   */
  function createDocumentFragment(ownerDocument, data){
    if (!ownerDocument) {
        ownerDocument = document;
    }
    if(supportsUnknownElements){
        return ownerDocument.createDocumentFragment();
    }
    data = data || getExpandoData(ownerDocument);
    var clone = data.frag.cloneNode(),
        i = 0,
        elems = getElements(),
        l = elems.length;
    for(;i<l;i++){
        clone.createElement(elems[i]);
    }
    return clone;
  }

  /**
   * Shivs the `createElement` and `createDocumentFragment` methods of the document.
   * @private
   * @param {Document|DocumentFragment} ownerDocument The document.
   * @param {Object} data of the document.
   */
  function shivMethods(ownerDocument, data) {
    if (!data.cache) {
        data.cache = {};
        data.createElem = ownerDocument.createElement;
        data.createFrag = ownerDocument.createDocumentFragment;
        data.frag = data.createFrag();
    }

    ownerDocument.createElement = function(nodeName) {
      //abort shiv
      if (!html5.shivMethods) {
          return data.createElem(nodeName);
      }
      return createElement(nodeName, ownerDocument, data);
    };

    ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' +
      'var n=f.cloneNode(),c=n.createElement;' +
      'h.shivMethods&&(' +
        // unroll the `createElement` calls
        getElements().join().replace(/[\w\-:]+/g, function(nodeName) {
          data.createElem(nodeName);
          data.frag.createElement(nodeName);
          return 'c("' + nodeName + '")';
        }) +
      ');return n}'
    )(html5, data.frag);
  }

  /*--------------------------------------------------------------------------*/

  /**
   * Shivs the given document.
   * @memberOf html5
   * @param {Document} ownerDocument The document to shiv.
   * @returns {Document} The shived document.
   */
  function shivDocument(ownerDocument) {
    if (!ownerDocument) {
        ownerDocument = document;
    }
    var data = getExpandoData(ownerDocument);

    if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) {
      data.hasCSS = !!addStyleSheet(ownerDocument,
        // corrects block display not defined in IE6/7/8/9
        'article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}' +
        // adds styling not present in IE6/7/8/9
        'mark{background:#FF0;color:#000}' +
        // hides non-rendered elements
        'template{display:none}'
      );
    }
    if (!supportsUnknownElements) {
      shivMethods(ownerDocument, data);
    }
    return ownerDocument;
  }

  /*--------------------------------------------------------------------------*/

  /**
   * The `html5` object is exposed so that more elements can be shived and
   * existing shiving can be detected on iframes.
   * @type Object
   * @example
   *
   * // options can be changed before the script is included
   * html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false };
   */
  var html5 = {

    /**
     * An array or space separated string of node names of the elements to shiv.
     * @memberOf html5
     * @type Array|String
     */
    'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video',

    /**
     * current version of html5shiv
     */
    'version': version,

    /**
     * A flag to indicate that the HTML5 style sheet should be inserted.
     * @memberOf html5
     * @type Boolean
     */
    'shivCSS': (options.shivCSS !== false),

    /**
     * Is equal to true if a browser supports creating unknown/HTML5 elements
     * @memberOf html5
     * @type boolean
     */
    'supportsUnknownElements': supportsUnknownElements,

    /**
     * A flag to indicate that the document's `createElement` and `createDocumentFragment`
     * methods should be overwritten.
     * @memberOf html5
     * @type Boolean
     */
    'shivMethods': (options.shivMethods !== false),

    /**
     * A string to describe the type of `html5` object ("default" or "default print").
     * @memberOf html5
     * @type String
     */
    'type': 'default',

    // shivs the document according to the specified `html5` object options
    'shivDocument': shivDocument,

    //creates a shived element
    createElement: createElement,

    //creates a shived documentFragment
    createDocumentFragment: createDocumentFragment,

    //extends list of elements
    addElements: addElements
  };

  /*--------------------------------------------------------------------------*/

  // expose html5
  window.html5 = html5;

  // shiv the document
  shivDocument(document);

  if(typeof module == 'object' && module.exports){
    module.exports = html5;
  }

}(typeof window !== "undefined" ? window : this, document));
<commit_msg>Delete html5shiv.min.js<commit_after><|endoftext|>


<commit_before>module.exports = require('./').should();
<commit_msg>Add script that register should into the global space<commit_after>global.should = module.exports = require('./').should();
<|endoftext|>


<commit_before>'use strict';

YUI.add('juju-notifications', function(Y) {

  var views = Y.namespace('juju.views'),
      Templates = views.Templates;

  /*
   * Abstract Base class used to view a ModelList  of notifications
   */
  var NotificationsBaseView = Y.Base.create('NotificationsBaseView',
      Y.View, [views.JujuBaseView], {

        initializer: function() {
          NotificationsView.superclass.constructor.apply(this, arguments);

          var notifications = this.get('notifications'),
              env = this.get('env');

          // Bind view to model list in a number of ways
          notifications.addTarget(this);
          // Re-render the model list changes
          notifications.after('add', this.slow_render, this);
          notifications.after('create', this.slow_render, this);
          notifications.after('remove', this.slow_render, this);
          notifications.after('reset', this.slow_render, this);

          // Env connection state watcher
          env.on('connectedChange', this.slow_render, this);

        },

        /*
         * Event handler for clicking the notification icon.
         */
        notify_toggle: function(evt) {
          var container = this.get('container'),
              notifications = this.get('notifications'),
              target = evt.target.getAttribute('data-target'),
              el = container.one('#' + target),
              parent = el.ancestor();

          if (notifications.size() === 0) {
            return;
          }

          if (parent && parent.hasClass('open')) {
            el.hide(true);
          }
          else {
            el.show(true);
          }

          if (parent) {
            parent.toggleClass('open');
          }

          el.toggleClass('active');

        },

        /*
         * Select/click on a notice. Currently this just removes it from the
         * model_list
         */
        notice_select: function(evt) {
          var notifications = this.get('notifications'),
              target = evt.target,
              model;

          if (!target) {
            return;
          }
          if (target.get('tagName') !== 'LI') {
            target = target.ancestor('li');
          }

          model = notifications.getByClientId(target.get('id'));

          if (this.selection.seen) {
            model.set('seen', true);
          }

          if (this.selection.hide) {
            target.hide(true);
          }
          this.slow_render();
        },

        /*
         * A flow of events can trigger many renders, from the event system
         * we debounce render requests with this method
         */
        slow_render: function() {
          var self = this,
              container = self.get('container');

          clearTimeout(this._renderTimeout);
          this._renderTimeout = setTimeout(function() {
            if (!container) {
                return;
            }
            self.render();
          }, 200);
        },

        render: function() {
          var container = this.get('container'),
              env = this.get('env'),
              app = this.get('app'),
              connected = env.get('connected'),
              notifications = this.get('notifications'),
              state,
              open = '',
              btngroup = container.one('.btn-group');

          // Honor the current active state if the view is already
          // rendered
          if (btngroup && btngroup.hasClass('open')) {
            open = 'open';
          }

          // However if the size of the message list is now
          // zero we can close the dialog
          if (notifications.size() === 0) {
            open = '';
          }

          var showable = this.get_showable(),
              show_count = showable.length || 0;

          if (!connected) {
            state = 'btn-warning';
          }
          else if (show_count > 0) {
            state = 'btn-danger';
          } else {
            state = 'btn-info';
          }

          container.setHTML(this.template({
            notifications: showable,
            count: show_count,
            state: state,
            open: open
          }));

          return this;
        }
      });

  /*
   * This is the view associated with the notifications indicator
   */
  var NotificationsView = Y.Base.create('NotificationsView',
      NotificationsBaseView, [], {
        template: Templates.notifications,
        /*
         * Actions associated with events
         * in this case selection events represent
         * policy flags inside the 'notice_select' callback.
         *
         * :hide: should the selected element be hidden on selection
         */
        selection: {hide: false,
          seen: false
        },

        events: {
          '#notify-indicator': {
            click: 'notify_toggle'
          },
          'li.notice': {
            click: 'notice_select'
          },

          '#notify-list li.header a': {
            click: 'closeIndicator'
          }
        },

        get_showable: function() {
          var notifications = this.get('notifications');
          return notifications.filter(function(n) {
            return n.get('level') === 'error' && n.get('seen') === false;
          }).map(function(n) {
            return n.getAttrs();
          });
        },

        closeIndicator: function() {
          var indicator = Y.one('#notify-indicator'),
              list = Y.one('#notify-list'),
              parent = indicator.ancestor();

          console.log('Close indicator');
          if (parent && parent.hasClass('open')) {
            indicator.ancestor().removeClass('open');
            list.hide();
          }
        },
        render: function() {
          NotificationsView.superclass.render.apply(this, arguments);
          this.get('container').on('clickoutside', this.closeIndicator);
        }

      });
  views.NotificationsView = NotificationsView;

  /*
   * This is the 'View All Notifications' view
   */
  var NotificationsOverview = Y.Base.create('NotificationsOverview',
      NotificationsBaseView, [], {
        template: Templates.notifications_overview,
        events: {
          'li.notice': {
            click: 'notice_select'
          }
        },
        // Actions for selecting a notice
        selection: {hide: false},

        /*
         *  The overview shows all events by default
         *  when real filtering is present this will have to take options
         */
        get_showable: function() {
          var notifications = this.get('notifications');
          return notifications.map(function(n) {
            return n.getAttrs();
          });
        }
      });

  views.NotificationsOverview = NotificationsOverview;

}, '0.1.0', {
  requires: [
    'view',
    'juju-view-utils',
    'node',
    'handlebars'
  ]
});
<commit_msg>lint foo<commit_after>'use strict';

YUI.add('juju-notifications', function(Y) {

  var views = Y.namespace('juju.views'),
      Templates = views.Templates;

  /*
   * Abstract Base class used to view a ModelList  of notifications
   */
  var NotificationsBaseView = Y.Base.create('NotificationsBaseView',
      Y.View, [views.JujuBaseView], {

        initializer: function() {
          NotificationsView.superclass.constructor.apply(this, arguments);

          var notifications = this.get('notifications'),
              env = this.get('env');

          // Bind view to model list in a number of ways
          notifications.addTarget(this);
          // Re-render the model list changes
          notifications.after('add', this.slow_render, this);
          notifications.after('create', this.slow_render, this);
          notifications.after('remove', this.slow_render, this);
          notifications.after('reset', this.slow_render, this);

          // Env connection state watcher
          env.on('connectedChange', this.slow_render, this);

        },

        /*
         * Event handler for clicking the notification icon.
         */
        notify_toggle: function(evt) {
          var container = this.get('container'),
              notifications = this.get('notifications'),
              target = evt.target.getAttribute('data-target'),
              el = container.one('#' + target),
              parent = el.ancestor();

          if (notifications.size() === 0) {
            return;
          }

          if (parent && parent.hasClass('open')) {
            el.hide(true);
          }
          else {
            el.show(true);
          }

          if (parent) {
            parent.toggleClass('open');
          }

          el.toggleClass('active');

        },

        /*
         * Select/click on a notice. Currently this just removes it from the
         * model_list
         */
        notice_select: function(evt) {
          var notifications = this.get('notifications'),
              target = evt.target,
              model;

          if (!target) {
            return;
          }
          if (target.get('tagName') !== 'LI') {
            target = target.ancestor('li');
          }

          model = notifications.getByClientId(target.get('id'));

          if (this.selection.seen) {
            model.set('seen', true);
          }

          if (this.selection.hide) {
            target.hide(true);
          }
          this.slow_render();
        },

        /*
         * A flow of events can trigger many renders, from the event system
         * we debounce render requests with this method
         */
        slow_render: function() {
          var self = this,
              container = self.get('container');

          clearTimeout(this._renderTimeout);
          this._renderTimeout = setTimeout(function() {
            if (!container) {
              return;
            }
            self.render();
          }, 200);
        },

        render: function() {
          var container = this.get('container'),
              env = this.get('env'),
              app = this.get('app'),
              connected = env.get('connected'),
              notifications = this.get('notifications'),
              state,
              open = '',
              btngroup = container.one('.btn-group');

          // Honor the current active state if the view is already
          // rendered
          if (btngroup && btngroup.hasClass('open')) {
            open = 'open';
          }

          // However if the size of the message list is now
          // zero we can close the dialog
          if (notifications.size() === 0) {
            open = '';
          }

          var showable = this.get_showable(),
              show_count = showable.length || 0;

          if (!connected) {
            state = 'btn-warning';
          }
          else if (show_count > 0) {
            state = 'btn-danger';
          } else {
            state = 'btn-info';
          }

          container.setHTML(this.template({
            notifications: showable,
            count: show_count,
            state: state,
            open: open
          }));

          return this;
        }
      });

  /*
   * This is the view associated with the notifications indicator
   */
  var NotificationsView = Y.Base.create('NotificationsView',
      NotificationsBaseView, [], {
        template: Templates.notifications,
        /*
         * Actions associated with events
         * in this case selection events represent
         * policy flags inside the 'notice_select' callback.
         *
         * :hide: should the selected element be hidden on selection
         */
        selection: {hide: false,
          seen: false
        },

        events: {
          '#notify-indicator': {
            click: 'notify_toggle'
          },
          'li.notice': {
            click: 'notice_select'
          },

          '#notify-list li.header a': {
            click: 'closeIndicator'
          }
        },

        get_showable: function() {
          var notifications = this.get('notifications');
          return notifications.filter(function(n) {
            return n.get('level') === 'error' && n.get('seen') === false;
          }).map(function(n) {
            return n.getAttrs();
          });
        },

        closeIndicator: function() {
          var indicator = Y.one('#notify-indicator'),
              list = Y.one('#notify-list'),
              parent = indicator.ancestor();

          console.log('Close indicator');
          if (parent && parent.hasClass('open')) {
            indicator.ancestor().removeClass('open');
            list.hide();
          }
        },
        render: function() {
          NotificationsView.superclass.render.apply(this, arguments);
          this.get('container').on('clickoutside', this.closeIndicator);
        }

      });
  views.NotificationsView = NotificationsView;

  /*
   * This is the 'View All Notifications' view
   */
  var NotificationsOverview = Y.Base.create('NotificationsOverview',
      NotificationsBaseView, [], {
        template: Templates.notifications_overview,
        events: {
          'li.notice': {
            click: 'notice_select'
          }
        },
        // Actions for selecting a notice
        selection: {hide: false},

        /*
         *  The overview shows all events by default
         *  when real filtering is present this will have to take options
         */
        get_showable: function() {
          var notifications = this.get('notifications');
          return notifications.map(function(n) {
            return n.getAttrs();
          });
        }
      });

  views.NotificationsOverview = NotificationsOverview;

}, '0.1.0', {
  requires: [
    'view',
    'juju-view-utils',
    'node',
    'handlebars'
  ]
});
<|endoftext|>


<commit_before>"use strict";

// The library for general signal manipulation. Includes `lift` function
// (that supports up to 8 inputs), combinations, filters, and past-dependence.
//
// Signals are time-varying values. Lifted functions are reevaluated whenver
// any of their input signals has an event. Signal events may be of the same
// value as the previous value of the signal. Such signals are useful for
// timing and past-dependence.
//
// Some useful functions for working with time (e.g. setting FPS) and combining
// signals and time (e.g. delaying updates, getting timestamps) can be found in
// the Time library.
//
// Module implements elm API: http://docs.elm-lang.org/library/Signal.elm

var slicer = Array.prototype.slice

function Meta(value) {
  return this.value = value
}
Meta.prototype.valueOf = function() {
  return this.value
}

var Break = new Meta(null)
var Skip = new Meta(null)

function Return(value) {
  if (!(this instanceof Return))
    return new Return(value)

  this.value = value
}
Return.prototype = new Meta()

function Signal(generator, initial) {
  if (!(this instanceof Signal))
    return new Signal(generator, initial)

  this.value = initial
  this.generate = generator
}
Signal.Return = Return
Signal.return = Return
Signal.Skip = Skip
Signal.Break = Break
exports.Break = Break

function dispatch(signal) {
  return function dispatch(value) {
    var result = void(0)
    // Optimal case with a single receiver.
    if (signal.receive) {
      result = signal.receive(value, signal)
      signal.value = value
    }
    // If multiple receivers are subscribed dispatches `value` to eoch one.
    else if (signal.receivers) {
      var receivers = signal.receivers
      var count = receivers.length
      var index = 0

      // Dispatch updated signal `value` to an every customer of this `signal`.
      while (index < count) {
        var receive = receivers[index]

        // If customer wishes to unsubscribe from updates
        // remove it from the set.
        try {
          result = receive(value, signal);
        }
        catch (error) {
          console.error(error);
        }

        if (result === Break) {
          receivers.splice(index, 1)
          count = count - 1
        }
        // Otherwise increment index, to send value to a
        // next customer.
        else {
          index = index + 1
        }
      }
      signal.value = value
      // If no more receivers `Break` the generator.
      result = receivers.length ? void(0) : Break
    }
    else {
      result = Break
    }

    if (result === Break) {
      signal.receive = null
      signal.receivers = null
    }

    return result
  }
}
// Internal field used for holding set of customers
// when `.dispatch` is used for sending values.
Signal.prototype.receivers = null
Signal.prototype.receive = null
Signal.prototype.valueOf = function() {
  return this.value
}

exports.Signal = Signal

// Takes `run` function, `xs` signal and invokes
// `run` with every value of `xs`.

// (x) -> Signal x -> nil
function spawn(run, signal) {
  if (!signal) {
    throw TypeError("Can't spawn non signal")
  }
  // If signal is already dispatching & there are
  // multiple receivers add new receiver to the
  // array of active receivers.
  else if (signal.receivers) {
    signal.receivers.push(run)
  }
  // If signal is already scheduled & there is a
  // single receiver, create an array of active
  // receivers and convert receiver to a dispatcher.
  else if (signal.receive) {
    signal.receivers = [signal.receive, run]
    signal.receive = null
  }
  // If signal has not being spawned yet set a
  // reciver and schedule a generator.
  else {
    signal.receive = run
    setTimeout(signal.generate, 0, dispatch(signal))
  }
}
exports.spawn = spawn

// # Combine

// Create a constant signal that never changes.

// a -> Signal a
function Constant(value) {
  if (!(this instanceof Constant))
    return new Constant(value)

  this.value = value
}
Constant.prototype = Object.create(Signal.prototype)
Constant.prototype.generate = function() {}
exports.constant = Constant

// Transform given signals with a given function.

// (x -> y -> ...) -> Signal x -> Signal y -> ... -> Signal z
function map(f, xs, ys) {
  var inputs = slicer.call(arguments, 1)
  var count = inputs.length
  var values = new Array(count)
  var index = 0
  while (index < count) {
    values[index] = inputs[index].value
    index = index + 1
  }

  return new Signal(function(next) {
    function forward(value, input) {
      values[inputs.indexOf(input)] = value
      return next(f.apply(f, values))
    }

    var index = 0
    while (index < count) {
      spawn(forward, inputs[index])
      index = index + 1
    }
  }, f.apply(f, values))
}
exports.map = map
exports.lift = map
exports.lift2 = map
exports.lift3 = map
exports.lift4 = map
exports.lift5 = map
exports.lift6 = map
exports.lift7 = map
exports.lift8 = map

// Merge two signals into one, biased towards the
// first signal if both signals update at the same time.

// Signal x -> Signal y -> ... -> Signal z
function merge(xs, ys) {
  var inputs = slicer.call(arguments, 0)
  var count = inputs.length
  return new Signal(function(next) {
    var index = 0
    while (index < count) {
      spawn(next, inputs[index])
      index = index + 1
    }
  }, xs.value)
}
exports.merge = merge

// Merge many signals into one, biased towards the
// left-most signal if multiple signals update simultaneously.
function merges(inputs) {
  return merge.apply(merge, inputs)
}
exports.merges = merges

// Combine a list of signals into a signal of lists.
function combine(inputs) {
  return map.apply(map, [Array].concat(inputs))
}
exports.combine = combine

// # Past-Dependence

// Create a past-dependent signal. Each value given on the input signal
// will be accumulated, producing a new output value.
function foldp(f, x, xs) {
  var output = new Signal(function(next) {
    spawn(function(value) {
      return next(f(output.value, value))
    }, xs)
  }, x)
  return output
}
exports.foldp = foldp

// Count the number of events that have occured.

// Signal x -> Signal Int
function count(xs) {
  return foldp(function(x, y) {
    return x + 1
  }, 0, xs)
}
exports.count = count

// Count the number of events that have occured that
// satisfy a given predicate.

// (x -> Bool) -> Signal x -> Signal Int
function countIf(p, xs) {
  return count(keepIf(p, xs.value, xs))
}
exports.countIf = countIf

// # Filters

// Keep only events that satisfy the given predicate.
// Elm does not allow undefined signals, so a base case
// must be provided in case the predicate is never satisfied.

// (x -> Bool) -> x -> Signal x -> Signal x
function keepIf(p, x, xs) {
  x = p(xs.value) ? xs.value : x
  return new Signal(function(next) {
    spawn(function(x) {
      return p(x) ? next(x) : Skip
    }, xs)
  }, x)
}
exports.keepIf = keepIf

// Drop events that satisfy the given predicate. Elm does not allow
// undefined signals, so a base case must be provided in case the
// predicate is never satisfied.

// (x -> Bool) -> x -> Signal x -> Signal x
function dropIf(p, x, xs) {
  x = p(xs.value) ? x : xs.value
  return new Signal(function(next) {
    spawn(function(x) {
      return p(x) ? Signal.Skip : next(x)
    }, xs)
  }, x)
}
exports.dropIf = dropIf

// Keep events only when the first signal is true. When the first signal
// becomes true, the most recent value of the second signal will be propagated.
// Until the first signal becomes false again, all events will be propagated.
// Elm does not allow undefined signals, so a base case must be provided in case
// the first signal is never true.

// Signal Bool -> x -> Signal x -> Signal x
function keepWhen(state, x, xs) {
  return new Signal(function(next) {
    spawn(function(value) {
      return !state.value && value ? next(xs.value) : Skip
    }, state)

    spawn(function(value) {
      return state.value ? next(value) : Skip
    }, xs)
  }, state.value ? xs.value : x)
}
exports.keepWhen = keepWhen

// Drop events when the first signal is true. When the first signal
// becomes false, the most recent value of the second signal will be
// propagated. Until the first signal becomes true again, all events
// will be propagated. Elm does not allow undefined signals, so a base
// case must be provided in case the first signal is always true.

// Signal Bool -> x -> Signal x -> Signal x
function dropWhen(state, x, xs) {
  return new Signal(function(next) {
    spawn(function(value) {
      return state.value && !value ? next(xs.value) : Skip
    }, state)
    spawn(function(value) {
      return state.value ? Skip : next(value)
    }, xs)
  }, state.value ? x : xs.value)
}
exports.dropWhen = dropWhen

// Drop sequential repeated values. For example, if a signal produces
// the sequence [1,1,2,2,1], it becomes [1,2,1] by dropping the values
// that are the same as the previous value.

// Signal x -> Signal x
function dropRepeats(xs) {
  var output = new Signal(function(next) {
    spawn(function(value) {
      return output.value === value ? Skip : next(value)
    }, xs)
  }, xs.value)
  return output
}
exports.dropRepeats = dropRepeats

// Sample from the second input every time an event occurs on the first
// input. For example, (sampleOn clicks (every second)) will give the
// approximate time of the latest click.

// Signal a -> Signal b -> Signal b
function sampleOn(ticks, data) {
  return new Signal(function(next) {
    var result = data.value

    spawn(function(value) { return result }, data)
    spawn(function(_) { return result = next(data.value) }, ticks)
  }, data.value)
}
exports.sampleOn = sampleOn

<commit_msg>Reimplement core in OOP style.<commit_after>"use strict";

// The library for general signal manipulation. Includes `lift` function
// (that supports up to 8 inputs), combinations, filters, and past-dependence.
//
// Signals are time-varying values. Lifted functions are reevaluated whenver
// any of their input signals has an event. Signal events may be of the same
// value as the previous value of the signal. Such signals are useful for
// timing and past-dependence.
//
// Some useful functions for working with time (e.g. setting FPS) and combining
// signals and time (e.g. delaying updates, getting timestamps) can be found in
// the Time library.
//
// Module implements elm API: http://docs.elm-lang.org/library/Signal.elm

var $source = "source@signal"
var $sources = "sources@signal"
var $outputs = "outputs@signal"
var $connect = "connect@signal"
var $disconnect = "disconnect@signal"
var $receive = "receive@signal"
var $error = "error@signal"
var $end = "end@signal"
var $start = "start@signal"
var $stop = "stop@signal"
var $state = "state@signal"

function outputs(input) { return input[$outputs] }
outputs.toString = function() { return $outputs }
exports.outputs = outputs

function start(input) { input[$start](input) }
start.toString = function() { return $start }
exports.start = start

function stop(input) { input[$stop](input) }
stop.toString = function() { return $stop }
exports.stop = stop

function connect(source, target) { source[$connect](source, target) }
connect.toString = function() { return $connect }
exports.connect = connect

function disconnect(source, target) { source[$disconnect](source, target) }
disconnect.toString = function() { return $disconnect }
exports.disconnect = disconnect

function receive(input, message) { input[$receive](input, message) }
receive.toString = function() { return $receive }
exports.receive = receive

function error(input, message) { input[$error](input, message) }
error.toString = function() { return $error }
exports.error = error

function end(input) { input[$end](input) }
end.toString = function() { return $end }
exports.end = end

function stringify(input) {
  return input.name + "[" + (input[$outputs] || []).map(function(x) { return x.name }) + "]"
}

var stringifier = Object.prototype.toString
function isError(message) {
  return stringifier.call(message) === "[object Error]"
}

function Return(value) {
  if (!(this instanceof Return))
    return new Return(value)

  this.value = value
}
exports.Return = Return

function send(input, message) {
  if (message instanceof Return) {
    // console.log("write message")
    input[$receive](input, message.value)
    input[$end](input)
  }
  else if (isError(message)) {
    input[$error](input, message)
  }
  else {
    input[$receive](input, message)
  }
}
exports.send = send

function Break() {}
exports.Break = Break

function Input() {}
exports.Input = Input

// `Input.start` is invoked with an `input` whenever system is
// ready to start receiving values. After this point `input` can
// start sending messages. Generic behavior is to `connect` to
// the `input[$source]` to start receiving messages.
Input.start = function(input) {
  var source = input[$source]
  source[$connect](source, input)
}

// `Input.stop` is invoked with an `input` whenever it needs to
// stop. After this point `input` should stop sending messages.
// Generic `Input` behavior is to `disconnect` from the
// `input[$source]` so no more `messages` will be received.
Input.stop = function(input) {
  //console.debug("<< stop", stringify(input))
  var source = input[$source]
  source[$disconnect](source, input)
}

// `Input.connect` is invoked with `input` and `output`. This
// implementation put's `output` to it's `$output` ports to
// delegate received `messages` to it.
Input.connect = function(input, output) {
  var outputs = input[$outputs]
  if (outputs.indexOf(output) < 0) {
    outputs.push(output)
    if (outputs.length === 1)
      input[$start](input)
  }
}

// `Input.disconnect` is invoked with `input` and an `output`
// connected to it. After this point `output` should not longer
// receive messages from the `input`. If it's a last `output`
// `input` will be stopped.
Input.disconnect = function(input, output) {
  var outputs = input[$outputs]
  var index = outputs.indexOf(output)
  if (index >= 0) {
    outputs.splice(index, 1)
    if (outputs.length === 0)
      input[$stop](input)
  }
}

// `Input.Port` creates a message receiver port. `Input` instances support
// `message`, `error`, `end` ports.
Input.Port = function(port) {
  var isError = port === $error
  var isEnd = port === $end
  var isMessage = port === $receive

  // Function will write `message` to a given `input`. This means
  // it will delegeate messages to it's `input[$outputs]` ports.
  return function write(input, message) {
    //console.log("write to", stringify(input)  + ":" + port)
    var outputs = input[$outputs]
    var result = void(0)
    var count = outputs.length
    var index = 0

    // Note: dispatch loop decreases count or increases index as needed.
    // This makes sure that new connections will not receive messages
    // until next dispatch loop & intentionally so.
    while (index < outputs.length) {
      // Attempt to send a value to a connected `output`. If this is
      // `$end` `port` return `Break` to cause `output` to be
      // disconnected. If any other `port` just deliver a `message`.
      var output = outputs[index]
      //console.log(index, output)
      try {
        result = isEnd ? output[port](output, input) :
                 output[port](output, message, input)
      }
      catch (reason) {
        throw reason
        // If exception was thrown and `message` was send to `$error`
        // `port` give up and log error.
        if (isError) {
          console.error("Failed to receive an error message",
                        message,
                        reason)
        }
        // If exception was thrown when writing to a different `port`
        // attempt to write to an `$error` `port` of the `output`.
        else {
          try {
            result = output[$error](output, reason, input)
          }
          // If exception is still thrown when writing to an `$error`
          // `port` give up and log `error`.
          catch (error) {
            console.error("Failed to receive message & an error",
                          message,
                          reason,
                          error);
          }
        }
      }

      // If result of sending `message` to an `output` was instance
      // of `Break`, disconnect that `output` so it no longer get's
      // messages. Note `index` is decremented as disconnect will
      // remove it from `outputs`.
      if (result instanceof Break || isEnd) {
        input[$disconnect](input, output)
      }
      // On any other `result` just move to a next output.
      else {
        index = index + 1
      }
    }

    // Once message was written to all outputs update `value` of
    // the input.
    if (isMessage)
      input.value = message
  }
}

// Inputs have `message`, `error` and `end` ports
Input.receive = Input.Port($receive)
Input.error = Input.Port($error)
Input.end = Input.Port($end)

// Same API functions are saved in the prototype in order to enable
// polymorphic dispatch.
Input.prototype[$start] = Input.start
Input.prototype[$stop] = Input.stop
Input.prototype[$connect] = Input.connect
Input.prototype[$disconnect] = Input.disconnect
Input.prototype[$receive] = Input.receive
Input.prototype[$error] = Input.error
Input.prototype[$end] = Input.end

function Constant(value) {
  this.value = value
}
Constant.ignore = function() {}

Constant.prototype = new Input()
Constant.prototype.constructor = Constant
Constant.prototype[$start] = Constant.ignore
Constant.prototype[$stop] = Constant.ignore
Constant.prototype[$connect] = Constant.ignore
Constant.prototype[$disconnect] = Constant.ignore
Constant.prototype[$receive] = Constant.ignore
Constant.prototype[$error] = Constant.ignore
Constant.prototype[$end] = Constant.ignore

// Create a constant signal that never changes.

// a -> Signal a

function constant(value) {
  return new Constant(value)
}
exports.constant = constant

function Merge(inputs) {
  this[$outputs] = []
  this[$sources] = inputs
  this.value = inputs[0].value
}
Merge.start = function(input) {
  var sources = input[$sources]
  var count = sources.length
  var id = 0

  while (id < count) {
    var source = sources[id]
    source[$connect](source, input)
    id = id + 1
  }
}
Merge.stop = function(input) {
  var inputs = input[$sources]
  var count = inputs.length
  var id = 0
  while (id < count) {
    var source = inputs[id]
    source[$disconnect](source, input)
    id = id + 1
  }
}
Merge.end = function(input, source) {
  var sources = input[$sources]
  var id = sources.indexOf(source)
  if (id >= 0) {
    sources.splice(id, 1)
    if (sources.length === 0)
      Input.end(input)
  }
}

Merge.prototype = new Input()
Merge.prototype.constructor = Merge
Merge.prototype[$start] = Merge.start
Merge.prototype[$stop] = Merge.stop
Merge.prototype[$end] = Merge.end

// Merge two signals into one, biased towards the
// first signal if both signals update at the same time.

// Signal x -> Signal y -> ... -> Signal z
function merge() {
  return new Merge(arguments)
}
exports.merge = merge

// Merge many signals into one, biased towards the
// left-most signal if multiple signals update simultaneously.
function merges(inputs) {
  return new Merge(inputs)
}
exports.merges = merges

// # Past-Dependence

// Create a past-dependent signal. Each value given on the input signal
// will be accumulated, producing a new output value.

function FoldP(step, value, input) {
  this[$outputs] = []
  this[$source] = input
  this.value = value
  this.step = step
}
FoldP.receive = function(input, message, source) {
  Signal.receive(input, input.step(input.value, message))
}

FoldP.prototype = new Input()
FoldP.prototype.constructor = FoldP
FoldP.prototype[$receive] = FoldP.receive

function foldp(step, x, xs) {
  return new FoldP(step, x, xs)
}
exports.foldp = foldp

// Optimized version that tracks single input.
function Lift(step, input) {
  this.step = step
  this[$source] = input
  this[$outputs] = []
  this.value = step(input.value)
}
Lift.receive = function(input, message) {
  Input.receive(input, input.step(message))
}

Lift.prototype = new Input()
Lift.prototype.constructor = Lift
Lift.prototype[$receive] = Lift.receive

function LiftN(step, inputs) {
  var count = inputs.length
  var id = 0
  var params = Array(count)
  while (id < count) {
    var input = inputs[id]
    params[id] = input.value
    id = id + 1
  }
  var value = step.apply(step, params)

  this.step = step
  this[$outputs] = []
  this[$sources] = inputs
  this[$state] = params
  this.value = value
}
LiftN.start = Merge.start
LiftN.stop = Merge.stop
LiftN.end = Merge.end

LiftN.receive = function(input, message, source) {
  var params = input[$state]
  var index = input[$sources].indexOf(source)
  var step = input.step
  params[index] = message
  return Input.receive(input, step.apply(step, params))
}

LiftN.prototype = new Input()
LiftN.prototype.constructor = LiftN
LiftN.prototype[$start] = LiftN.start
LiftN.prototype[$stop] = LiftN.stop
LiftN.prototype[$end] = LiftN.end
LiftN.prototype[$receive] = LiftN.receive

var slicer = [].slice

// Transform given signal(s) with a given `step` function.

// (x -> y -> ...) -> Signal x -> Signal y -> ... -> Signal z
function lift(step, xs, ys) {
  return ys ? new LiftN(step, slicer.call(arguments, 1)) :
         new Lift(step, xs)
}
exports.lift = lift
exports.lift2 = lift
exports.lift3 = lift
exports.lift4 = lift
exports.lift5 = lift
exports.lift6 = lift
exports.lift7 = lift
exports.lift8 = lift
exports.liftN = lift

// Combine a array of signals into a signal of arrays.
function combine(inputs) {
  return new LiftN(Array, inputs)
}
exports.combine = combine

// Count the number of events that have occured.

// Signal x -> Signal Int
function count(xs) {
  return foldp(function(x, y) {
    return x + 1
  }, 0, xs)
}
exports.count = count

// Count the number of events that have occured that
// satisfy a given predicate.

// (x -> Bool) -> Signal x -> Signal Int
function countIf(p, xs) {
  return count(keepIf(p, xs.value, xs))
}
exports.countIf = countIf

// # Filters

function KeepIf(p, value, input) {
  this.value = p(input.value) ? input.value : value
  this[$source] = input
}
KeepIf.receive = function(input, message) {
  if (p(message))
    Input.receive(input, message)
}
KeepIf.prototype.constructor = KeepIf
KeepIf.prototype = new Input()
KeepIf.prototype[$receive] = KeepIf.receive

// Keep only events that satisfy the given predicate.
// Elm does not allow undefined signals, so a base case
// must be provided in case the predicate is never satisfied.

// (x -> Bool) -> x -> Signal x -> Signal x
function keepIf(p, x, xs) {
  return new KeepIf(p, x, xs)
}
exports.keepIf = keepIf

function DropIf(p, value, input) {
  this.value = p(input.value) ? value : input.value
  this[$source] = input
}
DropIf.receive = function(input, message) {
  if (!p(message))
    Input.receive(input, message)
}
DropIf.prototype.constructor = DropIf
DropIf.prototype = new Input()
DropIf.prototype[$receive] = DropIf.receive

// Drop events that satisfy the given predicate. Elm does not allow
// undefined signals, so a base case must be provided in case the
// predicate is never satisfied.

// (x -> Bool) -> x -> Signal x -> Signal x
function dropIf(p, x, xs) {
  return new DropIf(p, x, xs)
}
exports.dropIf = dropIf

// Keep events only when the first signal is true. When the first signal
// becomes true, the most recent value of the second signal will be propagated.
// Until the first signal becomes false again, all events will be propagated.
// Elm does not allow undefined signals, so a base case must be provided in case
// the first signal is never true.

// Signal Bool -> x -> Signal x -> Signal x
function Skip() { return Skip }
function isSkip(x) { return x === isSkip }
function skipIfTrue(isTrue, x) { return isTrue ? Skip : x }
function skipIfFalse(isTrue, x) { return isTrue ? x : Skip }

function keepWhen(state, x, xs) {
  var input = lift(skipIfFalse, state, xs)
  return dropIf(isSkip, x, input)
}
exports.keepWhen = keepWhen

// Drop events when the first signal is true. When the first signal
// becomes false, the most recent value of the second signal will be
// propagated. Until the first signal becomes true again, all events
// will be propagated. Elm does not allow undefined signals, so a base
// case must be provided in case the first signal is always true.

// Signal Bool -> x -> Signal x -> Signal x
function dropWhen(state, x, xs) {
  var input = lift(skipIfTrue, state, xs)
  return dropIf(isSkip, x, input)
}
exports.dropWhen = dropWhen

// Drop sequential repeated values. For example, if a signal produces
// the sequence [1,1,2,2,1], it becomes [1,2,1] by dropping the values
// that are the same as the previous value.

// Signal x -> Signal x
function dropRepeats(xs) {
  return dropIf(function(x) {
    return xs.value === x
  }, xs.value, xs)
}
exports.dropRepeats = dropRepeats

// Sample from the second input every time an event occurs on the first
// input. For example, (sampleOn clicks (every second)) will give the
// approximate time of the latest click.

// Signal a -> Signal b -> Signal b
function sampleOn(ticks, input) {
  return merge(dropIf(True, input.value, input),
               lift(function(_) { return input.value }, ticks))
}
exports.sampleOn = sampleOn

function True() { return true }
<|endoftext|>


<commit_before>module.exports = function (app, req) {

	return {

		segment: function(i) {
			var uri = req.url.split('?');
		    return uri[0].split('/');
		}

	}

};<commit_msg>Delete tesla-uri.js<commit_after><|endoftext|>


<commit_before>BEST.component('famous-demos:six-surfaces', {
    tree: 'six-surfaces.html',
    behaviors: {
        '.square': {
            'size': function(size, $time) {
                    var chg = (Math.sin($time / 1000) / 2) + 1;
                    return [chg * size, chg * size];
            },
            'rotation': function(_isAnimating, $time) {
                if (_isAnimating)
                    return [0, 0, $time / 1000];
                else
                    return [$time / 1000, 0, 0];
            },
            'origin': [0.5, 0.5],
            'mount-point': [0.5, 0.5],
            'position': function(windowSize) {
                var px = Math.floor(Math.random() * windowSize[0]);
                var py = Math.floor(Math.random() * windowSize[1]);
                return [px, py];
            }
        },
        '.surface': {
            'style': function($every, key, value) {
                var hue = Math.floor(Math.random() * 240) + 140;
                return {
                    'color': 'white',
                    'text-align': 'center',
                    'font-family': 'Helvetica',
                    'font-weight': 'bold',
                    'background-color': 'hsla(' + hue + ', 80%, 60%, 0.8)',
                    'border': '1px solid black',
                    'padding-top': '20px'
                };
            }
        },

        '#circle-component' : {
            'handle-click' : function(_circleClickEvent) {
                return '_circleClickEvent';
            }
        },

    },
    events: {
        public: {
            'circle-click': function(state, event) {
                state.set('_circleClickEvent', event);
                state.chain('_isAnimating').flip();
            }
        }
    },
    states: {
        size: 130,
        windowSize: [window.innerWidth * .9, window.innerHeight * .9],
        _isAnimating: true,
        _circleClickEvent: null
    }
});
<commit_msg>demo: remove color change on every state change<commit_after>BEST.component('famous-demos:six-surfaces', {
    tree: 'six-surfaces.html',
    behaviors: {
        '.square': {
            'size': function(size, $time) {
                    var chg = (Math.sin($time / 1000) / 2) + 1;
                    return [chg * size, chg * size];
            },
            'rotation': function(_isAnimating, $time) {
                if (_isAnimating)
                    return [0, 0, $time / 1000];
                else
                    return [$time / 1000, 0, 0];
            },
            'origin': [0.5, 0.5],
            'mount-point': [0.5, 0.5],
            'position': function(windowSize) {
                var px = Math.floor(Math.random() * windowSize[0]);
                var py = Math.floor(Math.random() * windowSize[1]);
                return [px, py];
            }
        },
        '.surface': {
            'style': function() {
                var hue = Math.floor(Math.random() * 240) + 140;
                return {
                    'color': 'white',
                    'text-align': 'center',
                    'font-family': 'Helvetica',
                    'font-weight': 'bold',
                    'background-color': 'hsla(' + hue + ', 80%, 60%, 0.8)',
                    'border': '1px solid black',
                    'padding-top': '20px'
                };
            }
        },

        '#circle-component' : {
            'handle-click' : function(_circleClickEvent) {
                return '_circleClickEvent';
            }
        },

    },
    events: {
        public: {
            'circle-click': function(state, event) {
                state.set('_circleClickEvent', event);
                state.chain('_isAnimating').flip();
            }
        }
    },
    states: {
        size: 130,
        windowSize: [window.innerWidth * .9, window.innerHeight * .9],
        _isAnimating: true,
        _circleClickEvent: null
    }
});
<|endoftext|>


<commit_before>var elasticsearch = require('elasticsearch');

var elasticClient = new elasticsearch.Client({
  host: 'localhost:9200',
  log: 'info'
});

elasticClient.ping({
  requestTimeout: 30000,

  // undocumented params are appended to the query string
  hello: "elasticsearch"
}, function(error) {
  if (error) {
    console.error('elasticsearch cluster is down!');
  } else {
    console.log('All is well');
  }
});

var indexName = "chibleeRandomIndex";

/**
 * Delete an existing index
 */
function deleteIndex() {
  return elasticClient.indices.delete({
    index: indexName
  });
}
exports.deleteIndex = deleteIndex;

/**
 * create the index
 */
function initIndex() {
  return elasticClient.indices.create({
    index: indexName
  });
}
exports.initIndex = initIndex;

/**
 * check if the index exists
 */
function indexExists() {
  return elasticClient.indices.exists({
    index: indexName
  });
}
exports.indexExists = indexExists;

function initMapping() {
  return elasticClient.indices.putMapping({
    index: indexName,
    type: "document",
    body: {
      properties: {
        name: {
          type: "string"
        },
        category: {
          type: "string"
        },
        subCategory: {
          type: "string"
        },
        address: {
          type: "string"
        },
        area: {
          type: "string"
        },
        tags: {
          type: [String]
        },
        coords: {
          type: [Number],
          index: '2dsphere'
        },
        suggest: {
          type: "completion",
          analyzer: "simple",
          search_analyzer: "simple",
          payloads: true
        }
      }
    }
  });
}
exports.initMapping = initMapping;

function addDocument(document) {
  console.log('addDocument');
  return elasticClient.index({
    index: indexName,
    type: "document",
    body: {
      name: document.name,
      category: document.category,
      subCategory: document.subCategory,
      address: document.address,
      area: document.area,
      tags: document.tags,
      coords: document.coords,
      suggest: {
        input: document.name,
        output: document.name,
        payload: document.metadata || {}
      }
    }
  });
}
exports.addDocument = addDocument;

function getSuggestions(input) {
  return elasticClient.suggest({
    index: indexName,
    type: "document",
    body: {
      docsuggest: {
        text: input,
        completion: {
          field: "suggest",
          fuzzy: true
        }
      }
    }
  })
}
exports.getSuggestions = getSuggestions;
<commit_msg>code update<commit_after>// var elasticsearch = require('elasticsearch');
//
// var elasticClient = new elasticsearch.Client({
//   host: 'localhost:9200',
//   log: 'info'
// });
//
//
// elasticClient.ping({
//   requestTimeout: 30000,
//
//   // undocumented params are appended to the query string
//   hello: "elasticsearch"
// }, function(error) {
//   if (error) {
//     console.error('elasticsearch cluster is down!');
//   } else {
//     console.log('All is well');
//   }
// });
//
// var indexName = "chibleeRandomIndex";
//
// /**
//  * Delete an existing index
//  */
// function deleteIndex() {
//   return elasticClient.indices.delete({
//     index: indexName
//   });
// }
// exports.deleteIndex = deleteIndex;
//
// /**
//  * create the index
//  */
// function initIndex() {
//   return elasticClient.indices.create({
//     index: indexName
//   });
// }
// exports.initIndex = initIndex;
//
// /**
//  * check if the index exists
//  */
// function indexExists() {
//   return elasticClient.indices.exists({
//     index: indexName
//   });
// }
// exports.indexExists = indexExists;
//
// function initMapping() {
//   return elasticClient.indices.putMapping({
//     index: indexName,
//     type: "document",
//     body: {
//       properties: {
//         name: {
//           type: "string"
//         },
//         category: {
//           type: "string"
//         },
//         subCategory: {
//           type: "string"
//         },
//         address: {
//           type: "string"
//         },
//         area: {
//           type: "string"
//         },
//         tags: {
//           type: [String]
//         },
//         coords: {
//           type: [Number],
//           index: '2dsphere'
//         },
//         suggest: {
//           type: "completion",
//           analyzer: "simple",
//           search_analyzer: "simple",
//           payloads: true
//         }
//       }
//     }
//   });
// }
// exports.initMapping = initMapping;
//
// function addDocument(document) {
//   console.log('addDocument');
//   return elasticClient.index({
//     index: indexName,
//     type: "document",
//     body: {
//       name: document.name,
//       category: document.category,
//       subCategory: document.subCategory,
//       address: document.address,
//       area: document.area,
//       tags: document.tags,
//       coords: document.coords,
//       suggest: {
//         input: document.name,
//         output: document.name,
//         payload: document.metadata || {}
//       }
//     }
//   });
// }
// exports.addDocument = addDocument;
//
// function getSuggestions(input) {
//   return elasticClient.suggest({
//     index: indexName,
//     type: "document",
//     body: {
//       docsuggest: {
//         text: input,
//         completion: {
//           field: "suggest",
//           fuzzy: true
//         }
//       }
//     }
//   })
// }
// exports.getSuggestions = getSuggestions;
<|endoftext|>


<commit_before>(function($)
{
    'use strict';
    $.fn.ModPicker = function(options)
    {
        moment.locale(window.navigator.userLanguage || window.navigator.language);

        // This is the easiest way to have default options.
        var settings = $.extend({
            locale: moment.locale()
            // These are the defaults.
        }, options), _self = this;

        this.datetimepicker(settings).on('dp.change',function(){
            _self.trigger('change')
        });
        return this;

    };

}(jQuery));
<commit_msg>Fix: #SSW-168 Überarbeitung Datepicker<commit_after>(function($)
{
    'use strict';
    $.fn.ModPicker = function(options)
    {
        moment.locale(window.navigator.userLanguage || window.navigator.language);
        // This is the easiest way to have default options.
        var settings = $.extend({
            locale: moment.locale(),
            useCurrent: false,
            showTodayButton: true,
            calendarWeeks: true,
            focusOnShow: false,
            icons: {
                today: 'glyphicons glyphicons-home'
            },
            keyBinds: {
                up: false,
                down: false,
                left: false,
                right: false,
                delete: false
            },
            useStrict: true,
            format: 'DD.MM.YYYY',
            extraFormats: [ 'DD.MM.YY', 'DD.M.YY', 'D.MM.YY', 'D.M.YY', 'DDMMYYYY' ]
            // These are the defaults.
        }, options), _self = this;

        this.datetimepicker(settings).on('dp.change',function(){
            _self.trigger('change')
        });
        return this;

    };

}(jQuery));
<|endoftext|>


<commit_before>/**
 * Generate ACII art from image or video
 *
 * @module   Schwartz
 * @version  1.9
 *
 * @author   Zaytsev Alexandr
 *
 * @example
 *    // Exapmple with image
 *    var
 *        body    = document.getElementsByTagName('body')[0],
 *        outDiv  = document.createElement('div'),
 *        schwartz = new Schwartz({
 *            detail: 60
 *        });
 *    // end of vars
 *
 *    body.appendChild(outDiv);
 *    schwartz.generateFromImage('/path/to/img.jpg');
 *
 *
 *    // Example with video
 *    var
 *        body    = document.getElementsByTagName('body')[0],
 *        video   = document.getElementsByTagName('video')[0],
 *        outDiv  = document.createElement('div'),
 *
 *        schwartz = new Schwartz({
 *            inverse: true,
 *            detail: 60
 *        });
 *    // end of vars
 *
 *
 *    body.appendChild(outDiv);
 *    schwartz.generateFromVideo(video);
 */
!function( window, module ) {
    'use strict';

    var
        Schwartz = module();
        // end of vars

    // AMD
    if ( typeof define === 'function' && define.amd ) {
        define('Schwartz', [], function() {
            return Schwartz;
        });

    // YM Modules
    } else if ( typeof modules !== 'undefined' && typeof modules.define === 'function' ) {
        modules.define('Schwartz', [], function( provide ) {
            provide(Schwartz);
        });

    // Browser global
    } else {
        window.Schwartz = Schwartz;
    }
}( this, function() {
    'use strict';

    var
        Schwartz = (function() {
            var
                /**
                 * @const
                 */
                DEFAULT_DETAIL = 50,

                DEFAULT_INVERSE = false,

                /**
                 * After parse image callback
                 *
                 * @memberOf    module:Schwartz~Schwartz
                 * @callback    parseImageCallback
                 *
                 * @param       {Object[][]}  res       Art strings by line
                 * @param       {Number}      res.r     Red channel average
                 * @param       {Number}      res.g     Green channel average
                 * @param       {Number}      res.b     Blue channel average
                 * @param       {Number}      res.a     Alpha channel average
                 * @param       {Number}      res.c     Composite average
                 * @param       {Number}      res.sym   Symbol
                 */

                /**
                 * @memberOf     module:Schwartz~
                 *
                 * @constructs   Schwartz
                 *
                 * @param        {Object}               [options]
                 * @param        {Boolean}              [options.inverse=false]
                 * @param        {Number}               [options.detail=50]
                 * @param        {parseImageCallback}   [options.render]
                 */
                Schwartz = function Schwartz( options ) {
                    // enforces new
                    if ( !( this instanceof Schwartz ) ) {
                        return new Schwartz(options);
                    }

                    // constructor body
                    this.canvas        = document.createElement('canvas');
                    this.imgObj        = new Image();
                    this.c             = this.canvas.getContext('2d');

                    this.inverse       = options.inverse || DEFAULT_INVERSE;
                    this.callback      = options.render || false;

                    /**
                     * Default symbols
                     *
                     * @memberOf    module:Schwartz~Schwartz
                     * @member      loadImage
                     * @private
                     *
                     * @type        {Array}
                     */
                    this.charSet = [' ', '.', ',', ':', ';', '*', '|', '~', 'I', '1', '?', '7', '>', 'Y', 'F', '4', 'V', '#', '2', '9', '6', '8', '%', 'N', 'B', 'Q', 'M', '@', 'W'];

                    if ( options.detail ) {
                        this.setDetail(options.detail);
                    } else {
                        this.detail = DEFAULT_DETAIL;
                    }

                    this.charSet = ( this.inverse ) ? this.charSet : this.charSet.reverse();
                },

                /**
                 * ==============================
                 * ========PRIVATE METHODS=======
                 * ==============================
                 */

                /**
                 * Validate numbers
                 *
                 * @memberOf    module:Schwartz~Schwartz
                 * @method      isNumber
                 * @private
                 *
                 * @param       {*}         n
                 *
                 * @return      {Boolean}
                 */
                isNumber = function( n ) {
                    return !isNaN(parseFloat(n)) && isFinite(n);
                },

                /**
                 * After load image callback
                 *
                 * @memberOf    module:Schwartz~Schwartz
                 * @callback    loadImageCallback
                 *
                 * @param       {Object}    imageData
                 */

                /**
                 * @memberOf    module:Schwartz~Schwartz
                 * @method      loadImage
                 * @private
                 *
                 * @this        {Schwartz}
                 *
                 * @param       {String}                src
                 * @param       {loadImageCallback}     callback
                 */
                loadImage = function( src, callback ) {
                    var
                        self = this,

                        imageLoaded = function( ev ) {
                            var
                                imgW = self.imgObj.width,
                                imgH = self.imgObj.height,
                                img = ev.target,
                                imageData;
                            // end of vars

                            self.canvas.width = imgW;
                            self.canvas.height = imgH;

                            self.c.drawImage(img, 0, 0);
                            imageData = self.c.getImageData(0, 0, imgW, imgH);
                            callback.call(self, imageData);
                        };
                        // end of vars

                        this.imgObj.onload = imageLoaded;
                        this.imgObj.crossOrigin = 'use-credentials';
                        this.imgObj.src = src;
                },

                /**
                 * @memberOf    module:Schwartz~Schwartz
                 * @method      getSymbol
                 * @private
                 *
                 * @this        {Schwartz}
                 *
                 * @param       {Number}    val     Gray scale value
                 */
                getSymbol = function( val ) {
                    var
                        asciival;
                    // end of vars

                    // console.info(val);

                    if ( isNaN(val) ) {
                        asciival = this.charSet[this.charSet.length-1];
                    } else {
                        asciival = this.charSet[(this.charSet.length * val / 256 ) | 0];
                    }

                    return asciival;
                },

                /**
                 * @memberOf    module:Schwartz~Schwartz
                 * @method      getPixelGroupAvg
                 * @private
                 *
                 * @this        {Schwartz}
                 *
                 * @param       {Object}    options
                 * @param       {Object}    options.pixels              Canvas image data
                 * @param       {Number}    options.x                   Inital x position on the canvas
                 * @param       {Number}    options.y                   Inital y position on the canvas
                 * @param       {Number}    options.stepX
                 * @param       {Number}    options.stepY
                 *
                 * @return      {Object}    res
                 * @return      {Number}    res.r                       Red channel average
                 * @return      {Number}    res.g                       Green channel average
                 * @return      {Number}    res.b                       Blue channel average
                 * @return      {Number}    res.a                       Alpha channel average
                 * @return      {Number}    res.c                       Composite average
                 */
                getPixelGroupAvg = function( options ) {
                    var
                        imgPixels = options.pixels,
                        initX     = options.x,
                        initY     = options.y,
                        stepX     = options.stepX,
                        stepY     = options.stepY,

                        count     = 0,
                        sumR      = 0,
                        sumG      = 0,
                        sumB      = 0,
                        sumA      = 0,
                        sumC      = 0,

                        r, g, b, a, c,

                        x, y,
                        index;
                    // end of vars

                    for ( x = initX; x < initX + stepX; x++ ) {
                        for ( y = initY; y < initY + stepY; y++ ) {
                            index = (y * 4) * imgPixels.width + x * 4;

                            r = imgPixels.data[index];
                            g = imgPixels.data[index + 1];
                            b = imgPixels.data[index + 2];
                            a = imgPixels.data[index + 3];
                            c = (imgPixels.data[index] + imgPixels.data[index + 1] + imgPixels.data[index + 2]) / 3;

                            if ( !isNaN(r) && !isNaN(g) && !isNaN(b) && !isNaN(a) && !isNaN(c) ) {
                                sumR += r;
                                sumG += g;
                                sumB += b;
                                sumA += a;
                                sumC += c;
                                count++;
                            }
                        }
                    }

                    return {
                        r: (sumR/count) | 0,
                        g: (sumG/count) | 0,
                        b: (sumB/count) | 0,
                        a: (sumA/count) | 0,
                        c: (sumC/count) | 0
                    };
                },

                /**
                 * @memberOf    module:Schwartz~Schwartz
                 * @method      parseImage
                 * @private
                 *
                 * @this        {Schwartz}
                 *
                 * @param       {Object}    imageData   Canvas image data
                 */
                parseImage = function( imageData ) {
                    var
                        imgW = imageData.width,
                        imgH = imageData.height,
                        art  = [],

                        strChar, str, symbol,
                        p, x, y, avg;
                    //end of vars

                    this.dimX = Math.round((imgW * 100 / this.detail)/200);
                    this.dimY = Math.round((imgH * 100 / this.detail)/200);

                    this.dimX = ( this.dimX < 1) ? 1 : this.dimX;
                    this.dimY = ( this.dimY < 1) ? 1 : this.dimY;

                    for ( y = 0; y < imgH; ) {
                        str     = [];
                        strChar = '';

                        for ( x = 0; x < imgW; ) {
                            avg = getPixelGroupAvg({
                                pixels: imageData,
                                x: x,
                                y: y,
                                stepX: this.dimX,
                                stepY: this.dimY
                            });

                            symbol  = getSymbol.call(this, avg.c);
                            strChar += symbol;
                            avg.sym = symbol;

                            str.push(avg)

                            x += this.dimX;
                        }

                        art.push(str);

                        y += this.dimY;
                    }

                    if ( typeof this.callback !== 'undefined' && typeof this.callback === 'function' ) {
                        this.callback(art);
                    }
                },

                /**
                 * @memberOf    module:Schwartz~Schwartz
                 * @method      videoTimerCallback
                 * @private
                 *
                 * @this        {Schwartz}
                 */
                videoTimerCallback = function() {
                    var
                        videoWidth  = this.videoWidth,
                        videoHeight = this.videoHeight,
                        self        = this,
                        imageData;
                    // end of vars

                    if ( this.video.paused || this.video.ended ) {
                        return;
                    }

                    this.c.drawImage(this.video, 0, 0, videoWidth, videoHeight);
                    imageData = this.c.getImageData(0, 0, videoWidth, videoHeight);
                    parseImage.call(this, imageData);

                    setTimeout(function () {
                        videoTimerCallback.call(self);
                    }, 0);
                };
            // end of vars

            /**
             * ==============================
             * ========PUBLIC METHODS========
             * ==============================
             */

            /**
             * @memberOf    module:Schwartz~Schwartz
             * @method      setDetail
             * @public
             *
             * @param       {Number}    n   Level of detail
             */
            Schwartz.prototype.setDetail = function( n ) {
                var
                    newDetail;
                // end of vars

                // validate number
                if ( isNumber(n) ) {
                    newDetail = parseInt(n, 10);

                    this.detail = ( newDetail < 1 ) ? 1 : ( newDetail > 100 ) ? 100 : newDetail;
                } else {
                    this.detail = DEFAULT_DETAIL;
                }

                return;
            };

            /**
             * @memberOf    module:Schwartz~Schwartz
             * @method      setCharSet
             * @public
             *
             * @param       {String}    str
             */
            Schwartz.prototype.setCharSet = function( str ) {
                var
                    // create local canvas
                    canvas = document.createElement('canvas'),
                    c      = canvas.getContext('2d'),
                    all    = [],

                    i, avg, imgPixels;
                // end of vars

                canvas.width  = 10;
                canvas.height = 20;
                c.fillStyle   = '#000';
                c.font        = '18px monospace';
                this.charSet  = [];

                for ( i = 0; i < str.length; i++ ) {
                    // reset canvas
                    canvas.width = canvas.width;

                    c.fillText(str[i], 0, 18);
                    imgPixels = c.getImageData(0, 0, canvas.width, canvas.height);

                    avg = getPixelGroupAvg({
                        pixels: imgPixels,
                        x: 0,
                        y: 0,
                        stepX: canvas.width,
                        stepY: canvas.height
                    });

                    all[avg.a] = str[i];
                }

                for ( i = 0; i < all.length; i++ ) {
                    if ( all[i] ) {
                        this.charSet.push(all[i]);
                    }
                }

                this.charSet = ( this.inverse ) ? this.charSet : this.charSet.reverse();
            };

            /**
             * @memberOf    module:Schwartz~Schwartz
             * @method      loadImg
             * @public
             *
             * @param       {String} src    Image source URI
             */
            Schwartz.prototype.generateFromImage = function( src ) {
                loadImage.call(this, src, parseImage);
            };

            /**
             * Inverse image
             *
             * @memberOf    module:Schwartz~Schwartz
             * @method      inverseImage
             * @public
             */
            Schwartz.prototype.inverseImage = function() {
                this.charSet.reverse();
            };

            /**
             * @memberOf    module:Schwartz~Schwartz
             * @method      loadImg
             * @public
             *
             * @param       {DOM Element}   video    Video DOM element
             */
            Schwartz.prototype.generateFromVideo = function( video ) {
                var
                    self = this;
                // end of vars

                this.video       = video;
                this.videoWidth  = video.width;
                this.videoHeight = video.height;

                video.addEventListener('play', function() {
                    videoTimerCallback.call(self);
                }, false);
            };

            return Schwartz;
        }());
    // end of vars

    return Schwartz;
});
<commit_msg>Video demensions bug fix.<commit_after>/**
 * Generate ACII art from image or video
 *
 * @module   Schwartz
 * @version  1.9
 *
 * @author   Zaytsev Alexandr
 *
 * @example
 *    // Exapmple with image
 *    var
 *        body    = document.getElementsByTagName('body')[0],
 *        outDiv  = document.createElement('div'),
 *        schwartz = new Schwartz({
 *            detail: 60
 *        });
 *    // end of vars
 *
 *    body.appendChild(outDiv);
 *    schwartz.generateFromImage('/path/to/img.jpg');
 *
 *
 *    // Example with video
 *    var
 *        body    = document.getElementsByTagName('body')[0],
 *        video   = document.getElementsByTagName('video')[0],
 *        outDiv  = document.createElement('div'),
 *
 *        schwartz = new Schwartz({
 *            inverse: true,
 *            detail: 60
 *        });
 *    // end of vars
 *
 *
 *    body.appendChild(outDiv);
 *    schwartz.generateFromVideo(video);
 */
!function( window, module ) {
    'use strict';

    var
        Schwartz = module();
        // end of vars

    // AMD
    if ( typeof define === 'function' && define.amd ) {
        define('Schwartz', [], function() {
            return Schwartz;
        });

    // YM Modules
    } else if ( typeof modules !== 'undefined' && typeof modules.define === 'function' ) {
        modules.define('Schwartz', [], function( provide ) {
            provide(Schwartz);
        });

    // Browser global
    } else {
        window.Schwartz = Schwartz;
    }
}( this, function() {
    'use strict';

    var
        Schwartz = (function() {
            var
                /**
                 * @const
                 */
                DEFAULT_DETAIL = 50,

                DEFAULT_INVERSE = false,

                /**
                 * After parse image callback
                 *
                 * @memberOf    module:Schwartz~Schwartz
                 * @callback    parseImageCallback
                 *
                 * @param       {Object[][]}  res       Art strings by line
                 * @param       {Number}      res.r     Red channel average
                 * @param       {Number}      res.g     Green channel average
                 * @param       {Number}      res.b     Blue channel average
                 * @param       {Number}      res.a     Alpha channel average
                 * @param       {Number}      res.c     Composite average
                 * @param       {Number}      res.sym   Symbol
                 */

                /**
                 * @memberOf     module:Schwartz~
                 *
                 * @constructs   Schwartz
                 *
                 * @param        {Object}               [options]
                 * @param        {Boolean}              [options.inverse=false]
                 * @param        {Number}               [options.detail=50]
                 * @param        {parseImageCallback}   [options.render]
                 */
                Schwartz = function Schwartz( options ) {
                    // enforces new
                    if ( !( this instanceof Schwartz ) ) {
                        return new Schwartz(options);
                    }

                    // constructor body
                    this.canvas        = document.createElement('canvas');
                    this.imgObj        = new Image();
                    this.c             = this.canvas.getContext('2d');

                    this.inverse       = options.inverse || DEFAULT_INVERSE;
                    this.callback      = options.render || false;

                    /**
                     * Default symbols
                     *
                     * @memberOf    module:Schwartz~Schwartz
                     * @member      loadImage
                     * @private
                     *
                     * @type        {Array}
                     */
                    this.charSet = [' ', '.', ',', ':', ';', '*', '|', '~', 'I', '1', '?', '7', '>', 'Y', 'F', '4', 'V', '#', '2', '9', '6', '8', '%', 'N', 'B', 'Q', 'M', '@', 'W'];

                    if ( options.detail ) {
                        this.setDetail(options.detail);
                    } else {
                        this.detail = DEFAULT_DETAIL;
                    }

                    this.charSet = ( this.inverse ) ? this.charSet : this.charSet.reverse();
                },

                /**
                 * ==============================
                 * ========PRIVATE METHODS=======
                 * ==============================
                 */

                /**
                 * Validate numbers
                 *
                 * @memberOf    module:Schwartz~Schwartz
                 * @method      isNumber
                 * @private
                 *
                 * @param       {*}         n
                 *
                 * @return      {Boolean}
                 */
                isNumber = function( n ) {
                    return !isNaN(parseFloat(n)) && isFinite(n);
                },

                /**
                 * After load image callback
                 *
                 * @memberOf    module:Schwartz~Schwartz
                 * @callback    loadImageCallback
                 *
                 * @param       {Object}    imageData
                 */

                /**
                 * @memberOf    module:Schwartz~Schwartz
                 * @method      loadImage
                 * @private
                 *
                 * @this        {Schwartz}
                 *
                 * @param       {String}                src
                 * @param       {loadImageCallback}     callback
                 */
                loadImage = function( src, callback ) {
                    var
                        self = this,

                        imageLoaded = function( ev ) {
                            var
                                imgW = self.imgObj.width,
                                imgH = self.imgObj.height,
                                img = ev.target,
                                imageData;
                            // end of vars

                            self.canvas.width = imgW;
                            self.canvas.height = imgH;

                            self.c.drawImage(img, 0, 0);
                            imageData = self.c.getImageData(0, 0, imgW, imgH);
                            callback.call(self, imageData);
                        };
                        // end of vars

                        this.imgObj.onload = imageLoaded;
                        this.imgObj.crossOrigin = 'use-credentials';
                        this.imgObj.src = src;
                },

                /**
                 * @memberOf    module:Schwartz~Schwartz
                 * @method      getSymbol
                 * @private
                 *
                 * @this        {Schwartz}
                 *
                 * @param       {Number}    val     Gray scale value
                 */
                getSymbol = function( val ) {
                    var
                        asciival;
                    // end of vars

                    // console.info(val);

                    if ( isNaN(val) ) {
                        asciival = this.charSet[this.charSet.length-1];
                    } else {
                        asciival = this.charSet[(this.charSet.length * val / 256 ) | 0];
                    }

                    return asciival;
                },

                /**
                 * @memberOf    module:Schwartz~Schwartz
                 * @method      getPixelGroupAvg
                 * @private
                 *
                 * @this        {Schwartz}
                 *
                 * @param       {Object}    options
                 * @param       {Object}    options.pixels              Canvas image data
                 * @param       {Number}    options.x                   Inital x position on the canvas
                 * @param       {Number}    options.y                   Inital y position on the canvas
                 * @param       {Number}    options.stepX
                 * @param       {Number}    options.stepY
                 *
                 * @return      {Object}    res
                 * @return      {Number}    res.r                       Red channel average
                 * @return      {Number}    res.g                       Green channel average
                 * @return      {Number}    res.b                       Blue channel average
                 * @return      {Number}    res.a                       Alpha channel average
                 * @return      {Number}    res.c                       Composite average
                 */
                getPixelGroupAvg = function( options ) {
                    var
                        imgPixels = options.pixels,
                        initX     = options.x,
                        initY     = options.y,
                        stepX     = options.stepX,
                        stepY     = options.stepY,

                        count     = 0,
                        sumR      = 0,
                        sumG      = 0,
                        sumB      = 0,
                        sumA      = 0,
                        sumC      = 0,

                        r, g, b, a, c,

                        x, y,
                        index;
                    // end of vars

                    for ( x = initX; x < initX + stepX; x++ ) {
                        for ( y = initY; y < initY + stepY; y++ ) {
                            index = (y * 4) * imgPixels.width + x * 4;

                            r = imgPixels.data[index];
                            g = imgPixels.data[index + 1];
                            b = imgPixels.data[index + 2];
                            a = imgPixels.data[index + 3];
                            c = (imgPixels.data[index] + imgPixels.data[index + 1] + imgPixels.data[index + 2]) / 3;

                            if ( !isNaN(r) && !isNaN(g) && !isNaN(b) && !isNaN(a) && !isNaN(c) ) {
                                sumR += r;
                                sumG += g;
                                sumB += b;
                                sumA += a;
                                sumC += c;
                                count++;
                            }
                        }
                    }

                    return {
                        r: (sumR/count) | 0,
                        g: (sumG/count) | 0,
                        b: (sumB/count) | 0,
                        a: (sumA/count) | 0,
                        c: (sumC/count) | 0
                    };
                },

                /**
                 * @memberOf    module:Schwartz~Schwartz
                 * @method      parseImage
                 * @private
                 *
                 * @this        {Schwartz}
                 *
                 * @param       {Object}    imageData   Canvas image data
                 */
                parseImage = function( imageData ) {
                    var
                        imgW = imageData.width,
                        imgH = imageData.height,
                        art  = [],

                        strChar, str, symbol,
                        p, x, y, avg;
                    //end of vars

                    this.dimX = Math.round((imgW * 100 / this.detail)/200);
                    this.dimY = Math.round((imgH * 100 / this.detail)/200);

                    this.dimX = ( this.dimX < 1) ? 1 : this.dimX;
                    this.dimY = ( this.dimY < 1) ? 1 : this.dimY;

                    for ( y = 0; y < imgH; ) {
                        str     = [];
                        strChar = '';

                        for ( x = 0; x < imgW; ) {
                            avg = getPixelGroupAvg({
                                pixels: imageData,
                                x: x,
                                y: y,
                                stepX: this.dimX,
                                stepY: this.dimY
                            });

                            symbol  = getSymbol.call(this, avg.c);
                            strChar += symbol;
                            avg.sym = symbol;

                            str.push(avg)

                            x += this.dimX;
                        }

                        art.push(str);

                        y += this.dimY;
                    }

                    if ( typeof this.callback !== 'undefined' && typeof this.callback === 'function' ) {
                        this.callback(art);
                    }
                },

                /**
                 * @memberOf    module:Schwartz~Schwartz
                 * @method      videoTimerCallback
                 * @private
                 *
                 * @this        {Schwartz}
                 */
                videoTimerCallback = function() {
                    var
                        videoWidth  = this.video.width,
                        videoHeight = this.video.height,
                        self        = this,
                        imageData;
                    // end of vars

                    if ( this.video.paused || this.video.ended ) {
                        return;
                    }

                    this.c.drawImage(this.video, 0, 0, videoWidth, videoHeight);
                    imageData = this.c.getImageData(0, 0, videoWidth, videoHeight);
                    parseImage.call(this, imageData);

                    setTimeout(function () {
                        videoTimerCallback.call(self);
                    }, 0);
                };
            // end of vars

            /**
             * ==============================
             * ========PUBLIC METHODS========
             * ==============================
             */

            /**
             * @memberOf    module:Schwartz~Schwartz
             * @method      setDetail
             * @public
             *
             * @param       {Number}    n   Level of detail
             */
            Schwartz.prototype.setDetail = function( n ) {
                var
                    newDetail;
                // end of vars

                // validate number
                if ( isNumber(n) ) {
                    newDetail = parseInt(n, 10);

                    this.detail = ( newDetail < 1 ) ? 1 : ( newDetail > 100 ) ? 100 : newDetail;
                } else {
                    this.detail = DEFAULT_DETAIL;
                }

                return;
            };

            /**
             * @memberOf    module:Schwartz~Schwartz
             * @method      setCharSet
             * @public
             *
             * @param       {String}    str
             */
            Schwartz.prototype.setCharSet = function( str ) {
                var
                    // create local canvas
                    canvas = document.createElement('canvas'),
                    c      = canvas.getContext('2d'),
                    all    = [],

                    i, avg, imgPixels;
                // end of vars

                canvas.width  = 10;
                canvas.height = 20;
                c.fillStyle   = '#000';
                c.font        = '18px monospace';
                this.charSet  = [];

                for ( i = 0; i < str.length; i++ ) {
                    // reset canvas
                    canvas.width = canvas.width;

                    c.fillText(str[i], 0, 18);
                    imgPixels = c.getImageData(0, 0, canvas.width, canvas.height);

                    avg = getPixelGroupAvg({
                        pixels: imgPixels,
                        x: 0,
                        y: 0,
                        stepX: canvas.width,
                        stepY: canvas.height
                    });

                    all[avg.a] = str[i];
                }

                for ( i = 0; i < all.length; i++ ) {
                    if ( all[i] ) {
                        this.charSet.push(all[i]);
                    }
                }

                this.charSet = ( this.inverse ) ? this.charSet : this.charSet.reverse();
            };

            /**
             * @memberOf    module:Schwartz~Schwartz
             * @method      loadImg
             * @public
             *
             * @param       {String} src    Image source URI
             */
            Schwartz.prototype.generateFromImage = function( src ) {
                loadImage.call(this, src, parseImage);
            };

            /**
             * Inverse image
             *
             * @memberOf    module:Schwartz~Schwartz
             * @method      inverseImage
             * @public
             */
            Schwartz.prototype.inverseImage = function() {
                this.charSet.reverse();
            };

            /**
             * @memberOf    module:Schwartz~Schwartz
             * @method      loadImg
             * @public
             *
             * @param       {DOM Element}   video    Video DOM element
             */
            Schwartz.prototype.generateFromVideo = function( video ) {
                var
                    self = this;
                // end of vars

                this.video = video;

                video.addEventListener('play', function() {
                    videoTimerCallback.call(self);
                }, false);
            };

            return Schwartz;
        }());
    // end of vars

    return Schwartz;
});
<|endoftext|>


<commit_before>
var express = require('express');
var Twitter = require('twitter');
var dbModule = require('./dbModule');
var fbModule = require('./fbModule');

var client = new Twitter({
	consumer_key:process.env.TWITTER_CONSUMER_KEY,
	consumer_secret:process.env.TWITTER_CONSUMER_SECRET,
	access_token_key:process.env.TWITTER_ACCESS_TOKEN_KEY,
	access_token_secret:process.env.TWITTER_ACCESS_TOKEN_SECRET
});

module.exports.userTweet = function(){
	var userTweet = process.env.USER_TW_ID;

	console.log('(Twitter) Twitter id: ', userTweet);
	return userTweet;
};

module.exports.get = function(msg, callback){
	client.get('statuses/show',{ id:msg.tweet_id },function( err, tweet, response){
		if(err) return callback(err);

		console.log('(Twitter) Returning the tweets: ' + JSON.stringify(tweet));
		callback( null, msg, tweet);

	});
};

module.exports.post = function(msg, callback){
	client.post('statuses/update', { status:msg }, function( err, tweet, response){
		if(err) {
			callback(true,'Error posting Twitter');
			return;
		}
		console.log("(Twitter) Returning the tweet", JSON.stringify(tweet));
		callback(null,tweet);
	});
};

<commit_msg>Refactoring of the twitter module<commit_after>var Twitter = require('twitter');

var client = new Twitter({
	consumer_key:process.env.TWITTER_CONSUMER_KEY,
	consumer_secret:process.env.TWITTER_CONSUMER_SECRET,
	access_token_key:process.env.TWITTER_ACCESS_TOKEN_KEY,
	access_token_secret:process.env.TWITTER_ACCESS_TOKEN_SECRET
});

module.exports.userTweet = function(){
	var userTweet = process.env.USER_TW_ID;

	console.log('(Twitter) Twitter id: ', userTweet);
	return userTweet;
};

module.exports.get = function( tweetId, moduleCallback){
	var result = {
		success: true,
		data: null,
		error: null
	};

	client.get('statuses/show',{ id: tweetId },function( err, tweet, response){
		if( err ){
			console.log("(Twitter) Error loading a tweet...");
			result.success = false;
			result.error = err;
			moduleCallback( result );
			return;
		}

		console.log('(Twitter) Returning the tweets: ' + JSON.stringify(tweet));
		result.success = true;
		result.data = tweet;
		moduleCallback( result );
	});
};

module.exports.post = function( twitterStatus, moduleCallback){
	var result = {
		success: true,
		data: null,
		error: null
	};

	client.post('statuses/update', { status: twitterStatus }, function( err, tweet, response){
		if( err ){
			console.log("(Twitter) Error posting a tweet...");
			result.success = false;
			result.error = err;
			moduleCallback( result );
			return;
		}
		console.log("(Twitter) Returning the tweet", JSON.stringify(tweet));

		result.success = true;
		result.data = tweet;
		moduleCallback( result );
	});
};

<|endoftext|>