<commit_before>var Model = require('./Model');
var Note = require('./Note');
var Collection = require('./Collection');
var volumeParams = require('./mixins/volumeParams');
var connectable = require('./mixins/connectable');
var bypassable = require('./mixins/bypassable');
var expressions = require('dilla-expressions');

var NotesCollection = Collection.extend({
  model: Note
});

var Channel = Model.extend(volumeParams, bypassable, {

  type: 'channel',

  props: {
    transform: 'function'
  },

  collections: {
    rawNotes: NotesCollection,
    expandedNotes: NotesCollection
  },

  initialize: function () {
    Model.prototype.initialize.apply(this, arguments);

    this._cache = {};

    this.listenTo(this.rawNotes, 'add', this._onAddRawNote);
    this.listenTo(this.rawNotes, 'remove', this._onRemoveRawNote);
    this.listenTo(this.rawNotes, 'change:position', this._onChangeRawNote);

    this.listenTo(this.expandedNotes, 'start', this._start);
    this.listenTo(this.expandedNotes, 'stop', this._stop);
    this.listenTo(this.expandedNotes, 'add', this._onAddExpandedNote);
    this.listenTo(this.expandedNotes, 'remove', this._onRemoveExpandedNote);

    this.cacheMethodUntilEvent('notes', 'change:expandedNotes');
  },

  add: function () {
    var notes = [].slice.call(arguments).map(function (raw) {
      return raw instanceof Note ? raw : Note.fromRaw(raw);
    });
    this.rawNotes.add(notes);
    return this;
  },

  notes: function (bar, beat, tick) {
    if (!bar) return this.expandedNotes.models.slice();
    var cache = this._cache;
    var beats = cache[bar];
    if (!beat) return (beats && beats['*'] || []).slice();
    var ticks = beats && beats[beat];
    if (!tick) return (ticks && ticks['*'] || []).slice();
    return (ticks && ticks[tick] || []).slice();
  },

  transforms: function (note) {
    if (!note || !(note instanceof Note)) throw new Error('Invalid argument: note is not an instance of bap.note');
    var pattern = this.collection && this.collection.parent;

    var transforms = [];
    [note, this, pattern].forEach(function (source) {
      if (source && source.transform && typeof source.transform === 'function') {
        transforms.push(source.transform);
      }
    });

    if (!transforms.length) return false;

    return function (note) {
      transforms.forEach(function (fn) {
        fn(note);
      });
    };
  },

  _onAddExpandedNote: function (note) {
    var cache = this._cache;
    var bar = note.bar;
    var beat = note.beat;
    var tick = note.tick;

    cache[bar] = cache[bar] || {};
    cache[bar]['*'] = cache[bar]['*'] || [];
    cache[bar]['*'].push(note);
    cache[bar][beat] = cache[bar][beat] || {};
    cache[bar][beat]['*'] = cache[bar][beat]['*'] || [];
    cache[bar][beat]['*'].push(note);
    cache[bar][beat][tick] = cache[bar][beat][tick] || [];
    cache[bar][beat][tick].push(note);
  },

  _onRemoveExpandedNote: function (note) {
    var cache = this._cache;
    var bar = note.bar;
    var beat = note.beat;
    var tick = note.tick;

    var barIndex = cache[bar]['*'].indexOf(note);
    cache[bar]['*'].splice(barIndex, 1);
    var beatIndex = cache[bar][beat]['*'].indexOf(note);
    cache[bar][beat]['*'].splice(beatIndex, 1);
    var tickIndex = cache[bar][beat][tick].indexOf(note);
    cache[bar][beat][tick].splice(tickIndex, 1);
  },

  _onAddRawNote: function (note) {
    var transform = this.transforms(note);

    if (note.hasPlainPosition() && !transform) {
      note.original = note;
      return this.expandedNotes.add(note);
    }

    var pattern = this.collection && this.collection.parent;
    var options = {
      barsPerLoop: pattern && pattern.bars || 1,
      beatsPerBar: pattern && pattern.beatsPerBar || 4
    };

    expressions([[note.position]], options).forEach(function (position) {
      var expanded = note.with({ position: position[0] });

      expanded.original = note;
      expanded.delegateChangeHandler = function (note) {
        var changed = Object.assign({}, note._changed)
        delete changed.position;
        delete changed.bar;
        delete changed.beat;
        delete changed.tick;
        expanded.set(changed);
      };
      note.on('change', expanded.delegateChangeHandler);

      transform && transform(expanded);
      this.expandedNotes.add(expanded);
    }.bind(this));
  },

  _onRemoveRawNote: function (note) {
    this.expandedNotes.models.slice().forEach(function (expanded) {
      if (note === expanded.original) {
        this.expandedNotes.remove(expanded);
        expanded.original.off('change', expanded.delegateChangeHandler);
        expanded.original = null;
        expanded.delegateChangeHandler = null;
      }
    }.bind(this));
  },

  _onChangeRawNote: function (note) {
    this._onRemoveRawNote(note);
    this._onAddRawNote(note);
  },

  _start: function (time, note) {
    if (!this.mute) {
      this.trigger('start', time, note, this);
    }
  },

  _stop: function (time, note) {
    this.trigger('stop', time, note, this);
  }
}, connectable);

module.exports = Channel;
<commit_msg>Fix linting error<commit_after>var Model = require('./Model');
var Note = require('./Note');
var Collection = require('./Collection');
var volumeParams = require('./mixins/volumeParams');
var connectable = require('./mixins/connectable');
var bypassable = require('./mixins/bypassable');
var expressions = require('dilla-expressions');

var NotesCollection = Collection.extend({
  model: Note
});

var Channel = Model.extend(volumeParams, bypassable, {

  type: 'channel',

  props: {
    transform: 'function'
  },

  collections: {
    rawNotes: NotesCollection,
    expandedNotes: NotesCollection
  },

  initialize: function () {
    Model.prototype.initialize.apply(this, arguments);

    this._cache = {};

    this.listenTo(this.rawNotes, 'add', this._onAddRawNote);
    this.listenTo(this.rawNotes, 'remove', this._onRemoveRawNote);
    this.listenTo(this.rawNotes, 'change:position', this._onChangeRawNote);

    this.listenTo(this.expandedNotes, 'start', this._start);
    this.listenTo(this.expandedNotes, 'stop', this._stop);
    this.listenTo(this.expandedNotes, 'add', this._onAddExpandedNote);
    this.listenTo(this.expandedNotes, 'remove', this._onRemoveExpandedNote);

    this.cacheMethodUntilEvent('notes', 'change:expandedNotes');
  },

  add: function () {
    var notes = [].slice.call(arguments).map(function (raw) {
      return raw instanceof Note ? raw : Note.fromRaw(raw);
    });
    this.rawNotes.add(notes);
    return this;
  },

  notes: function (bar, beat, tick) {
    if (!bar) return this.expandedNotes.models.slice();
    var cache = this._cache;
    var beats = cache[bar];
    if (!beat) return (beats && beats['*'] || []).slice();
    var ticks = beats && beats[beat];
    if (!tick) return (ticks && ticks['*'] || []).slice();
    return (ticks && ticks[tick] || []).slice();
  },

  transforms: function (note) {
    if (!note || !(note instanceof Note)) throw new Error('Invalid argument: note is not an instance of bap.note');
    var pattern = this.collection && this.collection.parent;

    var transforms = [];
    [note, this, pattern].forEach(function (source) {
      if (source && source.transform && typeof source.transform === 'function') {
        transforms.push(source.transform);
      }
    });

    if (!transforms.length) return false;

    return function (note) {
      transforms.forEach(function (fn) {
        fn(note);
      });
    };
  },

  _onAddExpandedNote: function (note) {
    var cache = this._cache;
    var bar = note.bar;
    var beat = note.beat;
    var tick = note.tick;

    cache[bar] = cache[bar] || {};
    cache[bar]['*'] = cache[bar]['*'] || [];
    cache[bar]['*'].push(note);
    cache[bar][beat] = cache[bar][beat] || {};
    cache[bar][beat]['*'] = cache[bar][beat]['*'] || [];
    cache[bar][beat]['*'].push(note);
    cache[bar][beat][tick] = cache[bar][beat][tick] || [];
    cache[bar][beat][tick].push(note);
  },

  _onRemoveExpandedNote: function (note) {
    var cache = this._cache;
    var bar = note.bar;
    var beat = note.beat;
    var tick = note.tick;

    var barIndex = cache[bar]['*'].indexOf(note);
    cache[bar]['*'].splice(barIndex, 1);
    var beatIndex = cache[bar][beat]['*'].indexOf(note);
    cache[bar][beat]['*'].splice(beatIndex, 1);
    var tickIndex = cache[bar][beat][tick].indexOf(note);
    cache[bar][beat][tick].splice(tickIndex, 1);
  },

  _onAddRawNote: function (note) {
    var transform = this.transforms(note);

    if (note.hasPlainPosition() && !transform) {
      note.original = note;
      return this.expandedNotes.add(note);
    }

    var pattern = this.collection && this.collection.parent;
    var options = {
      barsPerLoop: pattern && pattern.bars || 1,
      beatsPerBar: pattern && pattern.beatsPerBar || 4
    };

    expressions([[note.position]], options).forEach(function (position) {
      var expanded = note.with({ position: position[0] });

      expanded.original = note;
      expanded.delegateChangeHandler = function (note) {
        var changed = Object.assign({}, note._changed);
        delete changed.position;
        delete changed.bar;
        delete changed.beat;
        delete changed.tick;
        expanded.set(changed);
      };
      note.on('change', expanded.delegateChangeHandler);

      transform && transform(expanded);
      this.expandedNotes.add(expanded);
    }.bind(this));
  },

  _onRemoveRawNote: function (note) {
    this.expandedNotes.models.slice().forEach(function (expanded) {
      if (note === expanded.original) {
        this.expandedNotes.remove(expanded);
        expanded.original.off('change', expanded.delegateChangeHandler);
        expanded.original = null;
        expanded.delegateChangeHandler = null;
      }
    }.bind(this));
  },

  _onChangeRawNote: function (note) {
    this._onRemoveRawNote(note);
    this._onAddRawNote(note);
  },

  _start: function (time, note) {
    if (!this.mute) {
      this.trigger('start', time, note, this);
    }
  },

  _stop: function (time, note) {
    this.trigger('stop', time, note, this);
  }
}, connectable);

module.exports = Channel;
<|endoftext|>


<commit_before>'use strict';

const WorldstateObject = require('./WorldstateObject.js');

/**
 * Represents a fissure mission
 * @extends {WorldstateObject}
 */
class Fissure extends WorldstateObject {
  /**
   * @param   {Object}             data            The fissure data
   * @param   {Object}             deps            The dependencies object
   * @param   {Translator}         deps.translator The string translator
   * @param   {TimeDateFunctions}  deps.timeDate   The time and date functions
   */
  constructor(data, { translator, timeDate }) {
    super(data);

    /**
     * The time and date functions
     * @type {TimeDateFunctions}
     * @private
     */
    this.timeDate = timeDate;
    Object.defineProperty(this, 'timeDate', { enumerable: false, configurable: false });

    /**
     * The node where the fissure has appeared
     * @type {string}
     */
    this.node = translator.node(data.Node);

    /**
     * The fissure mission type
     * @type {string}
     */
    this.missionType = translator.nodeMissionType(data.Node);

    /**
     * The faction controlling the node where the fissure has appeared
     * @type {string}
     */
    this.enemy = translator.nodeEnemy(data.Node);

    /**
     * The fissure's tier
     * @type {string}
     */
    this.tier = translator.fissureModifier(data.Modifier);

    /**
     * The date and time at which the fissure appeared
     * @type {Date}
     */
    this.activation = new Date(1000 * data.Activation.sec);

    /**
     * The date and time at which the fissure will disappear
     * @type {Date}
     */
    this.expiry = new Date(1000 * data.Expiry.sec);
  }

