<commit_before>/*!
 * benchmark.js
 * Copyright Mathias Bynens <http://mths.be/>
 * Based on JSLitmus.js, copyright Robert Kieffer <http://broofa.com/>
 * Modified by John-David Dalton <http://allyoucanleet.com/>
 * Available under MIT license <http://mths.be/mit>
 */

(function(global) {

  // MAX_COUNT divisors used to avoid hz of Infinity
  var CYCLE_DIVISORS = { '1': 8, '2': 6, '3': 4, '4': 2, '5': 1 };

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

  function Benchmark(fn, options) {
    options = extend({ }, options);
    extend(this, options);
    this.fn = fn;
    this.options = options;
  }

  function Calibration(fn, options) {
    Benchmark.call(this, fn, options);
  }

  function Klass() { }

  Klass.prototype = Benchmark.prototype;

  (function(proto) {
    // bypass calibrating the Calibration tests
    function run(count, synchronous) {
      var me = this;
      me.reset();
      me.running = true;
      me.count = count || me.INIT_COUNT;
      me.onStart(me);
      _run(me, synchronous);
    }
    proto.constructor = Calibration;
    proto.run = run;
  }(Calibration.prototype = new Klass));

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

  // fires callback after calibration or returns false
  function calibrate(callback) {
    var cal = Benchmark.CALIBRATION;
    if (!cal.cycles) {
      cal.onComplete = callback;
      cal.average();
      return true;
    }
    return false;
  }

  // call method sync or async (to allow UI redraws)
  function call(me, callback, synchronous) {
    synchronous
      ? callback(me, synchronous)
      : setTimeout(function() { callback(me); }, me.CYCLE_DELAY * 1e3);
  }

  // merge source results with destinations
  function merge(destination, source) {
    destination.count = source.count;
    destination.cycles += source.cycles;
    destination.error = source.error;
    destination.hz = source.hz;
    destination.period = source.period;
    return destination;
  }

  // copies source properties to destination object
  function extend(destination, source) {
    source || (source = { });
    for (var key in source) {
      destination[key] = source[key];
    }
    return destination;
  }

  // generic Array#filter
  function filter(array, callback) {
    var length = array.length,
        result = [];

    while (length--) {
      if (length in array && callback(array[length], length, array)) {
        result.unshift(array[length]);
      }
    }
    return result;
  }

  // generic Array#reduce
  function reduce(array, callback, accumulator) {
    var length = array.length;
    while (length--) {
      if (length in array) {
        accumulator = callback(accumulator, array[length], length, array);
      }
    }
    return accumulator;
  }

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

  // clock the time it takes to execute a function N times (milliseconds)
  var clock;

  // variable names are prefixed with $ to replace during compilation
  (function() {

    var interval = Function('$m,$c',
          'var $i=$m.count,$t=new $c.Interval;' +
          '$t.start();while($i--){$f()}$t.stop();' +
          '$m.time=$t.microseconds()/1e3'),

        now = Function('$m',
          'var $i=$m.count,$f=$m.fn,$t=Date.now();' +
          'while($i--){$f()}' +
          '$m.time=Date.now()-$t'),

        time = Function('$m',
          'var $i=$m.count,$f=$m.fn,$t=(new Date).getTime();' +
          'while($i--){$f()}' +
          '$m.time=(new Date).getTime()-$t'),

        // enable benchmarking via the --enable-benchmarking flag
        // in at least Chrome 7 to use chrome.Interval
        $c = typeof global.chrome != 'undefined' ? chrome :
          typeof global.chromium != 'undefined' ? chromium : null,

        // choose which timing api to use
        $clock = ($c && typeof $c.Interval == 'function') ? interval :
          (typeof Date.now == 'function') ? now : time,

        // used for method compilation
        uid     = +new Date,
        fnToken = '$f' + uid + '()',
        fnArg   = '$m' + uid + ',$c' + uid,
        fnBody  = ('(' + String($clock).replace('anonymous', '') +
                  ')($m,$c);return $m').replace(/(\$[a-z])/g, '$1' + uid);

    // if supported, compile tests to avoid extra function calls
    if (function() {
          try { return Function(fnArg, fnBody)({ }, $c).time; } catch(e) { }
        }() != null) {
      // TODO: check regexps in Safari 2.0.0
      clock = function(me) {
        var embed = String(me.fn).match(/^[^{]+{((?:.|\n)*)}\s*$/) || '';
        try {
          Function(fnArg, fnBody.replace(fnToken, embed && embed[1]))(me, $c);
        } catch(e) {
          embed = false;
        }
        if (embed === false) {
          $clock(me, $c);
        }
      };
    }
    else {
      clock = function(me) {
        $clock(me, $c);
      };
    }
  }());

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

  function getPlatform() {
    var result,
        description = [],
        ua = navigator.userAgent,
        os = (ua.match(/(?:Windows 98;|Windows |iP[ao]d|iPhone|Mac OS X|Linux)(?:[^);]| )*/) || [])[0],
        name = (ua.match(/Chrome|MSIE|Safari|Opera|Firefox|Minefield/) || [])[0],
        version = {}.toString.call(global.opera) == '[object Opera]' && opera.version(),
        mses = { '6.1': '7', '6.0': 'Vista', '5.2': 'Server 2003 / XP x64', '5.1': 'XP', '5.0': '2000', '4.0': 'NT', '4.9': 'ME' };

    // IE platform tokens
    // http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
    mses = os && os.indexOf('Windows') > -1 && mses[(os.match(/[456]\.\d/) || [])[0]];
    if (mses) {
      os = 'Windows ' + mses;
    } else if (/iP[ao]d|iPhone/.test(os)) {
      os = (ua.match(/\bOS ([\d_]+)/) || [])[1];
      os = 'iOS' + (os ? ' ' + os : '');
    }
    if (name && !version) {
      version = typeof document.documentMode == 'number'
        ? document.documentMode
        : (ua.match(RegExp('(?:version|' + name + ')[ /]([^ ;]*)', 'i')) || [])[1];
    }
    return {
      'name':        name ? description.push(name) && name : null,
      'version':     version ? description.push(version) && version : null,
      'os':          os ? description.push('on ' + (os = os.replace(/_/g, '.'))) && os : null,
      'description': description.length ? description.join(' ') : 'unknown platform',
      'toString':    function() { return this.description; }
    };
  }

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

  function average(times, count, synchronous) {
    var deviation,
        mean,
        stopped,
        me = this,
        clones = [],
        i = times || (times = me.DEFAULT_AVERAGE);

    function cbSum(sum, clone) {
      return sum + clone.period;
    }

    function cbVariance(sum, clone) {
      return sum + Math.pow(clone.period - mean, 2);
    }

    function cbOutlier(clone) {
      return clone.period < (mean + deviation) && clone.period > (mean - deviation);
    }

    function onCycle(clone) {
      // stop clone and raise flag if host has stopped running
      if (stopped = !me.running) {
        clone.stop();
      } else {
        // update host and fire its onCycle callback
        me.onCycle(merge(me, clone));
      }
    }

    function onComplete(clone) {
      // if host has stopped or this is the last clone to finish
      if (stopped || !--times) {
        if (!stopped && !merge(me, clone).error) {
          // compute average period and sample standard deviation
          mean = reduce(clones, cbSum, 0) / clones.length;
          deviation = Math.sqrt(reduce(clones, cbVariance, 0) / (clones.length - 1));

          if (deviation) {
            // remove outliers and compute average period on filtered results
            clones = filter(clones, cbOutlier, 0);
            mean = me.period = reduce(clones, cbSum, 0) / clones.length;
          }
          // compute other host results
          me.time = mean * me.count;
          me.hz = mean ? Math.round(1 / mean) : Number.MAX_VALUE;
        }
        delete me.averaging;
        me.running = false;
        me.onCycle(me);
        me.onComplete(me);
      }
      else if (!synchronous) {
        // run next clone in the sample
        clone = clones[times];
        call(clone, function() { clone.run(); });
      }
    }

    me.reset();
    me.averaging = me.running = true;
    me.onStart(me);

    while (i--) {
      // create clone and add to sample
      clones.push(me.clone({
        'onStart': onCycle,
        'onCycle': onCycle,
        'onComplete': onComplete
      }));
      // run instantly if sync or init async
      if (synchronous || !i) {
        clones[clones.length - 1].run(count, synchronous);
      }
    }
  }

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

  function clone(options) {
    var key,
        me = this,
        result = new me.constructor(me.fn, extend(extend({ }, me.options), options));

    // copy manually added properties
    for (key in me) {
      if (!result[key]) {
        result[key] = me[key];
      }
    }
    result.reset();
    return result;
  }

  function noop() {
    // no operation performed
  }

  function stop() {
    var me = this,
        cal = Benchmark.CALIBRATION,
        error = me.error;

    if (me.running) {
      if (me != cal && cal.running) {
        cal.stop();
      }
      me.reset();
      me.error = error;
      me.onStop(me);
    }
  }

  function reset() {
    var me = this,
        proto = this.constructor.prototype;

    me.count = proto.count;
    me.cycles = proto.cycles;
    me.error = proto.error;
    me.hz = proto.hz;
    me.period = proto.period;
    me.running = proto.running;
    me.time = proto.time;
    me.onReset(me);
  }

  function run(count, synchronous) {
    var me = this;
    me.reset();
    me.running = true;

    // ensure calibration test has run
    if (!calibrate(function() {
          function rerun() {
            // continue, if not stopped during calibration
            if (me.running) {
              me.run(count, synchronous);
            } else {
              me.onStart(me);
              me.onStop(me);
              me.onComplete(me);
            }
          }
          call(me, rerun, synchronous);
        })) {
      me.count = count || me.INIT_COUNT;
      me.onStart(me);
      _run(me, synchronous);
    }
  }

  function _run(me, synchronous) {
    var divisor,
        period,
        time,
        cal = me.constructor.CALIBRATION,
        count = me.count,
        cycles = me.cycles,
        max = me.MAX_COUNT,
        min = me.MIN_TIME;

    // continue, if not stopped between cycles
    if (me.running) {

      if (cycles) {
        cycles = ++me.cycles;
      } else {
        cycles = me.cycles = 1;
      }
      try {
        // clock executions of me.fn
        clock(me);

        time = me.time =
          // ensure positive numbers
          Math.max(0,
          // convert time from milliseconds to seconds
          (me.time / 1e3) -
          // calibrate by subtracting the base loop time
          (cal && cal.period || 0) * count);

        // per-operation time
        period = me.period = time / count;

        // ops per second
        me.hz = period ? Math.round(1 / period) : Number.MAX_VALUE;

        // do we need to do another cycle?
        me.running = time < min;

        // if so, compute the iteration count needed
        if (me.running) {
          // tests may return an initial time of 0 when INIT_COUNT is a small number,
          // to avoid that we set its count to something a bit higher
          if (!time && (divisor = CYCLE_DIVISORS[cycles])) {
            // try a fraction of the MAX_COUNT
            count = Math.floor(max / divisor);
          }
          else {
            // calculate how many more iterations it will take to achive the min testing time
            count += Math.ceil((min - time) / period);

            // to avoid freezing the browser stop running if the
            // next cycle would exceed the max count allowed
            if (count > max) {
              me.running = false;
            }
          }
        }
        me.count = count;
      }
      catch(e) {
        me.reset();
        me.error = e;
      }
      me.onCycle(me);
    }

    // figure out what to do next
    if (me.running) {
      call(me, _run, synchronous);
    }
    else if (me.averaging || me.error || (me.time * me.DEFAULT_AVERAGE) > 1) {
      me.onComplete(me);
    }
    else {
      // fast tests get their results averaged
      me.average(null, null, synchronous);
    }
  }

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

  // test to establish iteration loop overhead
  Benchmark.CALIBRATION = new Calibration(noop, { 'INIT_COUNT': 3e3 });

  Benchmark.getPlatform = getPlatform;

  Benchmark.noop = noop;

  extend(Benchmark.prototype, {
    // delay between test cycles (secs)
    'CYCLE_DELAY': 0.01,

    // number of runs to average for fast tests
    'DEFAULT_AVERAGE': 30,

    // initial number of iterations
    'INIT_COUNT': 10,

    // max iterations allowed per cycle (used avoid locking up the browser)
    'MAX_COUNT': 1e6, // 1 million

    // minimum time a test should take to get valid results (secs)
    'MIN_TIME': 0.2,

    // number of times a test was executed
    'count': null,

    // number of cycles performed during testing
    'cycles': null,

    // an error object if the test failed
    'error': null,

    // number of test executions per second
    'hz': null,

    // time a test takes to do one execution (secs)
    'period': null,

    // flag to indicate if the test is running
    'running': false,

    // time a test takes to do the `count` number of executions (secs)
    'time': null,

    // callback invoked when testing is complete
    'onComplete': noop,

    // callback invoked when one test cycle ends
    'onCycle': noop,

    // callback invoked when test is reset
    'onReset': noop,

    // callback invoked when testing is started
    'onStart': noop,

    // callback invoked when testing is stopped
    'onStop': noop,

    // runs the test `n` times and returns the averaged test results
    'average': average,

    // create new benchmark with the same test function and options
    'clone': clone,

    // reset test state
    'reset': reset,

    // run the test
    'run': run,

    // stop testing (does not record times)
    'stop': stop
  });

  // expose
  global.Benchmark = Benchmark;

}(this));<commit_msg>benchmark.js: Add missing $f assignment in interval(). [jddalton]<commit_after>/*!
 * benchmark.js
 * Copyright Mathias Bynens <http://mths.be/>
 * Based on JSLitmus.js, copyright Robert Kieffer <http://broofa.com/>
 * Modified by John-David Dalton <http://allyoucanleet.com/>
 * Available under MIT license <http://mths.be/mit>
 */

