<commit_before>/*
 * ContextMenu - jQuery plugin for right-click context menus
 *
 * Author: Chris Domigan
 * Contributors: Dan G. Switzer, II
 * Parts of this plugin are inspired by Joern Zaefferer's Tooltip plugin
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Version: r2
 * Date: 16 July 2007
 *
 * For documentation visit http://www.trendskitchens.co.nz/jquery/contextmenu/
 *
 */

(function($) {

 	var menu, shadow, trigger, content, hash, currentTarget;
  var defaults = {
    menuStyle: {
      listStyle: 'none',
      padding: '1px',
      margin: '0px',
      backgroundColor: '#fff',
      border: '1px solid #999',
      width: '100px'
    },
    itemStyle: {
      margin: '0px',
      color: '#000',
      display: 'block',
      cursor: 'default',
      padding: '3px',
      border: '1px solid #fff',
      backgroundColor: 'transparent'
    },
    itemHoverStyle: {
      border: '1px solid #0a246a',
      backgroundColor: '#b6bdd2'
    },
    eventPosX: 'pageX',
    eventPosY: 'pageY',
    shadow : true,
    onContextMenu: null,
    onShowMenu: null
 	};

  $.fn.contextMenu = function(id, options) {
    if (!menu) {                                      // Create singleton menu
      menu = $('

')
               .hide()
               .css({position:'absolute', zIndex:'500'})
               .appendTo('body')
               .bind('click', function(e) {
                 e.stopPropagation();
               });
    }
    if (!shadow) {
      shadow = $('

')
                 .css({backgroundColor:'#000',position:'absolute',opacity:0.2,zIndex:499})
                 .appendTo('body')
                 .hide();
    }
    hash = hash || [];
    hash.push({
      id : id,
      menuStyle: $.extend({}, defaults.menuStyle, options.menuStyle || {}),
      itemStyle: $.extend({}, defaults.itemStyle, options.itemStyle || {}),
      itemHoverStyle: $.extend({}, defaults.itemHoverStyle, options.itemHoverStyle || {}),
      bindings: options.bindings || {},
      shadow: options.shadow || options.shadow === false ? options.shadow : defaults.shadow,
      onContextMenu: options.onContextMenu || defaults.onContextMenu,
      onShowMenu: options.onShowMenu || defaults.onShowMenu,
      eventPosX: options.eventPosX || defaults.eventPosX,
      eventPosY: options.eventPosY || defaults.eventPosY
    });

    var index = hash.length - 1;
    $(this).bind('click', function(e) {
      // Check if onContextMenu() defined
      var bShowContext = (!!hash[index].onContextMenu) ? hash[index].onContextMenu(e) : true;
      if (bShowContext) display(index, this, e, options);
      return false;
    });
    return this;
  };

  $.displayMenu = function(index, trigger, e, options) {
    var cur = hash[index];
    content = $('#'+cur.id).find('ul:first').clone(true);
    content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(
      function() {
        $(this).css(cur.itemHoverStyle);
      },
      function(){
        $(this).css(cur.itemStyle);
      }
    ).find('img').css({verticalAlign:'middle',paddingRight:'2px'});

    // Send the content to the menu
    menu.html(content);

    // if there's an onShowMenu, run it now -- must run after content has been added
		// if you try to alter the content variable before the menu.html(), IE6 has issues
		// updating the content
    if (!!cur.onShowMenu) menu = cur.onShowMenu(e, menu);

    $.each(cur.bindings, function(id, func) {
      $('#'+id, menu).bind('click', function(e) {
        hide();
        func(trigger, currentTarget);
      });
    });

    menu.css({'left':e[cur.eventPosX],'top':e[cur.eventPosY]}).show();
    if (cur.shadow) shadow.css({width:menu.width(),height:menu.height(),left:e.pageX+2,top:e.pageY+2}).show();
    $(document).one('click', hide);
  }

  function hide() {
    menu.hide();
    shadow.hide();
  }

  // Apply defaults
  $.contextMenu = {
    defaults : function(userDefaults) {
      $.each(userDefaults, function(i, val) {
        if (typeof val == 'object' && defaults[i]) {
          $.extend(defaults[i], val);
        }
        else defaults[i] = val;
      });
    }
  };

})(jQuery);

$(function() {
  $('div.contextMenu').hide();
});
<commit_msg>- removed invalid file<commit_after><|endoftext|>


<commit_before>var fs = require('fs')
var qs = require('qs')
var request = require('request')
var csvWriter = require('csv-write-stream')

var config = require('./config.json')

var headers = ['dplaLink', 'link', 'title', 'sender', 'recipient',
               'year', 'description', 'place', 'date']

var writer = csvWriter({headers: headers})
writer.pipe(fs.createWriteStream('letters.csv'))

// Set our API query parameters
var baseUrl = 'http://api.dp.la/v2/items?'
var queryString = {
  api_key: config.api_key,
  sourceResource: {
    subject: {
      name: 'Maria Chapman'
    }
  },
  page_size: 500,
  page: 1
}

getData()

function getData() {
  // Build the URL string and set options for the request
  var options = {
    url: baseUrl + qs.stringify(queryString, {allowDots: true}),
    json: true
  }

  // Request data from the API
  request(options, (err, res, records) => {
    if (!err && res.statusCode == 200) {
      records.docs.map((l) => {

        letter = {link_dpla: l.hasOwnProperty('@id') ? l['@id'] : l.object['@id']}

        // Metadata contains most of the information we want, but isn't always present
        if (l.originalRecord.hasOwnProperty('metadata')) {

            letter.title = l.originalRecord.metadata.title
            letter.year = l.originalRecord.metadata.date
            letter.link_org = l.originalRecord.metadata['identifier-access']

            if (l.originalRecord.metadata.hasOwnProperty('creator')) {

              // If creator is a list of names, search for sender and recipient
              if(typeof l.originalRecord.metadata.creator == 'object') {
                letter.recipient = l.originalRecord.metadata.creator.reduce((p, c)=> {
                  return c.endsWith('recipient') ? c.replace(/,*\s*(recipient)$/,'') : p
                }, '')

                letter.sender = l.originalRecord.metadata.creator.reduce((p, c)=> {
                  return c.endsWith('recipient') ? p: c
                }, '')
              }
              // If creator isn't a list of names then it is a single string
              // Check if it lists the sender or recipient and assign as appropriate
              else {
                letter.recipient = l.originalRecord.metadata.creator.endsWith('recipient') ? l.originalRecord.metadata.creator.replace(/,*\s*(recipient)$/,'') : null
                letter.sender = l.originalRecord.metadata.creator.endsWith('recipient') ? null : l.originalRecord.metadata.creator
              }
            }

            if (l.originalRecord.metadata.hasOwnProperty('description')) {
              if(typeof l.originalRecord.metadata.description == 'object') {
                letter.description = l.originalRecord.metadata.description.reduce((p, c)=>{ return p += c + '.'},'')
              }
              else { letter.description = l.originalRecord.metadata.description }
            }
        }

        if (l.originalRecord.hasOwnProperty('record')) {
          letter.place = l.originalRecord.record.datafield.reduce((p, c) => {
            if (c.tag == '260') {
              if (Array.isArray(c.subfield)) {
                return c.subfield.reduce((a, b)=>{ return b.code == 'a' ? b['#text'] : a }, '')
              }
              else {
                return c.subfield.code == 'a' ? c.subfield['#text'] : p
              }
            }

            return p
          }, '')

          letter.date = l.originalRecord.record.datafield.reduce((p, c) => {
            if (c.tag == '260') {
              if (Array.isArray(c.subfield)) {
                return c.subfield.reduce((a, b)=>{ return b.code == 'c' ? b['#text'] : a }, '')
              }
              else {
                return c.subfield.code == 'c' ? c.subfield['#text'] : p
              }
            }

            return p
          }, '')
        }
        writer.write(letter)
      })

      console.log("Grabbed " + Math.min(records.count, (records.start + records.limit)) + " of " + records.count + " records")

      if ((records.start + records.limit) < records.count) {
        queryString.page++
        getData()
      }
      else {
        writer.end()
      }
    }
  })
}
<commit_msg>fix link and dplaLink columns<commit_after>var fs = require('fs')
var qs = require('qs')
var request = require('request')
var csvWriter = require('csv-write-stream')

var config = require('./config.json')

var headers = ['dplaLink', 'link', 'title', 'sender', 'recipient',
               'year', 'description', 'place', 'date']

var writer = csvWriter({headers: headers})
writer.pipe(fs.createWriteStream('letters.csv'))

// Set our API query parameters
var baseUrl = 'http://api.dp.la/v2/items?'
var queryString = {
  api_key: config.api_key,
  sourceResource: {
    subject: {
      name: 'Maria Chapman'
    }
  },
  page_size: 500,
  page: 1
}

getData()

function getData() {
  // Build the URL string and set options for the request
  var options = {
    url: baseUrl + qs.stringify(queryString, {allowDots: true}),
    json: true
  }

  // Request data from the API
  request(options, (err, res, records) => {
    if (!err && res.statusCode == 200) {
      records.docs.map((l) => {

        letter = {dplaLink: l.hasOwnProperty('@id') ? l['@id'] : l.object['@id']}

        // Metadata contains most of the information we want, but isn't always present
        if (l.originalRecord.hasOwnProperty('metadata')) {

            letter.title = l.originalRecord.metadata.title
            letter.year = l.originalRecord.metadata.date
            letter.link = l.originalRecord.metadata['identifier-access']

            if (l.originalRecord.metadata.hasOwnProperty('creator')) {

              // If creator is a list of names, search for sender and recipient
              if(typeof l.originalRecord.metadata.creator == 'object') {
                letter.recipient = l.originalRecord.metadata.creator.reduce((p, c)=> {
                  return c.endsWith('recipient') ? c.replace(/,*\s*(recipient)$/,'') : p
                }, '')

                letter.sender = l.originalRecord.metadata.creator.reduce((p, c)=> {
                  return c.endsWith('recipient') ? p: c
                }, '')
              }
              // If creator isn't a list of names then it is a single string
              // Check if it lists the sender or recipient and assign as appropriate
              else {
                letter.recipient = l.originalRecord.metadata.creator.endsWith('recipient') ? l.originalRecord.metadata.creator.replace(/,*\s*(recipient)$/,'') : null
                letter.sender = l.originalRecord.metadata.creator.endsWith('recipient') ? null : l.originalRecord.metadata.creator
              }
            }

            if (l.originalRecord.metadata.hasOwnProperty('description')) {
              if(typeof l.originalRecord.metadata.description == 'object') {
                letter.description = l.originalRecord.metadata.description.reduce((p, c)=>{ return p += c + '.'},'')
              }
              else { letter.description = l.originalRecord.metadata.description }
            }
        }

        if (l.originalRecord.hasOwnProperty('record')) {
          letter.place = l.originalRecord.record.datafield.reduce((p, c) => {
            if (c.tag == '260') {
              if (Array.isArray(c.subfield)) {
                return c.subfield.reduce((a, b)=>{ return b.code == 'a' ? b['#text'] : a }, '')
              }
              else {
                return c.subfield.code == 'a' ? c.subfield['#text'] : p
              }
            }

            return p
          }, '')

          letter.date = l.originalRecord.record.datafield.reduce((p, c) => {
            if (c.tag == '260') {
              if (Array.isArray(c.subfield)) {
                return c.subfield.reduce((a, b)=>{ return b.code == 'c' ? b['#text'] : a }, '')
              }
              else {
                return c.subfield.code == 'c' ? c.subfield['#text'] : p
              }
            }

            return p
          }, '')
        }
        writer.write(letter)
      })

      console.log("Grabbed " + Math.min(records.count, (records.start + records.limit)) + " of " + records.count + " records")

      if ((records.start + records.limit) < records.count) {
        queryString.page++
        getData()
      }
      else {
        writer.end()
      }
    }
  })
}
<|endoftext|>


<commit_before>/**
	An mochi-styled TextArea control. In addition to the features of
	enyo.TextArea, mochi.TextArea has a
	*defaultFocus* property that can be set to true to focus the TextArea when
	it's rendered. Only one TextArea should be set as the *defaultFocus*.

	Typically, an mochi.TextArea is placed inside an
	mochi.InputDecorator, which provides
	styling, e.g.:

		{kind: "mochi.InputDecorator", components: [
			{kind: "mochi.TextArea", onchange: "inputChange"}
		]}
*/
enyo.kind({
	name: "mochi.TextArea",
	kind: "enyo.TextArea",
	classes: "mochi-textarea"
});
<commit_msg>ENYO-13: Complete JSDoc3 conversion on Mochi<commit_after>/**
 * A mochi-styled TextArea control. In addition to the features of {@link enyo.TextArea}, `mochi.TextArea` has a
 * `defaultFocus` property that can be set to true to focus the TextArea when it is rendered. Only one `mochi.TextArea`
 * should be set as the `defaultFocus`.
 *
 * Typically, a `mochi.TextArea` is placed inside a {@link mochi.InputDecorator}, which provides styling, e.g.:
 *
 * ```
 * {kind: "mochi.InputDecorator", components: [
 *	{kind: "mochi.TextArea", onchange: "inputChange"}
 * ]}
 * ```
 *
 * @class mochi.TextArea
 * @extends enyo.TextArea
 * @ui
 * @public
 */
(function (enyo, scope) {
	enyo.kind(
		/** @lends mochi.TextArea.prototype */ {

		/**
		 * @private
		 */
		name: "mochi.TextArea",

		/**
		 * @private
		 */
		kind: "enyo.TextArea",

		/**
		 * @private
		 */
		classes: "mochi-textarea"
	});

})(enyo, this);
<|endoftext|>


<commit_before>var WebAudio = function() {

    var WebAudio = this;

    var currentTime = 0;
    var currentTrack;
    var audioContext;
    var analyser;
    var source;
    var freqDomain;
    var timeDomain;
    var progressBar;

    this.loaded = false;
    this.playing = false;
    this.time = null;
    this.sampleRate = null;
    this.context;
    this.queue = [];
    this.queuePosition = 0;

    // initialize audio context
    this.init = function() {
        audioContext = new(window.AudioContext || window.webkitAudioContext)();
    }

    // load / connect a track
    this.load = function() {
        console.log('WebAudio.load() called');
        this.connect();
    }

    // connect to destination
    this.connect = function() {

        console.log('WebAudio.connect() called');

        source = audioContext.createBufferSource();

        analyser = audioContext.createAnalyser();
        analyser.smoothingTimeConstant = .9;
        analyser.fftSize = 2048;

        gainNode = audioContext.createGain();
        gainNode.gain.value = .8;

        freqDomain = new Uint8Array(analyser.frequencyBinCount);

        source.connect(analyser);
        analyser.connect(gainNode);
        gainNode.connect(audioContext.destination);

        WebAudio.loaded = true;
        loaded = true;

        return source;

    }

    // connect the media element to the destination
    this.connectMediaElement = function(mediaElement) {

        analyser = audioContext.createAnalyser();
        analyser.smoothingTimeConstant = .9;
        analyser.fftSize = 2048;

        gainNode = audioContext.createGain();
        gainNode.gain.value = .8;

        freqDomain = new Uint8Array(analyser.frequencyBinCount);

        source.connect(analyser);
        analyser.connect(gainNode);
        gainNode.connect(audioContext.destination);
        mediaElement.connect(audioContext.destination);
    }

    // debugging function, logs the queue
    this.logQueue = function() {
        console.log('queue:' + this.queue);
        console.log('queuePosition: ' + this.queuePosition);
        console.log('queue.length: ' + this.queue.length);
    }

    this.insertQueue = function(audioElement) {
        this.queue.splice(this.queuePosition, 0, audioElement);
    }

    this.playPosition = function(position) {
        this.stop();
        WebAudio.queuePosition = position;
        this.start();
    }

    /**
    * Adds a track to the end of the queue, sets the queue position to the end an starts playback
    */
    this.startInstant = function(obj) {
        this.addQueue(obj);
        this.queuePosition = this.queue.length - 1;
        this.stop();
        this.start();
    }

    this.start = function() {
        try {

            // get the current track from the queue
            currentTrack = this.queue[this.queuePosition];

            // create source from createMediaELementSource
            source = audioContext.createMediaElementSource(currentTrack);

            // connect the source to the destination
            this.connectMediaElement(source, currentTrack);

        } catch (e) {
            console.log('An error occured in WebAudio.start()')
            console.log(e);
        } finally {
            if (WebAudio.getQueue().length > 0) {
                currentTrack.currentTime = 0;
                currentTrack.play();
                this.playing = true;
            }
        }
    }

    this.initProgressBar = function(element) {
        WebAudio.progressBar = element;

        function update() {
            try {
                currentTime = WebAudio.queue[WebAudio.queuePosition].currentTime;
                duration = WebAudio.queue[WebAudio.queuePosition].duration;
            } catch(e) {
                currentTime = 0;
                duration = 1;
            }
            progress = (currentTime / duration) * 100;
            WebAudio.progressBar.setAttribute('value', progress);
            requestAnimationFrame(update);
        }

        update();

    }

    this.time = function() {
        return audioContext.currentTime;
    }

    this.getByteFrequencyData = function() {
        if (!this.playing) return;
        analyser.getByteFrequencyData(freqDomain);
        return freqDomain;
    }

    this.getByteTimeDomainData = function() {
        if (!playing) return;
        analyser.getByteTimeDomainData(timeDomain);
        return timeDomain;
    }

    this.pause = function() {
        WebAudio.queue[WebAudio.queuePosition].pause();
    }

    this.stop = function() {
        try {
            currentTrack.pause();
            currentTrack.currentTime = 0;
            var e = new Event('audiojs:stopped');
            document.dispatchEvent(e);
        } catch (e) {
            return; // not currently playing
        }
    }

    this.addQueue = function(obj) {

        var audioElement = document.createElement('audio');
        audioElement.metadata = obj;
        audioElement.setAttribute('crossOrigin', 'anonymous');
        audioElement.setAttribute('src', obj['file']);
        audioElement.setAttribute('preload', 'auto');
        audioElement.load();

        // add queue position to audioElement
        audioElement['queue_position'] = this.queue.length;

        if (obj['play_button']) {
            obj['play_button'].addEventListener('click', function() {
                WebAudio.playPosition(audioElement['queue_position']);
            })
        }

        if (obj['element']) {
            audioElement.addEventListener('play', function(){
                console.log('Audio element has started playback');
                obj['element'].classList.add('playing');
            });

            audioElement.addEventListener('pause', function() {
                console.log('Audio element has paused playback');
                obj['element'].classList.remove('playing');
            });

            audioElement.addEventListener('ended', function() {
                console.log('Audio element has ended playback');
                obj['element'].classList.remove('playing');
            });
        }

        audioElement.addEventListener('ended', function() {
            var e = new Event('audiojs:ended');
            document.dispatchEvent(e);
        });

        this.queue.push(audioElement);

    }

    this.getQueue = function() {
        return this.queue;
    }

    this.getQueuePosition = function() {
        return this.queuePosition;
    }

    this.setQueuePosition = function(position) {
        this.queuePosition = position;
    }

    this.getCurrentTrack = function() {
        return this.queue[this.queuePosition];
    }

    this.removeFromQueue = function(position) {
        try {
            // stop audio if removing the currently playing track
            if (position == this.getQueuePosition()) {
                this.stop();
            }
            // readjust queue position if removing node before currently playing
            if (position < this.getQueuePosition()) {
                this.setQueuePosition(this.getQueuePosition() - 1);
            }
            this.queue.splice(position, 1);
        } catch (e) {
            // do nothing
        }
    }

    this.playNext = function() {
        WebAudio.queuePosition < WebAudio.queue.length - 1 ? playNext() : start();

        function playNext() {
            WebAudio.stop();
            WebAudio.queuePosition += 1;
            WebAudio.queue[WebAudio.queuePosition].currentTime = 0;
            WebAudio.load(WebAudio.queue[WebAudio.queuePosition]);
            WebAudio.start();
        }

        function start() {
            WebAudio.start();
        }
    }

    this.playPrevious = function() {
        WebAudio.queuePosition > 0 ? playPrevious() : restart();

        function playPrevious() {
            WebAudio.stop();
            WebAudio.queuePosition -= 1;
            WebAudio.queue[WebAudio.queuePosition].currentTime = 0;
            WebAudio.load(WebAudio.queue[WebAudio.queuePosition]);
            WebAudio.start();
        }

        function restart() {
            WebAudio.start();
        }
    }

    this.playIndex = function(index) {
        (WebAudio.queue.length < (index + 1) || index > -1) ? play(index) : false;

        function play(index) {
            WebAudio.stop();
            WebAudio.queue[WebAudio.queuePosition].currentTime = 0;
            WebAudio.setQueuePosition(index);
            WebAudio.start();
        }
    }

    this.isPlaying = function() {
        return this.playing;
    }

    this.init();

};
<commit_msg>audio should stop if there is no next track in the queue<commit_after>var WebAudio = function() {

    var WebAudio = this;

    var currentTime = 0;
    var currentTrack;
    var audioContext;
    var analyser;
    var source;
    var freqDomain;
    var timeDomain;
    var progressBar;

    this.loaded = false;
    this.playing = false;
    this.time = null;
    this.sampleRate = null;
    this.context;
    this.queue = [];
    this.queuePosition = 0;

    // initialize audio context
    this.init = function() {
        audioContext = new(window.AudioContext || window.webkitAudioContext)();
    }

    // load / connect a track
    this.load = function() {
        console.log('WebAudio.load() called');
        this.connect();
    }

    // connect to destination
    this.connect = function() {

        console.log('WebAudio.connect() called');

        source = audioContext.createBufferSource();

        analyser = audioContext.createAnalyser();
        analyser.smoothingTimeConstant = .9;
        analyser.fftSize = 2048;

        gainNode = audioContext.createGain();
        gainNode.gain.value = .8;

        freqDomain = new Uint8Array(analyser.frequencyBinCount);

        source.connect(analyser);
        analyser.connect(gainNode);
        gainNode.connect(audioContext.destination);

        WebAudio.loaded = true;
        loaded = true;

        return source;

    }

    // connect the media element to the destination
    this.connectMediaElement = function(mediaElement) {

        analyser = audioContext.createAnalyser();
        analyser.smoothingTimeConstant = .9;
        analyser.fftSize = 2048;

        gainNode = audioContext.createGain();
        gainNode.gain.value = .8;

        freqDomain = new Uint8Array(analyser.frequencyBinCount);

        source.connect(analyser);
        analyser.connect(gainNode);
        gainNode.connect(audioContext.destination);
        mediaElement.connect(audioContext.destination);
    }

    // debugging function, logs the queue
    this.logQueue = function() {
        console.log('queue:' + this.queue);
        console.log('queuePosition: ' + this.queuePosition);
        console.log('queue.length: ' + this.queue.length);
    }

    this.insertQueue = function(audioElement) {
        this.queue.splice(this.queuePosition, 0, audioElement);
    }

    this.playPosition = function(position) {
        this.stop();
        WebAudio.queuePosition = position;
        this.start();
    }

    /**
    * Adds a track to the end of the queue, sets the queue position to the end an starts playback
    */
    this.startInstant = function(obj) {
        this.addQueue(obj);
        this.queuePosition = this.queue.length - 1;
        this.stop();
        this.start();
    }

    this.start = function() {
        try {

            // get the current track from the queue
            currentTrack = this.queue[this.queuePosition];

            // create source from createMediaELementSource
            source = audioContext.createMediaElementSource(currentTrack);

            // connect the source to the destination
            this.connectMediaElement(source, currentTrack);

        } catch (e) {
            console.log('An error occured in WebAudio.start()')
            console.log(e);
        } finally {
            if (WebAudio.getQueue().length > 0) {
                currentTrack.currentTime = 0;
                currentTrack.play();
                this.playing = true;
            }
        }
    }

    this.initProgressBar = function(element) {
        WebAudio.progressBar = element;

        function update() {
            try {
                currentTime = WebAudio.queue[WebAudio.queuePosition].currentTime;
                duration = WebAudio.queue[WebAudio.queuePosition].duration;
            } catch(e) {
                currentTime = 0;
                duration = 1;
            }
            progress = (currentTime / duration) * 100;
            WebAudio.progressBar.setAttribute('value', progress);
            requestAnimationFrame(update);
        }

        update();

    }

    this.time = function() {
        return audioContext.currentTime;
    }

    this.getByteFrequencyData = function() {
        if (!this.playing) return;
        analyser.getByteFrequencyData(freqDomain);
        return freqDomain;
    }

    this.getByteTimeDomainData = function() {
        if (!playing) return;
        analyser.getByteTimeDomainData(timeDomain);
        return timeDomain;
    }

    this.pause = function() {
        WebAudio.queue[WebAudio.queuePosition].pause();
    }

    this.stop = function() {
        try {
            currentTrack.pause();
            currentTrack.currentTime = 0;
            this.playing = false;
            var e = new Event('audiojs:stopped');
            document.dispatchEvent(e);
        } catch (e) {
            return; // not currently playing
        }
    }

    this.addQueue = function(obj) {

        var audioElement = document.createElement('audio');
        audioElement.metadata = obj;
        audioElement.setAttribute('crossOrigin', 'anonymous');
        audioElement.setAttribute('src', obj['file']);
        audioElement.setAttribute('preload', 'auto');
        audioElement.load();

        // add queue position to audioElement
        audioElement['queue_position'] = this.queue.length;

        if (obj['play_button']) {
            obj['play_button'].addEventListener('click', function() {
                WebAudio.playPosition(audioElement['queue_position']);
            })
        }

        if (obj['element']) {
            audioElement.addEventListener('play', function(){
                console.log('Audio element has started playback');
                obj['element'].classList.add('playing');
            });

            audioElement.addEventListener('pause', function() {
                console.log('Audio element has paused playback');
                obj['element'].classList.remove('playing');
            });

            audioElement.addEventListener('ended', function() {
                console.log('Audio element has ended playback');
                obj['element'].classList.remove('playing');
            });
        }

        audioElement.addEventListener('ended', function() {
            var e = new Event('audiojs:ended');
            document.dispatchEvent(e);
        });

        this.queue.push(audioElement);

    }

    this.getQueue = function() {
        return this.queue;
    }

    this.getQueuePosition = function() {
        return this.queuePosition;
    }

    this.setQueuePosition = function(position) {
        this.queuePosition = position;
    }

    this.getCurrentTrack = function() {
        return this.queue[this.queuePosition];
    }

    this.removeFromQueue = function(position) {
        try {
            // stop audio if removing the currently playing track
            if (position == this.getQueuePosition()) {
                this.stop();
            }
            // readjust queue position if removing node before currently playing
            if (position < this.getQueuePosition()) {
                this.setQueuePosition(this.getQueuePosition() - 1);
            }
            this.queue.splice(position, 1);
        } catch (e) {
            // do nothing
        }
    }

    this.playNext = function() {
        WebAudio.queuePosition < (WebAudio.queue.length - 1) ? playNext() : stop();

        function playNext() {
            WebAudio.stop();
            WebAudio.queuePosition += 1;
            WebAudio.queue[WebAudio.queuePosition].currentTime = 0;
            WebAudio.load(WebAudio.queue[WebAudio.queuePosition]);
            WebAudio.start();
        }

        function stop() {
            WebAudio.stop();
        }
    }

    this.playPrevious = function() {
        WebAudio.queuePosition > 0 ? playPrevious() : restart();

        function playPrevious() {
            WebAudio.stop();
            WebAudio.queuePosition -= 1;
            WebAudio.queue[WebAudio.queuePosition].currentTime = 0;
            WebAudio.load(WebAudio.queue[WebAudio.queuePosition]);
            WebAudio.start();
        }

        function restart() {
            WebAudio.start();
        }
    }

    this.playIndex = function(index) {
        (WebAudio.queue.length < (index + 1) || index > -1) ? play(index) : false;

        function play(index) {
            WebAudio.stop();
            WebAudio.queue[WebAudio.queuePosition].currentTime = 0;
            WebAudio.setQueuePosition(index);
            WebAudio.start();
        }
    }

    this.isPlaying = function() {
        return this.playing;
    }

    this.init();

};
<|endoftext|>


<commit_before>var forOwn = require('./forOwn')

var keys = Object.keys || function (obj) {
  var keys = []
  forOwn(obj, function (value, key) {
    keys.push(key)
  })
  return keys
}

module.exports = keys
<commit_msg>refactor: object/keys.js<commit_after>function keys (obj) {
  var result = []
  var key

  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      result.push(key)
    }
  }
  return result
}