  /**
   * Get a string representation of how long the void fissure will remain active
   * @returns {string}
   */
  getETAString() {
    return this.timeDate.timeDeltaToString(this.timeDate.fromNow(this.expiry));
  }

  /**
   * Returns a string representation of the fissure
   * @returns {string}
   */
  toString() {
    return `[${this.getETAString()}] ${this.tier} fissure at ${this.node} - ${this.enemy} ${this.missionType}`;
  }
}

module.exports = Fissure;
<commit_msg>add fissure tierNum<commit_after>'use strict';

const WorldstateObject = require('./WorldstateObject.js');

/**
 * Represents a fissure mission
 * @extends {WorldstateObject}
 */
class Fissure extends WorldstateObject {
  /**
   * @param   {Object}             data            The fissure data
   * @param   {Object}             deps            The dependencies object
   * @param   {Translator}         deps.translator The string translator
   * @param   {TimeDateFunctions}  deps.timeDate   The time and date functions
   */
  constructor(data, { translator, timeDate }) {
    super(data);

    /**
     * The time and date functions
     * @type {TimeDateFunctions}
     * @private
     */
    this.timeDate = timeDate;
    Object.defineProperty(this, 'timeDate', { enumerable: false, configurable: false });

    /**
     * The node where the fissure has appeared
     * @type {string}
     */
    this.node = translator.node(data.Node);

    /**
     * The fissure mission type
     * @type {string}
     */
    this.missionType = translator.nodeMissionType(data.Node);

    /**
     * The faction controlling the node where the fissure has appeared
     * @type {string}
     */
    this.enemy = translator.nodeEnemy(data.Node);

    /**
     * The fissure's tier
     * @type {string}
     */
    this.tier = translator.fissureModifier(data.Modifier);

    /**
     * The fissure's tier as a number
     * @type {number}
     */
    this.tierNum = translator.fissureTier(data.Modifier);

    /**
     * The date and time at which the fissure appeared
     * @type {Date}
     */
    this.activation = new Date(1000 * data.Activation.sec);

    /**
     * The date and time at which the fissure will disappear
     * @type {Date}
     */
    this.expiry = new Date(1000 * data.Expiry.sec);
  }

  /**
   * Get a string representation of how long the void fissure will remain active
   * @returns {string}
   */
  getETAString() {
    return this.timeDate.timeDeltaToString(this.timeDate.fromNow(this.expiry));
  }

  /**
   * Returns a string representation of the fissure
   * @returns {string}
   */
  toString() {
    return `[${this.getETAString()}] ${this.tier} fissure at ${this.node} - ${this.enemy} ${this.missionType}`;
  }
}

module.exports = Fissure;
<|endoftext|>


<commit_before>var iopi = require("../index");
var sleep = require("sleep").sleep;
var usleep = require("sleep").usleep;
iopi.init(0x27);
class LED{
  constructor(bus,channels){
    this.bus=bus;
    this.channels=channels;
  }
  openChannel(channel){
    iopi.setPinDirection(this.bus,this.channels[channel],0);
    iopi.writePin(this.bus, this.channels[channel], 1);
  }
  closeChannel(channel){
    iopi.setPinDirection(this.bus,this.channels[channel],0);
    iopi.writePin(this.bus, this.channels[channel], 0);
  }
}
var led=new LED(0x27,{red:1,green:2,blue:3});
process.on('SIGINT', function(){
  led.closeChannel("red");
  led.closeChannel("green");
  led.closeChannel("blue");
}.bind(null, {exit:true}));

var loop=function(){
  led.openChannel("red");
  sleep(3);
  led.closeChannel("red");
  led.openChannel("green");
  sleep(3);
  led.closeChannel("green");
  led.openChannel("blue");
  sleep(3);
  led.closeChannel("blue");
  setTimeout(loop,0);
};
setTimeout(loop,0);
// iopi.setPinDirection(0x27, 1, 0x00);
// iopi.writePin(0x27, 1, 1);
// iopi.setPinDirection(0x27, 2, 0x00);
// iopi.writePin(0x27, 2, 1);
// setTimeout(() => {
//   iopi.writePin(0x27, 1, 0);
//   iopi.writePin(0x27, 2, 0);
// }, 500);
<commit_msg>fix timing and exir<commit_after>var iopi = require("../index");
var sleep = require("sleep").sleep;
var usleep = require("sleep").usleep;
iopi.init(0x27);
class LED{
  constructor(bus,channels){
    this.bus=bus;
    this.channels=channels;
  }
  openChannel(channel){
    iopi.setPinDirection(this.bus,this.channels[channel],0);
    iopi.writePin(this.bus, this.channels[channel], 1);
  }
  closeChannel(channel){
    iopi.setPinDirection(this.bus,this.channels[channel],0);
    iopi.writePin(this.bus, this.channels[channel], 0);
  }
}
var led=new LED(0x27,{red:1,green:2,blue:3});
process.on('SIGINT', function(){
  led.closeChannel("red");
  led.closeChannel("green");
  led.closeChannel("blue");
  process.exit();
}.bind(null, {exit:true}));

var loop=function(){
  led.openChannel("red");
  usleep(3000);
  led.closeChannel("red");
  led.openChannel("green");
  usleep(3000);
  led.closeChannel("green");
  led.openChannel("blue");
  usleep(3000);
  led.closeChannel("blue");
  setTimeout(loop,0);
};
setTimeout(loop,0);
// iopi.setPinDirection(0x27, 1, 0x00);
// iopi.writePin(0x27, 1, 1);
// iopi.setPinDirection(0x27, 2, 0x00);
// iopi.writePin(0x27, 2, 1);
// setTimeout(() => {
//   iopi.writePin(0x27, 1, 0);
//   iopi.writePin(0x27, 2, 0);
// }, 500);
<|endoftext|>


<commit_before>'use strict'

/**
 * Dependencies
 * @ignore
 */

/**
 * Module Dependencies
 * @ignore
 */
const Events = require('../../events')
const Manager = require('../../common/Manager')
const Game = require('./Game')

/**
 * Game Manager
 * @class
 */
class GameManager extends Manager {

  /**
   * constructor
   */
  constructor(system) {
    super(system)
  }

  static get type () {
    return Game
  }

  static get unsafeFields () {
    return ['admins']
  }

  /**
   * newGame
   *
   * @description
   *
   *
   * @param  {Object} body
   * @return {Promise<Game>}
   */
  newGame (body) {
    let { name: id } = body
    let { log } = GameManager

    return this.exists({ id }).then(exists => {
      if (exists) {
        return Promise.reject(`Game ${id} already exists`)
      }
    })
    .then(() => this.store({ id, body }))
    .then(() => new Game(this, body))
    .catch(error => Promise.reject(error))
  }

  /**
   * getGame
   *
   * @description
   *
   *
   * @param  {String}  id
   * @param  {Boolean} safe
   * @return {Promise<Game>}
   */
  getGame (id, safe=false) {
    return this.get({ id, safe })
      .then(response => Game.fromResponse(this, response))
      .catch(error => Promise.reject(error))
  }
}

/**
 * Export
 * @ignore
 */
module.exports = GameManager
<commit_msg>feat(GameManager): search for games<commit_after>'use strict'

/**
 * Dependencies
 * @ignore
 */

/**
 * Module Dependencies
 * @ignore
 */
const Events = require('../../events')
const Manager = require('../../common/Manager')
const Game = require('./Game')

/**
 * Game Manager
 * @class
 */
class GameManager extends Manager {

  /**
   * constructor
   */
  constructor(system) {
    super(system)
  }

  static get type () {
    return Game
  }

  static get unsafeFields () {
    return ['admins']
  }

  /**
   * newGame
   *
   * @description
   *
   *
   * @param  {Object} body
   * @return {Promise<Game>}
   */
  newGame (body) {
    let { name: id } = body
    let { log } = GameManager

    return this.exists({ id }).then(exists => {
      if (exists) {
        return Promise.reject(`Game ${id} already exists`)
      }
    })
    .then(() => this.store({ id, body }))
    .then(() => new Game(this, body))
    .catch(error => Promise.reject(error))
  }

  /**
   * getGame
   *
   * @description
   *
   *
   * @param  {String}  id
   * @param  {Boolean} safe
   * @return {Promise<Game>}
   */
  getGame (id, safe=false) {
    return this.get({ id, safe })
      .then(response => Game.fromResponse(this, response))
      .catch(error => Promise.reject(error))
  }

  /**
   * searchGame
   *
   * @description
   * Search for games
   *
   * @param  {Object}  query
   * @param  {Boolean} safe - include sensitive information
   * @return {Array<Game>}
   */
  searchGame (query, safe=false) {
    let { log } = GameManager

    return this.search({ query, safe })
      .then(response => Game.fromResponse(this, response))
      .catch(error => {
        log.error(error)
        return Promise.reject(error)
      })
  }
}

/**
 * Export
 * @ignore
 */
module.exports = GameManager
<|endoftext|>


<commit_before>/********************************************************
 * Metrics-Watcher
 *
 * Copyright 2012 Ben Bertola and iovation, Inc.
 *
 *******************************************************/

/**
 * Adds a Meter type graph to your page.
 * @param divId The id of the div to draw the graph in
 * @param className The class name of your metrics data, from the metrics servlet
 * @param metricName The metric name of your metrics data, from the metrics servlet
 * @param max What the max value target is, used to determine the % width of progress bars for this graph
 * @param title The user-displayed title of this graph
 */
function addMeter(divId, className, metricName, max, title){
	var metricInfo = new MetricInfo(divId, className, metricName, max, title, 'meter');
	graphs.push(metricInfo);
}

/**
 * Add a Counter graph
 * @param divId The id of the div to draw the graph in
 * @param className The class name of your metrics data, from the metrics servlet
 * @param metricName The metric name of your metrics data, from the metrics servlet
 * @param max What the max value target is, used to determine the % width of progress bars for this graph
 * @param title The user-displayed title of this graph
 */
function addCounter(divId, className, metricName, max, title){
	var metricInfo = new MetricInfo(divId, className, metricName, max, title, 'counter');
	graphs.push(metricInfo);
}

/**
 * Add a linked Counter graph.  Linked Counters differ from a plain counter graph in that both the numerator and denominator
 * of a linked counter graph each come from individual Counter Metrics.
 *
 * @param divId The id of the div to draw the graph in
 * @param className The class name of your metrics data, from the metrics servlet
 * @param metricName The metric name of your metrics data, from the metrics servlet
 * @param maxClassName
 * @param maxMetricName
 * @param title The user-displayed title of this graph
 */
function addLinkedCounter(divId, className, metricName, maxClassName, maxMetricName, title){
	var metricInfo = new MetricInfo(divId, className, metricName, null, title, 'counter');
	metricInfo.maxClassName = maxClassName;
	metricInfo.maxMetricName = maxMetricName;
	metricInfo.getMax = function(json){
		var maxNode = this.getMetricNode(this.maxClassName, this.maxMetricName, json);
		return maxNode["count"];
	};

	graphs.push(metricInfo);
}