(function(global) {

  // MAX_COUNT divisors used to avoid hz of Infinity
  var CYCLE_DIVISORS = { '1': 8, '2': 6, '3': 4, '4': 2, '5': 1 };

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

  function Benchmark(fn, options) {
    options = extend({ }, options);
    extend(this, options);
    this.fn = fn;
    this.options = options;
  }

  function Calibration(fn, options) {
    Benchmark.call(this, fn, options);
  }

  function Klass() { }

  Klass.prototype = Benchmark.prototype;

  (function(proto) {
    // bypass calibrating the Calibration tests
    function run(count, synchronous) {
      var me = this;
      me.reset();
      me.running = true;
      me.count = count || me.INIT_COUNT;
      me.onStart(me);
      _run(me, synchronous);
    }
    proto.constructor = Calibration;
    proto.run = run;
  }(Calibration.prototype = new Klass));

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

  // fires callback after calibration or returns false
  function calibrate(callback) {
    var cal = Benchmark.CALIBRATION;
    if (!cal.cycles) {
      cal.onComplete = callback;
      cal.average();
      return true;
    }
    return false;
  }

  // call method sync or async (to allow UI redraws)
  function call(me, callback, synchronous) {
    synchronous
      ? callback(me, synchronous)
      : setTimeout(function() { callback(me); }, me.CYCLE_DELAY * 1e3);
  }

  // merge source results with destinations
  function merge(destination, source) {
    destination.count = source.count;
    destination.cycles += source.cycles;
    destination.error = source.error;
    destination.hz = source.hz;
    destination.period = source.period;
    return destination;
  }

  // copies source properties to destination object
  function extend(destination, source) {
    source || (source = { });
    for (var key in source) {
      destination[key] = source[key];
    }
    return destination;
  }

  // generic Array#filter
  function filter(array, callback) {
    var length = array.length,
        result = [];

    while (length--) {
      if (length in array && callback(array[length], length, array)) {
        result.unshift(array[length]);
      }
    }
    return result;
  }

  // generic Array#reduce
  function reduce(array, callback, accumulator) {
    var length = array.length;
    while (length--) {
      if (length in array) {
        accumulator = callback(accumulator, array[length], length, array);
      }
    }
    return accumulator;
  }

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

  // clock the time it takes to execute a function N times (milliseconds)
  var clock;

  // variable names are prefixed with $ to replace during compilation
  (function() {

    var interval = Function('$m,$c',
          'var $i=$m.count,$f=$m.fn,$t=new $c.Interval;' +
          '$t.start();while($i--){$f()}$t.stop();' +
          '$m.time=$t.microseconds()/1e3'),

        now = Function('$m',
          'var $i=$m.count,$f=$m.fn,$t=Date.now();' +
          'while($i--){$f()}' +
          '$m.time=Date.now()-$t'),

        time = Function('$m',
          'var $i=$m.count,$f=$m.fn,$t=(new Date).getTime();' +
          'while($i--){$f()}' +
          '$m.time=(new Date).getTime()-$t'),

        // enable benchmarking via the --enable-benchmarking flag
        // in at least Chrome 7 to use chrome.Interval
        $c = typeof global.chrome != 'undefined' ? chrome :
          typeof global.chromium != 'undefined' ? chromium : null,

        // choose which timing api to use
        $clock = ($c && typeof $c.Interval == 'function') ? interval :
          (typeof Date.now == 'function') ? now : time,

        // used for method compilation
        uid     = +new Date,
        fnToken = '$f' + uid + '()',
        fnArg   = '$m' + uid + ',$c' + uid,
        fnBody  = ('(' + String($clock).replace('anonymous', '') +
                  ')($m,$c);return $m').replace(/(\$[a-z])/g, '$1' + uid);

    // if supported, compile tests to avoid extra function calls
    if (function() {
          try { return Function(fnArg, fnBody)({ }, $c).time; } catch(e) { }
        }() != null) {
      // TODO: check regexps in Safari 2.0.0
      clock = function(me) {
        var embed = String(me.fn).match(/^[^{]+{((?:.|\n)*)}\s*$/) || '';
        try {
          Function(fnArg, fnBody.replace(fnToken, embed && embed[1]))(me, $c);
        } catch(e) {
          embed = false;
        }
        if (embed === false) {
          $clock(me, $c);
        }
      };
    }
    else {
      clock = function(me) {
        $clock(me, $c);
      };
    }
  }());

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

  function getPlatform() {
    var result,
        description = [],
        ua = navigator.userAgent,
        os = (ua.match(/(?:Windows 98;|Windows |iP[ao]d|iPhone|Mac OS X|Linux)(?:[^);]| )*/) || [])[0],
        name = (ua.match(/Chrome|MSIE|Safari|Opera|Firefox|Minefield/) || [])[0],
        version = {}.toString.call(global.opera) == '[object Opera]' && opera.version(),
        mses = { '6.1': '7', '6.0': 'Vista', '5.2': 'Server 2003 / XP x64', '5.1': 'XP', '5.0': '2000', '4.0': 'NT', '4.9': 'ME' };

    // IE platform tokens
    // http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
    mses = os && os.indexOf('Windows') > -1 && mses[(os.match(/[456]\.\d/) || [])[0]];
    if (mses) {
      os = 'Windows ' + mses;
    } else if (/iP[ao]d|iPhone/.test(os)) {
      os = (ua.match(/\bOS ([\d_]+)/) || [])[1];
      os = 'iOS' + (os ? ' ' + os : '');
    }
    if (name && !version) {
      version = typeof document.documentMode == 'number'
        ? document.documentMode
        : (ua.match(RegExp('(?:version|' + name + ')[ /]([^ ;]*)', 'i')) || [])[1];
    }
    return {
      'name':        name ? description.push(name) && name : null,
      'version':     version ? description.push(version) && version : null,
      'os':          os ? description.push('on ' + (os = os.replace(/_/g, '.'))) && os : null,
      'description': description.length ? description.join(' ') : 'unknown platform',
      'toString':    function() { return this.description; }
    };
  }

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

  function average(times, count, synchronous) {
    var deviation,
        mean,
        stopped,
        me = this,
        clones = [],
        i = times || (times = me.DEFAULT_AVERAGE);

    function cbSum(sum, clone) {
      return sum + clone.period;
    }

    function cbVariance(sum, clone) {
      return sum + Math.pow(clone.period - mean, 2);
    }

    function cbOutlier(clone) {
      return clone.period < (mean + deviation) && clone.period > (mean - deviation);
    }

    function onCycle(clone) {
      // stop clone and raise flag if host has stopped running
      if (stopped = !me.running) {
        clone.stop();
      } else {
        // update host and fire its onCycle callback
        me.onCycle(merge(me, clone));
      }
    }

    function onComplete(clone) {
      // if host has stopped or this is the last clone to finish
      if (stopped || !--times) {
        if (!stopped && !merge(me, clone).error) {
          // compute average period and sample standard deviation
          mean = reduce(clones, cbSum, 0) / clones.length;
          deviation = Math.sqrt(reduce(clones, cbVariance, 0) / (clones.length - 1));

          if (deviation) {
            // remove outliers and compute average period on filtered results
            clones = filter(clones, cbOutlier, 0);
            mean = me.period = reduce(clones, cbSum, 0) / clones.length;
          }
          // compute other host results
          me.time = mean * me.count;
          me.hz = mean ? Math.round(1 / mean) : Number.MAX_VALUE;
        }
        delete me.averaging;
        me.running = false;
        me.onCycle(me);
        me.onComplete(me);
      }
      else if (!synchronous) {
        // run next clone in the sample
        clone = clones[times];
        call(clone, function() { clone.run(); });
      }
    }

    me.reset();
    me.averaging = me.running = true;
    me.onStart(me);

    while (i--) {
      // create clone and add to sample
      clones.push(me.clone({
        'onStart': onCycle,
        'onCycle': onCycle,
        'onComplete': onComplete
      }));
      // run instantly if sync or init async
      if (synchronous || !i) {
        clones[clones.length - 1].run(count, synchronous);
      }
    }
  }

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

  function clone(options) {
    var key,
        me = this,
        result = new me.constructor(me.fn, extend(extend({ }, me.options), options));

    // copy manually added properties
    for (key in me) {
      if (!result[key]) {
        result[key] = me[key];
      }
    }
    result.reset();
    return result;
  }

  function noop() {
    // no operation performed
  }

  function stop() {
    var me = this,
        cal = Benchmark.CALIBRATION,
        error = me.error;

    if (me.running) {
      if (me != cal && cal.running) {
        cal.stop();
      }
      me.reset();
      me.error = error;
      me.onStop(me);
    }
  }

  function reset() {
    var me = this,
        proto = this.constructor.prototype;

    me.count = proto.count;
    me.cycles = proto.cycles;
    me.error = proto.error;
    me.hz = proto.hz;
    me.period = proto.period;
    me.running = proto.running;
    me.time = proto.time;
    me.onReset(me);
  }

  function run(count, synchronous) {
    var me = this;
    me.reset();
    me.running = true;

    // ensure calibration test has run
    if (!calibrate(function() {
          function rerun() {
            // continue, if not stopped during calibration
            if (me.running) {
              me.run(count, synchronous);
            } else {
              me.onStart(me);
              me.onStop(me);
              me.onComplete(me);
            }
          }
          call(me, rerun, synchronous);
        })) {
      me.count = count || me.INIT_COUNT;
      me.onStart(me);
      _run(me, synchronous);
    }
  }

  function _run(me, synchronous) {
    var divisor,
        period,
        time,
        cal = me.constructor.CALIBRATION,
        count = me.count,
        cycles = me.cycles,
        max = me.MAX_COUNT,
        min = me.MIN_TIME;

    // continue, if not stopped between cycles
    if (me.running) {

      if (cycles) {
        cycles = ++me.cycles;
      } else {
        cycles = me.cycles = 1;
      }
      try {
        // clock executions of me.fn
        clock(me);

        time = me.time =
          // ensure positive numbers
          Math.max(0,
          // convert time from milliseconds to seconds
          (me.time / 1e3) -
          // calibrate by subtracting the base loop time
          (cal && cal.period || 0) * count);

        // per-operation time
        period = me.period = time / count;

        // ops per second
        me.hz = period ? Math.round(1 / period) : Number.MAX_VALUE;

        // do we need to do another cycle?
        me.running = time < min;

        // if so, compute the iteration count needed
        if (me.running) {
          // tests may return an initial time of 0 when INIT_COUNT is a small number,
          // to avoid that we set its count to something a bit higher
          if (!time && (divisor = CYCLE_DIVISORS[cycles])) {
            // try a fraction of the MAX_COUNT
            count = Math.floor(max / divisor);
          }
          else {
            // calculate how many more iterations it will take to achive the min testing time
            count += Math.ceil((min - time) / period);

            // to avoid freezing the browser stop running if the
            // next cycle would exceed the max count allowed
            if (count > max) {
              me.running = false;
            }
          }
        }
        me.count = count;
      }
      catch(e) {
        me.reset();
        me.error = e;
      }
      me.onCycle(me);
    }

    // figure out what to do next
    if (me.running) {
      call(me, _run, synchronous);
    }
    else if (me.averaging || me.error || (me.time * me.DEFAULT_AVERAGE) > 1) {
      me.onComplete(me);
    }
    else {
      // fast tests get their results averaged
      me.average(null, null, synchronous);
    }
  }

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

  // test to establish iteration loop overhead
  Benchmark.CALIBRATION = new Calibration(noop, { 'INIT_COUNT': 3e3 });

  Benchmark.getPlatform = getPlatform;

  Benchmark.noop = noop;

  extend(Benchmark.prototype, {
    // delay between test cycles (secs)
    'CYCLE_DELAY': 0.01,

    // number of runs to average for fast tests
    'DEFAULT_AVERAGE': 30,

    // initial number of iterations
    'INIT_COUNT': 10,

    // max iterations allowed per cycle (used avoid locking up the browser)
    'MAX_COUNT': 1e6, // 1 million

    // minimum time a test should take to get valid results (secs)
    'MIN_TIME': 0.2,

    // number of times a test was executed
    'count': null,

    // number of cycles performed during testing
    'cycles': null,

    // an error object if the test failed
    'error': null,

    // number of test executions per second
    'hz': null,

    // time a test takes to do one execution (secs)
    'period': null,

    // flag to indicate if the test is running
    'running': false,

    // time a test takes to do the `count` number of executions (secs)
    'time': null,

    // callback invoked when testing is complete
    'onComplete': noop,

    // callback invoked when one test cycle ends
    'onCycle': noop,

    // callback invoked when test is reset
    'onReset': noop,

    // callback invoked when testing is started
    'onStart': noop,

    // callback invoked when testing is stopped
    'onStop': noop,

    // runs the test `n` times and returns the averaged test results
    'average': average,

    // create new benchmark with the same test function and options
    'clone': clone,

    // reset test state
    'reset': reset,

    // run the test
    'run': run,

    // stop testing (does not record times)
    'stop': stop
  });

  // expose
  global.Benchmark = Benchmark;

}(this));<|endoftext|>