module.exports = keys
<|endoftext|>


<commit_before>var stripComments = require("strip-comments"),
    parser = {},
    quoteRegExp = /['"]/,
    dependencyRegExp = /^((.*)\!)*(.*?)(\?.*?)?$/;

// define([...] - for standard amd modules
var defineAmdRegExp = /(\s*define\s*\(\s*)\[([^\]]*?)\]/m;
// define({...}) - for nls modules
var defineNlsRegExp = /(\s*define\s*\(\s*)\(?\{([\s\S]*)\}\)?\s*\)/m;

// parse dojo AMD-modules and return:
// {
//      deps: Array of string - dependencies,
//      save: function(new_deps, inject) - return content string with replaced dependencies and injected code
// }
parser.parseModule = function(content){
    content = stripComments(content);
    var define_match = defineAmdRegExp.exec(content),
        result = {
            deps: [],
            save: null,
            type: null,
            moduleBody: null
        };
    if (define_match){
        // Process header of module ctor func:
        var function_match = /function\s*\(([\s\S]*?)\)/.exec(content.substring(define_match.index + define_match[0].length));
        var function_arguments_text = function_match[1];
        var function_arguments_array = function_arguments_text.split(",");
        var function_arguments_count = function_arguments_array.length; // count of really used dependencies
        if (function_arguments_count == 1 && function_arguments_text.trim() == '') function_arguments_count = 0;
        // Process body of module ctor func:
        var module_def_start = content.indexOf("{", function_match.index + function_match[0].length);
        var module_def_end = content.lastIndexOf("}");
        var module_def_body = content.substring(module_def_start + 1, module_def_end);

        if (function_match && module_def_start >= 0 && module_def_end >= 0) {
            var save_template_chunks = [content.substr(0, define_match.index) + define_match[1] + '['];
            var cur_chunk = 0;
            // list of module depencies: "module1", 'module2' ...
            var cur_incl_str = define_match[2];
            var dep_strpos_start;
            while ((dep_strpos_start = cur_incl_str.search(quoteRegExp)) >= 0){
                save_template_chunks[cur_chunk] = (save_template_chunks[cur_chunk] ? save_template_chunks[cur_chunk] : '') +
                    cur_incl_str.substr(0, dep_strpos_start);
                // search end quote
                var start_index = dep_strpos_start + 1;
                var dep_strpos_end = -1;
                while (dep_strpos_end < 0){
                    var quote_index = cur_incl_str.indexOf(cur_incl_str[dep_strpos_start], start_index);
                    if (quote_index < 0) throw new Error("DojoWebpackLoader: cannot find closing quoute in dojo module definition");
                    if (cur_incl_str[quote_index - 1] != '\\'){
                        dep_strpos_end = quote_index;
                    }
                    else {
                        // quoute is escaped => find next
                        start_index = quote_index + 1;
                    }
                }
                // get dependency
                var dep_string = cur_incl_str.substring(dep_strpos_start + 1, dep_strpos_end);
                // simple strip slashes
                dep_string = dep_string.replace(/\\(.)/g, "$1");
                result.deps.push({
                    dep: dep_string,
                    name: function_arguments_array[result.deps.length] ? function_arguments_array[result.deps.length].trim() : undefined
                });
                // prepare for searching next dependency:
                cur_incl_str = cur_incl_str.substr(dep_strpos_end + 1);
                cur_chunk++;
            }
            // Append before function ctor;
            save_template_chunks.push(cur_incl_str + "]" + content.substring(define_match.index + define_match[0].length, define_match.index + define_match[0].length + function_match.index));
            result.moduleBody = module_def_body;
            result.type = "amd";
            result.save = function (deps, inject) {
                // res_str will be: define([...],
                var res_str = save_template_chunks[0];
                for (var i = 1; i < save_template_chunks.length; i++) {
                    if (deps.length > 0 && deps[i - 1]) res_str += JSON.stringify(deps[i - 1]);
                    if (inject && inject.dependencies.length > 0 && (i == function_arguments_count || deps.length == 0)){
                        inject.dependencies.forEach(function(d, di) {
                            res_str += (di > 0 || deps.length > 0 ? "," : "") + JSON.stringify(d.dep);
                        });
                    }
                    res_str += save_template_chunks[i];
                }
                // res_str will be: define([...], function(x, y, z
                res_str += function_match[0].substr(0, function_match[0].length - 1);
                // res_str will be: define([...], function(x, y, z <injected>
                if (inject && inject.dependencies.length > 0){
                    inject.dependencies.forEach(function(d, di) {
                        res_str += (di > 0 || function_arguments_count > 0 ? "," : "") + d.name;
                    });
                }
                // res_str will be: define([...], function(x, y, z <injected>)
                res_str += ")";
                // res_str will be: define([...], function(x, y, z <injected>) {
                res_str += content.substring( define_match.index + define_match[0].length + function_match.index + function_match[0].length, module_def_start + 1);
                // res_str will be: define([...], function(x, y, z <injected>) { <injected>
                if (inject && inject.prepend) res_str += inject.prepend;
                // res_str will be: define([...], function(x, y, z <injected>) { <injected> ...
                res_str += this.moduleBody;
                // res_str will be: define([...], function(x, y, z <injected>) { <injected> ... <injected>
                if (inject && inject.append) res_str += inject.append;
                // res_str will be: define([...], function(x, y, z <injected>) { <injected> ... <injected> })
                res_str += content.substr(module_def_end);
                return res_str;
            }
        }
    } else {
        var nls_match = defineNlsRegExp.exec(content);
        if (nls_match){
            result.moduleBody =  "{" + nls_match[2] + "}";
            result.type = "nls";
            result.save = function (deps, inject){
                var res_str = content.substr(0, nls_match.index);
                // define(
                res_str += nls_match[1];
                if (inject && (inject.prepend || inject.append || inject.dependencies.length > 0)){
                    // -> define([...], function( ... ){ ... })
                    res_str += "[";
                    inject.dependencies.forEach(function(d, di) {
                        res_str += (di > 0 ? "," : "") + JSON.stringify(d.dep);
                    });
                    res_str += "], function(";
                    inject.dependencies.forEach(function(d, di) {
                        res_str += (di > 0 ? "," : "") + d.name;
                    });
                    res_str += "){"; // open function
                    if (inject.prepend) res_str += inject.prepend;
                    res_str += "return " + this.moduleBody + ";";
                    if (inject.append) res_str += inject.append;
                    res_str += "}";  // close function
                }
                else res_str += this.moduleBody;
                // define(...);
                res_str += ")";
                res_str += content.substr(nls_match.index + nls_match[0].length);
                return res_str;
            }
        }
    }
    if (!result.save) result.save = function() { return content; };
    return result;
};

// Output:
// {ifTest: "str", ifTrue: ..., ifFalse: ...}
parser.parseDojoHasTernaryExpression = function(expression){
    var stack = [];
    var symbols = /[\?:]/g;
    var match;
    var prev_index = 0;
    function add_value(val){
        if (stack.length > 0){
            if (stack[stack.length - 1].ifTrue === undefined) stack[stack.length - 1].ifTrue = val;
            else stack[stack.length - 1].ifFalse = val;
        }
    }
    while (match = symbols.exec(expression)) {
        var cut = expression.substring(prev_index, match.index);
        prev_index = match.index + match[0].length;
        if (match[0] == '?'){
            var val = {
                ifTest: cut,
                ifTrue: undefined,
                ifFalse: undefined
            };
            add_value(val);
            stack.push(val);
        }
        else {
            add_value(cut);
            if (stack.length > 1) stack.pop();
        }
    }
    var cut_last = expression.substring(prev_index);
    add_value(cut_last);
    return stack[0];
};

// Parse dependency
parser.parseDependency = function(dep){
    var match = dep.dep.match(dependencyRegExp);
    var loaders = match[2];
    if (loaders) loaders = loaders.split("!");
    var condition = null;
    if (match[4]) condition = parser.parseDojoHasTernaryExpression(match[3] + match[4]);
    return {
        name: dep.name,
        loaders: loaders ? loaders : [],
        main: match[3],
        // for dojo/has!
        condition: condition
    }
};

// Find pair { }
// from should point to first {
// type: {} - default, (), []
// return index of end }
parser.getCodeBlockEnd = function(text, from, type){
    var curles;
    if (!type) type = '{}';
    switch (type) {
        case '()': curles = /[\(\)]/g; break;
        case '[]': curles = /[\[\]]/g; break;
        default:   curles = /[{}]/g; break;
    }
    var text = text.substr(from + 1);
    var open = 1;
    var match;
    while (match = curles.exec(text)){
        if (match[0] == type[0]) open++;
        else open--;
        if (open == 0) break;
    }
    if (open != 0) throw new Error("DojoWebpackLoader: cannot find complete { } block");
    return from + 1 + match.index;
};

module.exports = parser;
<commit_msg>Update parser.js<commit_after>var stripComments = require("strip-comments"),
    parser = {},
    quoteRegExp = /['"]/,
    dependencyRegExp = /^((.*)\!)*(.*?)(\?.*?)?$/;

// define([...] - for standard amd modules
var defineAmdRegExp = /(\s*define\s*\(\s*)\[([^\]]*?)\]/m;
// define({...}) - for nls modules
var defineNlsRegExp = /(\s*define\s*\(\s*)\(?\{([\s\S]*)\}\)?\s*\)/m;

// parse dojo AMD-modules and return:
// {
//      deps: Array of string - dependencies,
//      save: function(new_deps, inject) - return content string with replaced dependencies and injected code
// }
parser.parseModule = function(content){
    // Skip single line comments since this can also end up removing regex by accident
    content = stripComments(content, {
        line: false
    });
    var define_match = defineAmdRegExp.exec(content),
        result = {
            deps: [],
            save: null,
            type: null,
            moduleBody: null
        };
    if (define_match){
        // Process header of module ctor func:
        var function_match = /function\s*\(([\s\S]*?)\)/.exec(content.substring(define_match.index + define_match[0].length));
        var function_arguments_text = function_match[1];
        var function_arguments_array = function_arguments_text.split(",");
        var function_arguments_count = function_arguments_array.length; // count of really used dependencies
        if (function_arguments_count == 1 && function_arguments_text.trim() == '') function_arguments_count = 0;
        // Process body of module ctor func:
        var module_def_start = content.indexOf("{", function_match.index + function_match[0].length);
        var module_def_end = content.lastIndexOf("}");
        var module_def_body = content.substring(module_def_start + 1, module_def_end);

        if (function_match && module_def_start >= 0 && module_def_end >= 0) {
            var save_template_chunks = [content.substr(0, define_match.index) + define_match[1] + '['];
            var cur_chunk = 0;
            // list of module depencies: "module1", 'module2' ...
            var cur_incl_str = define_match[2];
            var dep_strpos_start;
            while ((dep_strpos_start = cur_incl_str.search(quoteRegExp)) >= 0){
                save_template_chunks[cur_chunk] = (save_template_chunks[cur_chunk] ? save_template_chunks[cur_chunk] : '') +
                    cur_incl_str.substr(0, dep_strpos_start);
                // search end quote
                var start_index = dep_strpos_start + 1;
                var dep_strpos_end = -1;
                while (dep_strpos_end < 0){
                    var quote_index = cur_incl_str.indexOf(cur_incl_str[dep_strpos_start], start_index);
                    if (quote_index < 0) throw new Error("DojoWebpackLoader: cannot find closing quoute in dojo module definition");
                    if (cur_incl_str[quote_index - 1] != '\\'){
                        dep_strpos_end = quote_index;
                    }
                    else {
                        // quoute is escaped => find next
                        start_index = quote_index + 1;
                    }
                }
                // get dependency
                var dep_string = cur_incl_str.substring(dep_strpos_start + 1, dep_strpos_end);
                // simple strip slashes
                dep_string = dep_string.replace(/\\(.)/g, "$1");
                result.deps.push({
                    dep: dep_string,
                    name: function_arguments_array[result.deps.length] ? function_arguments_array[result.deps.length].trim() : undefined
                });
                // prepare for searching next dependency:
                cur_incl_str = cur_incl_str.substr(dep_strpos_end + 1);
                cur_chunk++;
            }
            // Append before function ctor;
            save_template_chunks.push(cur_incl_str + "]" + content.substring(define_match.index + define_match[0].length, define_match.index + define_match[0].length + function_match.index));
            result.moduleBody = module_def_body;
            result.type = "amd";
            result.save = function (deps, inject) {
                // res_str will be: define([...],
                var res_str = save_template_chunks[0];
                for (var i = 1; i < save_template_chunks.length; i++) {
                    if (deps.length > 0 && deps[i - 1]) res_str += JSON.stringify(deps[i - 1]);
                    if (inject && inject.dependencies.length > 0 && (i == function_arguments_count || deps.length == 0)){
                        inject.dependencies.forEach(function(d, di) {
                            res_str += (di > 0 || deps.length > 0 ? "," : "") + JSON.stringify(d.dep);
                        });
                    }
                    res_str += save_template_chunks[i];
                }
                // res_str will be: define([...], function(x, y, z
                res_str += function_match[0].substr(0, function_match[0].length - 1);
                // res_str will be: define([...], function(x, y, z <injected>
                if (inject && inject.dependencies.length > 0){
                    inject.dependencies.forEach(function(d, di) {
                        res_str += (di > 0 || function_arguments_count > 0 ? "," : "") + d.name;
                    });
                }
                // res_str will be: define([...], function(x, y, z <injected>)
                res_str += ")";
                // res_str will be: define([...], function(x, y, z <injected>) {
                res_str += content.substring( define_match.index + define_match[0].length + function_match.index + function_match[0].length, module_def_start + 1);
                // res_str will be: define([...], function(x, y, z <injected>) { <injected>
                if (inject && inject.prepend) res_str += inject.prepend;
                // res_str will be: define([...], function(x, y, z <injected>) { <injected> ...
                res_str += this.moduleBody;
                // res_str will be: define([...], function(x, y, z <injected>) { <injected> ... <injected>
                if (inject && inject.append) res_str += inject.append;
                // res_str will be: define([...], function(x, y, z <injected>) { <injected> ... <injected> })
                res_str += content.substr(module_def_end);
                return res_str;
            }
        }
    } else {
        var nls_match = defineNlsRegExp.exec(content);
        if (nls_match){
            result.moduleBody =  "{" + nls_match[2] + "}";
            result.type = "nls";
            result.save = function (deps, inject){
                var res_str = content.substr(0, nls_match.index);
                // define(
                res_str += nls_match[1];
                if (inject && (inject.prepend || inject.append || inject.dependencies.length > 0)){
                    // -> define([...], function( ... ){ ... })
                    res_str += "[";
                    inject.dependencies.forEach(function(d, di) {
                        res_str += (di > 0 ? "," : "") + JSON.stringify(d.dep);
                    });
                    res_str += "], function(";
                    inject.dependencies.forEach(function(d, di) {
                        res_str += (di > 0 ? "," : "") + d.name;
                    });
                    res_str += "){"; // open function
                    if (inject.prepend) res_str += inject.prepend;
                    res_str += "return " + this.moduleBody + ";";
                    if (inject.append) res_str += inject.append;
                    res_str += "}";  // close function
                }
                else res_str += this.moduleBody;
                // define(...);
                res_str += ")";
                res_str += content.substr(nls_match.index + nls_match[0].length);
                return res_str;
            }
        }
    }
    if (!result.save) result.save = function() { return content; };
    return result;
};

// Output:
// {ifTest: "str", ifTrue: ..., ifFalse: ...}
parser.parseDojoHasTernaryExpression = function(expression){
    var stack = [];
    var symbols = /[\?:]/g;
    var match;
    var prev_index = 0;
    function add_value(val){
        if (stack.length > 0){
            if (stack[stack.length - 1].ifTrue === undefined) stack[stack.length - 1].ifTrue = val;
            else stack[stack.length - 1].ifFalse = val;
        }
    }
    while (match = symbols.exec(expression)) {
        var cut = expression.substring(prev_index, match.index);
        prev_index = match.index + match[0].length;
        if (match[0] == '?'){
            var val = {
                ifTest: cut,
                ifTrue: undefined,
                ifFalse: undefined
            };
            add_value(val);
            stack.push(val);
        }
        else {
            add_value(cut);
            if (stack.length > 1) stack.pop();
        }
    }
    var cut_last = expression.substring(prev_index);
    add_value(cut_last);
    return stack[0];
};

// Parse dependency
parser.parseDependency = function(dep){
    var match = dep.dep.match(dependencyRegExp);
    var loaders = match[2];
    if (loaders) loaders = loaders.split("!");
    var condition = null;
    if (match[4]) condition = parser.parseDojoHasTernaryExpression(match[3] + match[4]);
    return {
        name: dep.name,
        loaders: loaders ? loaders : [],
        main: match[3],
        // for dojo/has!
        condition: condition
    }
};

// Find pair { }
// from should point to first {
// type: {} - default, (), []
// return index of end }
parser.getCodeBlockEnd = function(text, from, type){
    var curles;
    if (!type) type = '{}';
    switch (type) {
        case '()': curles = /[\(\)]/g; break;
        case '[]': curles = /[\[\]]/g; break;
        default:   curles = /[{}]/g; break;
    }
    var text = text.substr(from + 1);
    var open = 1;
    var match;
    while (match = curles.exec(text)){
        if (match[0] == type[0]) open++;
        else open--;
        if (open == 0) break;
    }
    if (open != 0) throw new Error("DojoWebpackLoader: cannot find complete { } block");
    return from + 1 + match.index;
};

module.exports = parser;
<|endoftext|>


<commit_before>/*
The MIT License (MIT)
Copyright (c) 2014 Microsoft Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

"use strict";

var crypto = require("crypto");

var AuthHandler = {
    getAuthorizationHeader: function (documentClient, verb, path, resourceId, resourceType, headers) {
        if (documentClient.masterKey) {
            return this.getAuthorizationTokenUsingMasterKey(verb, resourceId, resourceType, headers, documentClient.masterKey);
        } else if (documentClient.resourceTokens) {
            return this.getAuthorizationTokenUsingResourceTokens(documentClient.resourceTokens, path, resourceId);
        }
    },

    getAuthorizationTokenUsingMasterKey: function (verb, resourceId, resourceType, headers, masterKey) {
        var key = new Buffer(masterKey, "base64");

        var text = (verb || "").toLowerCase() + "\n" +
                   (resourceType || "").toLowerCase() + "\n" +
                   (resourceId || "") + "\n" +
                   (headers["x-ms-date"] || "").toLowerCase() + "\n" +
                   (headers["date"] || "").toLowerCase() + "\n";

        var body = new Buffer(text, "utf8");

        var signature = crypto.createHmac("sha256", key).update(body).digest("base64");

        var MasterToken = "master";

        var TokenVersion = "1.0";

        return "type=" + MasterToken + "&ver=" + TokenVersion + "&sig=" + signature;
    },

    getAuthorizationTokenUsingResourceTokens: function (resourceTokens, path, resourceId) {
        if (resourceTokens[resourceId]) {
            return resourceTokens[resourceId];
        } else {
            var pathParts = path.split("/");
            var resourceTypes = ["dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions", "attachments", "media", "conflicts", "offers"];
            for (var i = pathParts.length - 1; i >= 0; i--) {
                if (resourceTypes.indexOf(pathParts[i]) === -1) {
                    if (resourceTokens[pathParts[i]]) {
                        return resourceTokens[pathParts[i]];
                    }
                }
            }
        }
    }
};

if (typeof exports !== "undefined") {
    module.exports = AuthHandler;
}<commit_msg>Fixing auth issue for resource token based logic<commit_after>/*
The MIT License (MIT)
Copyright (c) 2014 Microsoft Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

"use strict";

var crypto = require("crypto");

var AuthHandler = {
    getAuthorizationHeader: function (documentClient, verb, path, resourceId, resourceType, headers) {
        if (documentClient.masterKey) {
            return this.getAuthorizationTokenUsingMasterKey(verb, resourceId, resourceType, headers, documentClient.masterKey);
        } else if (documentClient.resourceTokens) {
            return this.getAuthorizationTokenUsingResourceTokens(documentClient.resourceTokens, path, resourceId);
        }
    },

    getAuthorizationTokenUsingMasterKey: function (verb, resourceId, resourceType, headers, masterKey) {
        var key = new Buffer(masterKey, "base64");

        var text = (verb || "").toLowerCase() + "\n" +
                   (resourceType || "").toLowerCase() + "\n" +
                   (resourceId || "") + "\n" +
                   (headers["x-ms-date"] || "").toLowerCase() + "\n" +
                   (headers["date"] || "").toLowerCase() + "\n";

        var body = new Buffer(text, "utf8");

        var signature = crypto.createHmac("sha256", key).update(body).digest("base64");

        var MasterToken = "master";

        var TokenVersion = "1.0";

        return "type=" + MasterToken + "&ver=" + TokenVersion + "&sig=" + signature;
    },

    getAuthorizationTokenUsingResourceTokens: function (resourceTokens, path, resourceId) {
        if (resourceTokens && Object.keys(resourceTokens).length > 0) {
            // For database account access(through getDatabaseAccount API), path and resourceId are "",
            // so in this case we return the first token to be used for creating the auth header as the service will accept any token in this case
            if (!path && !resourceId) {
                return resourceTokens[Object.keys(resourceTokens)[0]];
            }
            if (resourceTokens[resourceId]) {
                return resourceTokens[resourceId];
            } else {
                var pathParts = path.split("/");
                var resourceTypes = ["dbs", "colls", "docs", "sprocs", "udfs", "triggers", "users", "permissions", "attachments", "media", "conflicts", "offers"];
                // Get the last resource id from the path and get it's token from resourceTokens
                for (var i = pathParts.length - 1; i >= 0; i--) {
                    if (resourceTypes.indexOf(pathParts[i]) === -1) {
                        if (resourceTokens[pathParts[i]]) {
                            return resourceTokens[pathParts[i]];
                        }
                    }
                }
            }
        }
        return null;
    }
};

if (typeof exports !== "undefined") {
    module.exports = AuthHandler;
}<|endoftext|>


<commit_before>import Inferno from 'inferno'
import Component from 'inferno-component'

export default class About extends Component {
    render() {
        return

About Inferno

                    Inferno 1.0 is really well written. It's how I would've written React. I'd recommend reading its source to learn.
                    — member of the React core team at Facebook

Objective

                    Inferno is designed to be a light-weight and blazing fast React-like
                    Javascript library for building modern interfaces. It was also designed
                    to be React compatible, modular and isomorphic. The community supporting
                    its development is tasked with continuously improving performance and
                    exploring new and efficient methods.

What's React?

                    For those not familiar with React, Inferno is a JavaScript library for
                    building user interfaces in a declarative manner. Rather than working
                    with MVC/MVVM style patterns, Inferno uses a component-based approach
                    where data flows in one direction, making coding predictable, re-usable
                    and highly testable. Based on the concept of learn once, write anywhere,
                    Inferno doesn't impose any restrictions on how you create components. You
                    literally write JavaScript to state how you'd like your UI to look –
                    Inferno does all the rest. Inferno also renders content on the server
                    via inferno-server and NodeJS, so you can write awesome UIs that get
                    rendered full-stack.

History

                    Inferno started as an idea two years ago, to see if a UI library could really
                    improve the experience, battery, memory usage and performance on mobile devices.
                    At the time we really struggled to get good performance on any UI library/framework
                    at the time – it simply wasn't happening, we spent a huge amount of time writing
                    lots of vanilla JavaScript code and it did the job – but it was a mess.

                    Since then, things haven't really improved much in the mobile space. Libraries
                    have gotten smaller, but the time to parse a 2mb app can result in 5+ seconds
                    time before the user can even see anything. Frameworks and libraries need to
                    lose bloat, they need to care about performance. Developing on a MacBook Pro
                    and seeing animations, routing, complex UIs instantly appear is not going to
                    happen on an average mobile device (especially in emerging countries).

Who's Using Inferno?

                    Inferno 1.0 was officially released in early January 2017, however many projects
                    have already started using Inferno either in production or for internal testing.
                    In a short period of time Inferno grew from around 150 Github stars at the start
                    of the year, to around 7300 by the end of the year, 15 NPM downloads to 15k a
                    month and 300k downloads from the CDN. Inferno is actively being vetted or already
                    in production by these companies:

The Grid

Evite.com

Globo.com (Brazil)

                    If your company/project is actively using Inferno, we'd love to know about it!

Read About Inferno

                    As the Inferno community grows and evolves, we hope that other people will
                    contribute by writing new articles about the library or the community surrounding it.
                    Here's a collection of some articles published to date:

Learn About Inferno JS: Build and Authenticate an App

Hacker News

Inferno - Blazing fast, React-like UI library - Interview with Dominic Gannaway

JS web frameworks benchmark – Round 4

Introduction To Functional Front-Ends With Inferno

Mobile

                    Inferno proves that it is possible to be fast on mobile. Parse-time, load-time,
                    rendering complex UIs and all the normal things you'd expect to just work. How
                    Inferno does that is based on many factors, but ultimately Inferno's code is much
                    better understood by modern JavaScript engines and can be highly optimised to
                    perform far better than other libraries/frameworks.

    }
}
<commit_msg>Push update to recompile<commit_after>import Inferno from 'inferno'
import Component from 'inferno-component'

export default class About extends Component {
    render() {
        return

About Inferno

                    Inferno 1.0 is really well written. It's how I would've written React. I'd recommend reading its source to learn.
                    — member of the React core team at Facebook

Objective

                    Inferno is designed to be a light-weight and blazing fast React-like
                    Javascript library for building modern interfaces. It was also designed
                    to be React compatible, modular and isomorphic. The community supporting
                    its development is tasked with continuously improving performance and
                    exploring new and efficient methods.

What's React?

                    For those not familiar with React, Inferno is a JavaScript library for
                    building user interfaces in a declarative manner. Rather than working
                    with MVC/MVVM style patterns, Inferno uses a component-based approach
                    where data flows in one direction, making coding predictable, re-usable
                    and highly testable. Based on the concept of learn once, write anywhere,
                    Inferno doesn't impose any restrictions on how you create components. You
                    literally write JavaScript to state how you'd like your UI to look –
                    Inferno does all the rest. Inferno also renders content on the server
                    via inferno-server and NodeJS, so you can write awesome UIs that get
                    rendered full-stack.

History

                    Inferno started as an idea two years ago, to see if a UI library could really
                    improve the experience, battery, memory usage and performance on mobile devices.
                    At the time we really struggled to get good performance on any UI library/framework
                    at the time – it simply wasn't happening, we spent a huge amount of time writing
                    lots of vanilla JavaScript code and it did the job – but it was a mess.

                    Since then, things haven't really improved much in the mobile space. Libraries
                    have gotten smaller, but the time to parse a 2mb app can result in 5+ seconds
                    time before the user can even see anything. Frameworks and libraries need to
                    lose bloat, they need to care about performance. Developing on a MacBook Pro
                    and seeing animations, routing, complex UIs instantly appear is not going to
                    happen on an average mobile device (especially in emerging countries).

Who's Using Inferno?

                    Inferno 1.0 was officially released in early January 2017, however many projects
                    have already started using Inferno either in production or for internal testing.
                    In a short period of time Inferno grew from around 150 Github stars at the start
                    of the year, to around 7300 by the end of the year, 15 NPM downloads to 15k a
                    month and 300k downloads from the CDN. Inferno is actively being vetted or already
                    in production by these companies:

The Grid

Evite.com

Globo.com (Brazil)

                    If your company/project is actively using Inferno, we'd love to know about it!

Read About Inferno

                    As the Inferno community grows and evolves, we hope that other people will
                    contribute by writing new articles about the library or the community surrounding it.
                    Here's a collection of some articles published to date:

Learn About Inferno JS: Build and Authenticate an App

Hacker News

Inferno - Blazing fast, React-like UI library - Interview with Dominic Gannaway

JS web frameworks benchmark – Round 4

Introduction To Functional Front-Ends With Inferno

Mobile

                    Inferno proves that it is possible to be fast on mobile. Parse-time, load-time,
                    rendering complex UIs and all the normal things you'd expect to just work. How
                    Inferno does that is based on many factors, but ultimately Inferno's code is much
                    better understood by modern JavaScript engines and can be highly optimised to
                    perform far better than other libraries/frameworks.

    }
}
<|endoftext|>


<commit_before>var THREE = require('three.js');
var _ = require('lodash');
var d3 = require('d3');
var utils = require('lightning-client-utils')
require('three-fly-controls')(THREE);

var Particles = function(selector, data, images, opts) {

    if(!opts) {
        opts = {};
    }

    this.opts = opts
    this.width = (opts.width || $(selector).width());
    this.height = (opts.height || (this.width * 0.6));

    this.data = this._formatData(data)
    this.defaultColor = d3.rgb('#A38EF3')
    this.selector = selector;
    this._init();

}

Particles.prototype._init = function() {

    var width = this.width;
    var height = this.height;
    var selector = this.selector;
    var data = this.data;
    var points = data.points;

    var container, stats;
    var controls;
    var camera, scene, renderer, particles, geometry, materials = [], parameters, i, h, color, size;
    var mouseX = 0, mouseY = 0;

    var halfWidth = width / 2;
    var halfHeight = height / 2;

    var self = this;

    function init() {

        camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 3000 );

        scene = new THREE.Scene();
        //scene.fog = new THREE.FogExp2( 0x000000, 0.001 );
        geometry = new THREE.Geometry();

        var avgs = [0, 0, 0];

        _.each(data.points, function(p) {
            avgs[0] += p.y;
            avgs[1] += p.z;
            avgs[2] += p.x;
        });

        avgs = _.map(avgs, function(n) { return n / data.points.length; });

        max = d3.max(data.points, function(p) {return p.z})

        var colors = [];

        _.each(data.points, function(p, i) {
            var vertex = new THREE.Vector3();
            vertex.x = p.y - avgs[0];
            vertex.y = p.z - avgs[1];
            vertex.z = p.x - avgs[2];
            geometry.vertices.push( vertex );
            colors[i] = new THREE.Color();
            var rgb = p.c || self.defaultColor;
            colors[i].setRGB(rgb.r / 255, rgb.g / 255, rgb.b / 255);
        });

        THREE.ImageUtils.crossOrigin = '';
        var sprite = THREE.ImageUtils.loadTexture( "http://i.gif.fm/janelia-images/textures/disc.png" );

        geometry.colors = colors

        camera.position.y = 0;
        camera.position.x = -max*1.75;
        camera.position.z = 1;

        camera.lookAt(new THREE.Vector3(0, 0, 0));

        var material = new THREE.PointCloudMaterial({
            size: 25,
            map: sprite,
            transparent: true,
            sizeAttenuation: false,
            vertexColors: THREE.VertexColors,
            opacity: 0.9
        });

        particles = new THREE.PointCloud( geometry, material );
        particles.sortParticles = true;
        scene.add( particles );

        renderer = new THREE.WebGLRenderer({alpha: true});
        renderer.setSize( width, height );
        $(selector)[0].appendChild( renderer.domElement );

        $('canvas').css('border','1px solid rgb(200,200,200)')
        $('canvas').css('outline','-moz-outline-style: none; ')

        self.scene = scene;
        self.parameters = parameters;
        controls = new THREE.FlyControls(camera, $(selector)[0]);

    }

    function animate() {
        requestAnimationFrame( animate );
        render();
    }

    function render() {
        controls.update();
        renderer.render( scene, camera );
    }

    init();
    animate();

};

Particles.prototype._formatData = function(data) {

    retColor = utils.getColorFromData(data)

    data.points = data.points.map(function(d, i) {
        var p = []
        p.x = d[0]
        p.y = d[1]
        p.z = d[2]
        p.i = i
        p.c = retColor.length > 1 ? retColor[i] : retColor[0]
        return p
    })

    return data

}

module.exports = Particles;

<commit_msg>Set movement speed automatically from scale<commit_after>var THREE = require('three.js');
var _ = require('lodash');
var d3 = require('d3');
var utils = require('lightning-client-utils')
require('three-fly-controls')(THREE);

var Particles = function(selector, data, images, opts) {

    if(!opts) {
        opts = {};
    }

    this.opts = opts
    this.width = (opts.width || $(selector).width());
    this.height = (opts.height || (this.width * 0.6));

    this.data = this._formatData(data)
    this.defaultColor = d3.rgb('#A38EF3')
    this.selector = selector;
    this._init();

}

Particles.prototype._init = function() {

    var width = this.width;
    var height = this.height;
    var selector = this.selector;
    var data = this.data;
    var points = data.points;

    var container, stats;
    var controls;
    var camera, scene, renderer, particles, geometry, materials = [], parameters, i, h, color, size;
    var mouseX = 0, mouseY = 0;

    var halfWidth = width / 2;
    var halfHeight = height / 2;

    var self = this;

    function init() {

        camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 3000 );

        scene = new THREE.Scene();
        //scene.fog = new THREE.FogExp2( 0x000000, 0.001 );
        geometry = new THREE.Geometry();

        var avgs = [0, 0, 0];

        _.each(data.points, function(p) {
            avgs[0] += p.y;
            avgs[1] += p.z;
            avgs[2] += p.x;
        });

        avgs = _.map(avgs, function(n) { return n / data.points.length; });

        max = d3.max(data.points, function(p) {return p.z})

        var colors = [];

        _.each(data.points, function(p, i) {
            var vertex = new THREE.Vector3();
            vertex.x = p.y - avgs[0];
            vertex.y = p.z - avgs[1];
            vertex.z = p.x - avgs[2];
            geometry.vertices.push( vertex );
            colors[i] = new THREE.Color();
            var rgb = p.c || self.defaultColor;
            colors[i].setRGB(rgb.r / 255, rgb.g / 255, rgb.b / 255);
        });

        THREE.ImageUtils.crossOrigin = '';
        var sprite = THREE.ImageUtils.loadTexture( "http://i.gif.fm/janelia-images/textures/disc.png" );

        geometry.colors = colors

        camera.position.y = 0;
        camera.position.x = -max*1.75;
        camera.position.z = 1;

        camera.lookAt(new THREE.Vector3(0, 0, 0));

        var material = new THREE.PointCloudMaterial({
            size: 25,
            map: sprite,
            transparent: true,
            sizeAttenuation: false,
            vertexColors: THREE.VertexColors,
            opacity: 0.9
        });

        particles = new THREE.PointCloud( geometry, material );
        particles.sortParticles = true;
        scene.add( particles );

        renderer = new THREE.WebGLRenderer({alpha: true});
        renderer.setSize( width, height );
        $(selector)[0].appendChild( renderer.domElement );

        $('canvas').css('border','1px solid rgb(200,200,200)')
        $('canvas').css('outline','-moz-outline-style: none; ')

        self.scene = scene;
        self.parameters = parameters;
        controls = new THREE.FlyControls(camera, $(selector)[0], { movementSpeed: 0.1 * max / 4 });

    }

    function animate() {
        requestAnimationFrame( animate );
        render();
    }

    function render() {
        controls.update();
        renderer.render( scene, camera );
    }

    init();
    animate();

};

Particles.prototype._formatData = function(data) {

    retColor = utils.getColorFromData(data)

    data.points = data.points.map(function(d, i) {
        var p = []
        p.x = d[0]
        p.y = d[1]
        p.z = d[2]
        p.i = i
        p.c = retColor.length > 1 ? retColor[i] : retColor[0]
        return p
    })

    return data

}

module.exports = Particles;

<|endoftext|>