function addTimer(divId, className, metricName, max, title, eventType, durationMax){
	var metricInfo = new MetricInfo(divId, className, metricName, max, title, 'timer');
	metricInfo.eventType = eventType;

	metricInfo.getMeterInfo = function(){

		var myDivId = this.divId + " div.timerGraph div.row div.meterGraph";
		var retVal = new MetricInfo(myDivId, this.className, this.metricName, this.max, "Frequency", 'meter');

		retVal.getMetricNode = function getMetricNode(className, metricName, jsonRoot){
			var classNode = jsonRoot[className];
			if(!classNode){
				return null;
			}
			return classNode[metricName]["rate"];
		};

		return retVal;
	};

	metricInfo.getTimerStatsDivId = function(){
		return "#" + this.divId + " div.timerGraph div.row div.timerStatsGraph";
	}

	metricInfo.getTimerHistogramDivId = function(){
		return "#" + this.divId + " div.timerGraph div.row div.timerHistogram";
	}

	metricInfo.durationMax = durationMax;

	graphs.push(metricInfo);
}

function initGraphs(){
	//draw all graphs for the first time
	for(var i = 0; i < graphs.length; i++){
		if(graphs[i].type == "meter")
			drawMeter(graphs[i]);
		else if(graphs[i].type == "counter")
			drawCounter(graphs[i]);
		else if(graphs[i].type == "timer")
			drawTimer(graphs[i]);
		else
			alert("Unknown meter info type: " + graphs[i].type);
	}

}

function updateGraphs(json){
	//draw all graphs for the first time
	for(var i = 0; i < graphs.length; i++){
		if(graphs[i].type == "meter")
			updateMeter(graphs[i], json);
		else if(graphs[i].type == "counter")
			updateCounter(graphs[i], json);
		else if(graphs[i].type == "timer")
			updateTimer(graphs[i], json);
		else
			alert("Unknown meter info type: " + graphs[i].type);
	}

}

/********************************
 * Internal Methods
 *******************************/
var graphs = new Array();

function MetricInfo(divId, className, metricName, max, title, type){
	this.divId = divId;
	this.className = className;
	this.metricName = metricName;
	this.max = max;
	this.title = title;
	this.type = type;

	this.getMax = function(json){
		return this.max;
	}

	this.getMetricNode = function getMetricNode(className, metricName, jsonRoot){
		var classNode = jsonRoot[className];
		if(!classNode){
			return null;
		}

		return classNode[metricName];
	};
}

function calculatePercentage(currentVal, maxVal){
	var p = (currentVal/maxVal) * 100;
	return p.toFixed(0);
}

function formatNumber(varNumber){
	return varNumber.toFixed(1);
}

function showMeters(){
	alert(JSON.stringify(graphs));
}

/**********************
 * Counter specific methods
 **********************/
function drawCounter(counterInfo){
	var parentDiv = $("#" + counterInfo.divId);
	var html = "

" + counterInfo.title + "

";
	parentDiv.html(html);
}

function updateCounter(counterInfo, json){
	var metricData = counterInfo.getMetricNode(counterInfo.className, counterInfo.metricName, json);
	var pct = calculatePercentage(metricData["count"], counterInfo.getMax(json));

	$("#" + counterInfo.divId + " div.progress div.bar").css("width", pct + "%");
	$("#" + counterInfo.divId + " div.progress div.bar").html(metricData["count"] + "/" + counterInfo.getMax(json));
}

/**********************
 * Timer specific methods
 **********************/
function drawTimer(timerInfo){
	var parentDiv = $("#" + timerInfo.divId);

	//set up the parent container
	var html = "

" + timerInfo.title + "

"
			+ "
meter graph
"
			+ "
timer graph
"
			+ "
timer histogram

";
	parentDiv.html(html);

	//now draw the children
	drawMeter(timerInfo.getMeterInfo());

	drawDurationStats(timerInfo);
	drawDurationHistogram(timerInfo);
}

function drawDurationStats(timerInfo){
	var html = "
Recent Duration

";
	html += addMeterRow( "Min", "min");
	html += addMeterRow( "Mean", "mean");
	html += addMeterRow( "Median", "median");
	html += addMeterRow( "Max", "max");
	html += addMeterRow( "Std Dev", "std_dev");
	html += "

";
	var parentDiv = $(timerInfo.getTimerStatsDivId());
	parentDiv.html(html);
}

function drawDurationHistogram(timerInfo){
	var html = "
Histogram

";
	html += addMeterRow( "99.9%", "p999");
	html += addMeterRow( "99%", "p99");
	html += addMeterRow( "98%", "p98");
	html += addMeterRow( "95%", "p95");
	html += addMeterRow( "75%", "p75");
	html += "

";
	var parentDiv = $(timerInfo.getTimerHistogramDivId());
	parentDiv.html(html);
}

function updateTimer(timerInfo, json){
	//update the meter info for the meter
	updateMeter(timerInfo.getMeterInfo(), json);
	updateDurationStats(timerInfo, json);
	updateDurationHistogram(timerInfo, json);
}

function updateDurationStats(timerInfo, json){
	//get data node
	var metricData = timerInfo.getMetricNode(timerInfo.className, timerInfo.metricName, json)["duration"];

	var timeUnitDiv = $(timerInfo.getTimerStatsDivId() + " p");
	timeUnitDiv.html("(" + metricData["unit"] + ")");

	updateDuration(timerInfo.getTimerStatsDivId(), metricData, "min", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerStatsDivId(), metricData, "mean", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerStatsDivId(), metricData, "median", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerStatsDivId(), metricData, "max", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerStatsDivId(), metricData, "std_dev", timerInfo.durationMax);

}

function updateDuration(timerStatsDivId, durationData, style, max){
	$(timerStatsDivId + " tr." + style + " td.progressValue").html(formatNumber(durationData[style]));
	$(timerStatsDivId + " tr." + style + " td.progressBar div.progress div.bar").css("width", calculatePercentage(durationData[style], max) + "%");
	//$("#" + meterInfo.divId + " tr." + rowStyle + " td.progressBar div.progress div.bar").css("width", calculatePercentage(meterData[rowType], meterInfo.max) + "%");
}

function updateDurationHistogram(timerInfo, json){
	var metricData = timerInfo.getMetricNode(timerInfo.className, timerInfo.metricName, json)["duration"];

	updateDuration(timerInfo.getTimerHistogramDivId(), metricData, "p999", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerHistogramDivId(), metricData, "p99", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerHistogramDivId(), metricData, "p98", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerHistogramDivId(), metricData, "p95", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerHistogramDivId(), metricData, "p75", timerInfo.durationMax);

}

/************************************************
 * Meter specific methods
 ***********************************************/

/**
 * Draws a meter for the first time.
 * @param meterInfo
 */
function drawMeter(meterInfo){
	var parentDiv = $("#" + meterInfo.divId);

	var html = "

" + meterInfo.title + "

";
	html += addMeterRow("1 min", "onemin");
	html += addMeterRow("5 min", "fivemin");
	html += addMeterRow("15 min", "fifteenmin");
	html += addMeterRow("Mean", "mean");

	html += "

";
	parentDiv.html(html);
}

function addMeterRow(type, className){
	var retVal = "
" + type + "	"
	+ "

"
	+ "
	0
";

	return retVal;
}

function updateMeter(meterInfo, json){
	var metricData = meterInfo.getMetricNode(meterInfo.className, meterInfo.metricName, json);
	if(metricData){
		updateMeterData(meterInfo, metricData);
	}
}

function updateMeterData(meterInfo, meterData){
	//set the big counter
	var gaugeDiv = $("#" + meterInfo.divId + " h1");
	gaugeDiv.html(formatNumber(meterData["m1"]));

	//and the {whats}/{time unit} value
	var eventType = meterInfo.eventType;
	if(!eventType)
		eventType = meterData["event_type"];

	var dispVal = eventType + "/" + meterData["unit"] + " (1 min)
" + meterData["count"] + " Total";
	$("#" + meterInfo.divId + " p").html(dispVal);

	//set the mean count
	setMeterRow(meterInfo, meterData, "mean", "mean");
	setMeterRow(meterInfo, meterData, "m1", "onemin");
	setMeterRow(meterInfo, meterData, "m5", "fivemin");
	setMeterRow(meterInfo, meterData, "m15", "fifteenmin");
}

function setMeterRow(meterInfo, meterData, rowType, rowStyle){
	$("#" + meterInfo.divId + " tr." + rowStyle + " td.progressValue").html(formatNumber(meterData[rowType]));
	$("#" + meterInfo.divId + " tr." + rowStyle + " td.progressBar div.progress div.bar").css("width", calculatePercentage(meterData[rowType], meterInfo.max) + "%");

}

<commit_msg>Finished public API documentation<commit_after>/********************************************************
 * Metrics-Watcher
 *
 * Copyright 2012 Ben Bertola and iovation, Inc.
 *
 * To use this library:
 * 1.  Call addXXX() for each graph you want on your page
 * 2.  Call initGraphs() once to draw the initial graphs
 * 3.  Call updateGraphs(jsonData) with the JSON data from your metrics/servlet as often as you would like your graphs to update.
 *
 *******************************************************/

/**
 * Adds a Meter type graph to your page.
 * @param divId The id of the div to draw the graph in
 * @param className The class name of your metrics data, from the metrics servlet
 * @param metricName The metric name of your metrics data, from the metrics servlet
 * @param max What the max value target is, used to determine the % width of progress bars for this graph
 * @param title The user-displayed title of this graph
 */
function addMeter(divId, className, metricName, max, title){
	var metricInfo = new MetricInfo(divId, className, metricName, max, title, 'meter');
	graphs.push(metricInfo);
}

/**
 * Add a Counter graph
 * @param divId The id of the div to draw the graph in
 * @param className The class name of your metrics data, from the metrics servlet
 * @param metricName The metric name of your metrics data, from the metrics servlet
 * @param max What the max value target is, used to determine the % width of progress bars for this graph
 * @param title The user-displayed title of this graph
 */
function addCounter(divId, className, metricName, max, title){
	var metricInfo = new MetricInfo(divId, className, metricName, max, title, 'counter');
	graphs.push(metricInfo);
}

/**
 * Add a linked Counter graph.  Linked Counters differ from a plain counter graph in that both the numerator and denominator
 * of a linked counter graph each come from individual Counter Metrics.
 *
 * @param divId The id of the div to draw the graph in
 * @param className The class name of your metrics data, from the metrics servlet
 * @param metricName The metric name of your metrics data, from the metrics servlet
 * @param maxClassName
 * @param maxMetricName
 * @param title The user-displayed title of this graph
 */
function addLinkedCounter(divId, className, metricName, maxClassName, maxMetricName, title){
	var metricInfo = new MetricInfo(divId, className, metricName, null, title, 'counter');
	metricInfo.maxClassName = maxClassName;
	metricInfo.maxMetricName = maxMetricName;
	metricInfo.getMax = function(json){
		var maxNode = this.getMetricNode(this.maxClassName, this.maxMetricName, json);
		return maxNode["count"];
	};

	graphs.push(metricInfo);
}

/**
 * Add a Timer graph.  This will include a Meter, Timing Info, and a Histogram.
 *
 * @param divId The id of the div to draw the graph in
 * @param className The class name of your metrics data, from the metrics servlet
 * @param metricName The metric name of your metrics data, from the metrics servlet
 * @param max The max target value for the Meter, showing frequency
 * @param title The user-displayed title of this graph
 * @param eventType a name for this event type
 * @param durationMax The max target value for duration
 */