<commit_before>/* eslint-disable max-params, complexity, max-statements */

import { inspect } from 'util';

import merge from './merge';

// Public API
// =========

/*
`notate` is a new alternative to the these two methods of dealing with errors in
javascript:

```
if (err) {
  return cb(err);
}
```

and

```
if (err) {
  myFavoriteLogger.error('methodName: strange situation! ' + JSON.stringify(user));
  return cb(err);
}
```

To accomplish the same thing with `notate()`, attach the user to the error for
future log output, and `add()` adds the current file and line to the top of the stack.
So after an error happens deep in some library, you know how it propagated through your
code afterwards.

```
if (notate(cb, err, {user: user})) {
  return;
}
```

The first parameter, `err` is required. If `err` is truthy, any provided callback will
be called and `add()` will return true.

There are three more optional parameters:

+ `cb` is called with `err` if `err` is truthy.
+ `data` will have its keys merged into the returned error
+ `depth` allows you to put this method in your own helper, just set the depth to the
number of stack frames you add between the client code and `notate()`.
*/
export default function notate(cb, err, data, providedDepth) {
  if (cb && !_isFunction(cb)) {
    throw new Error('notate: provided first parameter cb was not a function');
  }
  if (!err) {
    return false;
  }

  const depth = (providedDepth || 0) + _internals.layerSize;
  justNotate(err, data, depth);

  if (cb) {
    // we really mean to omit the return here
    /* eslint-disable callback-return */
    cb(err);
    /* eslint-enable callback-return */
  }

  return true;
}

/*
`justNotate` does the same thing as `notate`, without taking (and requiring) the initial
`cb` parameter.
*/
export function justNotate(err, data, providedDepth) {
  if (!err) {
    return false;
  }

  try {
    const depth = (providedDepth || 0) + _internals.layerSize;

    const stack = _getStackTrace(depth);
    const line = _getFirstLine(stack);

    _insert(err, line);
    merge(err, data);
  }
  catch (e) {
    // do nothing; we must never crash!
  }

  return true;
}

/*
`prettyPrint()  ` prints out errors. Now that you're using `breadcrumbs.add()` to annotate
your errors as they propagate through your system, it's time to print them out properly.

First we do a `util.inspect()` of the error, grabbing all of those keys we've merged
into it for debugging purposes, and then we print out the stack after removing all
instances of `process.cwd()` (if we're on the server).

You can prevent the stack from being printed by setting `err.log` to something other
than 'warn' or 'error'.
*/
export function prettyPrint(err, providedOptions) {
  let result = '';

  try {
    if (!err) {
      return result;
    }
    if (!_isError(err)) {
      return inspect(err);
    }

    // More special-casing for IE - util.inspect checks for message and description in
    //   keys, if found, switches to a basic err.toString() call, and we lose all extra
    //   data added to the error for debuggability.
    if (propertyIsEnumerable.call(err, 'message')) {
      defineProperty(err, 'message', {
        enumerable: false,
        value: err.message,
      });
    }

    if (err.description) {
      err._description = err.description;
      delete err.description;
    }
    // ...end IE weirdness

    result = inspect(err, { depth: 5 });

    if (!err.log || err.log === 'warn' || err.log === 'error') {
      result += `\n${_prepareStack(err, providedOptions)}`;
    }
  }
  catch (e) {
    // do nothing
  }

  return result;
}

// Internals
// ========

const MAX_LINES = 10;
const propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
const getDescriptor = Object.getOwnPropertyDescriptor;
const defineProperty = Object.defineProperty;

export const _internals = {
  at: 'at ',
  prefix: '**breadcrumb: ',
  layerSize: 1,
  truncation: '... (additional lines truncated)',
};

export function _isFunction(fn) {
  if (!fn) {
    return false;
  }
  if (typeof fn !== 'function') {
    return false;
  }

  return true;
}

export function _getStackTrace(providedDepth) {
  let err = new Error('Something');

  // fuck internet explorer
  if (!err.stack) {
    try {
      throw err;
    }
    catch (e) {
      err = e;
    }
  }

  const stack = (err.stack || '')
    .replace(/^ +at/, '  at')
    .split(/\n +at /)
    .join('\n  at ');

  const lines = stack.split('\n');

  // stack depth between _getStackTrace() and original caller
  let depth = (providedDepth || 0) + _internals.layerSize;

  if (lines && lines.length && (/^Error/).test(lines[0])) {
    depth += 1;
  }

  return lines.slice(depth);
}

