<commit_before>/*
 * This file is part of Invenio.
 * Copyright (C) 2014 CERN.
 *
 * Invenio is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * Invenio is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Invenio; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 */

define(['jquery', 'js/search/typeahead'], function($) {
    "use strict";

    $("form[name=search]").submit(function() {
        $('.add_to_search-form').remove()
        return true; // ensure form still submits
    })

    var spanWidth = "100px"

    // side buttons for results number field
    $('form[name=settings] select[name="of"]').buttonSelect({
        button: '
',
        span: '',
        next: '',
        prev: ''
    })

    // side buttons for output format field
    $('form[name=settings] select[name="rg"]').buttonSelect({
        button: '
',
        span: '',
        next: '',
        prev: ''
    })

    // if (!("autofocus" in $("form[name=search] input[name=q]"))) {
    //  // ensure we get the focus always in search input
    //  $("form[name=search] input[name=q]").focus();
    // }

    /**
     * Allows to deactivate a radio buttons (like check-buttons)
     * and make them behave as radio ones when the another one is clicked
     */
    $(".invenio-collapsable-tabs a").each(function(elem) {
        $(elem).click(function (){
            var buttons = $(this).siblings();
            if (buttons.hasClass("active")) {
                buttons.click()
            }
        })
    })

    // ------------ typeahead for "Add to search" form ----------------

    $('[data-provide="typeahead-url"]').each(function(index, elem) {

        var field = $(elem),
            source = field.data('source')

        var engine = new Bloodhound({
           datumTokenizer: function(d) {
                return Bloodhound.tokenizers.whitespace(d.value)
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            limit: 10,
            remote: {
                url: source,
                replace: function(url, query) {
                    return url + '?q=' + query
                },
                filter: function(response) {
                    return response.results
                }
            }
        })

        engine.initialize()

        field.typeahead(
            {
                minLength: 3
            },
            {
                source: engine.ttAdapter(),
                displayKey: 'value'
            }
        )
    })

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

    return function(form) {

        var operators = {'a': 'AND ', 'o': 'OR ', 'n': 'AND NOT '},
            // the visible search field
            searchQueryField = $('form[name=search] input[name=p]'),
            // all fields containg search query, there are some hidden ones too
            allSearchQueryFields = $('[name=p]')

       /**
         * Sets value of the main search field. Should be used
         * instead of jQuery's val() to update typeahead's
         * internal query.
         *
         * @method setSearchFieldValue
         * @param {String} val value to be set
         */
        function setSearchFieldValue(val) {
            searchQueryField.data('search_typeahead').setFieldValue(val)
            allSearchQueryFields.val(val)
        }

        /**
         * Merges value from 'advanced' tab in 'Add to search' form
         * with the current search query
         *
         * @method addAdvancedQuery
         * @returns {String} search query after adding the form content
         */
        function getAdvancedQuery() {
            var m1 = $('[name=m1]').val(),
                p1 = $('[name=p1]').val(),
                f = $('[name=f]').val(),
                p = $('[name=p]')

            if (p1 === "") {
                return ''
            }
            if (f !== "") {
                f += ':'
            }

            return form.matchingTypes[m1](p1, f)
        }

        /**
         * Removes query value from 'what?' field in 'advanced' tab
         *
         * @method cleanAdvancedQuery
         */
        function cleanAdvancedQueryForm() {
            $('[name=p1]').val('')
        }

        /**
         * Removes query values from all fields in 'simple' tab
         *
         * @method cleanSimpleQueryForm
         */
        function cleanSimpleQueryForm() {
            $(':focus').blur()
            $('#simple-search input').val('')
        }

        /**
         * Creates search query from 'simple' tab in 'Add to search' form
         *
         * @method getSimpleQuery
         * @returns {String} query from the form content
         *
         */
        function getSimpleQuery() {
            var query_str = '';

            // get values
            var p = $('[name=p]'),
                query = [],
                op1 = $('#add_type-btn-group .active').children(':first').val(),
                author = $('#author').val(),
                title = $('#title').val(),
                rn = $('#rn').val(),
                aff = $('#aff').val(),
                cn = $('#cn').val(),
                k = $('#k').val(),
                //eprinttype = $('#eprint-type').val(),
                //eprintnumber = $('#eprint-number').val(),
                j = $('#journal-name').val(),
                jvol = $('#journal-vol').val(),
                jpage = $('#journal-page').val()

            if (author !== '') { query.push('author:' + author) }
            if (title !== '') { query.push('title:' + title) }
            if (rn !== '') { query.push('reportnumber:' + rn) }
            if (aff !== '') { query.push('affiliation:' + aff) }
            if (cn !== '') { query.push('collaboration:' + cn) }
            if (k !== '') { query.push('keyword:' + k) }
            if (j !== '') { query.push('journal:' + j) }
            if (jvol !== '') { query.push('909C4v:' + jvol) }
            if (jpage !== '') { query.push('909C4c:' + jpage) }

            if (query.length > 0) {
                query_str = query.join(' ' + operators[op1])
            }

            return query_str
        }

        /**
         * Adds query from 'advanced' tab to the search field
         *
         * @method addAdvancedQueryToSearch
         */
        function addAdvancedQueryToSearch() {
            var current_query = $.trim(searchQueryField.val());
            var new_part = getAdvancedQuery();
            cleanAdvancedQueryForm();
            setSearchFieldValue(mergeQuery(current_query, new_part));
        }

        /**
         * Merges new part to old query using currently
         * chosen logic function
         *
         * @method mergeQuery
         * @param {String} old_query old query
         * @param {String} new_part a string which user is going to merge
         */
        function mergeQuery(current_query, new_part) {
            if (new_part === "") {
                return current_query;
            }

            var op1 = $('#add_type-btn-group .active').children(':first').val(),
                op = '';

            if (op1 !== 'a' || current_query !== "") {
                op = operators[op1]
            }

            if (current_query + new_part !== "") {
                current_query += ' ' + op;
            }

            return current_query + new_part;
        }

        /**
         * Updates query value in the search field
         *
         * @method makeSearchQuery
         */
        function makeSearchQuery() {
            var active_tab = $('.add_to_search-form .tab-buttons li.active a').attr('href');

            if (active_tab === '#simple-search') {
                var current_query = $.trim(searchQueryField.val())
                var new_part = getSimpleQuery()
                setSearchFieldValue(mergeQuery(current_query, new_part))
                cleanSimpleQueryForm()
            } else {
                addAdvancedQueryToSearch()
                $('.add_to_search-form .appender').trigger('click')
            }
        }

        // search buttons
        $('.add_to_search-form button[name=action_search]').on('click', function(e) {
            makeSearchQuery()
            e.stopPropagation()
        })

        // browse buttons
        $('.add_to_search-form button[name=action_browse]').on('click', function(e) {
            makeSearchQuery()
            var $main_search_button = $('#searchform-input-group button[name=action_search]')
            $main_search_button.attr('name', 'action_browse')
            $main_search_button.trigger('click')
        })

        $('#add_to_search-button').on('click', function(e) {
            addAdvancedQueryToSearch()
            return false
        })

        $('.add_to_search-form #advanced-search input, .add_to_search-form #simple-search input').keypress(function(event) {
            // on 'return' key
            if ( event.which == 13 ) {
                makeSearchQuery()
                return false
            }
        })

        $('.add_to_search-form #advanced-search .appender').on('click', function(e) {
            var op1 = $('#add_type-btn-group .active').children(':first').val(),
                btn = $(this),
                source = $('[name=' + btn.data('source') + ']'),
                target = $('[name=' + btn.data('target') + ']'),
                val = $.trim(target.val()),
                op = (op1 == 'a' && val === '') ? '' : operators[op1]

            if (val !== '') {
                val += ' ' + op
            }
            if (source.val().length > 0) {
                target.val(val + source.attr('name') + ':"' + source.val() + '"')
                source.val('')
            }
            e.stopPropagation()
            return false
        })

        // -------------- SEARCH FIELD TYPEAHEAD ----------------

        var areaKeywords = $.map(form.keywords, function(val, i) {
            return val[0]
        })

        $('form[name=search] input[name=p]').searchTypeahead({
          value_hints_url: form.hintsUrl,
          options_sets: {
            invenio: getDefaultParserConf(areaKeywords)
          },
          default_set: form.defaultSet
        })
    }
})
<commit_msg>search: fix query string in add-to-search<commit_after>/*
 * This file is part of Invenio.
 * Copyright (C) 2014 CERN.
 *
 * Invenio is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * Invenio is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Invenio; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 */

define(['jquery', 'js/search/typeahead'], function($) {
    "use strict";

    $("form[name=search]").submit(function() {
        $('.add_to_search-form').remove()
        return true; // ensure form still submits
    })

    var spanWidth = "100px"

    // side buttons for results number field
    $('form[name=settings] select[name="of"]').buttonSelect({
        button: '
',
        span: '',
        next: '',
        prev: ''
    })

    // side buttons for output format field
    $('form[name=settings] select[name="rg"]').buttonSelect({
        button: '
',
        span: '',
        next: '',
        prev: ''
    })

    // if (!("autofocus" in $("form[name=search] input[name=q]"))) {
    //  // ensure we get the focus always in search input
    //  $("form[name=search] input[name=q]").focus();
    // }

    /**
     * Allows to deactivate a radio buttons (like check-buttons)
     * and make them behave as radio ones when the another one is clicked
     */
    $(".invenio-collapsable-tabs a").each(function(elem) {
        $(elem).click(function (){
            var buttons = $(this).siblings();
            if (buttons.hasClass("active")) {
                buttons.click()
            }
        })
    })

    // ------------ typeahead for "Add to search" form ----------------

    $('[data-provide="typeahead-url"]').each(function(index, elem) {

        var field = $(elem),
            source = field.data('source')

        var engine = new Bloodhound({
           datumTokenizer: function(d) {
                return Bloodhound.tokenizers.whitespace(d.value)
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            limit: 10,
            remote: {
                url: source,
                replace: function(url, query) {
                    return url + '?q=' + query
                },
                filter: function(response) {
                    return response.results
                }
            }
        })

        engine.initialize()

        field.typeahead(
            {
                minLength: 3
            },
            {
                source: engine.ttAdapter(),
                displayKey: 'value'
            }
        )
    })

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

    return function(form) {

        var operators = {'a': 'AND ', 'o': 'OR ', 'n': 'AND NOT '},
            // the visible search field
            searchQueryField = $('form[name=search] input[name=p]'),
            // all fields containg search query, there are some hidden ones too
            allSearchQueryFields = $('[name=p]')

       /**
         * Sets value of the main search field. Should be used
         * instead of jQuery's val() to update typeahead's
         * internal query.
         *
         * @method setSearchFieldValue
         * @param {String} val value to be set
         */
        function setSearchFieldValue(val) {
            searchQueryField.data('search_typeahead').setFieldValue(val)
            allSearchQueryFields.val(val)
        }

        /**
         * Merges value from 'advanced' tab in 'Add to search' form
         * with the current search query
         *
         * @method addAdvancedQuery
         * @returns {String} search query after adding the form content
         */
        function getAdvancedQuery() {
            var m1 = $('[name=m1]').val(),
                p1 = $('[name=p1]').val(),
                f = $('[name=f]').val(),
                p = $('[name=p]')

            if (p1 === "") {
                return ''
            }
            if (f !== "") {
                f += ':'
            }

            return form.matchingTypes[m1](p1, f)
        }

        /**
         * Removes query value from 'what?' field in 'advanced' tab
         *
         * @method cleanAdvancedQuery
         */
        function cleanAdvancedQueryForm() {
            $('[name=p1]').val('')
        }

        /**
         * Removes query values from all fields in 'simple' tab
         *
         * @method cleanSimpleQueryForm
         */
        function cleanSimpleQueryForm() {
            $(':focus').blur()
            $('#simple-search input').val('')
        }

        /**
         * Creates search query from 'simple' tab in 'Add to search' form
         *
         * @method getSimpleQuery
         * @returns {String} query from the form content
         *
         */
        function getSimpleQuery() {
            var query_str = '';

            // get values
            var p = $('[name=p]'),
                query = [],
                op1 = $('#add_type-btn-group .active').children(':first').val(),
                author = $('#author').val(),
                title = $('#title').val(),
                rn = $('#rn').val(),
                aff = $('#aff').val(),
                cn = $('#cn').val(),
                k = $('#k').val(),
                //eprinttype = $('#eprint-type').val(),
                //eprintnumber = $('#eprint-number').val(),
                j = $('#journal-name').val(),
                jvol = $('#journal-vol').val(),
                jpage = $('#journal-page').val(),
                //match every word or the whole sentence in the quotes
                matcher = /("(?:[^"\\]|\\.)*")|('(?:[^'\\]|\\.)*')|(\S+)/g

            function buildQueryElement(fieldName, input, reg) {
                reg = reg ? reg : matcher;
                var matches = input.match(reg);

                return $.map(matches, function(item) {
                    return fieldName + item;
                }).join(" " + operators[op1] + " ");
            }

            if (author !== '') {
                query.push('author:' + '\"' + author + '\"');
            }
            if (title !== '') {
                query.push('title:' + '\"' + title + '\"');
            }
            if (rn !== '') {
                query.push(buildQueryElement("reportnumber:", rn));
            }
            if (aff !== '') {
                query.push(buildQueryElement("affiliation:", aff));
            }
            if (cn !== '') {
                query.push(buildQueryElement('collaboration:', cn));
            }
            if (k !== '') {
                query.push(buildQueryElement('keyword:', k));
            }

            if (j !== '') { query.push('journal:' + j); }
            if (jvol !== '') { query.push('909C4v:' + jvol); }
            if (jpage !== '') { query.push('909C4c:' + jpage); }

            if (query.length > 0) {
                query_str = query.join(' ' + operators[op1]);
            }

            return query_str;
        }

        /**
         * Adds query from 'advanced' tab to the search field
         *
         * @method addAdvancedQueryToSearch
         */
        function addAdvancedQueryToSearch() {
            var current_query = $.trim(searchQueryField.val());
            var new_part = getAdvancedQuery();
            cleanAdvancedQueryForm();
            setSearchFieldValue(mergeQuery(current_query, new_part));
        }

        /**
         * Merges new part to old query using currently
         * chosen logic function
         *
         * @method mergeQuery
         * @param {String} old_query old query
         * @param {String} new_part a string which user is going to merge
         */
        function mergeQuery(current_query, new_part) {
            if (new_part === "") {
                return current_query;
            }

            var op1 = $('#add_type-btn-group .active').children(':first').val(),
                op = '';

            if (op1 !== 'a' || current_query !== "") {
                op = operators[op1]
            }

            if (current_query + new_part !== "") {
                current_query += ' ' + op;
            }

            return current_query + new_part;
        }

        /**
         * Updates query value in the search field
         *
         * @method makeSearchQuery
         */
        function makeSearchQuery() {
            var active_tab = $('.add_to_search-form .tab-buttons li.active a').attr('href');

            if (active_tab === '#simple-search') {
                var current_query = $.trim(searchQueryField.val())
                var new_part = getSimpleQuery()
                setSearchFieldValue(mergeQuery(current_query, new_part))
                cleanSimpleQueryForm()
            } else {
                addAdvancedQueryToSearch()
                $('.add_to_search-form .appender').trigger('click')
            }
        }

        // search buttons
        $('.add_to_search-form button[name=action_search]').on('click', function(e) {
            makeSearchQuery()
            e.stopPropagation()
        })

        // browse buttons
        $('.add_to_search-form button[name=action_browse]').on('click', function(e) {
            makeSearchQuery()
            var $main_search_button = $('#searchform-input-group button[name=action_search]')
            $main_search_button.attr('name', 'action_browse')
            $main_search_button.trigger('click')
        })

        $('#add_to_search-button').on('click', function(e) {
            addAdvancedQueryToSearch()
            return false
        })

        $('.add_to_search-form #advanced-search input, .add_to_search-form #simple-search input').keypress(function(event) {
            // on 'return' key
            if ( event.which == 13 ) {
                makeSearchQuery()
                return false
            }
        })

        $('.add_to_search-form #advanced-search .appender').on('click', function(e) {
            var op1 = $('#add_type-btn-group .active').children(':first').val(),
                btn = $(this),
                source = $('[name=' + btn.data('source') + ']'),
                target = $('[name=' + btn.data('target') + ']'),
                val = $.trim(target.val()),
                op = (op1 == 'a' && val === '') ? '' : operators[op1]

            if (val !== '') {
                val += ' ' + op
            }
            if (source.val().length > 0) {
                target.val(val + source.attr('name') + ':"' + source.val() + '"')
                source.val('')
            }
            e.stopPropagation()
            return false
        })

        // -------------- SEARCH FIELD TYPEAHEAD ----------------

        var areaKeywords = $.map(form.keywords, function(val, i) {
            return val[0]
        })

        $('form[name=search] input[name=p]').searchTypeahead({
          value_hints_url: form.hintsUrl,
          options_sets: {
            invenio: getDefaultParserConf(areaKeywords)
          },
          default_set: form.defaultSet
        })
    }
})
<|endoftext|>


<commit_before>function AudioEngine () {

    // soundfont setup

    // instrument names used by Musyng Kite soundfont, in order to match scratch instruments
    this.instrumentNames = ['acoustic_grand_piano', 'electric_piano_1', 'drawbar_organ', 'acoustic_guitar_nylon',
        'electric_guitar_clean', 'acoustic_bass', 'pizzicato_strings', 'cello', 'trombone', 'clarinet'];

    Soundfont.instrument(Tone.context, 'acoustic_grand_piano').then(function (piano) {
        this.instrument = piano;
    }.bind(this));

    // tone setup

	this.tone = new Tone();

	// effects setup

    this.delay = new Tone.FeedbackDelay(0.25, 0.5);
    this.delay.wet.value = 0;

    this.pitchShift = new Tone.PitchShift();

    this.panner = new Tone.Panner();

    this.reverb = new Tone.Freeverb();
    this.reverb.wet.value = 0;

    Tone.Master.chain(this.delay, this.pitchShift, this.panner, this.reverb);

    // drum sounds

    var drumFileNames = ['high_conga', 'small_cowbell', 'snare_drum', 'splash cymbal'];
    this.drumSamplers = this._loadSoundFiles(drumFileNames);

    // sound urls - map each url to its tone.sampler
    this.soundSamplers = [];
}

AudioEngine.prototype.playSound = function (soundNum) {
    this.soundSamplers[soundNum].triggerAttack();
};

AudioEngine.prototype.playSoundFromUrl = function (url) {
    if (url) {
        // if we've loaded it already, play it
        if (this.soundSamplers[url]) {
            this.soundSamplers[url].triggerAttack();
        } else {
        // else load, play, and store it
        // this results in a delay the first time you play the sound
            var sampler = new Tone.Sampler(url, function() {
                sampler.triggerAttack();
                this.soundSamplers[url] = sampler;
            }.bind(this)).toMaster();
        }
    }
};

AudioEngine.prototype.getSoundDuration = function (soundNum) {
    return this.soundSamplers[soundNum].player.buffer.duration;
};

AudioEngine.prototype.playNoteForBeats = function(note, beats) {
};

AudioEngine.prototype.playNoteForBeats = function(note, beats) {
    this.instrument.play(note, Tone.context.currentTime, {duration : Number(beats)});
};

AudioEngine.prototype.playDrumForBeats = function(drumNum, beats) {
    this.drumSamplers[drumNum].triggerAttack();
};

AudioEngine.prototype.stopAllSounds = function() {
    // stop drum notes
    for (var i=0; i<this.drumSamplers.length; i++) {
        this.drumSamplers[i].triggerRelease();
    }
    // stop sounds triggered with playSound (indexed by their urls)
    for (var i in this.soundSamplers) {
        this.soundSamplers[i].triggerRelease();
    }
    // stop soundfont notes
    this.instrument.stop();
};

AudioEngine.prototype.setEffect = function(effect, value) {
    switch (effect) {
        case 'ECHO':
            this.delay.wet.value = (value / 100) / 2; // max 50% wet (need dry signal too)
            break;
        case 'PAN':
            this.panner.pan.value = value / 100;
            break;
        case 'REVERB':
            this.reverb.wet.value = value / 100;
            break;
        case 'PITCH':
            this.pitchShift.pitch = value / 20; // arbitrary scaling of 20 per semitone, for now... default 100 is a perfect fourth
            break;
    }
}

AudioEngine.prototype.changeEffect = function(effect, value) {
    switch (effect) {
        case 'ECHO':
            this.delay.wet.value += (value / 100) / 2; // max 50% wet (need dry signal too)
            this.delay.wet.value = this._clamp(this.delay.wet.value, 0, 0.5);
            break;
        case 'PAN':
            this.panner.pan.value += value / 100;
            this.panner.pan.value = this._clamp(this.panner.pan.value, -1, 1);
            break;
        case 'REVERB':
            this.reverb.wet.value += value / 100;
            this.reverb.wet.value = this._clamp(this.reverb.wet.value, 0, 1);
            break;
        case 'PITCH':
            this.pitchShift.pitch += value / 20;
            break;
    }
}

AudioEngine.prototype.clearEffects = function() {
    this.delay.wet.value = 0;
    this.panner.pan.value = 0;
    this.reverb.wet.value = 0;
    this.pitchShift.pitch = 0;
}

AudioEngine.prototype.loadSoundFromUrl = function(url) {

};

AudioEngine.prototype._loadSoundFiles = function(filenames) {
    var samplers = [];

    for (var name of filenames) {
        var sampler = new Tone.Sampler('sounds/' + name + '.mp3').toMaster();
        samplers.push(sampler);
    }

    return samplers;
};

AudioEngine.prototype._midiToFreq = function(midiNote) {
	var freq = this.tone.intervalToFrequencyRatio(midiNote - 60) * 261.63; // 60 is C4
	return freq;
};

AudioEngine.prototype._clamp = function(input, min, max) {
    return Math.min(Math.max(input, min), max);
};

<commit_msg>cleanup<commit_after>function AudioEngine () {

    // tone setup

	this.tone = new Tone();

	// effects setup

    this.delay = new Tone.FeedbackDelay(0.25, 0.5);
    this.delay.wet.value = 0;

    this.pitchShift = new Tone.PitchShift();

    this.panner = new Tone.Panner();

    this.reverb = new Tone.Freeverb();
    this.reverb.wet.value = 0;

    Tone.Master.chain(this.delay, this.pitchShift, this.panner, this.reverb);

    // drum sounds

    var drumFileNames = ['high_conga', 'small_cowbell', 'snare_drum', 'splash cymbal'];
    this.drumSamplers = this._loadSoundFiles(drumFileNames);

    // sound urls - map each url to its tone.sampler
    this.soundSamplers = [];

       // soundfont setup

    // instrument names used by Musyng Kite soundfont, in order to match scratch instruments
    this.instrumentNames = ['acoustic_grand_piano', 'electric_piano_1', 'drawbar_organ', 'acoustic_guitar_nylon',
        'electric_guitar_clean', 'acoustic_bass', 'pizzicato_strings', 'cello', 'trombone', 'clarinet'];

    Soundfont.instrument(Tone.context, this.instrumentNames[0], {destination:this.delay}).then(function (inst) {
        this.instrument = inst;
        this.instrument.connect(Tone.Master);
    }.bind(this));
}

AudioEngine.prototype.playSound = function (soundNum) {
    this.soundSamplers[soundNum].triggerAttack();
};

AudioEngine.prototype.playSoundFromUrl = function (url) {
    if (url) {
        // if we've loaded it already, play it
        if (this.soundSamplers[url]) {
            this.soundSamplers[url].triggerAttack();
        } else {
        // else load, play, and store it
        // this results in a delay the first time you play the sound
            var sampler = new Tone.Sampler(url, function() {
                sampler.triggerAttack();
                this.soundSamplers[url] = sampler;
            }.bind(this)).toMaster();
        }
    }
};

AudioEngine.prototype.getSoundDuration = function (soundNum) {
    return this.soundSamplers[soundNum].player.buffer.duration;
};

AudioEngine.prototype.playNoteForBeats = function(note, beats) {
    this.instrument.play(note, Tone.context.currentTime, {duration : Number(beats)});
};

AudioEngine.prototype.playDrumForBeats = function(drumNum, beats) {
    this.drumSamplers[drumNum].triggerAttack();
};

AudioEngine.prototype.stopAllSounds = function() {
    // stop drum notes
    for (var i=0; i<this.drumSamplers.length; i++) {
        this.drumSamplers[i].triggerRelease();
    }
    // stop sounds triggered with playSound (indexed by their urls)
    for (var i in this.soundSamplers) {
        this.soundSamplers[i].triggerRelease();
    }
    // stop soundfont notes
    this.instrument.stop();
};

AudioEngine.prototype.setEffect = function(effect, value) {
    switch (effect) {
        case 'ECHO':
            this.delay.wet.value = (value / 100) / 2; // max 50% wet (need dry signal too)
            break;
        case 'PAN':
            this.panner.pan.value = value / 100;
            break;
        case 'REVERB':
            this.reverb.wet.value = value / 100;
            break;
        case 'PITCH':
            this.pitchShift.pitch = value / 20; // arbitrary scaling of 20 per semitone, for now... default 100 is a perfect fourth
            break;
    }
}

AudioEngine.prototype.changeEffect = function(effect, value) {
    switch (effect) {
        case 'ECHO':
            this.delay.wet.value += (value / 100) / 2; // max 50% wet (need dry signal too)
            this.delay.wet.value = this._clamp(this.delay.wet.value, 0, 0.5);
            break;
        case 'PAN':
            this.panner.pan.value += value / 100;
            this.panner.pan.value = this._clamp(this.panner.pan.value, -1, 1);
            break;
        case 'REVERB':
            this.reverb.wet.value += value / 100;
            this.reverb.wet.value = this._clamp(this.reverb.wet.value, 0, 1);
            break;
        case 'PITCH':
            this.pitchShift.pitch += value / 20;
            break;
    }
}

AudioEngine.prototype.clearEffects = function() {
    this.delay.wet.value = 0;
    this.panner.pan.value = 0;
    this.reverb.wet.value = 0;
    this.pitchShift.pitch = 0;
}

AudioEngine.prototype.loadSoundFromUrl = function(url) {

};

AudioEngine.prototype._loadSoundFiles = function(filenames) {
    var samplers = [];

    for (var name of filenames) {
        var sampler = new Tone.Sampler('sounds/' + name + '.mp3').toMaster();
        samplers.push(sampler);
    }

    return samplers;
};

AudioEngine.prototype._midiToFreq = function(midiNote) {
	var freq = this.tone.intervalToFrequencyRatio(midiNote - 60) * 261.63; // 60 is C4
	return freq;
};

AudioEngine.prototype._clamp = function(input, min, max) {
    return Math.min(Math.max(input, min), max);
};

<|endoftext|>


<commit_before>const Discord = require('discord.js');
const client = new Discord.Client();

const auth = require('./auth.json');

const serverID = auth.serverID;

client.on('ready', () => {
  console.log('I am ready!');
});

client.on('message', message => {
  if(message.content === '!warframe'){
    addToRole(message,"Warframe");
  }
});

client.login(auth.token);

function addToRole(message, roleName){
  var user = message.member;
  var server = message.channel.guild;
  var roles = server.roles;
  var currRoles = user.roles;
  console.log("User:"+user+" Server:"+server);
  console.log(roles.size);
  roles.every(function(role){
    console.log(role.name);
    if(currRoles.indexOf(role) !== -1){
      message.reply('You are already in the ' + roleName + ' Group');
    }else if(role.name === roleName){
      user.addRole(role);
      message.reply('Added you to the ' + roleName + ' Group');
      console.log('ADDED USER '+ user.name + ' TO ROLE '+ roleName);
    }
  });
  message.reply('Could not add you to the ' + roleName + ' Group due to an error');
  console.log('[!]ERROR ADDING USER '+ user.name + ' TO ROLE '+ roleName);
}
<commit_msg>changed the existing check<commit_after>const Discord = require('discord.js');
const client = new Discord.Client();

const auth = require('./auth.json');

const serverID = auth.serverID;

client.on('ready', () => {
  console.log('I am ready!');
});

client.on('message', message => {
  if(message.content === '!warframe'){
    addToRole(message,"Warframe");
  }
});

client.login(auth.token);

function addToRole(message, roleName){
  var user = message.member;
  var server = message.channel.guild;
  var roles = server.roles;
  var currRoles = user.roles;
  console.log("User:"+user+" Server:"+server);
  console.log(roles.size);
  roles.every(function(role){
    console.log(role.name);
    if(currRoles.find('name',role.name) !== undefined){
      message.reply('You are already in the ' + roleName + ' Group');
    }else if(role.name === roleName){
      user.addRole(role);
      message.reply('Added you to the ' + roleName + ' Group');
      console.log('ADDED USER '+ user.name + ' TO ROLE '+ roleName);
    }
  });
  message.reply('Could not add you to the ' + roleName + ' Group due to an error');
  console.log('[!]ERROR ADDING USER '+ user.name + ' TO ROLE '+ roleName);
}
<|endoftext|>


<commit_before>import {parseDateString, formatDate} from 'ghost/utils/date-formatting';

var PostSettingsMenuController = Ember.ObjectController.extend({
    isStaticPage: function (key, val) {
        var self = this;

        if (arguments.length > 1) {
            this.set('page', val ? 1 : 0);

            return this.get('model').save().then(function () {
                self.notifications.showSuccess('Successfully converted to ' + (val ? 'static page' : 'post'));

                return !!self.get('page');
            }, this.notifications.showErrors);
        }

        return !!this.get('page');
    }.property('page'),

    newSlugBinding: Ember.computed.oneWay('slug'),

    slugPlaceholder: function () {
        return this.get('model').generateSlug();
    }.property('title'),

    actions: {
        updateSlug: function () {
            var newSlug = this.get('newSlug'),
                slug = this.get('slug'),
                placeholder = this.get('slugPlaceholder'),
                self = this;

            newSlug = (!newSlug && placeholder) ? placeholder : newSlug;

            // Ignore unchanged slugs
            if (slug === newSlug) {
                return;
            }
            //reset to model's slug on empty string
            if (!newSlug) {
                this.set('newSlug', slug);
                return;
            }

            //Validation complete
            this.set('slug', newSlug);

            // If the model doesn't currently
            // exist on the server
            // then just update the model's value
            if (!this.get('isNew')) {
                return;
            }

            this.get('model').save().then(function () {
                self.notifications.showSuccess('Permalink successfully changed to ' +
                    self.get('slug') + '.');
            }, this.notifications.showErrors);
        },

        updatePublishedAt: function (userInput) {
            var self = this,
                errMessage = '',
                newPubDate = formatDate(parseDateString(userInput)),
                pubDate = this.get('publishedAt'),
                newPubDateMoment,
                pubDateMoment;

            // if there is no new pub date, mark that until the post is published,
            //    when we'll fill in with the current time.
            if (!newPubDate) {
                this.set('publishedAt', '');
                return;
            }

            // Check for missing time stamp on new data
            // If no time specified, add a 12:00
            if (newPubDate && !newPubDate.slice(-5).match(/\d+:\d\d/)) {
                newPubDate += ' 12:00';
            }

            newPubDateMoment = parseDateString(newPubDate);

            // If there was a published date already set
            if (pubDate) {
                // Check for missing time stamp on current model
                // If no time specified, add a 12:00
                if (!pubDate.slice(-5).match(/\d+:\d\d/)) {
                    pubDate += ' 12:00';
                }

                pubDateMoment = parseDateString(pubDate);

                // Quit if the new date is the same
                if (pubDateMoment.isSame(newPubDateMoment)) {
                    return;
                }
            }

            // Validate new Published date
            if (!newPubDateMoment.isValid() || newPubDate.substr(0, 12) === 'Invalid date') {
                errMessage = 'Published Date must be a valid date with format: ' +
                    'DD MMM YY @ HH:mm (e.g. 6 Dec 14 @ 15:00)';
            }

            if (newPubDateMoment.diff(new Date(), 'h') > 0) {
                errMessage = 'Published Date cannot currently be in the future.';
            }

            if (errMessage) {
                // Show error message
                this.notifications.showError(errMessage);
                //Hack to push a "change" when it's actually staying
                //  the same.
                //This alerts the listener on post-settings-menu
                this.notifyPropertyChange('publishedAt');
                return;
            }

            //Validation complete
            this.set('published_at', newPubDateMoment.toDate());

            // If the model doesn't currently
            // exist on the server
            // then just update the model's value
            if (!this.get('isNew')) {
                return;
            }

            this.get('model').save().then(function () {
                this.notifications.showSuccess('Publish date successfully changed to ' +
                    self.get('publishedAt') + '.');
            }, this.notifications.showErrors);
        }
    }
});

export default PostSettingsMenuController;
<commit_msg>Fixes static pages when permalinks are active.<commit_after>import {parseDateString, formatDate} from 'ghost/utils/date-formatting';

var PostSettingsMenuController = Ember.ObjectController.extend({
    isStaticPage: function (key, val) {
        var self = this;

        if (arguments.length > 1) {
            this.set('page', val);

            return this.get('model').save().then(function () {
                self.notifications.showSuccess('Successfully converted to ' + (val ? 'static page' : 'post'));

                return self.get('page');
            }, this.notifications.showErrors);
        }

        return this.get('page');
    }.property('page'),

    newSlugBinding: Ember.computed.oneWay('slug'),

    slugPlaceholder: function () {
        return this.get('model').generateSlug();
    }.property('title'),

    actions: {
        updateSlug: function () {
            var newSlug = this.get('newSlug'),
                slug = this.get('slug'),
                placeholder = this.get('slugPlaceholder'),
                self = this;

            newSlug = (!newSlug && placeholder) ? placeholder : newSlug;

            // Ignore unchanged slugs
            if (slug === newSlug) {
                return;
            }
            //reset to model's slug on empty string
            if (!newSlug) {
                this.set('newSlug', slug);
                return;
            }

            //Validation complete
            this.set('slug', newSlug);

            // If the model doesn't currently
            // exist on the server
            // then just update the model's value
            if (!this.get('isNew')) {
                return;
            }

            this.get('model').save().then(function () {
                self.notifications.showSuccess('Permalink successfully changed to ' +
                    self.get('slug') + '.');
            }, this.notifications.showErrors);
        },

        updatePublishedAt: function (userInput) {
            var self = this,
                errMessage = '',
                newPubDate = formatDate(parseDateString(userInput)),
                pubDate = this.get('publishedAt'),
                newPubDateMoment,
                pubDateMoment;

            // if there is no new pub date, mark that until the post is published,
            //    when we'll fill in with the current time.
            if (!newPubDate) {
                this.set('publishedAt', '');
                return;
            }

            // Check for missing time stamp on new data
            // If no time specified, add a 12:00
            if (newPubDate && !newPubDate.slice(-5).match(/\d+:\d\d/)) {
                newPubDate += ' 12:00';
            }

            newPubDateMoment = parseDateString(newPubDate);

            // If there was a published date already set
            if (pubDate) {
                // Check for missing time stamp on current model
                // If no time specified, add a 12:00
                if (!pubDate.slice(-5).match(/\d+:\d\d/)) {
                    pubDate += ' 12:00';
                }

                pubDateMoment = parseDateString(pubDate);

                // Quit if the new date is the same
                if (pubDateMoment.isSame(newPubDateMoment)) {
                    return;
                }
            }

            // Validate new Published date
            if (!newPubDateMoment.isValid() || newPubDate.substr(0, 12) === 'Invalid date') {
                errMessage = 'Published Date must be a valid date with format: ' +
                    'DD MMM YY @ HH:mm (e.g. 6 Dec 14 @ 15:00)';
            }

            if (newPubDateMoment.diff(new Date(), 'h') > 0) {
                errMessage = 'Published Date cannot currently be in the future.';
            }

            if (errMessage) {
                // Show error message
                this.notifications.showError(errMessage);
                //Hack to push a "change" when it's actually staying
                //  the same.
                //This alerts the listener on post-settings-menu
                this.notifyPropertyChange('publishedAt');
                return;
            }

            //Validation complete
            this.set('published_at', newPubDateMoment.toDate());

            // If the model doesn't currently
            // exist on the server
            // then just update the model's value
            if (!this.get('isNew')) {
                return;
            }

            this.get('model').save().then(function () {
                this.notifications.showSuccess('Publish date successfully changed to ' +
                    self.get('publishedAt') + '.');
            }, this.notifications.showErrors);
        }
    }
});

export default PostSettingsMenuController;
<|endoftext|>


<commit_before>// var chai = require('chai');
// expect = chai.expect;
var expect = require('chai').expect;

var taskList = []

// I can list my tasks
/* var i = 0
function listTasks (i){
  for (var i = 0; i < taskList.length; i++){
    return taskList[i];
  }
}*/

// I can add a task to my list

function addTaskToList(task, list){
  // What is the task? parameter task
  // Where is the task goin? parameter list
  // What order / priority? lowest, on the bottom
  return list.push({
  text: task, completed: false
});
}

function deleteTask(task, list){
  return list.splice(task, 1);

}

function editTask(position, newTaskName){
  taskList[position] = newTaskName;
  return newTaskName;

}

Array.prototype.move = function(from, to){
  this.splice(to, 0, this.splice(from, 1)[0]);
  return this;
}

/*function prioritizeTask(task, list){

}*/

function completeTask(task, position){
  return task[position] = ("[X] " + task[position]);

}

expect(taskList.length).to.equal(0);
addTaskToList("Remember the milk", taskList);
expect(taskList[0].text).to.equal("Remember the milk");
expect(taskList.length).to.equal(1);
expect(taskList.length).to.equal(1);
addTaskToList("Take out the trash", taskList);
expect(taskList[1].text).to.equal("Take out the trash");
expect(taskList.length).to.equal(2);

expect(completeTask).to.exist;
completeTask(taskList, 1);
expect(taskList[1].text).to.equal("[X] Take out the trash");
console.log(taskList);
// listTasks();
// expect(listTasks()).to.equal("Remember the milk", "Take out the trash");
expect(taskList[0].text).to.equal("Remember the milk");
editTask(0, "Remember the milk and eggs");
expect(taskList[0].text).to.equal("Remember the milk and eggs");
console.log(taskList);

expect(taskList.length).to.equal(2);
deleteTask(1, taskList);
expect(taskList.length).to.equal(1);
expect(taskList[0].text).to.equal("Remember the milk and eggs");
console.log(taskList)
<commit_msg>move todo.js<commit_after><|endoftext|>


<commit_before>/**
 * Event handler for the modify class view.
 * @author Grant Plaster
 */

define(['app/app', 'text!templates/modifyStudentView.hbs', ], function(App, template) {

    var ModifyStudentView = App.Mn.ItemView.extend({
        model: App.Course,
        template: App.Handlebars.compile(template),
        ui: {
            'modifyStudentButton' : '.modifyStudentButton',
            'ok' : '.ok',
            'cancel' : '.cancel',
            'dialog' : '.popup-dialog',
            'studentFirstName' : '.studentFirstName',
            'studentLastName' : '.studentLastName',
            'studentID' : '.studentID',
            //'studentNickname' : '.studentNickname',
            //'studentGroup' : '.studentGroup',
            'studentEmail' : '.studentEmail',
            //'studentPhone' : '.studentPhone'

        },

        /**
         * Hides the dialog on initial load
         *
         * @this {ModifyStudentView}
         */
        onShow : function(){
            this.ui.dialog.hide();
        },
        events : {
           'click @ui.modifyStudentButton' :  'showModifyStudent',
            'click @ui.ok' :  'updateStudentInfo',
            'click @ui.cancel' :  'closeModifyStudent'
        },

        /**
         * Hides the pop-up button to display fields for modifying student data.
         * Fields are automatically filled with existing student data for the selected student.
         *
         * @this {ModifyStudentView}
         */
        showModifyStudent : function() {
            this.ui.dialog.show();
            this.ui.modifyStudentButton.hide();

            this.ui.studentFirstName.val("COOL");
            this.ui.studentLastName.val(this.model.get('students')[1].first);
            this.ui.studentID.val(this.model.get('students').emplId);
            this.ui.studentEmail.val(this.model.get('students').email);

            //this.ui.studentFirstName.val(this.model.get('first'));
            //this.ui.studentLastName.val(this.model.get('last'));
            //this.ui.studentID.val(this.model.get('emplId'));
            //this.ui.studentEmail.val(this.model.get('email'));
            //this.ui.studentPhone.val(this.model.get('phone'));
        },

        /**
         * Saves any changes to the selected student data in the database.
         *
         * @this {ModifyStudentView}
         */
        updateStudentInfo : function () {

            var firstName = this.ui.studentFirstName.val();
            var lastName = this.ui.studentLastName.val();
            var id = this.ui.studentID.val();
            //var nickname = this.ui.studentNickname;
            //var group = this.ui.studentGroup;
            var email = this.ui.studentEmail.val();
            //var phone = this.ui.studentPhone;

            this.model.set({"first": firstName});
            this.model.set({"last": lastName});
            this.model.set({"emplId": id});
            //this.model.set({"studentNickname": nickname});
            //this.model.set({"studentGroup": group});
            this.model.set({"email": email});
            //this.model.set({"studentPhone": phone});
            this.ui.dialog.hide();
            this.ui.modifyStudentButton.show();

            Backbone.emulateHTTP = true;
            this.model.save();
        },

        /**
         * Closes the modify student dialog without any changes to information.
         *
         * @this {ModifyStudentView}
         */

        closeModifyStudent : function() {
            this.ui.dialog.hide();
            this.ui.modifyStudentButton.show();
        },
    })

    App.Router.route("modifyStudent", "home", function() {
        App.UserCourses.fetch().then(function () {
            var course = App.UserCourses.at(0);
            var students = course.get('students');
            var promises = [];
            students.forEach(function(student){
                var url = '/api/Users?_id=' + student.user;
                var p = App.$.ajax({
                    url: url
                });
                promises.push(p);
            });
            App.Q.all(promises).then(function(arr) {
                arr = App._.flatten(arr);
                for(var i = 0; i < arr.length; ++i) {
                    students[i].user = arr[i];
                }
                var modifyView = new ModifyStudentView({
                    model: course
                });
                App.PopupRegion.show(modifyView);
            })
        });
    });
});<commit_msg>first name is properly populated in view<commit_after>/**
 * Event handler for the modify class view.
 * @author Grant Plaster
 */

define(['app/app', 'text!templates/modifyStudentView.hbs', ], function(App, template) {

    var ModifyStudentView = App.Mn.ItemView.extend({
        model: App.Course,
        template: App.Handlebars.compile(template),
        ui: {
            'modifyStudentButton' : '.modifyStudentButton',
            'ok' : '.ok',
            'cancel' : '.cancel',
            'dialog' : '.popup-dialog',
            'studentFirstName' : '.studentFirstName',
            'studentLastName' : '.studentLastName',
            'studentID' : '.studentID',
            //'studentNickname' : '.studentNickname',
            //'studentGroup' : '.studentGroup',
            'studentEmail' : '.studentEmail',
            //'studentPhone' : '.studentPhone'

        },

        /**
         * Hides the dialog on initial load
         *
         * @this {ModifyStudentView}
         */
        onShow : function(){
            this.ui.dialog.hide();
        },
        events : {
           'click @ui.modifyStudentButton' :  'showModifyStudent',
            'click @ui.ok' :  'updateStudentInfo',
            'click @ui.cancel' :  'closeModifyStudent'
        },

        /**
         * Hides the pop-up button to display fields for modifying student data.
         * Fields are automatically filled with existing student data for the selected student.
         *
         * @this {ModifyStudentView}
         */
        showModifyStudent : function() {
            this.ui.dialog.show();
            this.ui.modifyStudentButton.hide();

            if (this.model.get('students')[1].first)
                this.ui.studentFirstName.val(this.model.get('students')[1].first);
            else
                this.ui.studentFirstName.val(this.model.get('students')[1].user.first);

            this.ui.studentLastName.val(this.model.get('students')[1].first);
            this.ui.studentID.val(this.model.get('students').emplId);
            this.ui.studentEmail.val(this.model.get('students').email);

            //this.ui.studentFirstName.val(this.model.get('first'));
            //this.ui.studentLastName.val(this.model.get('last'));
            //this.ui.studentID.val(this.model.get('emplId'));
            //this.ui.studentEmail.val(this.model.get('email'));
            //this.ui.studentPhone.val(this.model.get('phone'));
        },

        /**
         * Saves any changes to the selected student data in the database.
         *
         * @this {ModifyStudentView}
         */
        updateStudentInfo : function () {

            var firstName = this.ui.studentFirstName.val();
            var lastName = this.ui.studentLastName.val();
            var id = this.ui.studentID.val();
            //var nickname = this.ui.studentNickname;
            //var group = this.ui.studentGroup;
            var email = this.ui.studentEmail.val();
            //var phone = this.ui.studentPhone;

            this.model.set({"first": firstName});
            this.model.set({"last": lastName});
            this.model.set({"emplId": id});
            //this.model.set({"studentNickname": nickname});
            //this.model.set({"studentGroup": group});
            this.model.set({"email": email});
            //this.model.set({"studentPhone": phone});
            this.ui.dialog.hide();
            this.ui.modifyStudentButton.show();

            Backbone.emulateHTTP = true;
            this.model.save();
        },

        /**
         * Closes the modify student dialog without any changes to information.
         *
         * @this {ModifyStudentView}
         */

        closeModifyStudent : function() {
            this.ui.dialog.hide();
            this.ui.modifyStudentButton.show();
        },
    })

    App.Router.route("modifyStudent", "home", function() {
        App.UserCourses.fetch().then(function () {
            var course = App.UserCourses.at(0);
            var students = course.get('students');
            var promises = [];
            students.forEach(function(student){
                var url = '/api/Users?_id=' + student.user;
                var p = App.$.ajax({
                    url: url
                });
                promises.push(p);
            });
            App.Q.all(promises).then(function(arr) {
                arr = App._.flatten(arr);
                for(var i = 0; i < arr.length; ++i) {
                    students[i].user = arr[i];
                }
                var modifyView = new ModifyStudentView({
                    model: course
                });
                App.PopupRegion.show(modifyView);
            })
        });
    });
});<|endoftext|>


<commit_before>import _ from 'lodash';
import Cookies from 'js-cookie';
import localStorage from 'local-storage-fallback';
import URI from 'urijs';

import auth from '../apps/Account/auth';
import NewLibConnection from '../apps/Session/NewLibConnection';

import SessionStore from '../apps/Session/SessionStore';
import AuthStore from '../apps/Account/AuthStore';

const RoutesUtil = {
  checkActiveSubscriptions(nextState, replace, callback) {
    const connection = NewLibConnection.get();
    const token = localStorage.getItem('token');

    if (token) {
      connection.setAccountKey(token);
    }

    return connection
      .Profile
      .please()
      .get()
      .then(({ status }) => {
        const redirectRoute = {
          no_active_subscription: '/expired/',
          free_limits_exceeded: '/free-limits-exceeded/',
          hard_limit_reached: '/hard-limits-reached/',
          overdue_invoices: '/failed-payment/'
        }[status];

        redirectRoute && replace(redirectRoute);
        callback();
      });
  },

  checkInstanceActiveSubscription(nextState, replace, callback) {
    const connection = NewLibConnection.get();
    const token = localStorage.getItem('token');
    const { instanceName } = nextState.params;

    if (token) {
      connection.setAccountKey(token);
    }

    if (instanceName) {
      let currentUserEmail;

      return connection
        .Account
        .getUserDetails()
        .then(({ email }) => {
          currentUserEmail = email;
        })
        .then(() => (
          connection
            .Instance
            .please()
            .get({ name: instanceName })
        ))
        .then(({ owner }) => {
          if (owner.email === currentUserEmail) {
            return RoutesUtil.checkActiveSubscriptions(nextState, replace, callback);
          }

          return callback();
        })
        .catch(console.error);
    }

    return callback();
  },

  isInstanceAvailable(instanceName) {
    const connection = NewLibConnection.get();

    return connection
      .Instance
      .please()
      .get({ name: instanceName });
  },

  onAppEnter(nextState, replace) {
    const uri = new URI();
    const originalUri = uri.normalize().toString();
    let pathname = decodeURIComponent(nextState.location.pathname).replace('//', '/');
    const query = _.extend({}, uri.search(true), nextState.location.query);

    if (!localStorage.getItem('token')) {
      localStorage.setItem('token', Cookies.get('token'));
    }
    SessionStore.setUTMData(nextState.location.query);

    // remove trailing slash
    if (pathname.length > 1 && pathname.match('/$') !== null) {
      pathname = pathname.slice(0, -1);
    }

    uri.search(query);
    uri.hash(`${pathname}${uri.search()}`);
    uri.search('');

    const normalizedUri = uri.normalize().toString();

    if (originalUri !== normalizedUri) {
      location.href = normalizedUri;
      return null;
    }

    let name = 'app';
    const names = nextState.routes.map((route) => route.name).filter((routeName) => typeof routeName !== 'undefined');

    if (names.length > 0) {
      name = names[names.length - 1];
    }

    if (name === 'login' || name === 'signup') {
      window.analytics.page(`Dashboard ${_.capitalize(name)}`, {
        path: nextState.location.pathname
      });
    } else {
      window.analytics.page('Dashboard', {
        Page: name,
        path: nextState.location.pathname,
        category: 'Dashboard',
        label: name
      });
    }

    if (nextState.location.query.invitation_key) {
      return AuthStore.acceptInvitationFromUrl();
    }

    if (auth.loggedIn() && nextState.location.pathname === '/' && !query.token) {
      return this.redirectToLastPathname(nextState, replace);
    }

    return null;
  },

  onDashboardChange(prevState, nextState, replace) {
    localStorage.setItem('lastPathname', nextState.location.pathname);

    if (nextState.location.pathname === '/') {
      this.redirectToLastInstance(nextState, replace);
    }
  },

  onDashboardEnter(nextState, replace) {
    const { signUpMode } = nextState.location.query;

    if (!auth.loggedIn() && !signUpMode) {
      return this.redirectToLogin(nextState, replace);
    }

    return null;
  },

  redirectToDashboard(nextState, replace) {
    if (auth.loggedIn()) {
      replace({ pathname: '/' });
    }
  },

  redirectToLastInstance(nextState, replace) {
    const lastInstanceName = localStorage.getItem('lastInstanceName');

    if (lastInstanceName) {
      this.isInstanceAvailable(lastInstanceName).then(() => replace({
        pathname: `/instances/${lastInstanceName}/my-sockets/`
      }));
    }
  },

  redirectToLastPathname(nextState, replace) {
    const lastPathname = localStorage.getItem('lastPathname');

    if (lastPathname && lastPathname !== '/') {
      return replace({ pathname: lastPathname });
    }

    return null;
  },

  redirectToLogin(nextState, replace) {
    const query = _.omit(nextState.location.query, 'next');

    if (nextState.location.query.next) {
      return replace({
        name: 'login',
        state: { nextPathname: nextState.location.pathname },
        query: _.merge({ next: nextState.location.pathname }, query)
      });
    }

    Cookies.remove('logged_in', { domain: APP_CONFIG.SYNCANO_BASE_DOMAIN });

    return replace({ name: 'login', query: _.merge({ next: nextState.location.pathname }, query) });
  },

  onInstanceEnter(nextState, replace, cb) {
    this.checkInstanceActiveSubscription(nextState, replace, cb);
    const lastInstanceName = localStorage.getItem('lastInstanceName');

    return this.isInstanceAvailable(lastInstanceName)
      .then((instance = {}) => {
        const instanceCreatedAt = Date.parse(instance.created_at);
        const releaseDate = Number(APP_CONFIG.SYNCANO5_RELEASE_DATE);

        if (instanceCreatedAt < releaseDate && !instance.metadata.testInstance) {
          Cookies.set('token', localStorage.getItem('token'));
          window.location = `${APP_CONFIG.SYNCANO_OLD_DASHBOARD}/#/instances/${instance.name}`;
        }
      });
  }
};

export default RoutesUtil;
<commit_msg>[SYN5-58] Remove unnecessary items from local Storage if redirect from other dashboard [e2e-skip]<commit_after>import _ from 'lodash';
import Cookies from 'js-cookie';
import localStorage from 'local-storage-fallback';
import URI from 'urijs';

import auth from '../apps/Account/auth';
import NewLibConnection from '../apps/Session/NewLibConnection';

import SessionStore from '../apps/Session/SessionStore';
import AuthStore from '../apps/Account/AuthStore';

const RoutesUtil = {
  checkActiveSubscriptions(nextState, replace, callback) {
    const connection = NewLibConnection.get();
    const token = localStorage.getItem('token');

    if (token) {
      connection.setAccountKey(token);
    }

    return connection
      .Profile
      .please()
      .get()
      .then(({ status }) => {
        const redirectRoute = {
          no_active_subscription: '/expired/',
          free_limits_exceeded: '/free-limits-exceeded/',
          hard_limit_reached: '/hard-limits-reached/',
          overdue_invoices: '/failed-payment/'
        }[status];

        redirectRoute && replace(redirectRoute);
        callback();
      });
  },

  checkInstanceActiveSubscription(nextState, replace, callback) {
    const connection = NewLibConnection.get();
    const token = localStorage.getItem('token');
    const { instanceName } = nextState.params;

    if (token) {
      connection.setAccountKey(token);
    }

    if (instanceName) {
      let currentUserEmail;

      return connection
        .Account
        .getUserDetails()
        .then(({ email }) => {
          currentUserEmail = email;
        })
        .then(() => (
          connection
            .Instance
            .please()
            .get({ name: instanceName })
        ))
        .then(({ owner }) => {
          if (owner.email === currentUserEmail) {
            return RoutesUtil.checkActiveSubscriptions(nextState, replace, callback);
          }

          return callback();
        })
        .catch(console.error);
    }

    return callback();
  },

  isInstanceAvailable(instanceName) {
    const connection = NewLibConnection.get();

    return connection
      .Instance
      .please()
      .get({ name: instanceName });
  },

  onAppEnter(nextState, replace) {
    const uri = new URI();
    const originalUri = uri.normalize().toString();
    let pathname = decodeURIComponent(nextState.location.pathname).replace('//', '/');
    const query = _.extend({}, uri.search(true), nextState.location.query);

    if (!localStorage.getItem('token')) {
      localStorage.setItem('token', Cookies.get('token'));
    }
    if (Cookies.get('redirectMode')) {
      localStorage.removeItem('lastPathname');
      localStorage.removeItem('lastInstanceName');
    }
    SessionStore.setUTMData(nextState.location.query);

    // remove trailing slash
    if (pathname.length > 1 && pathname.match('/$') !== null) {
      pathname = pathname.slice(0, -1);
    }

    uri.search(query);
    uri.hash(`${pathname}${uri.search()}`);
    uri.search('');

    const normalizedUri = uri.normalize().toString();

    if (originalUri !== normalizedUri) {
      location.href = normalizedUri;
      return null;
    }

    let name = 'app';
    const names = nextState.routes.map((route) => route.name).filter((routeName) => typeof routeName !== 'undefined');

    if (names.length > 0) {
      name = names[names.length - 1];
    }

    if (name === 'login' || name === 'signup') {
      window.analytics.page(`Dashboard ${_.capitalize(name)}`, {
        path: nextState.location.pathname
      });
    } else {
      window.analytics.page('Dashboard', {
        Page: name,
        path: nextState.location.pathname,
        category: 'Dashboard',
        label: name
      });
    }

    if (nextState.location.query.invitation_key) {
      return AuthStore.acceptInvitationFromUrl();
    }

    if (auth.loggedIn() && nextState.location.pathname === '/' && !query.token) {
      return this.redirectToLastPathname(nextState, replace);
    }

    return null;
  },

  onDashboardChange(prevState, nextState, replace) {
    localStorage.setItem('lastPathname', nextState.location.pathname);

    if (nextState.location.pathname === '/') {
      this.redirectToLastInstance(nextState, replace);
    }
  },

  onDashboardEnter(nextState, replace) {
    const { signUpMode } = nextState.location.query;

    if (!auth.loggedIn() && !signUpMode) {
      return this.redirectToLogin(nextState, replace);
    }

    return null;
  },

  redirectToDashboard(nextState, replace) {
    if (auth.loggedIn()) {
      replace({ pathname: '/' });
    }
  },

  redirectToLastInstance(nextState, replace) {
    const lastInstanceName = localStorage.getItem('lastInstanceName');

    if (lastInstanceName) {
      this.isInstanceAvailable(lastInstanceName).then(() => replace({
        pathname: `/instances/${lastInstanceName}/my-sockets/`
      }));
    }
  },

  redirectToLastPathname(nextState, replace) {
    const lastPathname = localStorage.getItem('lastPathname');

    if (lastPathname && lastPathname !== '/') {
      return replace({ pathname: lastPathname });
    }

    return null;
  },

  redirectToLogin(nextState, replace) {
    const query = _.omit(nextState.location.query, 'next');

    if (nextState.location.query.next) {
      return replace({
        name: 'login',
        state: { nextPathname: nextState.location.pathname },
        query: _.merge({ next: nextState.location.pathname }, query)
      });
    }

    Cookies.remove('logged_in', { domain: APP_CONFIG.SYNCANO_BASE_DOMAIN });

    return replace({ name: 'login', query: _.merge({ next: nextState.location.pathname }, query) });
  },

  onInstanceEnter(nextState, replace, cb) {
    this.checkInstanceActiveSubscription(nextState, replace, cb);
    const lastInstanceName = localStorage.getItem('lastInstanceName');

    return this.isInstanceAvailable(lastInstanceName)
      .then((instance = {}) => {
        const instanceCreatedAt = Date.parse(instance.created_at);
        const releaseDate = Number(APP_CONFIG.SYNCANO5_RELEASE_DATE);

        if (instanceCreatedAt < releaseDate && !instance.metadata.testInstance) {
          Cookies.set('token', localStorage.getItem('token'));
          Cookies.set('redirectMode', true);
          window.location = `${APP_CONFIG.SYNCANO_OLD_DASHBOARD}/#/instances/${instance.name}`;
        }
      });
  }
};

export default RoutesUtil;
<|endoftext|>


<commit_before>/*
 * Chat log viewer plugin by jd
 */
var fs = require('fs');
var sanitizeHtml = require('sanitize-html');

function sanitizeHTML(html) {
	return sanitizeHtml(html, {
		allowedTags: [ 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em',
			'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre', 'img', 'font',
			'center', 'button'],
		allowedAttributes: {
		  a: [ 'href', 'name', 'target' ],
		  img: [ 'src' ],
		  br: ['clear'],
		  div: ['class'],
		  font: ['color', 'size'],
		  button: ['name', 'value', 'class']
		},
	});
}

exports.commands = {
	viewlogs: function(target, room, user) {
		if (!target) return this.sendReply("Usage: /viewlogs [room], [year-month-day / 2014-12-08] - Provides you with a temporary link to view the target rooms chat logs.");
		var targetSplit = target.split(',');
		if (!targetSplit[1]) return this.sendReply("Usage: /viewlogs [room], [year-month-day / 2014-12-08] -Provides you with a temporary link to view the target rooms chat logs.");
		for (var u in targetSplit) targetSplit[u] = targetSplit[u].trim();
		var targetRoom = targetSplit[0];
		if (!user.can('lock') && !user.can('roommod', null, Rooms(targetRoom))) return this.sendReply("/viewlogs - Access denied.");
		if (toId(targetRoom) === 'staff' && !user.can('warn')) return this.sendReply("/viewlogs - Access denied.");
		if (toId(targetRoom) === 'administrators' && !user.can('hotpatch')) return this.sendReply("/viewlogs - Access denied.");
		if (toId(targetRoom) === 'upperstaff' && !user.can('pban')) return this.sendReply("/viewlogs - Access denied.");
		if (Rooms(targetRoom) && Rooms(targetRoom).isPrivate && !user.can('warn', null, Rooms(targetRoom))) return this.sendReply("/viewlogs - Access denied.");
		var date = targetSplit[1];
		var splitDate = date.split('-');
		if (splitDate.length < 3) return this.sendReply("Usage: /viewlogs [room], [year-month-day / 2014-12-08] -Provides you with a temporary link to view the target rooms chat logs.");
		var self = this;

		fs.readFile('logs/chat/' + toId(targetRoom) + '/' + splitDate[0] + '-' + splitDate[1] + '/' + date + '.txt', 'utf8', function(err, data) {
			if (err) return self.sendReply("/viewlogs - Error: " + err);
			var filename = require('crypto').randomBytes(16).toString('hex') + '.html';
			var newDate = new Date();
			data = data.split('\n');
			var newFile = ['',
			'<link rel="stylesheet" type="text/css" href="http://goldservers.info/style/client.css"><link rel="stylesheet" type="text/css" href="http://goldservers.info/js/style.css">' +
			'<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />',
			'
Room: ' + Tools.escapeHTML(targetRoom) +
			' Date: ' + Tools.escapeHTML(date) + '
' ,
			'Logs obtained ' + newDate.toUTCString() + ' by ' + Tools.escapeHTML(user.name) + '

',
			'
','
','
'];

			for (var u in data) {
				var timestamp = data[u].substr(0, 9).trim();
				var line = data[u].substr(9, data[u].length);
				if (timestamp.substr(0,1) === '|') line = data[u].trim();
				//if (data[u].substr(2,1) !== ':') line = ''+data[u];
				if (line.substr(0,1) !== '|') line = '||'+line;
				var lineSplit = line.substr(1).split('|');
				switch (lineSplit[0]) {
					case 'c':
						var name = lineSplit[1];
						if (name === '~') break;
						var highlight = new RegExp("\\b" + user.name.toLowerCase() + "\\b", 'gi');
						var div = "chat";
						if (lineSplit.slice(2).join('|').match(highlight)) div = "chat highlighted";
						var Gold = global.Gold;
						newFile.push('
[' + timestamp + '] ' + '' + name.substr(0,1) + '' + name.substr(1, name.length) + ':' +
							Tools.escapeHTML(lineSplit.slice(2).join('|')) + '
');
						break;
					case 'raw':
					case 'html':
					case 'uhtml': // this is mostly for emoticon messages
						var currentLine = lineSplit.splice(1).join('|').trim();
						newFile.push('
' + sanitizeHTML(currentLine) + '
');
						break;
					case 'j':
					case 'J':
					case 'l':
					case 'L':
					case 'N':
					case 'unlink':
					case 'userstats':
					case 'tournament':
						break;
					case '':
						if (lineSplit.slice(1).join('|').substr(0,1) === '(' && !user.can('warn')) break;
						newFile.push('
' + Tools.escapeHTML(lineSplit.slice(1).join('|')) + '
');
						break;
					default:
						if (lineSplit.join('|').substr(0,1) === '(' && !user.can('warn')) break;
						newFile.push('
' + Tools.escapeHTML(lineSplit.join('|')) + '
');
						break;
				}
			}
			newFile.push('

');
			fs.writeFile('static/logs/' + filename, newFile.join('\n'), function(err) {
				if (err) return self.sendReply("/viewlogs - " + err);
				self.sendReply("|raw|You can view the logs at http://goldservers.info:" + Config.port + "/logs/" + filename + "");
				var deleteFile = setTimeout(function(){fs.unlink('static/logs/' + filename);},1*1000*60);
			});
		});
	},
};<commit_msg>Fix emoticon messages in viewlogs script<commit_after>/*
 * Chat log viewer plugin by jd
 */
var fs = require('fs');
var sanitizeHtml = require('sanitize-html');

function sanitizeHTML(html) {
	return sanitizeHtml(html, {
		allowedTags: [ 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em',
			'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre', 'img', 'font',
			'center', 'button'],
		allowedAttributes: {
		  a: [ 'href', 'name', 'target' ],
		  img: [ 'src' ],
		  br: ['clear'],
		  div: ['class'],
		  font: ['color', 'size'],
		  button: ['name', 'value', 'class']
		},
	});
}

exports.commands = {
	viewlogs: function(target, room, user) {
		if (!target) return this.sendReply("Usage: /viewlogs [room], [year-month-day / 2014-12-08] - Provides you with a temporary link to view the target rooms chat logs.");
		var targetSplit = target.split(',');
		if (!targetSplit[1]) return this.sendReply("Usage: /viewlogs [room], [year-month-day / 2014-12-08] -Provides you with a temporary link to view the target rooms chat logs.");
		for (var u in targetSplit) targetSplit[u] = targetSplit[u].trim();
		var targetRoom = targetSplit[0];
		if (!user.can('lock') && !user.can('roommod', null, Rooms(targetRoom))) return this.sendReply("/viewlogs - Access denied.");
		if (toId(targetRoom) === 'staff' && !user.can('warn')) return this.sendReply("/viewlogs - Access denied.");
		if (toId(targetRoom) === 'administrators' && !user.can('hotpatch')) return this.sendReply("/viewlogs - Access denied.");
		if (toId(targetRoom) === 'upperstaff' && !user.can('pban')) return this.sendReply("/viewlogs - Access denied.");
		if (Rooms(targetRoom) && Rooms(targetRoom).isPrivate && !user.can('warn', null, Rooms(targetRoom))) return this.sendReply("/viewlogs - Access denied.");
		var date = targetSplit[1];
		var splitDate = date.split('-');
		if (splitDate.length < 3) return this.sendReply("Usage: /viewlogs [room], [year-month-day / 2014-12-08] -Provides you with a temporary link to view the target rooms chat logs.");
		var self = this;

		fs.readFile('logs/chat/' + toId(targetRoom) + '/' + splitDate[0] + '-' + splitDate[1] + '/' + date + '.txt', 'utf8', function(err, data) {
			if (err) return self.sendReply("/viewlogs - Error: " + err);
			var filename = require('crypto').randomBytes(16).toString('hex') + '.html';
			var newDate = new Date();
			data = data.split('\n');
			var newFile = ['',
			'<link rel="stylesheet" type="text/css" href="http://goldservers.info/style/client.css"><link rel="stylesheet" type="text/css" href="http://goldservers.info/js/style.css">' +
			'<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />',
			'
Room: ' + Tools.escapeHTML(targetRoom) +
			' Date: ' + Tools.escapeHTML(date) + '
' ,
			'Logs obtained ' + newDate.toUTCString() + ' by ' + Tools.escapeHTML(user.name) + '

',
			'
','
','
'];

			for (var u in data) {
				var timestamp = data[u].substr(0, 9).trim();
				var line = data[u].substr(9, data[u].length);
				if (timestamp.substr(0,1) === '|') line = data[u].trim();
				//if (data[u].substr(2,1) !== ':') line = ''+data[u];
				if (line.substr(0,1) !== '|') line = '||'+line;
				var lineSplit = line.substr(1).split('|');
				switch (lineSplit[0]) {
					case 'c':
						var name = lineSplit[1];
						if (name === '~') break;
						var highlight = new RegExp("\\b" + user.name.toLowerCase() + "\\b", 'gi');
						var div = "chat";
						if (lineSplit.slice(2).join('|').match(highlight)) div = "chat highlighted";
						var Gold = global.Gold;
						newFile.push('
[' + timestamp + '] ' + '' + name.substr(0,1) + '' + name.substr(1, name.length) + ':' +
							Tools.escapeHTML(lineSplit.slice(2).join('|')) + '
');
						break;
					case 'uhtml': // this is mostly for emoticon messages
						var currentLine = lineSplit.splice(3).join('|').trim();
						newFile.push('
' + sanitizeHTML(currentLine) + '
');
						break;
					case 'raw':
					case 'html':
						var currentLine = lineSplit.splice(1).join('|').trim();
						newFile.push('
' + sanitizeHTML(currentLine) + '
');
						break;
					case 'j':
					case 'J':
					case 'l':
					case 'L':
					case 'N':
					case 'unlink':
					case 'userstats':
					case 'tournament':
						break;
					case '':
						if (lineSplit.slice(1).join('|').substr(0,1) === '(' && !user.can('warn')) break;
						newFile.push('
' + Tools.escapeHTML(lineSplit.slice(1).join('|')) + '
');
						break;
					default:
						if (lineSplit.join('|').substr(0,1) === '(' && !user.can('warn')) break;
						newFile.push('
' + Tools.escapeHTML(lineSplit.join('|')) + '
');
						break;
				}
			}
			newFile.push('

');
			fs.writeFile('static/logs/' + filename, newFile.join('\n'), function(err) {
				if (err) return self.sendReply("/viewlogs - " + err);
				self.sendReply("|raw|You can view the logs at http://goldservers.info:" + Config.port + "/logs/" + filename + "");
				var deleteFile = setTimeout(function(){fs.unlink('static/logs/' + filename);},1*1000*60);
			});
		});
	},
};<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name wavesApp.voiceVisualizer
 * @description
 * # voiceVisualizer
 * Service in the wavesApp.
 */
angular.module('wavesApp')
  .service('voiceVisualizer', ['$window', function ($window) {
      $window.navigator.getUserMedia = ($window.navigator.getUserMedia ||
                            $window.navigator.webkitGetUserMedia ||
                            $window.navigator.mozGetUserMedia ||
                            $window.navigator.msGetUserMedia);

      // set up forked web audio context, for multiple browsers
      // window. is needed otherwise Safari explodes

      var audioCtx = new ($window.AudioContext || $window.webkitAudioContext)();
      // var voiceSelect = document.getElementById("voice");
      var source;
      var stream;

      //set up the different audio nodes we will use for the app
      var analyser = audioCtx.createAnalyser();
      analyser.minDecibels = -90;
      analyser.maxDecibels = -10;
      analyser.smoothingTimeConstant = 0.85;

      var distortion = audioCtx.createWaveShaper();
      var gainNode = audioCtx.createGain();
      var biquadFilter = audioCtx.createBiquadFilter();
      var convolver = audioCtx.createConvolver();

      var canvas,
          canvasCtx,
          intendedWidth,
          drawVisual;

      var WIDTH;
      var HEIGHT;

      return {
        init: function( cnvs ){
          // set up canvas context for visualizer
          canvas = cnvs;
          canvasCtx = cnvs.getContext("2d");
          intendedWidth = document.querySelector('.visualizer-wrapper').clientWidth;
          canvas.setAttribute('width', intendedWidth);
          canvas.setAttribute('height', 400);

          //main block for doing the audio recording
          if ($window.navigator.getUserMedia) {
            console.log('getUserMedia supported.');
            $window.navigator.getUserMedia (
              { audio: true },
              function(stream) {
                source = audioCtx.createMediaStreamSource(stream);
                source.connect(analyser);
                analyser.connect(distortion);
                distortion.connect(biquadFilter);
                biquadFilter.connect(convolver);
                convolver.connect(gainNode);
                gainNode.connect(audioCtx.destination);

                $window.cancelAnimationFrame(drawVisual);
              },
              function(err) {
                console.log('The following gUM error occured: ' + err);
              });
          } else {
            console.log('getUserMedia not supported on your browser!');
          }
          this.visualize();
          return this;
        },
        visualize: function (){
          WIDTH = canvas.width;
          HEIGHT = canvas.height;
          // var visualSetting = 'sinewave';

          analyser.fftSize = 2048;
          var bufferLength = analyser.fftSize;

          var dataArray = new Uint8Array(bufferLength);

          canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);

          function draw() {
            drawVisual = requestAnimationFrame(draw);
            analyser.getByteTimeDomainData(dataArray);
            canvasCtx.fillStyle = 'rgb(0, 0, 0)';
            canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
            canvasCtx.lineWidth = 2;
            canvasCtx.strokeStyle = 'rgb(255, 255, 255)';
            canvasCtx.beginPath();

            var sliceWidth = WIDTH * 1.0 / bufferLength;
            var x = 0;

            for(var i = 0; i < bufferLength; i++) {
              var v = dataArray[i] / 128.0;
              var y = v * HEIGHT/2;
              if(i === 0) {
                canvasCtx.moveTo(x, y);
              } else {
                canvasCtx.lineTo(x, y);
              }
              x += sliceWidth;
            }
            canvasCtx.lineTo(canvas.width, canvas.height/2);
            canvasCtx.stroke();
          };

          draw();
        }
      }
    }]);
<commit_msg>Show voice wave less electric.<commit_after>'use strict';

/**
 * @ngdoc service
 * @name wavesApp.voiceVisualizer
 * @description
 * # voiceVisualizer
 * Service in the wavesApp.
 */
angular.module('wavesApp')
  .service('voiceVisualizer', ['$window', function ($window) {
      $window.navigator.getUserMedia = ($window.navigator.getUserMedia ||
                            $window.navigator.webkitGetUserMedia ||
                            $window.navigator.mozGetUserMedia ||
                            $window.navigator.msGetUserMedia);

      // set up forked web audio context, for multiple browsers
      // window. is needed otherwise Safari explodes

      var audioCtx = new ($window.AudioContext || $window.webkitAudioContext)();
      // var voiceSelect = document.getElementById("voice");
      var source;
      var stream;

      //set up the different audio nodes we will use for the app
      var analyser = audioCtx.createAnalyser();
      analyser.minDecibels = -90;
      analyser.maxDecibels = -10;
      analyser.smoothingTimeConstant = 0.85;

      var distortion = audioCtx.createWaveShaper();
      var gainNode = audioCtx.createGain();
      var biquadFilter = audioCtx.createBiquadFilter();
      var convolver = audioCtx.createConvolver();

      var canvas,
          canvasCtx,
          intendedWidth,
          drawVisual;

      var WIDTH;
      var HEIGHT;

      return {
        init: function( cnvs ){
          // set up canvas context for visualizer
          canvas = cnvs;
          canvasCtx = cnvs.getContext("2d");
          intendedWidth = document.querySelector('.visualizer-wrapper').clientWidth;
          canvas.setAttribute('width', intendedWidth);
          canvas.setAttribute('height', 400);

          //main block for doing the audio recording
          if ($window.navigator.getUserMedia) {
            console.log('getUserMedia supported.');
            $window.navigator.getUserMedia (
              { audio: true },
              function(stream) {
                source = audioCtx.createMediaStreamSource(stream);
                source.connect(analyser);
                analyser.connect(distortion);
                distortion.connect(biquadFilter);
                biquadFilter.connect(convolver);
                convolver.connect(gainNode);
                gainNode.connect(audioCtx.destination);

                $window.cancelAnimationFrame(drawVisual);
              },
              function(err) {
                console.log('The following gUM error occured: ' + err);
              });
          } else {
            console.log('getUserMedia not supported on your browser!');
          }
          this.visualize();
          return this;
        },
        visualize: function (){
          WIDTH = canvas.width;
          HEIGHT = canvas.height;
          // var visualSetting = 'sinewave';

          analyser.fftSize = 2048;
          var bufferLength = analyser.frequencyBinCount;
          // var bufferLength = analyser.fftSize;

          var dataArray = new Uint8Array(bufferLength);
          var reflectedDataArray = new Uint8Array(bufferLength);
          reflectedDataArray.set(dataArray.reverse(), dataArray);

          canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);

          function draw() {
            drawVisual = requestAnimationFrame(draw);
            analyser.getByteFrequencyData(dataArray);
            // analyser.getByteTimeDomainData(dataArray);

            canvasCtx.fillStyle = 'rgb(0, 0, 0)';
            canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
            canvasCtx.lineWidth = 2;
            canvasCtx.strokeStyle = 'rgb(255, 255, 255)';
            canvasCtx.beginPath();

            var sliceWidth = WIDTH * 1.0 / bufferLength;
            var x = 0;

            for(var i = 0; i < bufferLength; i++) {
              var v = dataArray[i];
              var y = (HEIGHT-HEIGHT/4) - v;
              if(i === 0) {
                canvasCtx.moveTo(x, y);
              } else {
                canvasCtx.lineTo(x, y);
              }
              x += 3*sliceWidth;
            }
            canvasCtx.lineTo(WIDTH, HEIGHT/2);
            canvasCtx.stroke();
          };

          draw();
        }
      }
    }]);
<|endoftext|>


<commit_before>import { run } from '@ember/runloop';
import EmberObject from '@ember/object';
import $ from 'jquery';
import ArrayProxy from '@ember/array/proxy';
import Component from '@ember/component';
import config from 'travis/config/environment';
import { computed } from 'ember-decorators/object';
import { service } from 'ember-decorators/service';

export default Component.extend({
  @service router: null,
  @service permissions: null,
  @service externalLinks: null,

  tagName: 'li',
  classNameBindings: ['branch.last_build.state'],
  classNames: ['branch-row', 'row-li'],
  isLoading: false,
  isTriggering: false,
  hasTriggered: false,

  @computed('branch.repository.slug', 'branch.last_build.commit.sha')
  urlGithubCommit(slug, sha) {
    return this.get('externalLinks').githubCommit(slug, sha);
  },

  @computed()
  getLast5Builds() {
    let apiEndpoint, branchName, lastBuilds, options, repoId;
    lastBuilds = ArrayProxy.create({
      content: [{}, {}, {}, {}, {}],
      isLoading: true,
      count: 0
    });
    if (!this.get('branch.last_build')) {
      lastBuilds.set('isLoading', false);
    } else {
      apiEndpoint = config.apiEndpoint;
      repoId = this.get('branch.repository.id');
      branchName = encodeURIComponent(this.get('branch.name'));
      options = {
        headers: {
          'Travis-API-Version': '3'
        }
      };
      if (this.get('auth.signedIn')) {
        options.headers.Authorization = `token ${this.auth.token}`;
      }
      let path = `${apiEndpoint}/repo/${repoId}/builds`;
      let params = `?branch.name=${branchName}&limit=5&build.event_type=push,api,cron`;
      let url = `${path}${params}`;

      $.ajax(url, options).then(response => {
        let array, i, trueLength;
        array = response.builds.map(build => EmberObject.create(build));
        // We need exactly 5 elements in array
        if (array.length < 5) {
          trueLength = array.length;
          for (i = trueLength; i < 5; i++) {
            array.push({});
          }
        }

        run(() => {
          lastBuilds.set('count', response['@pagination'].count);
          lastBuilds.set('content', array);
          lastBuilds.set('isLoading', false);
        });
      });
    }
    return lastBuilds;
  },

  actions: {
    viewAllBuilds() {
      return this.get('router').transitionTo('builds');
    }
  }
});
<commit_msg>attempt to fix api token on branches page<commit_after>import { run } from '@ember/runloop';
import EmberObject from '@ember/object';
import $ from 'jquery';
import ArrayProxy from '@ember/array/proxy';
import Component from '@ember/component';
import config from 'travis/config/environment';
import { computed } from 'ember-decorators/object';
import { service } from 'ember-decorators/service';

export default Component.extend({
  @service router: null,
  @service permissions: null,
  @service externalLinks: null,

  tagName: 'li',
  classNameBindings: ['branch.last_build.state'],
  classNames: ['branch-row', 'row-li'],
  isLoading: false,
  isTriggering: false,
  hasTriggered: false,

  @computed('branch.repository.slug', 'branch.last_build.commit.sha')
  urlGithubCommit(slug, sha) {
    return this.get('externalLinks').githubCommit(slug, sha);
  },

  @computed()
  getLast5Builds() {
    let apiEndpoint, branchName, lastBuilds, options, repoId;
    lastBuilds = ArrayProxy.create({
      content: [{}, {}, {}, {}, {}],
      isLoading: true,
      count: 0
    });
    if (!this.get('branch.last_build')) {
      lastBuilds.set('isLoading', false);
    } else {
      apiEndpoint = config.apiEndpoint;
      repoId = this.get('branch.repository.id');
      branchName = encodeURIComponent(this.get('branch.name'));
      options = {
        headers: {
          'Travis-API-Version': '3'
        }
      };
      if (this.get('auth.signedIn')) {
        options.headers.Authorization = `token ${this.get('auth.token')}`;
      }
      let path = `${apiEndpoint}/repo/${repoId}/builds`;
      let params = `?branch.name=${branchName}&limit=5&build.event_type=push,api,cron`;
      let url = `${path}${params}`;

      $.ajax(url, options).then(response => {
        let array, i, trueLength;
        array = response.builds.map(build => EmberObject.create(build));
        // We need exactly 5 elements in array
        if (array.length < 5) {
          trueLength = array.length;
          for (i = trueLength; i < 5; i++) {
            array.push({});
          }
        }

        run(() => {
          lastBuilds.set('count', response['@pagination'].count);
          lastBuilds.set('content', array);
          lastBuilds.set('isLoading', false);
        });
      });
    }
    return lastBuilds;
  },

  actions: {
    viewAllBuilds() {
      return this.get('router').transitionTo('builds');
    }
  }
});
<|endoftext|>