function addTimer(divId, className, metricName, max, title, eventType, durationMax){
	var metricInfo = new MetricInfo(divId, className, metricName, max, title, 'timer');
	metricInfo.eventType = eventType;

	metricInfo.getMeterInfo = function(){

		var myDivId = this.divId + " div.timerGraph div.row div.meterGraph";
		var retVal = new MetricInfo(myDivId, this.className, this.metricName, this.max, "Frequency", 'meter');

		retVal.getMetricNode = function getMetricNode(className, metricName, jsonRoot){
			var classNode = jsonRoot[className];
			if(!classNode){
				return null;
			}
			return classNode[metricName]["rate"];
		};

		return retVal;
	};

	metricInfo.getTimerStatsDivId = function(){
		return "#" + this.divId + " div.timerGraph div.row div.timerStatsGraph";
	}

	metricInfo.getTimerHistogramDivId = function(){
		return "#" + this.divId + " div.timerGraph div.row div.timerHistogram";
	}

	metricInfo.durationMax = durationMax;

	graphs.push(metricInfo);
}

/**
 * Initialized each of the graphs that you have added through addXXX() calls, and draws them on the screen for the first time
 */
function initGraphs(){
	//draw all graphs for the first time
	for(var i = 0; i < graphs.length; i++){
		if(graphs[i].type == "meter")
			drawMeter(graphs[i]);
		else if(graphs[i].type == "counter")
			drawCounter(graphs[i]);
		else if(graphs[i].type == "timer")
			drawTimer(graphs[i]);
		else
			alert("Unknown meter info type: " + graphs[i].type);
	}

}

/**
 * Update the existing graphs with new data.  You can call this method as frequently as you would like to, and all graph info will be updated.
 *
 * @param json The root of the json node returned from your ajax call to the metrics servlet
 */
function updateGraphs(json){
	//draw all graphs for the first time
	for(var i = 0; i < graphs.length; i++){
		if(graphs[i].type == "meter")
			updateMeter(graphs[i], json);
		else if(graphs[i].type == "counter")
			updateCounter(graphs[i], json);
		else if(graphs[i].type == "timer")
			updateTimer(graphs[i], json);
		else
			alert("Unknown meter info type: " + graphs[i].type);
	}

}

/********************************
 * Internal Methods
 *******************************/
var graphs = new Array();

function MetricInfo(divId, className, metricName, max, title, type){
	this.divId = divId;
	this.className = className;
	this.metricName = metricName;
	this.max = max;
	this.title = title;
	this.type = type;

	this.getMax = function(json){
		return this.max;
	}

	this.getMetricNode = function getMetricNode(className, metricName, jsonRoot){
		var classNode = jsonRoot[className];
		if(!classNode){
			return null;
		}

		return classNode[metricName];
	};
}

function calculatePercentage(currentVal, maxVal){
	var p = (currentVal/maxVal) * 100;
	return p.toFixed(0);
}

function formatNumber(varNumber){
	return varNumber.toFixed(1);
}

function showMeters(){
	alert(JSON.stringify(graphs));
}

/**********************
 * Counter specific methods
 **********************/
function drawCounter(counterInfo){
	var parentDiv = $("#" + counterInfo.divId);
	var html = "

" + counterInfo.title + "

";
	parentDiv.html(html);
}

function updateCounter(counterInfo, json){
	var metricData = counterInfo.getMetricNode(counterInfo.className, counterInfo.metricName, json);
	var pct = calculatePercentage(metricData["count"], counterInfo.getMax(json));

	$("#" + counterInfo.divId + " div.progress div.bar").css("width", pct + "%");
	$("#" + counterInfo.divId + " div.progress div.bar").html(metricData["count"] + "/" + counterInfo.getMax(json));
}

/**********************
 * Timer specific methods
 **********************/
function drawTimer(timerInfo){
	var parentDiv = $("#" + timerInfo.divId);

	//set up the parent container
	var html = "

" + timerInfo.title + "

"
			+ "
meter graph
"
			+ "
timer graph
"
			+ "
timer histogram

";
	parentDiv.html(html);

	//now draw the children
	drawMeter(timerInfo.getMeterInfo());

	drawDurationStats(timerInfo);
	drawDurationHistogram(timerInfo);
}

function drawDurationStats(timerInfo){
	var html = "
Recent Duration

";
	html += addMeterRow( "Min", "min");
	html += addMeterRow( "Mean", "mean");
	html += addMeterRow( "Median", "median");
	html += addMeterRow( "Max", "max");
	html += addMeterRow( "Std Dev", "std_dev");
	html += "

";
	var parentDiv = $(timerInfo.getTimerStatsDivId());
	parentDiv.html(html);
}

function drawDurationHistogram(timerInfo){
	var html = "
Histogram

";
	html += addMeterRow( "99.9%", "p999");
	html += addMeterRow( "99%", "p99");
	html += addMeterRow( "98%", "p98");
	html += addMeterRow( "95%", "p95");
	html += addMeterRow( "75%", "p75");
	html += "

";
	var parentDiv = $(timerInfo.getTimerHistogramDivId());
	parentDiv.html(html);
}

function updateTimer(timerInfo, json){
	//update the meter info for the meter
	updateMeter(timerInfo.getMeterInfo(), json);
	updateDurationStats(timerInfo, json);
	updateDurationHistogram(timerInfo, json);
}

function updateDurationStats(timerInfo, json){
	//get data node
	var metricData = timerInfo.getMetricNode(timerInfo.className, timerInfo.metricName, json)["duration"];

	var timeUnitDiv = $(timerInfo.getTimerStatsDivId() + " p");
	timeUnitDiv.html("(" + metricData["unit"] + ")");

	updateDuration(timerInfo.getTimerStatsDivId(), metricData, "min", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerStatsDivId(), metricData, "mean", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerStatsDivId(), metricData, "median", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerStatsDivId(), metricData, "max", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerStatsDivId(), metricData, "std_dev", timerInfo.durationMax);

}

function updateDuration(timerStatsDivId, durationData, style, max){
	$(timerStatsDivId + " tr." + style + " td.progressValue").html(formatNumber(durationData[style]));
	$(timerStatsDivId + " tr." + style + " td.progressBar div.progress div.bar").css("width", calculatePercentage(durationData[style], max) + "%");
}

function updateDurationHistogram(timerInfo, json){
	var metricData = timerInfo.getMetricNode(timerInfo.className, timerInfo.metricName, json)["duration"];

	updateDuration(timerInfo.getTimerHistogramDivId(), metricData, "p999", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerHistogramDivId(), metricData, "p99", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerHistogramDivId(), metricData, "p98", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerHistogramDivId(), metricData, "p95", timerInfo.durationMax);
	updateDuration(timerInfo.getTimerHistogramDivId(), metricData, "p75", timerInfo.durationMax);

}

/************************************************
 * Meter specific methods
 ***********************************************/

/**
 * Draws a meter for the first time.
 * @param meterInfo
 */
function drawMeter(meterInfo){
	var parentDiv = $("#" + meterInfo.divId);

	var html = "

" + meterInfo.title + "

";
	html += addMeterRow("1 min", "onemin");
	html += addMeterRow("5 min", "fivemin");
	html += addMeterRow("15 min", "fifteenmin");
	html += addMeterRow("Mean", "mean");

	html += "

";
	parentDiv.html(html);
}

function addMeterRow(type, className){
	var retVal = "
" + type + "	"
	+ "

"
	+ "
	0
";

	return retVal;
}

function updateMeter(meterInfo, json){
	var metricData = meterInfo.getMetricNode(meterInfo.className, meterInfo.metricName, json);
	if(metricData){
		updateMeterData(meterInfo, metricData);
	}
}

function updateMeterData(meterInfo, meterData){
	//set the big counter
	var gaugeDiv = $("#" + meterInfo.divId + " h1");
	gaugeDiv.html(formatNumber(meterData["m1"]));

	//and the {whats}/{time unit} value
	var eventType = meterInfo.eventType;
	if(!eventType)
		eventType = meterData["event_type"];

	var dispVal = eventType + "/" + meterData["unit"] + " (1 min)
" + meterData["count"] + " Total";
	$("#" + meterInfo.divId + " p").html(dispVal);

	//set the mean count
	setMeterRow(meterInfo, meterData, "mean", "mean");
	setMeterRow(meterInfo, meterData, "m1", "onemin");
	setMeterRow(meterInfo, meterData, "m5", "fivemin");
	setMeterRow(meterInfo, meterData, "m15", "fifteenmin");
}

function setMeterRow(meterInfo, meterData, rowType, rowStyle){
	$("#" + meterInfo.divId + " tr." + rowStyle + " td.progressValue").html(formatNumber(meterData[rowType]));
	$("#" + meterInfo.divId + " tr." + rowStyle + " td.progressBar div.progress div.bar").css("width", calculatePercentage(meterData[rowType], meterInfo.max) + "%");

}

<|endoftext|>


<commit_before>/**
 * Copyright 2018 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

const url = require('url');
const punycode = require('punycode');
const mime = require('mime-types');

/**
 * Translates the canonicalUrl to the AMP Cache equivalent, for a given AMP Cache.
 * @param {string} domainSuffix the AMP Cache domain suffix
 * @param {string} url the canonical URL
 */
function createCacheUrl(domainSuffix, url) {
  const cacheUrl = new url.URL(url);
  const originalHostname = cacheUrl.hostname;
  let unicodeHostname = punycode.toUnicode(originalHostname);
  unicodeHostname = unicodeHostname.replace(/-/g, '--');
  unicodeHostname = unicodeHostname.replace(/\./g, '-');

  let pathSegment = _getResourcePath(cacheUrl.pathname);
  pathSegment += cacheUrl.protocol === 'https:' ? '/s/' : '/';

  cacheUrl.protocol = 'https';
  cacheUrl.hostname = punycode.toASCII(unicodeHostname) + '.' + domainSuffix;
  cacheUrl.pathname = pathSegment + originalHostname + cacheUrl.pathname;
  return cacheUrl.toString();
}

/**
 * Returns the AMP Cache path, based on the mime type of the file that is being loaded.
 * @param {string} pathname the pathname on the canonical url.
 */
function _getResourcePath(pathname) {
  const mimetype = mime.lookup(pathname);
  if (!mimetype) {
    return '/c';
  }

  if (mimetype.indexOf('image/') === 0) {
    return '/i';
  }

  if (mimetype.indexOf('font') >= 0) {
    return '/r';
  }

  // Default to document
  return '/c';
}

/** @module AmpUrl */
module.exports = createCacheUrl;
<commit_msg>Fixed tests for Url<commit_after>/**
 * Copyright 2018 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

const Url = require('url').URL;
const punycode = require('punycode');
const mime = require('mime-types');

/**
 * Translates the canonicalUrl to the AMP Cache equivalent, for a given AMP Cache.
 * @param {string} domainSuffix the AMP Cache domain suffix
 * @param {string} url the canonical URL
 */
function createCacheUrl(domainSuffix, url) {
  const cacheUrl = new Url(url);
  const originalHostname = cacheUrl.hostname;
  let unicodeHostname = punycode.toUnicode(originalHostname);
  unicodeHostname = unicodeHostname.replace(/-/g, '--');
  unicodeHostname = unicodeHostname.replace(/\./g, '-');

  let pathSegment = _getResourcePath(cacheUrl.pathname);
  pathSegment += cacheUrl.protocol === 'https:' ? '/s/' : '/';

  cacheUrl.protocol = 'https';
  cacheUrl.hostname = punycode.toASCII(unicodeHostname) + '.' + domainSuffix;
  cacheUrl.pathname = pathSegment + originalHostname + cacheUrl.pathname;
  return cacheUrl.toString();
}