export function _insert(err, line) {
  if (!err) {
    return;
  }

  const v8 = /\n +at /;
  // we use alternateStack when we can't update stack (PhantomJS)
  let stack = err.alternateStack || err.stack || '';
  const indentation = _getIndentation(stack);

  if (_startsWithError(stack)) {
    const lines = stack.split(v8);
    const updated = [lines[0], line].concat(lines.slice(1));

    stack = updated.join(`\n${indentation}${_internals.at}`);
  }
  else {
    stack = indentation + line + (stack ? `\n${stack}` : '');
  }

  try {
    if (!getDescriptor || !defineProperty) {
      err.stack = stack;
    }

    const descriptor = getDescriptor(err, 'stack');
    if (!descriptor || descriptor.configurable
      && (!descriptor.writable || descriptor.enumerable)) {
      defineProperty(err, 'stack', {
        value: stack,
        configurable: true,
        enumerable: false,
        writable: true,
      });
    }
    else if (descriptor.writable) {
      err.stack = stack;
    }
    else {
      defineProperty(err, 'alternateStack', {
        value: stack,
        configurable: true,
        enumerable: false,
        writable: true,
      });
    }
  }
  catch (error) {
    if (typeof console !== 'undefined' && console && console.error) {
      console.error(`Error: Cannot add line to stack -- ${error.message}`);
    }
  }
}

export function _prepareStack(providedErr, providedOptions) {
  const err = providedErr || {};
  let stack = err.alternateStack || err.stack || '';
  const cwd = process.cwd();

  if (cwd !== '/') {
    stack = stack.split(cwd).join('');
  }

  const indentation = _getIndentation(stack);
  const options = providedOptions || {};
  const maxLines = options.maxLines || MAX_LINES;

  // V8-style stacks include the error message before showing the actual stack;
  // remove it, even if it has newlines in it, by using each line's prefix to split it.
  if (_startsWithError(stack)) {
    const lines = stack.split(/\n +at /);
    if (lines && lines.length) {
      stack = indentation + _internals.at
        + lines.slice(1).join(`\n${indentation}${_internals.at}`);
    }
  }

  // limit to ten lines
  const lines = stack.split('\n');
  if (lines.length > maxLines) {
    stack =
      `${lines.slice(0, maxLines).join('\n')}\n${indentation}${_internals.truncation}`;
  }

  return stack;
}

export function _getFirstLine(lines) {
  const v8 = /^ +at /;
  let result = `${_internals.prefix}<empty>`;

  if (lines && lines.length) {
    result = lines[0];

    if (v8.test(result)) {
      result = result.replace(v8, _internals.prefix);
    }
    else {
      result = _internals.prefix + result;
    }
  }

  return result;
}

export function _getIndentation(text) {
  if (!text || !text.split) {
    return '';
  }

  const lines = text.split('\n');
  const last = lines[lines.length - 1];

  const match = (/^ +/).exec(last);
  if (match) {
    return match[0];
  }

  return '';
}

export function _startsWithError(stack) {
  const v8 = /^[a-zA-z]+rror(:|\n)/;
  return Boolean(v8.test(stack));
}

export function _isError(err) {
  return typeof err === 'object' && err !== null
    && (Object.prototype.toString.call(err) === '[object Error]' || err instanceof Error);
}
<commit_msg>feat(node-v6): normalize output on node v6, so it matches v4 and below<commit_after>/* eslint-disable max-params, complexity, max-statements */

import { inspect } from 'util';

import merge from './merge';

// Public API
// =========

/*
`notate` is a new alternative to the these two methods of dealing with errors in
javascript:

```
if (err) {
  return cb(err);
}
```

and

```
if (err) {
  myFavoriteLogger.error('methodName: strange situation! ' + JSON.stringify(user));
  return cb(err);
}
```

To accomplish the same thing with `notate()`, attach the user to the error for
future log output, and `add()` adds the current file and line to the top of the stack.
So after an error happens deep in some library, you know how it propagated through your
code afterwards.

```
if (notate(cb, err, {user: user})) {
  return;
}
```

The first parameter, `err` is required. If `err` is truthy, any provided callback will
be called and `add()` will return true.

There are three more optional parameters:

+ `cb` is called with `err` if `err` is truthy.
+ `data` will have its keys merged into the returned error
+ `depth` allows you to put this method in your own helper, just set the depth to the
number of stack frames you add between the client code and `notate()`.
*/
export default function notate(cb, err, data, providedDepth) {
  if (cb && !_isFunction(cb)) {
    throw new Error('notate: provided first parameter cb was not a function');
  }
  if (!err) {
    return false;
  }

  const depth = (providedDepth || 0) + _internals.layerSize;
  justNotate(err, data, depth);

  if (cb) {
    // we really mean to omit the return here
    /* eslint-disable callback-return */
    cb(err);
    /* eslint-enable callback-return */
  }

  return true;
}

/*
`justNotate` does the same thing as `notate`, without taking (and requiring) the initial
`cb` parameter.
*/
export function justNotate(err, data, providedDepth) {
  if (!err) {
    return false;
  }

  try {
    const depth = (providedDepth || 0) + _internals.layerSize;

    const stack = _getStackTrace(depth);
    const line = _getFirstLine(stack);

    _insert(err, line);
    merge(err, data);
  }
  catch (e) {
    // do nothing; we must never crash!
  }

  return true;
}