/**
 * Returns the AMP Cache path, based on the mime type of the file that is being loaded.
 * @param {string} pathname the pathname on the canonical url.
 */
function _getResourcePath(pathname) {
  const mimetype = mime.lookup(pathname);
  if (!mimetype) {
    return '/c';
  }

  if (mimetype.indexOf('image/') === 0) {
    return '/i';
  }

  if (mimetype.indexOf('font') >= 0) {
    return '/r';
  }

  // Default to document
  return '/c';
}

/** @module AmpUrl */
module.exports = createCacheUrl;
<|endoftext|>


<commit_before>let commander = require("commander");
let readdir   = require("fs-readdir-recursive");
let index     = require("./index");
let babel     = require("babel-core");
let util      = require("babel-core").util;
let path      = require("path");
let fs        = require("fs");
let _         = require("lodash");

export function chmod(src, dest) {
  fs.chmodSync(dest, fs.statSync(src).mode);
}

export function readdirFilter(filename) {
  return readdir(filename).filter(function (filename) {
    return util.canCompile(filename);
  });
}

export { readdir };

export let canCompile = util.canCompile;

export function shouldIgnore(loc) {
  return util.shouldIgnore(loc, index.opts.ignore, index.opts.only);
}

export function addSourceMappingUrl(code, loc) {
  return code + "\n//# sourceMappingURL=" + path.basename(loc);
}

export function log(msg) {
  if (!commander.quiet) console.log(msg);
}

export function transform(filename, code, opts) {
  opts = _.defaults(opts || {}, index.opts);
  opts.filename = filename;
  opts.ignore = null;
  opts.only = null;

  let result = babel.transform(code, opts);
  result.filename = filename;
  result.actual = code;
  return result;
}

export function compile(filename, opts) {
  try {
    let code = fs.readFileSync(filename, "utf8");
    return transform(filename, code, opts);
  } catch (err) {
    if (commander.watch) {
      console.error(toErrorStack(err));
      return { ignored: true };
    } else {
      throw err;
    }
  }
}

function toErrorStack(err) {
  if (err._babel && err instanceof SyntaxError) {
    return `${err.name}: ${err.message}\n${err.codeFrame}`;
  } else {
    return err.stack;
  }
}

process.on("uncaughtException", function (err) {
  console.error(toErrorStack(err));
  process.exit(1);
});

export function requireChokidar() {
  try {
    return require("chokidar");
  } catch (err) {
    console.error(
      "The optional dependency chokidar failed to install and is required for " +
      "--watch. Chokidar is likely not supported on your platform."
    );
    throw err;
  }
}
<commit_msg>Fixes #6726 ignore config option (#3644)<commit_after>let commander = require("commander");
let readdir   = require("fs-readdir-recursive");
let index     = require("./index");
let babel     = require("babel-core");
let util      = require("babel-core").util;
let path      = require("path");
let fs        = require("fs");
let _         = require("lodash");

export function chmod(src, dest) {
  fs.chmodSync(dest, fs.statSync(src).mode);
}

export function readdirFilter(filename) {
  return readdir(filename).filter(function (filename) {
    return util.canCompile(filename);
  });
}

export { readdir };

export let canCompile = util.canCompile;

export function shouldIgnore(loc) {
  return util.shouldIgnore(loc, index.opts.ignore, index.opts.only);
}

export function addSourceMappingUrl(code, loc) {
  return code + "\n//# sourceMappingURL=" + path.basename(loc);
}

export function log(msg) {
  if (!commander.quiet) console.log(msg);
}

export function transform(filename, code, opts) {
  opts = _.defaults(opts || {}, index.opts);
  opts.filename = filename;

  let result = babel.transform(code, opts);
  result.filename = filename;
  result.actual = code;
  return result;
}

export function compile(filename, opts) {
  try {
    let code = fs.readFileSync(filename, "utf8");
    return transform(filename, code, opts);
  } catch (err) {
    if (commander.watch) {
      console.error(toErrorStack(err));
      return { ignored: true };
    } else {
      throw err;
    }
  }
}

function toErrorStack(err) {
  if (err._babel && err instanceof SyntaxError) {
    return `${err.name}: ${err.message}\n${err.codeFrame}`;
  } else {
    return err.stack;
  }
}

process.on("uncaughtException", function (err) {
  console.error(toErrorStack(err));
  process.exit(1);
});

export function requireChokidar() {
  try {
    return require("chokidar");
  } catch (err) {
    console.error(
      "The optional dependency chokidar failed to install and is required for " +
      "--watch. Chokidar is likely not supported on your platform."
    );
    throw err;
  }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Link, withRouter } from 'olymp-router';
import { Dropdown, Menu, Icon, Button, Tabs } from 'antd';
import { Image } from 'olymp-cloudinary';
import { get } from 'lodash';
import { Sidebar, List } from 'olymp-ui';
import { FieldValue } from '../components';

const states = {
  PUBLISHED: 'Öffentlich',
  DRAFT: 'Ablage',
  REMOVED: 'Papierkorb',
};

@withRouter
export default class CollectionListSidebar extends Component {
  getLink = ({ id }) => {
    const { typeName, location } = this.props;
    const { pathname } = location;

    return {
      pathname,
      query: { ...location.query, [`@${typeName.toLowerCase()}`]: id },
    };
  };

  resolveFieldValue = (
    item,
    field,
    { defaultFieldName, defaultValue },
    fieldProps
  ) => {
    const fieldName = this.resolveFieldName(item, field, defaultFieldName);
    const meta = this.resolveField(fieldName);

    // Wenn Feld ein Range ist
    const startField = this.resolveFieldName(item, 'start');
    const endField = this.resolveFieldName(item, 'end');
    if (startField && endField && fieldName === startField) {
      const start = !!item[startField] && (
        <FieldValue
          value={item[startField]}
          meta={meta}
          fieldProps={fieldProps}
        />
      );
      const end = !!item[endField] && (
        <FieldValue
          value={item[endField]}
          meta={meta}
          fieldProps={fieldProps}
        />
      );

      if (start && end) {
        return (

            {start} bis

            {end}

        );
      } else if (start) {
        return Ab {start};
      }
      if (end) {
        return Bis {end};
      }
    }

    return (
      <FieldValue
        value={item[fieldName] || defaultValue}
        meta={meta}
        fieldProps={fieldProps}
      />
    );
  };

  resolveFieldName = (item, field, defaultFieldName) => {
    const { collection } = this.props;
    const { specialFields } = collection;

    return (
      (!!specialFields[field] && specialFields[field].field) || defaultFieldName
    );
  };

  resolveField = fieldName => {
    const { collection } = this.props;
    const { fields } = collection;

    return fields.find(x => x.name === fieldName);
  };

  renderMenu = ({ id, state }) => (
    <Menu>
      <Menu.Item>
        <Link to={this.getLink({ id })}>Bearbeiten</Link>
      </Menu.Item>
      <Menu.Item disabled>Kopieren</Menu.Item>
      <Menu.Item disabled>
        {state !== 'REMOVED' ? 'Löschen' : 'Wiederherstellen'}
      </Menu.Item>
    </Menu>
  );

  render() {
    const {
      router,
      id,
      pathname,
      query,
      collection,
      onSearch,
      searchText,
      onClose,
    } = this.props;

    const items = (this.props.items || []).map(item => {
      const name = this.resolveFieldValue(item, 'name', {
        defaultFieldName: 'name',
        defaultValue: item.kurz || item.name || 'Kein Titel',
      });
      const description = this.resolveFieldValue(item, 'description', {});
      const image = item[this.resolveFieldName(item, 'image', 'bild')];
      const color =
        (collection.specialFields &&
          collection.specialFields.color &&
          !!item[collection.specialFields.color.field] &&
          collection.specialFields.color.arg0) ||
        item[this.resolveFieldName(item, 'color', 'color')];

      return {
        item,
        id: item.id,
        name,
        description,
        image,
        color,
        extra: (
          <Dropdown overlay={this.renderMenu(item)}>
            <Icon type="edit" />
          </Dropdown>
        ),
        isActive: item.id === id,
        onClick: () => router.push(this.getLink(item)),
      };
    });

    const childs = items.map(item => (
      <List.Item
        image={
          (item.image || item.bild) && (
            <Image value={item.image || item.bild} width={37} height={37} />
          )
        }
        description={
          item.item[get(collection, 'specialFields.description.field', '')]
        }
        color={item.color}
        active={item.id === id}
        label={item.name}
        onClick={item.onClick}
        key={item.id}
      />
    ));

    console.log(collection);

    return (
      <Sidebar
        header={
          <List.Filter
            placeholder="Filter ..."
            onChange={onSearch}
            value={searchText}
          />
        }
        rightButtons={
          <Sidebar.Button
            onClick={() => router.push(this.getLink({ id: null }))}
            shape="circle"
            icon="plus"
          />
        }
        isOpen
        padding={0}
        title={collection.name}
      >
        {!searchText ? (
          <Tabs
            size="small"
            defaultActiveKey={query.state || 'PUBLISHED'}
            onChange={state =>
              router.push({ pathname, query: { ...query, state } })}
          >
            {Object.keys(states).map(key => (
              <Tabs.TabPane tab={states[key]} key={key}>
                {childs}
              </Tabs.TabPane>
            ))}
          </Tabs>
        ) : (
          childs
        )}
      </Sidebar>
    );
  }
}
<commit_msg>delete console.log<commit_after>import React, { Component } from 'react';
import { Link, withRouter } from 'olymp-router';
import { Dropdown, Menu, Icon, Button, Tabs } from 'antd';
import { Image } from 'olymp-cloudinary';
import { get } from 'lodash';
import { Sidebar, List } from 'olymp-ui';
import { FieldValue } from '../components';

const states = {
  PUBLISHED: 'Öffentlich',
  DRAFT: 'Ablage',
  REMOVED: 'Papierkorb',
};

@withRouter
export default class CollectionListSidebar extends Component {
  getLink = ({ id }) => {
    const { typeName, location } = this.props;
    const { pathname } = location;

    return {
      pathname,
      query: { ...location.query, [`@${typeName.toLowerCase()}`]: id },
    };
  };

  resolveFieldValue = (
    item,
    field,
    { defaultFieldName, defaultValue },
    fieldProps,
  ) => {
    const fieldName = this.resolveFieldName(item, field, defaultFieldName);
    const meta = this.resolveField(fieldName);

    // Wenn Feld ein Range ist
    const startField = this.resolveFieldName(item, 'start');
    const endField = this.resolveFieldName(item, 'end');
    if (startField && endField && fieldName === startField) {
      const start = !!item[startField] && (
        <FieldValue
          value={item[startField]}
          meta={meta}
          fieldProps={fieldProps}
        />
      );
      const end = !!item[endField] && (
        <FieldValue
          value={item[endField]}
          meta={meta}
          fieldProps={fieldProps}
        />
      );

      if (start && end) {
        return (

            {start} bis

            {end}

        );
      } else if (start) {
        return Ab {start};
      }
      if (end) {
        return Bis {end};
      }
    }

    return (
      <FieldValue
        value={item[fieldName] || defaultValue}
        meta={meta}
        fieldProps={fieldProps}
      />
    );
  };

  resolveFieldName = (item, field, defaultFieldName) => {
    const { collection } = this.props;
    const { specialFields } = collection;

    return (
      (!!specialFields[field] && specialFields[field].field) || defaultFieldName
    );
  };

  resolveField = fieldName => {
    const { collection } = this.props;
    const { fields } = collection;

    return fields.find(x => x.name === fieldName);
  };

  renderMenu = ({ id, state }) => (
    <Menu>
      <Menu.Item>
        <Link to={this.getLink({ id })}>Bearbeiten</Link>
      </Menu.Item>
      <Menu.Item disabled>Kopieren</Menu.Item>
      <Menu.Item disabled>
        {state !== 'REMOVED' ? 'Löschen' : 'Wiederherstellen'}
      </Menu.Item>
    </Menu>
  );

  render() {
    const {
      router,
      id,
      pathname,
      query,
      collection,
      onSearch,
      searchText,
      onClose,
    } = this.props;

    const items = (this.props.items || []).map(item => {
      const name = this.resolveFieldValue(item, 'name', {
        defaultFieldName: 'name',
        defaultValue: item.kurz || item.name || 'Kein Titel',
      });
      const description = this.resolveFieldValue(item, 'description', {});
      const image = item[this.resolveFieldName(item, 'image', 'bild')];
      const color =
        (collection.specialFields &&
          collection.specialFields.color &&
          !!item[collection.specialFields.color.field] &&
          collection.specialFields.color.arg0) ||
        item[this.resolveFieldName(item, 'color', 'color')];

      return {
        item,
        id: item.id,
        name,
        description,
        image,
        color,
        extra: (
          <Dropdown overlay={this.renderMenu(item)}>
            <Icon type="edit" />
          </Dropdown>
        ),
        isActive: item.id === id,
        onClick: () => router.push(this.getLink(item)),
      };
    });

    const childs = items.map(item => (
      <List.Item
        image={
          (item.image || item.bild) && (
            <Image value={item.image || item.bild} width={37} height={37} />
          )
        }
        description={
          item.item[get(collection, 'specialFields.description.field', '')]
        }
        color={item.color}
        active={item.id === id}
        label={item.name}
        onClick={item.onClick}
        key={item.id}
      />
    ));

    return (
      <Sidebar
        header={
          <List.Filter
            placeholder="Filter ..."
            onChange={onSearch}
            value={searchText}
          />
        }
        rightButtons={
          <Sidebar.Button
            onClick={() => router.push(this.getLink({ id: null }))}
            shape="circle"
            icon="plus"
          />
        }
        isOpen
        padding={0}
        title={collection.name}
      >
        {!searchText ? (
          <Tabs
            size="small"
            defaultActiveKey={query.state || 'PUBLISHED'}
            onChange={state =>
              router.push({ pathname, query: { ...query, state } })}
          >
            {Object.keys(states).map(key => (
              <Tabs.TabPane tab={states[key]} key={key}>
                {childs}
              </Tabs.TabPane>
            ))}
          </Tabs>
        ) : (
          childs
        )}
      </Sidebar>
    );
  }
}
<|endoftext|>


<commit_before>active_play=0;
buildpage_running = 0;
currently_playing=0;
last_call = 0;
page_title = 'ScanOC';
first_load = 1;
first_play = 1;
seen = [];
curr_id_list = [];
curr_file_list = [];
curr_tg_list = [];
var force_page_rebuild = 0;
var base_api_url = "/api_v1/";
//var url_params = document.location.search
//var api_url = base_api_url + "/scanlist/default/";
//var pathArray = window.location.pathname.split( '/' );
// leading slash (/) causes a blank first object
//pathArray.shift();
//api_url = base_api_url + pathArray.join('/');
//if(url_params) {
//  api_url = api_url + url_params
//
var api_url = null;
var url_params = null;

var buildpage_running = 0;

function update_scan_list() {
    start_socket();
    buildpage();
}

function update_api_url() {
    url_params = document.location.search
    pathArray = window.location.pathname.split( '/' );
    pathArray.shift();
    console.log("url build");
    if(pathArray[0] == "userscan") {
        // Build TGs from select box
        console.log("In userscan url build");
        tg_array = $('.tg-multi-select').select2("val")
        if(tg_array) {
          api_url = base_api_url + "tg/" + tg_array.join('+');
          console.log("New API url " + api_url)
        } else {
          api_url = null;
        }
    } else {
        api_url = base_api_url + pathArray.join('/');
    }
    if(api_url && url_params) {
        api_url = api_url + url_params
    }
    //start_socket(); // reconnect with new talkgroups
}

function url_change(new_url) {
    clearpage();
    // Simple funcation to change url and rebuild the page
    var stateObj = { foo: "bar" };
    window.history.pushState(stateObj, "ScanOC.com", new_url);
    //window.history.pushState(.object or string., .Title., ./new-url.);
    $("#jquery_jplayer_1").jPlayer("stop");
    force_page_rebuild = 1;
    first_load = 1;
    first_play = 1;
    buildpage();
    return false;
}

function clearpage() {
    if(buildpage_running == 1) {
       return false;
    }
    $('#main-data-table').html("");
}

function buildpage() {
    console.log("In build page running : " + buildpage_running);
    if(buildpage_running == 1) {
       return false;
    }
    buildpage_running = 1;
    update_api_url();
    if( ! api_url) {
        buildpage_running = 0;
        return false;
    }
    $.getJSON(api_url, function(data) {
      //console.log(data);
      //console.log("Checking for new calls")
      //console.log("Last Call " + last_call + " New last " + data.results[0].pk)
      if (data.results[0].pk != last_call || force_page_rebuild == 1) {
      console.log("Rebuild");
      force_page_rebuild = 0;
      var new_html = '

 \

 	TalkGroup	Description	Start Time

';
      new_id_list = []
      new_file_list = []
      new_tg_list = []
      for (var a in data.results) {
          new_id_list.unshift(data.results[a].pk);
          new_file_list.unshift(data.results[a].audio_file);
          new_tg_list.unshift(data.results[a].tg_name);
          button_type = "btn-default";
          if(currently_playing == data.results[a].pk) {
              console.log("Match on " + currently_playing)
              button_type = "btn-success"
          }
	  new_html += '
<button id="button_' + data.results[a].pk + '" type="button" class="btn play-btn ' + button_type + ' btn-sm" onclick="click_play_clip(\'//s3.amazonaws.com/scanoc-audio-001/' + data.results[a].audio_file + '\', ' + data.results[a].pk + ')"> Play </button>	  ' + data.results[a].talkgroup_info.alpha_tag + '	' + data.results[a].talkgroup_info.description + '	' + data.results[a].local_start_datetime + '
';
          new_html += '
' + data.results[a].print_play_length + '	Units: ';
          for (unit in data.results[a].units) {
              if(data.results[a].units[unit].description) {
                  new_html += data.results[a].units[unit].description + ', ';
              } else {
                  if(js_logged_in_edit_units) {
                      new_html += '?' + data.results[a].units[unit].dec_id + ', ';
                  } else {
                      new_html += '?' + data.results[a].units[unit].dec_id + ', ';
                  }
              }
          }
          // Drop last ,
          new_html = new_html.slice(0, -2);
          new_html += '
';
      }
      curr_id_list = new_id_list;
      curr_file_list = new_file_list;
      curr_tg_list = new_tg_list;
      new_html += '
';
      $('#main-data-table').html(new_html);
      }
      last_call = data.results[0].pk;
      first_load = 0;
    });
    buildpage_running = 0;
}

function click_play_clip(audio_file, audio_id){
    $("#button_start_scanner").hide();
    reset_play_list(audio_id);
    play_clip(audio_file, audio_id);
    play_next();
}

function play_clip(audio_file, audio_id){
      console.log("Play clip")
      $(".play-btn").removeClass('btn-success').addClass('btn-default ');
      currently_playing=audio_id;
      if(audio_id == 0) {
        $("#button_start_scanner").removeClass('btn-default').addClass('btn-success ');
      } else {
	console.log("Trying to set button");
        $("#button_" + audio_id).removeClass('btn-default').addClass('btn-success ');
      }
      $("#jquery_jplayer_1").jPlayer("setMedia", {
         //oga: audio_file + ".ogg",
         //m4a: audio_file + ".m4a",
         mp3: audio_file + ".mp3",
       } );
       $("#jquery_jplayer_1").jPlayer("play");
}

function reset_play_list(audio_id){
    seen.length = 0; // Clear the array
    found_me = 0;
    for (var r_id in curr_id_list) {
        if(found_me == 0) {
            seen.push(curr_id_list[r_id]);
        }
        if(curr_id_list[r_id] == audio_id) {
            found_me = 1;
        }
    }
}

function play_next() {
    if(active_play == 0){
        return false;
    }
    for (var r_id in curr_id_list) {
        if ( seen.indexOf( curr_id_list[r_id] ) < 0 ) {
            if ( currently_playing == 0) {
              seen.push(curr_id_list[r_id]);
              //play_clip(audio_file, audio_id){
              mp3 = "//s3.amazonaws.com/scanoc-audio-001/" + curr_file_list[r_id];
              if(first_load == 0 && first_play == 0) { // Dont play them all on first load
                  tmp_title = '>>' + curr_tg_list[r_id] + '<< ' + page_title
                  document.title = tmp_title;
                  play_clip(mp3, curr_id_list[r_id]);
              }
            }
        }
    }
    if(first_load == 0) {
      first_play = 0;
    }
 }

function setup_player() {
      $("#jquery_jplayer_1").jPlayer({
       ready: function () {
        console.log("Setting up jPlayer")
       },
       ended: function() {
           active_play=1
           $("#button_" + currently_playing).removeClass('btn-success').addClass('btn-default ');
           $("#button_start_scanner").hide();
           currently_playing=0;
           $(document).prop('title', page_title);
       },
       swfPath: "https://jplayer.org/latest/dist/jplayer/",
       solution: "html,flash",
       supplied: "mp3",
       remainingDuration: true,
       errorAlerts: true,
       warningAlerts: true,
       volume: 1,
       cssSelectorAncestor: "",
       cssSelector: {
          title: "#title",
          play: "#jp1_play",
          pause: "#jp1_pause",
          stop: "#jp1_stop",
          mute: "#jp1_mute",
          unmute: "#jp1_unmute",
          currentTime: "#jp1_c_time",
         duration: "#jp1_duration"
       }
      });
      $("#jquery_jplayer_1").bind($.jPlayer.event.error + ".myProject", function(event) {
          console.log("Error Event: type = " + event.jPlayer.error.type);
          active_play=1
          $("#button_" + currently_playing).removeClass('btn-success').addClass('btn-default ');
          currently_playing=0;
          $(document).prop('title', page_title);
      });
  }

$(document).ready(function(){
    if($(".tg-multi-select").length) {
        $(".tg-multi-select").select2()
    }
    setup_player();
    play_clip("//s3.amazonaws.com/scanoc-audio-001/point1sec", 0, 0)
    first_load = 1;
    buildpage();
    //setInterval(buildpage, 2000);
    play_next();
    setInterval(play_next, 500);

    //first_load = 0;
});

window.onfocus = function() {
    force_page_rebuild = 1;
    buildpage();
};
<commit_msg>Cancel pending ajax request before calling agian<commit_after>active_play=0;
buildpage_running = 0;
currently_playing=0;
last_call = 0;
page_title = 'ScanOC';
first_load = 1;
first_play = 1;
seen = [];
curr_id_list = [];
curr_file_list = [];
curr_tg_list = [];
var force_page_rebuild = 0;
var base_api_url = "/api_v1/";
//var url_params = document.location.search
//var api_url = base_api_url + "/scanlist/default/";
//var pathArray = window.location.pathname.split( '/' );
// leading slash (/) causes a blank first object
//pathArray.shift();
//api_url = base_api_url + pathArray.join('/');
//if(url_params) {
//  api_url = api_url + url_params
//
var api_url = null;
var url_params = null;