/*
`prettyPrint()  ` prints out errors. Now that you're using `breadcrumbs.add()` to annotate
your errors as they propagate through your system, it's time to print them out properly.

First we do a `util.inspect()` of the error, grabbing all of those keys we've merged
into it for debugging purposes, and then we print out the stack after removing all
instances of `process.cwd()` (if we're on the server).

You can prevent the stack from being printed by setting `err.log` to something other
than 'warn' or 'error'.
*/
export function prettyPrint(err, providedOptions) {
  let result = '';

  try {
    if (!err) {
      return result;
    }
    if (!_isError(err)) {
      return inspect(err);
    }

    // More special-casing for IE - util.inspect checks for message and description in
    //   keys, if found, switches to a basic err.toString() call, and we lose all extra
    //   data added to the error for debuggability.
    if (propertyIsEnumerable.call(err, 'message')) {
      defineProperty(err, 'message', {
        enumerable: false,
        value: err.message,
      });
    }

    if (err.description) {
      err._description = err.description;
      delete err.description;
    }
    // ...end IE weirdness

    result = inspect(err, { depth: 5 });

    // Normalize new Node v6 util.inspect() behavior
      // v4: https://github.com/nodejs/node/blob/2ce83bd8f91dec603740cce216259f3f3ac1b364/lib/util.js#L458-L460
      // v6: https://github.com/nodejs/node/blob/ee8e7cd25d232a115ff4b1b5f5dd91ca442bacae/lib/util.js#L629-L631
    const withKeys = /^\{ \[/;
    const plain = /^\[/;
    if (!withKeys.test(result) && !plain.test(result)) {
      result = result.replace(err.stack, `[${Error.prototype.toString.call(err)}]`);
    }

    if (!err.log || err.log === 'warn' || err.log === 'error') {
      result += `\n${_prepareStack(err, providedOptions)}`;
    }
  }
  catch (e) {
    // do nothing
  }

  return result;
}

// Internals
// ========

const MAX_LINES = 10;
const propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
const getDescriptor = Object.getOwnPropertyDescriptor;
const defineProperty = Object.defineProperty;

export const _internals = {
  at: 'at ',
  prefix: '**breadcrumb: ',
  layerSize: 1,
  truncation: '... (additional lines truncated)',
};

export function _isFunction(fn) {
  if (!fn) {
    return false;
  }
  if (typeof fn !== 'function') {
    return false;
  }

  return true;
}

export function _getStackTrace(providedDepth) {
  let err = new Error('Something');

  // fuck internet explorer
  if (!err.stack) {
    try {
      throw err;
    }
    catch (e) {
      err = e;
    }
  }

  const stack = (err.stack || '')
    .replace(/^ +at/, '  at')
    .split(/\n +at /)
    .join('\n  at ');

  const lines = stack.split('\n');

  // stack depth between _getStackTrace() and original caller
  let depth = (providedDepth || 0) + _internals.layerSize;

  if (lines && lines.length && (/^Error/).test(lines[0])) {
    depth += 1;
  }

  return lines.slice(depth);
}

export function _insert(err, line) {
  if (!err) {
    return;
  }

  const v8 = /\n +at /;
  // we use alternateStack when we can't update stack (PhantomJS)
  let stack = err.alternateStack || err.stack || '';
  const indentation = _getIndentation(stack);

  if (_startsWithError(stack)) {
    const lines = stack.split(v8);
    const updated = [lines[0], line].concat(lines.slice(1));

    stack = updated.join(`\n${indentation}${_internals.at}`);
  }
  else {
    stack = indentation + line + (stack ? `\n${stack}` : '');
  }

  try {
    if (!getDescriptor || !defineProperty) {
      err.stack = stack;
    }

    const descriptor = getDescriptor(err, 'stack');
    if (!descriptor || descriptor.configurable
      && (!descriptor.writable || descriptor.enumerable)) {
      defineProperty(err, 'stack', {
        value: stack,
        configurable: true,
        enumerable: false,
        writable: true,
      });
    }
    else if (descriptor.writable) {
      err.stack = stack;
    }
    else {
      defineProperty(err, 'alternateStack', {
        value: stack,
        configurable: true,
        enumerable: false,
        writable: true,
      });
    }
  }
  catch (error) {
    if (typeof console !== 'undefined' && console && console.error) {
      console.error(`Error: Cannot add line to stack -- ${error.message}`);
    }
  }
}

export function _prepareStack(providedErr, providedOptions) {
  const err = providedErr || {};
  let stack = err.alternateStack || err.stack || '';
  const cwd = process.cwd();

  if (cwd !== '/') {
    stack = stack.split(cwd).join('');
  }

  const indentation = _getIndentation(stack);
  const options = providedOptions || {};
  const maxLines = options.maxLines || MAX_LINES;

  // V8-style stacks include the error message before showing the actual stack;
  // remove it, even if it has newlines in it, by using each line's prefix to split it.
  if (_startsWithError(stack)) {
    const lines = stack.split(/\n +at /);
    if (lines && lines.length) {
      stack = indentation + _internals.at
        + lines.slice(1).join(`\n${indentation}${_internals.at}`);
    }
  }

  // limit to ten lines
  const lines = stack.split('\n');
  if (lines.length > maxLines) {
    stack =
      `${lines.slice(0, maxLines).join('\n')}\n${indentation}${_internals.truncation}`;
  }

  return stack;
}

export function _getFirstLine(lines) {
  const v8 = /^ +at /;
  let result = `${_internals.prefix}<empty>`;

  if (lines && lines.length) {
    result = lines[0];

    if (v8.test(result)) {
      result = result.replace(v8, _internals.prefix);
    }
    else {
      result = _internals.prefix + result;
    }
  }

  return result;
}

export function _getIndentation(text) {
  if (!text || !text.split) {
    return '';
  }

  const lines = text.split('\n');
  const last = lines[lines.length - 1];

  const match = (/^ +/).exec(last);
  if (match) {
    return match[0];
  }

  return '';
}

export function _startsWithError(stack) {
  const v8 = /^[a-zA-z]+rror(:|\n)/;
  return Boolean(v8.test(stack));
}

export function _isError(err) {
  return typeof err === 'object' && err !== null
    && (Object.prototype.toString.call(err) === '[object Error]' || err instanceof Error);
}
<|endoftext|>


<commit_before>

var _ 	= require('underscore');
var api = require('./apis.js');
var User = require('./models/user.js');

var blog_url = 'http://meavisa.tumblr.com' // 'http://meavisa.tumblr.com'
var blog = api.getBlog("meavisa.tumblr.com");

// var twit = api.getTwitterApi();

// function notifyUser (user, tags) {
// 	var msg = "@"+user.screen_name+", he have updates on some tags ("+
// 		tags.slice(0,2)
// 		+") that you're following! Check your account on MeAvisa.herokuapp.com "
// 		+"account!"+Math.floor(Math.random()*100)
// 	console.log('processing ', user.screen_name, msg, '\n')
// 	twit.post('statuses/update', {
// 		status: msg
// 	}, function (err, reply) {
// 		console.log(err, reply)
// 		if (err) throw err;
// 	})
// }

var mongoUri = process.env.MONGOLAB_URI
	|| process.env.MONGOHQ_URL
	|| 'mongodb://localhost/madb';

var mongoose = require('mongoose');
mongoose.connect(mongoUri);

onGetPosts = function (posts) {
	console.log('call 1');

	User.find({}, function (err, users) {
		console.log('oi')

		users.forEach(function (user) {
			var tags = _.union.apply(null, _.pluck(_.filter(posts, function (post) {
					return new Date(post.date) > new Date(user.lastUpdate);
				}), 'tags'));

			if (tags.length)
				api.sendNotification(user.facebookId, tags)

			user.lastUpdate = new Date();
			user.save();
		});

		mongoose.connection.close();
	});
}

blog.posts(function (err, data) {
	if (err) throw err;
	onGetPosts(data.posts);
})

<commit_msg>Date updation updated lol<commit_after>// Generated by CoffeeScript 1.6.3
(function() {
  var User, api, blog, blog_url, mongoUri, mongoose, onGetPosts, _;

  _ = require('underscore');

  api = require('./apis.js');

  mongoose = require('mongoose');

  User = require('./models/user.js');

  blog_url = 'http://meavisa.tumblr.com';

  blog = api.getBlog("meavisa.tumblr.com");

  mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/madb';

  mongoose.connect(mongoUri);

  onGetPosts = function(posts) {
    return User.find({}, function(err, users) {
      var tags, user, _i, _len;
      console.log('oi');
      for (_i = 0, _len = users.length; _i < _len; _i++) {
        user = users[_i];
        tags = _.union.apply(null, _.pluck(_.filter(posts, function(post) {
          return new Date(post.date) > new Date(user.lastUpdate);
        }), 'tags'));
        if (tags.length) {
          api.sendNotification(user.facebookId, "We have updated on some of the tags you are following.");
        }
        user.lastUpdate = new Date();
        user.save();
      }
      return mongoose.connection.close();
    });
  };

  blog.posts(function(err, data) {
    if (err) {
      throw err;
    }
    return onGetPosts(data.posts);
  });

}).call(this);
<|endoftext|>


<commit_before>// Firing the first event sequence (the title)
function create() {
   typingsound = game.add.audio('typingsound');

   var r = new Rule1();

   r.init({conditions: function(scene){
             return !(scene.objects['first_text'].isVisible);},

           actions: function(scene){
               var o = scene.objects['first_text'];

               o.isVisible = true;
               fadeIn(o.sprite, 1000, function(){
                   fadeOut(o.sprite, 1000,
                      function(){
                        scene.game.scenes['title'].deactivate();
                        scene.game.scenes['room'].activate()}
                    )});
           }
     });

   var scene1 = new Scene1();
   var text = new Object1()

   text.init({name : 'first_text',
             text : 'Dans trois minutes au plus tard, \n'+
                     '  je devrai avoir quitte cet endroit \n'+
                     'une fois pour toutes...'});
   scene1.init(game, {name:'title',
                      objects: [text],
                     rules: [r]});

   var r2 = new Rule1();
   r2.init({conditions: function(scene){
             var o1 = scene.game.scenes['title'].objects['first_text'];
             var o2 = scene.objects['room'];
             return (o2.sprite.alpha ==0 && o1.sprite.alpha==0); },

           actions: function(scene){
               // The room appears
               var o = scene.objects['room'];
               o.animate();
               fadeIn(o.sprite, 1000)
               //console.log("display room");
           }
     });

   var scene2 = new Scene1();
   var room = new Object1();

   map = {name: 'roomMap',
        4294902015: function(scene){
          addDialog('You clicked the computer')
        },
        4294901778: function(scene){
          addDialog('You clicked the bottle')

          console.log(scene.game.scenes);
          scene.game.scenes['room'].deactivate();
          scene.game.scenes['title'].objects['first_text'].isVisible = false;
          scene.game.scenes['title'].objects['first_text'].sprite.alpha = 0;
          fadeOut(scene.game.scenes['room'].objects['room'].sprite, 3000,
            function(){scene.game.scenes['title'].activate()});
        },
        4278190335: function(){addDialog('you clicked the mouchoirs')} }

   room.init({name: 'room',
             image: 'room',
             map: map,
             })
   scene2.init(game, {name: 'room',
                      objects: [room],
                      rules: [r2]});
   scene1.activate();

   var scene3 = new Scene1();
   var campfire = new Object1();
   campfire.init({name: 'campfire'})
}
<commit_msg>test mobile/desktop<commit_after>// Firing the first event sequence (the title)
function create() {
   typingsound = game.add.audio('typingsound');
   game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT;
  if (game.device.desktop) {
         alert('dekstop')
           //code for desktop devices
       } else {
           alert('mobile')
           //code for mobile devices
       }

   var r = new Rule1();

   r.init({conditions: function(scene){
             return !(scene.objects['first_text'].isVisible);},

           actions: function(scene){
               var o = scene.objects['first_text'];

               o.isVisible = true;
               fadeIn(o.sprite, 1000, function(){
                   fadeOut(o.sprite, 1000,
                      function(){
                        scene.game.scenes['title'].deactivate();
                        scene.game.scenes['room'].activate()}
                    )});
           }
     });

   var scene1 = new Scene1();
   var text = new Object1()

   text.init({name : 'first_text',
             text : 'Dans trois minutes au plus tard, \n'+
                     '  je devrai avoir quitte cet endroit \n'+
                     'une fois pour toutes...'});
   scene1.init(game, {name:'title',
                      objects: [text],
                     rules: [r]});

   var r2 = new Rule1();
   r2.init({conditions: function(scene){
             var o1 = scene.game.scenes['title'].objects['first_text'];
             var o2 = scene.objects['room'];
             return (o2.sprite.alpha ==0 && o1.sprite.alpha==0); },

           actions: function(scene){
               // The room appears
               var o = scene.objects['room'];
               o.animate();
               fadeIn(o.sprite, 1000)
               //console.log("display room");
           }
     });

   var scene2 = new Scene1();
   var room = new Object1();

   map = {name: 'roomMap',
        4294902015: function(scene){
          addDialog('You clicked the computer')
        },
        4294901778: function(scene){
          addDialog('You clicked the bottle')

          console.log(scene.game.scenes);
          scene.game.scenes['room'].deactivate();
          scene.game.scenes['title'].objects['first_text'].isVisible = false;
          scene.game.scenes['title'].objects['first_text'].sprite.alpha = 0;
          fadeOut(scene.game.scenes['room'].objects['room'].sprite, 3000,
            function(){scene.game.scenes['title'].activate()});
        },
        4278190335: function(){addDialog('you clicked the mouchoirs')} }

   room.init({name: 'room',
             image: 'room',
             map: map,
             })
   scene2.init(game, {name: 'room',
                      objects: [room],
                      rules: [r2]});
   scene1.activate();

   var scene3 = new Scene1();
   var campfire = new Object1();
   campfire.init({name: 'campfire'})
}
<|endoftext|>


<commit_before>//Hook a callback into the rendered Google Search. From my understanding, this is possible because the outermost rendered div has id of "___gcse_0".
window.__gcse = {
  callback: googleCSELoaded
};
function googleCSELoaded() {
  // The hook in question.
  $("#fullsearch-btn").submit(function() {
	  	var cities = {
			30301:"atlanta",
			73301:"austin",
			02108:"boston",
			60290:"chicago",
			75201:"dallas",
			80123:"denver",
			48201:"detroit",
			77001:"houston",
			89101:"lasvegas",
			90001:"losangeles",
			33101:"miami",
			55401:"minneapolis",
			10001:"newyork",
			92799:"orangecounty",
			19019:"philadelphia",
			85001:"phoenix",
			97201:"portland",
			27601:"raleigh",
			94203:"sacramento",
			92093:"sandiego",
			98101:"seattle",
			94101:"sfbay",
			20001:"washingtondc"
	}
	  var location = $("#location").val();
		for (var key in cities) {
			if(key == location){
				location = cities[key];
			}
        }
		var search_string = $("#search_string").val();
		var min_price = $("#minAsk8").val();
		var max_price = $("#maxAsk8").val();
		var min_year = $("#minYear8").val();
		var max_year = $("#maxYear8").val();
		var searchText = "site:"+location+".craigslist.org"+" "+search_string+" "+"$"+min_price+".."+max_price+" "+"odometer:"+min_year+".."+max_year+" "+"filetype:html";
    console.log(searchText);
    var element = google.search.cse.element.getElement('searchOnlyCSE');
    element.execute(searchText);
  })
}

// CSE Code. This is a free version, so please don't make too many requests.
(function() {
  //var cx = '001386805071419863133:cb1vfab8b4y';
	var cx = '014940883816157527715:_1dsxowig5w';
  var gcse = document.createElement('script');
  gcse.type = 'text/javascript';
  gcse.async = true;
  gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(gcse, s);
})();

<commit_msg>Little changes<commit_after>//Hook a callback into the rendered Google Search. From my understanding, this is possible because the outermost rendered div has id of "___gcse_0".
window.__gcse = {
  callback: googleCSELoaded
};
function googleCSELoaded() {
  // The hook in question.
  $("#fullsearch-btn").submit(function() {
	  console.log("Ready....");
	  	var cities = {
			30301:"atlanta",
			73301:"austin",
			02108:"boston",
			60290:"chicago",
			75201:"dallas",
			80123:"denver",
			48201:"detroit",
			77001:"houston",
			89101:"lasvegas",
			90001:"losangeles",
			33101:"miami",
			55401:"minneapolis",
			10001:"newyork",
			92799:"orangecounty",
			19019:"philadelphia",
			85001:"phoenix",
			97201:"portland",
			27601:"raleigh",
			94203:"sacramento",
			92093:"sandiego",
			98101:"seattle",
			94101:"sfbay",
			20001:"washingtondc"
	}
	  var location = $("#location").val();
		for (var key in cities) {
			if(key == location){
				location = cities[key];
			}
        }
		var search_string = $("#search_string").val();
		var min_price = $("#minAsk8").val();
		var max_price = $("#maxAsk8").val();
		var min_year = $("#minYear8").val();
		var max_year = $("#maxYear8").val();
		var searchText = "site:"+location+".craigslist.org"+" "+search_string+" "+"$"+min_price+".."+max_price+" "+"odometer:"+min_year+".."+max_year+" "+"filetype:html";
    console.log(searchText);
    var element = google.search.cse.element.getElement('searchOnlyCSE');
    element.execute(searchText);
  })
}

// CSE Code. This is a free version, so please don't make too many requests.
(function() {
  //var cx = '001386805071419863133:cb1vfab8b4y';
	var cx = '014940883816157527715:_1dsxowig5w';
  var gcse = document.createElement('script');
  gcse.type = 'text/javascript';
  gcse.async = true;
  gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(gcse, s);
})();

<|endoftext|>


<commit_before>var konami = [38,38,40,40,37,39,37,39,66,65];
var index = 0;

$(document).keydown(function(e){

    if(e.which == konami[index]){
        index++;
    }else{
        index = 0;
    }

    if(index == konami.length){
        konami_entered();
        index = 0;
    }
}
);

function konami_entered(){
    $("body").addClass('comic-sans');
    clippy.load('Clippy', function(agent) {
        agent.show();
        agent.moveTo($(document).width()-400, 50);
        agent.speak("Looks like you're signing up for a hackathon, need any help?");
    });
}
<commit_msg>moar generic change<commit_after>var konami = [38,38,40,40,37,39,37,39,66,65];
var index = 0;

$(document).keydown(function(e){

    if(e.which == konami[index]){
        index++;
    }else{
        index = 0;
    }

    if(index == konami.length){
        konami_entered();
        index = 0;
    }
}
);

function konami_entered(){
    ga('send', 'event', 'konami', 'konami_entered');
    $("body").addClass('comic-sans');
    clippy.load('Clippy', function(agent) {
        agent.show();
        agent.moveTo($(document).width()-400, 50);
        agent.speak("Looks like you're signing up for a hackathon, need any help?");
    });
}
<|endoftext|>


<commit_before>$(function() {
	$('.aj-nav').click(function(e) {
		e.preventDefault();
		$(this).parent().siblings().find('ul').slideUp();
		$(this).next().slideToggle();
	});

	// Bootstrap Table Class
	$('table').addClass('table');
});<commit_msg>Javascript workaround for mobile nag bar<commit_after>$(function() {
	$('.aj-nav').click(function(e) {
		e.preventDefault();
		$(this).parent().siblings().find('ul').slideUp();
		$(this).next().slideToggle();
	});

	// Bootstrap Table Class
	$('table').addClass('table');

	var mobileNavWorkaround = function() {
		if($(window).width()< 768) {
			$('#sub-nav-collapse').css('height', '0px');
		} else {
			$('#sub-nav-collapse').css('height', 'auto');
		}
	}

	$(window).resize(function() {
		mobileNavWorkaround();
	});
	mobileNavWorkaround();
});<|endoftext|>


<commit_before>// Utility functions for operating on existing DOM elements

// Source: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/
jQuery.fn.textOnly = function() {
  return $(this)
    .clone()
    .children()
    .remove()
    .end() // Go back to cloned element
    .text();
};

jQuery.fn.exists = function() {
  return this.length;
}

jQuery.fn.isEmpty = function() {
  return !$(this).val();
}

jQuery.fn.check = function() {
  return $(this).attr('checked', true);
}

jQuery.fn.select = function() {
  return $(this).attr('selected', true);
}

jQuery.fn.enable = function() {
  return $(this).prop('disabled', false);
}

jQuery.fn.disable = function() {
  return $(this).prop('disabled', true);
}

jQuery.fn.makeEditable = function() {
  return $(this).addClass('editable').attr('contenteditable', true);
}

jQuery.fn.dataToArray = function(dataAttribute) {
  var dataToConvert = $(this).data(dataAttribute);
  if (typeof(dataToConvert) === 'string') {
    return dataToConvert.substring(1, dataToConvert.length-1).split(/, */);
  } else {
    return dataToConvert;
  }
}

// Utility functions for operating on strings

jQuery.matches = function(str, input) {
  return str.indexOf(input) !== -1;
}

jQuery.cap = function(str) {
  return str.charAt(0).toUpperCase() + str.substring(1);
}

// Utility functions for creating new DOM elements

jQuery.div = function(klass) {
  var div = $('
');
  if (klass) {
    div.addClass(klass);
  }
  return div;
}

jQuery.span = function(klass) {
  return $('').addClass(klass);
}

jQuery.placeholder = function(text) {
  return $.div('droppable placeholder').text(text);
}

jQuery.alertMsg = function(text) {
  return $('').addClass('alert-msg text-danger').text(text);
}

jQuery.hr = function() {
  return $('
');
}

jQuery.h3 = function(text) {
  return $('
').text(text);
}

jQuery.h4 = function(text) {
  return $('
').text(text);
}

jQuery.h5 = function(text) {
  return $('
').text(text);
}

jQuery.small = function() {
  return $('');
}

jQuery.p = function(text) {
  return $('
').text(text);
}

jQuery.a = function(target, text) {
  return $('').attr('href', target).text(text);
}

jQuery.form = function() {
  return $('<form>').attr('role', 'form');
}

jQuery.formGroup = function(field, id) {
  var label = $.label().attr('for', id).text($.cap(field) + ':');
  var inputField = $.textInput()
    .attr('id', id)
    .attr('placeholder', 'Enter ' + field + ' ...');
  return $('
').addClass('form-group').append(label).append(inputField);
}

jQuery.radioButton = function(group, value, controlClass) {
  var label = $.label();
  var input = $.radioInput(group, value).addClass(controlClass);
  label.append(input);
  label.append(document.createTextNode(value));
  return $('
').addClass('radio').append(label);
}

jQuery.label = function() {
  return $('');
}

jQuery.input = function(type) {
  return $('<input>').attr('type', type);
}

jQuery.textInput = function() {
  return $.input('text').addClass('form-control');
}

jQuery.selectMenu = function() {
  return $('<select>').addClass('form-control');
}

jQuery.option = function(text) {
  return $('<option>').text(text);
}

jQuery.radioInput = function(group, value) {
  return $.input('radio').attr('name', group).attr('value', value);
}

jQuery.button = function(text) {
  return $('<button>').addClass('btn').text(text);
}

jQuery.infoButton = function(text) {
  return $.button(text).addClass('btn-info');
}

jQuery.successButton = function(text) {
  return $.button(text).addClass('btn-success');
}

jQuery.addButton = function() {
  return $.infoButton('Add');
}

jQuery.okButton = function() {
  return $.infoButton('OK');
}

jQuery.createButton = function() {
  return $.successButton('Create').addClass('btn-lg').attr('id', 'create');
}

jQuery.editButton = function(target) {
  return $('').addClass('glyphicon glyphicon-pencil edit-button')
    .data('target', target);
}

jQuery.plusButton = function(target) {
  return $('').addClass('glyphicon glyphicon-plus plus-button');
}

jQuery.minusButton = function(target) {
  return $('').addClass('glyphicon glyphicon-minus minus-button');
}

jQuery.copyButton = function(target) {
  return $('').addClass('glyphicon glyphicon-new-window copy-button');
}

jQuery.removeButton = function(target) {
  return $('').addClass('glyphicon glyphicon-remove remove-button')
    .data('target', target);
}

jQuery.emptyButton = function() {
  return $('').addClass('glyphicon glyphicon-unchecked empty-button');
}

jQuery.table = function() {
  return $('
').addClass('table');
}

jQuery.thead = function() {
  return $('
').html($.tr());
}

jQuery.tr = function() {
  return $('
');
}

jQuery.th = function() {
  return $('');
}

jQuery.tbody = function() {
  return $('
');
}

jQuery.td = function() {
  return $('');
}
<commit_msg>[Search] WIP: Enable sorting of search results.<commit_after>// Utility functions for operating on existing DOM elements

// Source: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/
jQuery.fn.textOnly = function() {
  return $(this)
    .clone()
    .children()
    .remove()
    .end() // Go back to cloned element
    .text();
};

jQuery.fn.exists = function() {
  return this.length;
}

jQuery.fn.isEmpty = function() {
  return !$(this).val();
}

jQuery.fn.check = function() {
  return $(this).attr('checked', true);
}

jQuery.fn.select = function() {
  return $(this).attr('selected', true);
}

jQuery.fn.enable = function() {
  return $(this).prop('disabled', false);
}

jQuery.fn.disable = function() {
  return $(this).prop('disabled', true);
}

jQuery.fn.makeEditable = function() {
  return $(this).addClass('editable').attr('contenteditable', true);
}

jQuery.fn.dataToArray = function(dataAttribute) {
  var dataToConvert = $(this).data(dataAttribute);
  if (typeof(dataToConvert) === 'string') {
    return dataToConvert.substring(1, dataToConvert.length-1).split(/, */);
  } else {
    return dataToConvert;
  }
}

// Utility functions for operating on strings

jQuery.matches = function(str, input) {
  return str.indexOf(input) !== -1;
}

jQuery.cap = function(str) {
  return str.charAt(0).toUpperCase() + str.substring(1);
}

// Utility functions for creating new DOM elements

jQuery.div = function(klass) {
  var div = $('
');
  if (klass) {
    div.addClass(klass);
  }
  return div;
}

jQuery.span = function(klass) {
  return $('').addClass(klass);
}

jQuery.placeholder = function(text) {
  return $.div('droppable placeholder').text(text);
}

jQuery.alertMsg = function(text) {
  return $('').addClass('alert-msg text-danger').text(text);
}

jQuery.hr = function() {
  return $('
');
}

jQuery.h3 = function(text) {
  return $('
').text(text);
}

jQuery.h4 = function(text) {
  return $('
').text(text);
}

jQuery.h5 = function(text) {
  return $('
').text(text);
}

jQuery.small = function() {
  return $('');
}

jQuery.p = function(text) {
  return $('
').text(text);
}

jQuery.a = function(target, text) {
  return $('').attr('href', target).text(text);
}

jQuery.form = function() {
  return $('<form>').attr('role', 'form');
}

jQuery.formGroup = function(field, id) {
  var label = $.label().attr('for', id).text($.cap(field) + ':');
  var inputField = $.textInput()
    .attr('id', id)
    .attr('placeholder', 'Enter ' + field + ' ...');
  return $('
').addClass('form-group').append(label).append(inputField);
}

jQuery.radioButton = function(group, value, controlClass) {
  var label = $.label();
  var input = $.radioInput(group, value).addClass(controlClass);
  label.append(input);
  label.append(document.createTextNode(value));
  return $('
').addClass('radio').append(label);
}

jQuery.label = function() {
  return $('');
}

jQuery.input = function(type) {
  return $('<input>').attr('type', type);
}

jQuery.textInput = function() {
  return $.input('text').addClass('form-control');
}

jQuery.selectMenu = function() {
  return $('<select>').addClass('form-control');
}

jQuery.option = function(text) {
  return $('<option>').text(text);
}

jQuery.radioInput = function(group, value) {
  return $.input('radio').attr('name', group).attr('value', value);
}

jQuery.button = function(text) {
  return $('<button>').addClass('btn').text(text);
}

jQuery.infoButton = function(text) {
  return $.button(text).addClass('btn-info');
}

jQuery.successButton = function(text) {
  return $.button(text).addClass('btn-success');
}

jQuery.addButton = function() {
  return $.infoButton('Add');
}

jQuery.okButton = function() {
  return $.infoButton('OK');
}

jQuery.createButton = function() {
  return $.successButton('Create').addClass('btn-lg').attr('id', 'create');
}

jQuery.editButton = function(target) {
  return $('').addClass('glyphicon glyphicon-pencil edit-button')
    .data('target', target);
}

jQuery.plusButton = function(target) {
  return $('').addClass('glyphicon glyphicon-plus plus-button');
}

jQuery.minusButton = function(target) {
  return $('').addClass('glyphicon glyphicon-minus minus-button');
}

jQuery.copyButton = function(target) {
  return $('').addClass('glyphicon glyphicon-new-window copy-button');
}

jQuery.removeButton = function(target) {
  return $('').addClass('glyphicon glyphicon-remove remove-button')
    .data('target', target);
}

jQuery.emptyButton = function() {
  return $('').addClass('glyphicon glyphicon-unchecked empty-button');
}

jQuery.table = function() {
  return $('
').addClass('table table-striped table-hover');
}

jQuery.thead = function() {
  return $('
').html($.tr());
}

jQuery.tr = function() {
  return $('
');
}

jQuery.th = function() {
  return $('');
}

jQuery.tbody = function() {
  return $('
');
}

jQuery.td = function() {
  return $('');
}
<|endoftext|>


<commit_before>module.exports = {
  queryFieldTranslations: {
    'ag': 'ageLimit',
    'aktør': 'agents',
    'aldersgrense': 'ageLimit',
    'alf': 'writingSystem',
    'alfabet': 'writingSystem',
    'arr': 'musicalArranger',
    'arrangør': 'musicalArranger',
    'be': 'instrumentation',
    'bearb': 'adaptor',
    'bearbeider': 'adaptor',
    'besetning': 'instrumentation',
    'bid': 'contributor',
    'bidragsyter': 'contributor',
    'bio': 'biography',
    'biografi': 'biography',
    'delnummer': 'partNumber',
    'deltittel': 'partTitle',
    'dir': 'conductor',
    'dirigent': 'conductor',
    'dn': 'partNumber',
    'dt': 'partTitle',
    'em': 'subject',
    'emne': 'subject',
    'f': 'format',
    'fo': 'author',
    'forfatter': 'author',
    'forl': 'publishedBy',
    'forlag': 'publishedBy',
    'form': 'litform',
    'foto': 'photographer',
    'fotograf': 'photographer',
    'ge': 'genre',
    'hovedtittel': 'mainTitle',
    'ht': 'mainTitle',
    'ill': 'illustrator',
    'illustratør': 'illustrator',
    'innl': 'reader',
    'innleser': 'reader',
    'kl': 'dewey',
    'klasse': 'dewey',
    'komp': 'composer',
    'komponist': 'composer',
    'komposisjonstype': 'compType',
    'kor': 'coreographer',
    'koreograf': 'coreographer',
    'kt': 'compType',
    'land': 'country',
    'lf': 'litform',
    'manus': 'scriptWriter',
    'manusforfatter': 'scriptWriter',
    'medietype': 'mt',
    'nasj': 'nationality',
    'nasjonalitet': 'nationality',
    'odn': 'workPartNumber',
    'odt': 'workPartTitle',
    'oht': 'workMainTitle',
    'originalDelnummer': 'workPartNumber',
    'originalDeltittel': 'workPartTitle',
    'originalHovedtittel': 'workMainTitle',
    'originalSpråk': 'origLang',
    'originalUndertittel': 'workSubtitle',
    'originalÅr': 'firstPublicationYear',
    'ospr': 'origLang',
    'out': 'workSubtitle',
    'ov': 'translator',
    'oversetter': 'translator',
    'oår': 'firstPublicationYear',
    'person': 'agents',
    'prod': 'producer',
    'produsent': 'producer',
    'red': 'editor',
    'redaktør': 'editor',
    'reg': 'director',
    'regissør': 'director',
    'se': 'series',
    'serie': 'series',
    'sjanger': 'genre',
    'sku': 'actor',
    'skuespiller': 'actor',
    'spr': 'language',
    'språk': 'language',
    'tekst': 'subtitles',
    'tekstforfatter': 'lyricist',
    'tfo': 'lyricist',
    'ti': 'title',
    'tilp': 'adaptation',
    'tilpasning': 'adaptation',
    'tittel': 'title',
    'tittelnummer': 'recordId',
    'tnr': 'recordId',
    'undertekster': 'subtitles',
    'undertittel': 'subtitle',
    'ut': 'subtitle',
    'utg': 'publisher',
    'utgivelsesår': 'publicationYear',
    'utgiver': 'publisher',
    'utøv': 'performer',
    'utøver': 'performer',
    'år': 'publicationYear'
  },
  backendUri: '/services',
  maxVisibleFilterItems: 5,
  maxSearchResults: 100,
  maxSearchResultsPerPage: 10,
  filterableFields: {
    language: {
      name: 'languages',
      prefix: 'http://lexvo.org/id/iso639-3/'
    },
    branch: {
      name: 'branches',
      prefix: ''
    },
    mediatype: {
      name: 'mediatype',
      prefix: 'http://data.deichman.no/mediaType#'
    },
    format: {
      name: 'formats',
      prefix: 'http://data.deichman.no/format#'
    },
    audience: {
      name: 'audiences',
      prefix: 'http://data.deichman.no/audience#'
    },
    fictionNonfiction: {
      name: 'fictionNonfiction',
      prefix: 'http://data.deichman.no/fictionNonfiction#'
    }
  },
  mediaTypeIcons: {
    'http://data.deichman.no/mediaType#Book': 'book',
    'http://data.deichman.no/mediaType#Audiobook': 'audiobook',
    'http://data.deichman.no/mediaType#LanguageCourse': 'book',
    'http://data.deichman.no/mediaType#MusicRecording': 'music',
    'http://data.deichman.no/mediaType#SheetMusic': 'music-note',
    'http://data.deichman.no/mediaType#Film': 'movie',
    'http://data.deichman.no/mediaType#Game': 'play',
    'http://data.deichman.no/mediaType#ComicBook': 'book',
    'http://data.deichman.no/mediaType#Map': 'book',
    'http://data.deichman.no/mediaType#Periodical': 'book',
    '': 'undefined'
  },
  mediaTypeIconsMap: {
    'book': 'icon-book',
    'audiobook': 'icon-audiobook',
    'music': 'icon-music',
    'music-note': 'icon-music',
    'movie': 'icon-movie',
    'play': 'icon-cd',
    'undefined': 'icon-help'
  },
  preferredLanguages: [
    'http://lexvo.org/id/iso639-3/nob',
    'http://lexvo.org/id/iso639-3/nno',
    'http://lexvo.org/id/iso639-3/nor',
    'http://lexvo.org/id/iso639-3/eng',
    'http://lexvo.org/id/iso639-3/swe',
    'http://lexvo.org/id/iso639-3/dan',
    'http://lexvo.org/id/iso639-3/ger',
    'http://lexvo.org/id/iso639-3/fre',
    'http://lexvo.org/id/iso639-3/spa',
    'http://lexvo.org/id/iso639-3/ita'
  ],
  enabledParameter: null /* used to clarify url parameters without value, e.g. ?hideFilters */
}
<commit_msg>patron-client: correct some field code translations<commit_after>module.exports = {
  queryFieldTranslations: {
    'ag': 'ageLimit',
    'aktør': 'agents',
    'aldersgrense': 'ageLimit',
    'alf': 'writingSystem',
    'alfabet': 'writingSystem',
    'arr': 'musicalArranger',
    'arrangør': 'musicalArranger',
    'be': 'inst',
    'bearb': 'adaptor',
    'bearbeider': 'adaptor',
    'besetning': 'inst',
    'bid': 'contributor',
    'bidragsyter': 'contributor',
    'biografi': 'bio',
    'biography': 'bio',
    'delnummer': 'partNumber',
    'deltittel': 'partTitle',
    'dir': 'conductor',
    'dirigent': 'conductor',
    'dn': 'partNumber',
    'dt': 'partTitle',
    'em': 'subject',
    'emne': 'subject',
    'f': 'format',
    'fo': 'author',
    'forfatter': 'author',
    'forl': 'publishedBy',
    'forlag': 'publishedBy',
    'form': 'litform',
    'foto': 'photographer',
    'fotograf': 'photographer',
    'ge': 'genre',
    'hovedtittel': 'mainTitle',
    'ht': 'mainTitle',
    'ill': 'illustrator',
    'illustratør': 'illustrator',
    'innl': 'reader',
    'innleser': 'reader',
    'kl': 'dewey',
    'klasse': 'dewey',
    'komp': 'composer',
    'komponist': 'composer',
    'komposisjonstype': 'compType',
    'kor': 'coreographer',
    'koreograf': 'coreographer',
    'kt': 'compType',
    'land': 'country',
    'lf': 'litform',
    'manus': 'scriptWriter',
    'manusforfatter': 'scriptWriter',
    'medietype': 'mt',
    'nasj': 'nationality',
    'nasjonalitet': 'nationality',
    'odn': 'workPartNumber',
    'odt': 'workPartTitle',
    'oht': 'workMainTitle',
    'originalDelnummer': 'workPartNumber',
    'originalDeltittel': 'workPartTitle',
    'originalHovedtittel': 'workMainTitle',
    'originalSpråk': 'origLang',
    'originalUndertittel': 'workSubtitle',
    'originalÅr': 'firstPublicationYear',
    'ospr': 'origLang',
    'out': 'workSubtitle',
    'ov': 'translator',
    'oversetter': 'translator',
    'oår': 'firstPublicationYear',
    'person': 'agents',
    'prod': 'producer',
    'produsent': 'producer',
    'red': 'editor',
    'redaktør': 'editor',
    'reg': 'director',
    'regissør': 'director',
    'se': 'series',
    'serie': 'series',
    'sjanger': 'genre',
    'sku': 'actor',
    'skuespiller': 'actor',
    'spr': 'language',
    'språk': 'language',
    'tekst': 'subtitles',
    'tekstforfatter': 'lyricist',
    'tfo': 'lyricist',
    'ti': 'title',
    'tilp': 'adaptation',
    'tilpasning': 'adaptation',
    'tittel': 'title',
    'tittelnummer': 'recordId',
    'tnr': 'recordId',
    'undertekster': 'subtitles',
    'undertittel': 'subtitle',
    'ut': 'subtitle',
    'utg': 'publisher',
    'utgivelsesår': 'publicationYear',
    'utgiver': 'publisher',
    'utøv': 'performer',
    'utøver': 'performer',
    'år': 'publicationYear'
  },
  backendUri: '/services',
  maxVisibleFilterItems: 5,
  maxSearchResults: 100,
  maxSearchResultsPerPage: 10,
  filterableFields: {
    language: {
      name: 'languages',
      prefix: 'http://lexvo.org/id/iso639-3/'
    },
    branch: {
      name: 'branches',
      prefix: ''
    },
    mediatype: {
      name: 'mediatype',
      prefix: 'http://data.deichman.no/mediaType#'
    },
    format: {
      name: 'formats',
      prefix: 'http://data.deichman.no/format#'
    },
    audience: {
      name: 'audiences',
      prefix: 'http://data.deichman.no/audience#'
    },
    fictionNonfiction: {
      name: 'fictionNonfiction',
      prefix: 'http://data.deichman.no/fictionNonfiction#'
    }
  },
  mediaTypeIcons: {
    'http://data.deichman.no/mediaType#Book': 'book',
    'http://data.deichman.no/mediaType#Audiobook': 'audiobook',
    'http://data.deichman.no/mediaType#LanguageCourse': 'book',
    'http://data.deichman.no/mediaType#MusicRecording': 'music',
    'http://data.deichman.no/mediaType#SheetMusic': 'music-note',
    'http://data.deichman.no/mediaType#Film': 'movie',
    'http://data.deichman.no/mediaType#Game': 'play',
    'http://data.deichman.no/mediaType#ComicBook': 'book',
    'http://data.deichman.no/mediaType#Map': 'book',
    'http://data.deichman.no/mediaType#Periodical': 'book',
    '': 'undefined'
  },
  mediaTypeIconsMap: {
    'book': 'icon-book',
    'audiobook': 'icon-audiobook',
    'music': 'icon-music',
    'music-note': 'icon-music',
    'movie': 'icon-movie',
    'play': 'icon-cd',
    'undefined': 'icon-help'
  },
  preferredLanguages: [
    'http://lexvo.org/id/iso639-3/nob',
    'http://lexvo.org/id/iso639-3/nno',
    'http://lexvo.org/id/iso639-3/nor',
    'http://lexvo.org/id/iso639-3/eng',
    'http://lexvo.org/id/iso639-3/swe',
    'http://lexvo.org/id/iso639-3/dan',
    'http://lexvo.org/id/iso639-3/ger',
    'http://lexvo.org/id/iso639-3/fre',
    'http://lexvo.org/id/iso639-3/spa',
    'http://lexvo.org/id/iso639-3/ita'
  ],
  enabledParameter: null /* used to clarify url parameters without value, e.g. ?hideFilters */
}
<|endoftext|>


<commit_before>E2.p = E2.plugins["audio_gain_modulator"] = function(core, node)
{
	this.desc = '(De)amplify or mix audio data.';

	this.input_slots = [
		{ name: 'gain', dt: core.datatypes.FLOAT, desc: 'Amplification scalar.', def: null }
	];

	this.output_slots = [
		{ name: 'source', dt: core.datatypes.OBJECT, desc: 'A (de)amplified audio source', def: null }
	];

	this.state = {
		slot_uids: []
	};

	this.core = core;
	this.node = node;
	this.gain_node = core.audio_ctx ? core.audio_ctx.createGain() : null;
	this.lsg = new LinkedSlotGroup(core, node, [], []);
	this.srcs = [];
	this.gain = null;
	this.first = true;
};

E2.p.prototype.reset = function()
{
	this.first = true;
};

E2.p.prototype.create_ui = function()
{
	var layout = make('div');
	var inp_add = makeButton('+', 'Click to add another input.');
	var inp_rem = makeButton('-', 'Click to remove the last input.');

	inp_add.css({'width': '20px', 'float': 'left'});
	inp_rem.css({'width': '20px', 'float': 'right', 'margin-left': '5px'});

	inp_add.click(function(self) { return function(v)
	{
		var suid = self.node.add_slot(E2.slot_type.input, { name: '' + self.state.slot_uids.length, dt: self.core.datatypes.OBJECT });

		self.state.slot_uids.push(suid);
		self.lsg.add_dyn_slot(self.node.find_dynamic_slot(E2.slot_type.input, suid));
	}}(this));

	inp_rem.click(function(self) { return function(v)
	{
		if(self.state.slot_uids.length < 1)
			return;

		var suid = self.state.slot_uids.pop();

		self.lsg.remove_dyn_slot(self.node.find_dynamic_slot(E2.slot_type.input, suid));
		self.node.remove_slot(E2.slot_type.input, suid);
	}}(this));

	layout.append(inp_add);
	layout.append(inp_rem);

	return layout;
};

E2.p.prototype.update_input = function(slot, data)
{
	if(slot.uid !== undefined)
	{
		if(this.srcs[slot.index])
			this.srcs[slot.index].disconnect(0);

		this.srcs[slot.index] = data;

		if(data)
		{
			data.connect(this.gain_node);
			this.gain_node.player = data.player;
		}
	}
	else if(slot.index === 0)
	{
		this.gain = data;
	}
};

E2.p.prototype.update_state = function()
{
	if((this.gain_node.gain.value !== this.gain) || this.first)
	{
		this.gain_node.gain.value = this.gain !== null ? this.gain : 1.0;
		this.first = false;
	}
};

E2.p.prototype.update_output = function(slot)
{
	return this.gain_node;
};

E2.p.prototype.state_changed = function(ui)
{
	if(!ui)
	{
		for(var i = 0, len = this.state.slot_uids.length; i < len; i++)
			this.lsg.add_dyn_slot(this.node.find_dynamic_slot(E2.slot_type.input, this.state.slot_uids[i]));
	}
};
<commit_msg>AudioGainModulator: undoable slot addition/removal<commit_after>(function(){

var AudioGainModulator = E2.plugins.audio_gain_modulator = function(core, node) {
	var that = this

	this.desc = '(De)amplify or mix audio data.';

	this.input_slots = [
		{ name: 'gain', dt: core.datatypes.FLOAT, desc: 'Amplification scalar.', def: null }
	];

	this.output_slots = [
		{ name: 'source', dt: core.datatypes.OBJECT, desc: 'A (de)amplified audio source', def: null }
	];

	this.state = {
		slot_uids: []
	};

	this.core = core;
	this.node = node;
	this.gain_node = core.audio_ctx ? core.audio_ctx.createGain() : null;
	this.lsg = new LinkedSlotGroup(core, node, [], []);
	this.srcs = [];
	this.gain = null;
	this.first = true;

	this.node.on('slotAdded', function(slot) {
		that.state.slot_uids.push(slot.uid)
		that.updated = true
	})

	this.node.on('slotRemoved', function(slot) {
		that.state.slot_uids = that.state.slot_uids
			.filter(function(uid) {
				return (slot.uid !== uid)
			})

		that.updated = true
	})

}

AudioGainModulator.prototype.reset = function() {
	this.first = true;
}

AudioGainModulator.prototype.create_ui = function() {
	var that = this

	var layout = make('div')
	var inp_add = makeButton('+', 'Click to add another input.')
	var inp_rem = makeButton('-', 'Click to remove the last input.')

	inp_add.css({'width': '20px', 'float': 'left'})
	inp_rem.css({'width': '20px', 'float': 'right', 'margin-left': '5px'})

	inp_add.click(function() {
		E2.app.graphApi.addSlot(that.node.parent_graph, that.node, {
			type: E2.slot_type.input,
			name: that.state.slot_uids.length + '',
			dt: that.core.datatypes.OBJECT
		})
	})

	inp_rem.click(function() {
		if (that.state.slot_uids.length < 1)
			return;

		var suid = that.state.slot_uids[that.state.slot_uids.length-1]
		E2.app.graphApi.removeSlot(that.node.parent_graph, that.node, suid)
	})

	layout.append(inp_add)
	layout.append(inp_rem)

	return layout;
}

AudioGainModulator.prototype.update_input = function(slot, data)
{
	if(slot.uid !== undefined)
	{
		if(this.srcs[slot.index])
			this.srcs[slot.index].disconnect(0);

		this.srcs[slot.index] = data;

		if(data)
		{
			data.connect(this.gain_node);
			this.gain_node.player = data.player;
		}
	}
	else if(slot.index === 0)
	{
		this.gain = data;
	}
};

AudioGainModulator.prototype.update_state = function()
{
	if((this.gain_node.gain.value !== this.gain) || this.first)
	{
		this.gain_node.gain.value = this.gain !== null ? this.gain : 1.0;
		this.first = false;
	}
};

AudioGainModulator.prototype.update_output = function(slot)
{
	return this.gain_node;
};

AudioGainModulator.prototype.state_changed = function(ui)
{
	if(!ui)
	{
		for(var i = 0, len = this.state.slot_uids.length; i < len; i++)
			this.lsg.add_dyn_slot(this.node.find_dynamic_slot(E2.slot_type.input, this.state.slot_uids[i]));
	}
};

})();

<|endoftext|>