var buildpage_running = 0;

function update_scan_list() {
    start_socket();
    buildpage();
}

function update_api_url() {
    url_params = document.location.search
    pathArray = window.location.pathname.split( '/' );
    pathArray.shift();
    console.log("url build");
    if(pathArray[0] == "userscan") {
        // Build TGs from select box
        console.log("In userscan url build");
        tg_array = $('.tg-multi-select').select2("val")
        if(tg_array) {
          api_url = base_api_url + "tg/" + tg_array.join('+');
          console.log("New API url " + api_url)
        } else {
          api_url = null;
        }
    } else {
        api_url = base_api_url + pathArray.join('/');
    }
    if(api_url && url_params) {
        api_url = api_url + url_params
    }
    //start_socket(); // reconnect with new talkgroups
}

function url_change(new_url) {
    clearpage();
    // Simple funcation to change url and rebuild the page
    var stateObj = { foo: "bar" };
    window.history.pushState(stateObj, "ScanOC.com", new_url);
    //window.history.pushState(.object or string., .Title., ./new-url.);
    $("#jquery_jplayer_1").jPlayer("stop");
    force_page_rebuild = 1;
    first_load = 1;
    first_play = 1;
    buildpage();
    return false;
}

function clearpage() {
    if(buildpage_running == 1) {
       return false;
    }
    $('#main-data-table').html("");
}

var last_ajax;

function buildpage() {
    console.log("In build page running : " + buildpage_running);
    if(buildpage_running == 1) {
       return false;
    }
    buildpage_running = 1;
    update_api_url();
    if( ! api_url) {
        buildpage_running = 0;
        return false;
    }
    if(last_ajax) {
        // Cancel any pending ajax calls
        last_ajax.abort();
    }
    last_ajax = $.getJSON(api_url, function(data) {
      //console.log(data);
      //console.log("Checking for new calls")
      //console.log("Last Call " + last_call + " New last " + data.results[0].pk)
      if (data.results[0].pk != last_call || force_page_rebuild == 1) {
      console.log("Rebuild");
      force_page_rebuild = 0;
      var new_html = '

 \

 	TalkGroup	Description	Start Time

';
      new_id_list = []
      new_file_list = []
      new_tg_list = []
      for (var a in data.results) {
          new_id_list.unshift(data.results[a].pk);
          new_file_list.unshift(data.results[a].audio_file);
          new_tg_list.unshift(data.results[a].tg_name);
          button_type = "btn-default";
          if(currently_playing == data.results[a].pk) {
              console.log("Match on " + currently_playing)
              button_type = "btn-success"
          }
	  new_html += '
<button id="button_' + data.results[a].pk + '" type="button" class="btn play-btn ' + button_type + ' btn-sm" onclick="click_play_clip(\'//s3.amazonaws.com/scanoc-audio-001/' + data.results[a].audio_file + '\', ' + data.results[a].pk + ')"> Play </button>	  ' + data.results[a].talkgroup_info.alpha_tag + '	' + data.results[a].talkgroup_info.description + '	' + data.results[a].local_start_datetime + '
';
          new_html += '
' + data.results[a].print_play_length + '	Units: ';
          for (unit in data.results[a].units) {
              if(data.results[a].units[unit].description) {
                  new_html += data.results[a].units[unit].description + ', ';
              } else {
                  if(js_logged_in_edit_units) {
                      new_html += '?' + data.results[a].units[unit].dec_id + ', ';
                  } else {
                      new_html += '?' + data.results[a].units[unit].dec_id + ', ';
                  }
              }
          }
          // Drop last ,
          new_html = new_html.slice(0, -2);
          new_html += '
';
      }
      curr_id_list = new_id_list;
      curr_file_list = new_file_list;
      curr_tg_list = new_tg_list;
      new_html += '
';
      $('#main-data-table').html(new_html);
      }
      last_call = data.results[0].pk;
      first_load = 0;
    });
    buildpage_running = 0;
}

function click_play_clip(audio_file, audio_id){
    $("#button_start_scanner").hide();
    reset_play_list(audio_id);
    play_clip(audio_file, audio_id);
    play_next();
}

function play_clip(audio_file, audio_id){
      console.log("Play clip")
      $(".play-btn").removeClass('btn-success').addClass('btn-default ');
      currently_playing=audio_id;
      if(audio_id == 0) {
        $("#button_start_scanner").removeClass('btn-default').addClass('btn-success ');
      } else {
	console.log("Trying to set button");
        $("#button_" + audio_id).removeClass('btn-default').addClass('btn-success ');
      }
      $("#jquery_jplayer_1").jPlayer("setMedia", {
         //oga: audio_file + ".ogg",
         //m4a: audio_file + ".m4a",
         mp3: audio_file + ".mp3",
       } );
       $("#jquery_jplayer_1").jPlayer("play");
}

function reset_play_list(audio_id){
    seen.length = 0; // Clear the array
    found_me = 0;
    for (var r_id in curr_id_list) {
        if(found_me == 0) {
            seen.push(curr_id_list[r_id]);
        }
        if(curr_id_list[r_id] == audio_id) {
            found_me = 1;
        }
    }
}

function play_next() {
    if(active_play == 0){
        return false;
    }
    for (var r_id in curr_id_list) {
        if ( seen.indexOf( curr_id_list[r_id] ) < 0 ) {
            if ( currently_playing == 0) {
              seen.push(curr_id_list[r_id]);
              //play_clip(audio_file, audio_id){
              mp3 = "//s3.amazonaws.com/scanoc-audio-001/" + curr_file_list[r_id];
              if(first_load == 0 && first_play == 0) { // Dont play them all on first load
                  tmp_title = '>>' + curr_tg_list[r_id] + '<< ' + page_title
                  document.title = tmp_title;
                  play_clip(mp3, curr_id_list[r_id]);
              }
            }
        }
    }
    if(first_load == 0) {
      first_play = 0;
    }
 }

function setup_player() {
      $("#jquery_jplayer_1").jPlayer({
       ready: function () {
        console.log("Setting up jPlayer")
       },
       ended: function() {
           active_play=1
           $("#button_" + currently_playing).removeClass('btn-success').addClass('btn-default ');
           $("#button_start_scanner").hide();
           currently_playing=0;
           $(document).prop('title', page_title);
       },
       swfPath: "https://jplayer.org/latest/dist/jplayer/",
       solution: "html,flash",
       supplied: "mp3",
       remainingDuration: true,
       errorAlerts: true,
       warningAlerts: true,
       volume: 1,
       cssSelectorAncestor: "",
       cssSelector: {
          title: "#title",
          play: "#jp1_play",
          pause: "#jp1_pause",
          stop: "#jp1_stop",
          mute: "#jp1_mute",
          unmute: "#jp1_unmute",
          currentTime: "#jp1_c_time",
         duration: "#jp1_duration"
       }
      });
      $("#jquery_jplayer_1").bind($.jPlayer.event.error + ".myProject", function(event) {
          console.log("Error Event: type = " + event.jPlayer.error.type);
          active_play=1
          $("#button_" + currently_playing).removeClass('btn-success').addClass('btn-default ');
          currently_playing=0;
          $(document).prop('title', page_title);
      });
  }

$(document).ready(function(){
    if($(".tg-multi-select").length) {
        $(".tg-multi-select").select2()
    }
    setup_player();
    play_clip("//s3.amazonaws.com/scanoc-audio-001/point1sec", 0, 0)
    first_load = 1;
    buildpage();
    //setInterval(buildpage, 2000);
    play_next();
    setInterval(play_next, 500);

    //first_load = 0;
});

window.onfocus = function() {
    force_page_rebuild = 1;
    buildpage();
};
<|endoftext|>


<commit_before>"use strict";

var suit = {};

// When set to a suit.Window object, events are channeled directly to it.
suit.lock = null;

suit.widgets = []; // Mapping of unique id's to widgets

suit.unique = (function() {
	var unique = 1;
	return function() {
		return unique++;
	};
})();

suit.register = function(widget, event, event_dom) {

	if (widget.event && widget.event (event)) {
		event_dom.stopPropagation();
		event_dom.preventDefault();
		return false;
	}

	return true;
};

suit.DomEvent = {
	MouseDown:    1,
	MouseUp:      2,
	MouseMove:    4,
	MouseWheel:   8,
	ContextMenu: 16,
	TouchStart:  32,
	TouchEnd:    64,
	TouchMove:  128
};

suit.get_relevant_widget = function(event, mask, no_lock) {
	var target, widget;

	if (!no_lock && suit.lock) return suit.lock;

	target = event.target || event.srcElement;
	if (target.nodeType === 3) target = target.parentNode;

	do {
		if (!target.suit_unique) return null;

		widget = suit.widgets[target.suit_unique];
		if (widget.event_mask & mask) break;

		if (target.suit_empty) target = target.parentNode.firstChild;
		else target = target.parentNode.parentNode.firstChild;

	} while (target);

	return widget;
};

suit.get_event_position = function(event, target) {
	var x, y, box;

	x = 0;
	y = 0;

	if (event.pageX || event.pageY) {
		x = event.pageX;
		y = event.pageY;
	} else if (event.clientX || event.clientY) {
		x = event.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		y = event.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}

	box = target.getBoundingClientRect();
	x -= box.top;
	y -= box.left;

	return {x: x, y: y};
};

suit.get_event_button = function(event) {
	var right_click;

	right_click = false;
	if (event.which) right_click = (event.which == 3);
	else if (event.button) right_click = (event.button == 2);
	return right_click ? 3 : 1;
};

suit.do_event = function(type, event) {
	var widget, target, pos, stype;

	switch (type) {
	case suit.DomEvent.MouseDown:
	case suit.DomEvent.MouseUp:

		stype = (type === suit.DomEvent.MouseDown) ?
			suit.Event.ButtonPress :
			suit.Event.ButtonRelease;

		widget = suit.get_relevant_widget (event, stype);
		if (!widget) return true;

		target = widget.window.base;
		pos = suit.get_event_position (event, target);
		button = suit.get_event_button (event);

		return suit.register (
			widget,
			new suit.EventButton (
				stype,
				suit.Modifiers.None,
				button, pos.x, pos.y, -1),
			event);

		break;

	case suit.DomEvent.MouseMove:

		widget = suit.get_relevant_widget (event, suit.Event.Motion);
		if (!widget) return true;

		target = widget.window.base;
		pos = suit.get_event_position (event, target);

		return suit.register (
			widget,
			new suit.EventMotion (
				suit.Modifiers.None,
				pos.x, pos.y, -1),
			event);

		break;

	case suit.DomEvent.MouseWheel:

		var deltaX = 0, deltaY = 0;

		if (event.wheelDelta) {
			if (event.wheelDeltaX || event.wheelDeltaY) {
				deltaX = event.wheelDeltaX;
				deltaY = event.wheelDeltaY;
			} else {
				deltaY = event.wheelDelta;
			}
		} else if (event.axis === event.HORIZONTAL_AXIS) {
			deltaX = -event.detail;
		} else if (event.axis === event.VERTICAL_AXIS) {
			deltaY = -event.detail;
		}

		if (deltaX === 0 && deltaY === 0) return false;

		widget = suit.get_relevant_widget (event, suit.Event.Scroll);
		if (!widget) return true;

		target = widget.window.base;
		pos = suit.get_event_position (event, target);

		return suit.register (
			widget,
			new suit.EventScroll (
				suit.Modifiers.None,
				pos.x, pos.y, deltaX, deltaY, -1),
			event);

		break;

	default:
		suit.warn ("Unhandled event: "+type);

	}
};

suit.init = function() {

	addEventListener("mousedown", function(event) {
		return suit.do_event(suit.DomEvent.MouseDown, event || window.event);
	}, false);

	addEventListener("mouseup", function(event) {
		return suit.do_event(suit.DomEvent.MouseUp, event || window.event);
	}, false);

	addEventListener("MozMousePixelScroll", function(event) {
		return suit.do_event(suit.DomEvent.MouseWheel, event || window.event);
	}, false)

	addEventListener("mousewheel", function(event) {
		return suit.do_event(suit.DomEvent.MouseWheel, event || window.event);
	}, false);
;
	addEventListener("mousemove", function(event) {
		return suit.do_event(suit.DomEvent.MouseMove, event || window.event);
	}, false);

	addEventListener("touchstart", function(event) {
		return suit.do_event (suit.DomEvent.TouchStart, event || window.event);
	}, false);

	addEventListener("touchend", function(event) {
		return suit.do_event (suit.DomEvent.TouchEnd, event || window.event);
	}, false);

	addEventListener("touchmove", function(event) {
		return suit.do_event (suit.DomEvent.TouchMove, event || window.event);
	}, false);

	addEventListener("contextmenu", function(event) {

		// TODO: Only do this if we're not on a suit window

		event.stopPropagation();
		event.preventDefault();
		return false;
	}, false);

};

suit.ensure = function(variable, expect) {
	var type = typeof variable;

	if (Array.isArray(expect)) {
		return;
	}

	if (typeof expect === "string") {
		if (type !== expect) {
			throw new Error("Failed type check. Was expecting `"+expect+"` but got `"+type+"`.");
		}
	} else if (typeof expect === "function") {
		var hrtype = type;
		if (type === "object") {
			hrtype = "object of " +
				(variable.constructor.name?variable.constructor.name:"[object Function]");
		}
		if (!(variable instanceof expect)) {
			throw new Error("Failed type check. Was expecting instance of `" +
				(expect.name?expect.name:"[object Function]")+"` but got `"+hrtype+"`.");
		}
	}
};

//addEventListener("error", function(e){ console.log(e.stack); }, 0);

Function.prototype.inherit = (function() {
	if (typeof Object.create === "function") {
		return function(base) {
			this.prototype = Object.create(base.prototype, {
				constructor: {
					value: this,
					enumerable: false,
					writable: true,
					configurable: true
				}
			});
		};
	}

	if (typeof Object.defineProperties === "function") {
		return function(base) {
			var dummy = function() {};
			dummy.prototype = base.prototype;

			this.prototype = new dummy;
			Object.defineProperties(this.prototype, {
				constructor: {
					value: this,
					enumerable: false,
					writable: true,
					configurable: true
				}
			});
		};
	}

	return function(base) {
		var dummy = function() {};
		dummy.prototype = base.prototype;

		this.prototype = new dummy;
		this.prototype.constructor = this;
	};
})();

if (!Function.prototype.bind) {
	Function.prototype.bind = function( obj ) {
		var slice = [].slice,
			args = slice.call(arguments, 1),
			self = this,
			nop = function () {},
			bound = function () {
				return self.apply( this instanceof nop ? this : ( obj || {} ),
					args.concat( slice.call(arguments) ) );
			};
		nop.prototype = self.prototype;
		bound.prototype = new nop();
		return bound;
	};
}

if (!Array.isArray) {
	Array.isArray = function(o) {
		return Object.prototype.toString.call(o) === "[object Array]";
	};
}
<commit_msg>Allow browser context menu to open on non-suit elements<commit_after>"use strict";

var suit = {};

// When set to a suit.Window object, events are channeled directly to it.
suit.lock = null;

suit.widgets = []; // Mapping of unique id's to widgets

suit.unique = (function() {
	var unique = 1;
	return function() {
		return unique++;
	};
})();

suit.register = function(widget, event, event_dom) {

	if (widget.event && widget.event (event)) {
		event_dom.stopPropagation();
		event_dom.preventDefault();
		return false;
	}

	return true;
};

suit.DomEvent = {
	MouseDown:    1,
	MouseUp:      2,
	MouseMove:    4,
	MouseWheel:   8,
	ContextMenu: 16,
	TouchStart:  32,
	TouchEnd:    64,
	TouchMove:  128
};

suit.get_relevant_widget = function(event, mask, no_lock) {
	var target, widget;

	if (!no_lock && suit.lock) return suit.lock;

	target = event.target || event.srcElement;
	if (target.nodeType === 3) target = target.parentNode;

	do {
		if (!target.suit_unique) return null;

		widget = suit.widgets[target.suit_unique];
		if (widget.event_mask & mask || mask === suit.Event.None) break;

		if (target.suit_empty) target = target.parentNode.firstChild;
		else target = target.parentNode.parentNode.firstChild;

	} while (target);

	return widget;
};

suit.get_event_position = function(event, target) {
	var x, y, box;

	x = 0;
	y = 0;

	if (event.pageX || event.pageY) {
		x = event.pageX;
		y = event.pageY;
	} else if (event.clientX || event.clientY) {
		x = event.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		y = event.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}

	box = target.getBoundingClientRect();
	x -= box.top;
	y -= box.left;

	return {x: x, y: y};
};

suit.get_event_button = function(event) {
	var right_click;

	right_click = false;
	if (event.which) right_click = (event.which == 3);
	else if (event.button) right_click = (event.button == 2);
	return right_click ? 3 : 1;
};

suit.do_event = function(type, event) {
	var widget, target, pos, stype;

	switch (type) {
	case suit.DomEvent.MouseDown:
	case suit.DomEvent.MouseUp:

		stype = (type === suit.DomEvent.MouseDown) ?
			suit.Event.ButtonPress :
			suit.Event.ButtonRelease;

		widget = suit.get_relevant_widget (event, stype);
		if (!widget) return true;

		target = widget.window.base;
		pos = suit.get_event_position (event, target);
		button = suit.get_event_button (event);

		return suit.register (
			widget,
			new suit.EventButton (
				stype,
				suit.Modifiers.None,
				button, pos.x, pos.y, -1),
			event);

		break;

	case suit.DomEvent.MouseMove:

		widget = suit.get_relevant_widget (event, suit.Event.Motion);
		if (!widget) return true;

		target = widget.window.base;
		pos = suit.get_event_position (event, target);

		return suit.register (
			widget,
			new suit.EventMotion (
				suit.Modifiers.None,
				pos.x, pos.y, -1),
			event);

		break;

	case suit.DomEvent.MouseWheel:

		var deltaX = 0, deltaY = 0;

		if (event.wheelDelta) {
			if (event.wheelDeltaX || event.wheelDeltaY) {
				deltaX = event.wheelDeltaX;
				deltaY = event.wheelDeltaY;
			} else {
				deltaY = event.wheelDelta;
			}
		} else if (event.axis === event.HORIZONTAL_AXIS) {
			deltaX = -event.detail;
		} else if (event.axis === event.VERTICAL_AXIS) {
			deltaY = -event.detail;
		}

		if (deltaX === 0 && deltaY === 0) return false;

		widget = suit.get_relevant_widget (event, suit.Event.Scroll);
		if (!widget) return true;

		target = widget.window.base;
		pos = suit.get_event_position (event, target);

		return suit.register (
			widget,
			new suit.EventScroll (
				suit.Modifiers.None,
				pos.x, pos.y, deltaX, deltaY, -1),
			event);

		break;

	default:
		suit.warn ("Unhandled event: "+type);

	}
};

suit.init = function() {

	addEventListener("mousedown", function(event) {
		return suit.do_event(suit.DomEvent.MouseDown, event || window.event);
	}, false);

	addEventListener("mouseup", function(event) {
		return suit.do_event(suit.DomEvent.MouseUp, event || window.event);
	}, false);

	addEventListener("MozMousePixelScroll", function(event) {
		return suit.do_event(suit.DomEvent.MouseWheel, event || window.event);
	}, false)

	addEventListener("mousewheel", function(event) {
		return suit.do_event(suit.DomEvent.MouseWheel, event || window.event);
	}, false);
;
	addEventListener("mousemove", function(event) {
		return suit.do_event(suit.DomEvent.MouseMove, event || window.event);
	}, false);

	addEventListener("touchstart", function(event) {
		return suit.do_event (suit.DomEvent.TouchStart, event || window.event);
	}, false);

	addEventListener("touchend", function(event) {
		return suit.do_event (suit.DomEvent.TouchEnd, event || window.event);
	}, false);

	addEventListener("touchmove", function(event) {
		return suit.do_event (suit.DomEvent.TouchMove, event || window.event);
	}, false);

	addEventListener("contextmenu", function(event) {
		var widget;

		widget = suit.get_relevant_widget (event, suit.Event.None, true);
		if (widget) {
			event.stopPropagation();
			event.preventDefault();
			return false;
		}

	}, false);

};

suit.ensure = function(variable, expect) {
	var type = typeof variable;

	if (Array.isArray(expect)) {
		return;
	}

	if (typeof expect === "string") {
		if (type !== expect) {
			throw new Error("Failed type check. Was expecting `"+expect+"` but got `"+type+"`.");
		}
	} else if (typeof expect === "function") {
		var hrtype = type;
		if (type === "object") {
			hrtype = "object of " +
				(variable.constructor.name?variable.constructor.name:"[object Function]");
		}
		if (!(variable instanceof expect)) {
			throw new Error("Failed type check. Was expecting instance of `" +
				(expect.name?expect.name:"[object Function]")+"` but got `"+hrtype+"`.");
		}
	}
};

//addEventListener("error", function(e){ console.log(e.stack); }, 0);

Function.prototype.inherit = (function() {
	if (typeof Object.create === "function") {
		return function(base) {
			this.prototype = Object.create(base.prototype, {
				constructor: {
					value: this,
					enumerable: false,
					writable: true,
					configurable: true
				}
			});
		};
	}

	if (typeof Object.defineProperties === "function") {
		return function(base) {
			var dummy = function() {};
			dummy.prototype = base.prototype;

			this.prototype = new dummy;
			Object.defineProperties(this.prototype, {
				constructor: {
					value: this,
					enumerable: false,
					writable: true,
					configurable: true
				}
			});
		};
	}

	return function(base) {
		var dummy = function() {};
		dummy.prototype = base.prototype;

		this.prototype = new dummy;
		this.prototype.constructor = this;
	};
})();

if (!Function.prototype.bind) {
	Function.prototype.bind = function( obj ) {
		var slice = [].slice,
			args = slice.call(arguments, 1),
			self = this,
			nop = function () {},
			bound = function () {
				return self.apply( this instanceof nop ? this : ( obj || {} ),
					args.concat( slice.call(arguments) ) );
			};
		nop.prototype = self.prototype;
		bound.prototype = new nop();
		return bound;
	};
}

if (!Array.isArray) {
	Array.isArray = function(o) {
		return Object.prototype.toString.call(o) === "[object Array]";
	};
}
<|endoftext|>


<commit_before>console.log(
  Math.ceil(
    Math.log(process.argv[2]) * Math.LOG2E
  )
);
<commit_msg>make bits.js a one-liner<commit_after>console.log(Math.ceil(Math.log(process.argv[2]) * Math.LOG2E));
<|endoftext|>