<commit_before>// Detect language immediately
var cookie_value = document.cookie.match('cookie=.n');

if (cookie_value == "cookie=jn" && window.location.href.indexOf("/en/") != -1)
    window.location = window.location.href.replace('/en/', '/ja/');
else if (cookie_value == "cookie=en" && window.location.href.indexOf("/ja/") != -1)
    window.location = window.location.href.replace('/ja/', '/en/');
else if (cookie_value != "cookie=en" && cookie_value != "cookie=jn") {
    var userLang = (navigator.language) ? navigator.language : navigator.userLanguage;

    if ((userLang == "en-us" || userLang == "en-US") && window.location.pathname == '/ja/home') {
        window.location = window.location.href.replace('/ja/', '/en/');
    }
    else if (userLang == "ja" && window.location.pathname == '/en/home') {
        window.location = window.location.href.replace('/en/', '/ja/');
    }
}

$(document).ready(function () {

    var BrowserDetect = {
        init: function () {

            /**************************************************/

            this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
            this.version = this.searchVersion(navigator.userAgent)
                || this.searchVersion(navigator.appVersion)
                || "an unknown version";
            this.OS = this.searchString(this.dataOS) || "an unknown OS";
        },
        searchString: function (data) {
            for (var i = 0; i < data.length; i++) {
                var dataString = data[i].string;
                var dataProp = data[i].prop;
                this.versionSearchString = data[i].versionSearch || data[i].identity;
                if (dataString) {
                    if (dataString.indexOf(data[i].subString) != -1)
                        return data[i].identity;
                }
                else if (dataProp)
                    return data[i].identity;
            }
        },
        searchVersion: function (dataString) {
            var index = dataString.indexOf(this.versionSearchString);
            if (index == -1) return;
            return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
        },
        dataBrowser: [
            {
                string: navigator.userAgent,
                subString: "Chrome",
                identity: "Chrome"
            },
            {
                string: navigator.userAgent,
                subString: "OmniWeb",
                versionSearch: "OmniWeb/",
                identity: "OmniWeb"
            },
            {
                string: navigator.vendor,
                subString: "Apple",
                identity: "Safari",
                versionSearch: "Version"
            },
            {
                prop: window.opera,
                identity: "Opera",
                versionSearch: "Version"
            },
            {
                string: navigator.vendor,
                subString: "iCab",
                identity: "iCab"
            },
            {
                string: navigator.vendor,
                subString: "KDE",
                identity: "Konqueror"
            },
            {
                string: navigator.userAgent,
                subString: "Firefox",
                identity: "Firefox"
            },
            {
                string: navigator.vendor,
                subString: "Camino",
                identity: "Camino"
            },
            {		// for newer Netscapes (6+)
                string: navigator.userAgent,
                subString: "Netscape",
                identity: "Netscape"
            },
            {
                string: navigator.userAgent,
                subString: "MSIE",
                identity: "Explorer",
                versionSearch: "MSIE"
            },
            {
                string: navigator.userAgent,
                subString: "Gecko",
                identity: "Mozilla",
                versionSearch: "rv"
            },
            { 		// for older Netscapes (4-)
                string: navigator.userAgent,
                subString: "Mozilla",
                identity: "Netscape",
                versionSearch: "Mozilla"
            }
        ],
        dataOS: [
            {
                string: navigator.platform,
                subString: "Win",
                identity: "Windows"
            },
            {
                string: navigator.platform,
                subString: "Mac",
                identity: "Mac"
            },
            {
                string: navigator.userAgent,
                subString: "iPhone",
                identity: "iPhone/iPod"
            },
            {
                string: navigator.platform,
                subString: "Linux",
                identity: "Linux"
            }
        ]

    };
    BrowserDetect.init();

    if ((BrowserDetect.browser == 'Firefox' && BrowserDetect.version < 12) || (BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 9)) {
        $('#browserModal').modal('show');
        console.log(BrowserDetect.version);
    }

	var visited_value = document.cookie.match('visited=1');
	if (visited_value != "visited=1"){
		console.log("new");
		$('#firstTimeModal').modal('show');
		document.cookie = "visited=1; max-age=" + 60 * 60 * 24 * 365 + "; path=/";
	}

    /***************************************************/
    /*************** HEADER ****************************/
    /***************************************************/

    /*************** USER LOGIN ************************/

    $('#sign-in').click(function () {
        $('#user-modal-body').empty().append('');
        $('#user-modal').modal('show');
        return false;
    });

    $('#user-modal').bind('authenticated', function () {
        $('#sign-in').hide();
        $('#user-dropdown').show();
        $('#jda-header-me').show();
        if (!_.isUndefined(window.jda)) jda.app.userAuthenticated();
        return false;
    });

    $('#user-modal').bind('close', function () { $("#user-modal-close").trigger('click'); });

    /*************** ACCOUNT SETTINGS ************************/

    $('#account-settings').click(function () {
        $('#user-modal-body').empty().append('');
        $('#user-modal').modal('show');
        return false;

    });

    /************  BUG REPORT **********************/

    $('.bug-report').click(function (e) { e.stopPropagation(); });

    $('.bug-report').parent().click(function () {
        $('.bug-unsubmitted').show();
        $('.bug-submitted').hide();
    });

    $('.close-bug').click(function () {
        $('.bug-report').parent().trigger('click');
    });

    $('.submit-bug').click(function () {

        var bug = new Backbone.Model({

            url: window.location.href,
            hash: window.location.hash.substr(1),
            description: $('.bug-description').val(),
            email: $('.bug-email').val(),
            browser: BrowserDetect.browser,
            version: BrowserDetect.version,
            os: BrowserDetect.OS,
            login: sessionStorage.getItem('user')

        });

        bug.url = "../bugs/report.php";
        bug.save();
        $('.bug-description').attr('value', '');
        $('.bug-unsubmitted').fadeOut('fast', function () {
            $('.bug-submitted').fadeIn();
        });

    });

    /*************** LANGUAGE TOGGLE ************************/
    $('#jda-language-toggle').find('.btn').click(function () {

        function set_cookie(cookie_name, cookie_value, lifespan_in_days, valid_domain) {
            // http://www.thesitewizard.com/javascripts/cookies.shtml
            var domain_string = valid_domain ? ("; domain=" + valid_domain) : '';
            document.cookie = cookie_name + "=" + encodeURIComponent(cookie_value) + "; max-age=" + 60 * 60 * 24 * lifespan_in_days + "; path=/" + domain_string;
        }

        if (!$(this).hasClass('active')) {
            console.log('switching languages');
            $('#jda-language-toggle').find('.btn').removeClass('active');
            $(this).addClass('active');
            console.log($(this).data('language'));
            if ($(this).data('language') == 'en') {
                set_cookie("cookie", "en", "365", "jdarchive.org");
                if (window.location.href.indexOf("/en/") == -1) {
                    window.location.href = window.location.href.replace('/ja/', '/en/');
                }
            }
            else {
                set_cookie("cookie", "jn", "365", "jdarchive.org");
                if (window.location.href.indexOf("/ja/") == -1) {
                    window.location = window.location.href.replace('/en/', '/ja/');
                }
            }
        }

    });

    $('.jda-home-featured-collection').height(Math.max($(window).height() - 50, 600));

    $(window).resize(function () { $('.jda-home-featured-collection').height(Math.max($(window).height() - 50, 600)); });

    // Shorthand the application namespace
    //http://documentcloud.github.com/visualsearch/
    VisualSearch = VS.init({
        container: $('.visual_search'),
        query: '',
        callbacks: {

            loaded: function () {

                if ($(location).attr('href').indexOf('home') >= 0) {
                    $('.VS-search-box').css('width', '600px');
					$('.VS-search-box').css('margin-left', 'auto');
					$('.VS-search-box').css('margin-right', 'auto');
                    $('#VS-search input').css('width', '550px');
                } else {
                    $('.VS-search-box').css('width', '500px');
                    $('#VS-search input').css('width', '430px');
                }
                $("#jda-home-search-div, #search-bar").fadeTo('slow', 1);
                $('#VS-search input').attr('placeholder', 'Explore the Archive');

                $('#VS-search input').css('padding-top', '9px');
                $('#VS-search input').focus(function () {
                    //$(this).attr('placeholder', '');
                    $(this).css('width', '3px');
                });

                $('#jda-go-button').click(function () {
                    var query = VisualSearch.searchBox.value();
                    window.location = 'search#q=' + query;
                });
            },

            search: function () {

                var facets = VisualSearch.searchQuery.models;

                var tagQuery = "tag:";
                var textQuery = "";
                //var usernameQuery = "";

                _.each(facets, function (facet) {
                    console.log(facet.get('category'));
                    switch (facet.get('category')) {
                        case 'text':
                            textQuery = (textQuery.length > 0) ? textQuery + " AND " + facet.get('value') : facet.get('value');
                            textQuery = textQuery.replace(/^#/, '');
                            break;
                        case 'tag':
                            tagQuery = (tagQuery.length > 4) ? tagQuery + ", " + facet.get('value') : tagQuery + facet.get('value');
                            tagQuery = tagQuery.replace(/^#/, '');
                            break;
                            /*
                            case 'user':
                                usernameQuery = facet.get('value');
                                break;
                            */
                    }
                });

                var query = textQuery + (textQuery.length > 0 && tagQuery.length > 4 ? " " : "") + (tagQuery.length > 4 ? tagQuery : "");

                window.location = 'search#q=' + query;

            },

            clearSearch: function () { $('input').val(''); },
            // These are the facets that will be autocompleted in an empty input.
            facetMatches: function (callback) {
                callback([
					//'tag', 'keyword', 'text', 'data:time & place','collection','user'
					'tag', 'text'
                ]);
            },
            // These are the values that match specific categories, autocompleted
            // in a category's input field.  searchTerm can be used to filter the
            // list on the server-side, prior to providing a list to the widget.
            valueMatches: function (facet, searchTerm, callback) {
                switch (facet) {
                    case 'user':
                        callback([]);
                        break;
                    case 'tag':
                        callback([]);
                        break;
                    case 'keyword':
                        callback([]);
                        break;
                    case 'text':
                        callback([]);
                        break;
                    case 'data:time & place':
                        callback([]);
                        break;
                }
            }
        } //callbacks
    });

    $('#jda-go-button').click(function () {
        var e = jQuery.Event("keydown");
        e.which = 13;

        //For whatever reason there are two ways of telling VS to search
        //based on whether the facet has been created yet or not
        if ($(".search_facet_input_container input").length) {
            $(".search_facet_input_container input").trigger(e);
        } else {
            VisualSearch.searchBox.searchEvent(e);
        }

        return false;
    });

});
<commit_msg>testing cookies<commit_after>// Detect language immediately
var cookie_value = document.cookie.match('cookie=.n');

if (cookie_value == "cookie=jn" && window.location.href.indexOf("/en/") != -1)
    window.location = window.location.href.replace('/en/', '/ja/');
else if (cookie_value == "cookie=en" && window.location.href.indexOf("/ja/") != -1)
    window.location = window.location.href.replace('/ja/', '/en/');
else if (cookie_value != "cookie=en" && cookie_value != "cookie=jn") {
    var userLang = (navigator.language) ? navigator.language : navigator.userLanguage;

    if ((userLang == "en-us" || userLang == "en-US") && window.location.pathname == '/ja/home') {
        window.location = window.location.href.replace('/ja/', '/en/');
    }
    else if (userLang == "ja" && window.location.pathname == '/en/home') {
        window.location = window.location.href.replace('/en/', '/ja/');
    }
}
console.log("browser done");

$(document).ready(function () {

    var BrowserDetect = {
        init: function () {

            /**************************************************/

            this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
            this.version = this.searchVersion(navigator.userAgent)
                || this.searchVersion(navigator.appVersion)
                || "an unknown version";
            this.OS = this.searchString(this.dataOS) || "an unknown OS";
        },
        searchString: function (data) {
            for (var i = 0; i < data.length; i++) {
                var dataString = data[i].string;
                var dataProp = data[i].prop;
                this.versionSearchString = data[i].versionSearch || data[i].identity;
                if (dataString) {
                    if (dataString.indexOf(data[i].subString) != -1)
                        return data[i].identity;
                }
                else if (dataProp)
                    return data[i].identity;
            }
        },
        searchVersion: function (dataString) {
            var index = dataString.indexOf(this.versionSearchString);
            if (index == -1) return;
            return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
        },
        dataBrowser: [
            {
                string: navigator.userAgent,
                subString: "Chrome",
                identity: "Chrome"
            },
            {
                string: navigator.userAgent,
                subString: "OmniWeb",
                versionSearch: "OmniWeb/",
                identity: "OmniWeb"
            },
            {
                string: navigator.vendor,
                subString: "Apple",
                identity: "Safari",
                versionSearch: "Version"
            },
            {
                prop: window.opera,
                identity: "Opera",
                versionSearch: "Version"
            },
            {
                string: navigator.vendor,
                subString: "iCab",
                identity: "iCab"
            },
            {
                string: navigator.vendor,
                subString: "KDE",
                identity: "Konqueror"
            },
            {
                string: navigator.userAgent,
                subString: "Firefox",
                identity: "Firefox"
            },
            {
                string: navigator.vendor,
                subString: "Camino",
                identity: "Camino"
            },
            {		// for newer Netscapes (6+)
                string: navigator.userAgent,
                subString: "Netscape",
                identity: "Netscape"
            },
            {
                string: navigator.userAgent,
                subString: "MSIE",
                identity: "Explorer",
                versionSearch: "MSIE"
            },
            {
                string: navigator.userAgent,
                subString: "Gecko",
                identity: "Mozilla",
                versionSearch: "rv"
            },
            { 		// for older Netscapes (4-)
                string: navigator.userAgent,
                subString: "Mozilla",
                identity: "Netscape",
                versionSearch: "Mozilla"
            }
        ],
        dataOS: [
            {
                string: navigator.platform,
                subString: "Win",
                identity: "Windows"
            },
            {
                string: navigator.platform,
                subString: "Mac",
                identity: "Mac"
            },
            {
                string: navigator.userAgent,
                subString: "iPhone",
                identity: "iPhone/iPod"
            },
            {
                string: navigator.platform,
                subString: "Linux",
                identity: "Linux"
            }
        ]

    };
    BrowserDetect.init();

    if ((BrowserDetect.browser == 'Firefox' && BrowserDetect.version < 12) || (BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 9)) {
        $('#browserModal').modal('show');
        console.log(BrowserDetect.version);
    }

	var visited_value = document.cookie.match('visited=1');
	if (visited_value != "visited=1"){
		console.log("new");
		$('#firstTimeModal').modal('show');
		document.cookie = "visited=1; max-age=" + 60 * 60 * 24 * 365 + "; path=/";
	}

    /***************************************************/
    /*************** HEADER ****************************/
    /***************************************************/

    /*************** USER LOGIN ************************/

    $('#sign-in').click(function () {
        $('#user-modal-body').empty().append('');
        $('#user-modal').modal('show');
        return false;
    });

    $('#user-modal').bind('authenticated', function () {
        $('#sign-in').hide();
        $('#user-dropdown').show();
        $('#jda-header-me').show();
        if (!_.isUndefined(window.jda)) jda.app.userAuthenticated();
        return false;
    });

    $('#user-modal').bind('close', function () { $("#user-modal-close").trigger('click'); });

    /*************** ACCOUNT SETTINGS ************************/

    $('#account-settings').click(function () {
        $('#user-modal-body').empty().append('');
        $('#user-modal').modal('show');
        return false;

    });

    /************  BUG REPORT **********************/

    $('.bug-report').click(function (e) { e.stopPropagation(); });

    $('.bug-report').parent().click(function () {
        $('.bug-unsubmitted').show();
        $('.bug-submitted').hide();
    });

    $('.close-bug').click(function () {
        $('.bug-report').parent().trigger('click');
    });

    $('.submit-bug').click(function () {

        var bug = new Backbone.Model({

            url: window.location.href,
            hash: window.location.hash.substr(1),
            description: $('.bug-description').val(),
            email: $('.bug-email').val(),
            browser: BrowserDetect.browser,
            version: BrowserDetect.version,
            os: BrowserDetect.OS,
            login: sessionStorage.getItem('user')

        });

        bug.url = "../bugs/report.php";
        bug.save();
        $('.bug-description').attr('value', '');
        $('.bug-unsubmitted').fadeOut('fast', function () {
            $('.bug-submitted').fadeIn();
        });

    });

    /*************** LANGUAGE TOGGLE ************************/
    $('#jda-language-toggle').find('.btn').click(function () {

        function set_cookie(cookie_name, cookie_value, lifespan_in_days, valid_domain) {
            // http://www.thesitewizard.com/javascripts/cookies.shtml
            var domain_string = valid_domain ? ("; domain=" + valid_domain) : '';
            document.cookie = cookie_name + "=" + encodeURIComponent(cookie_value) + "; max-age=" + 60 * 60 * 24 * lifespan_in_days + "; path=/" + domain_string;
        }

        if (!$(this).hasClass('active')) {
            console.log('switching languages');
            $('#jda-language-toggle').find('.btn').removeClass('active');
            $(this).addClass('active');
            console.log($(this).data('language'));
            if ($(this).data('language') == 'en') {
                set_cookie("cookie", "en", "365", "jdarchive.org");
                if (window.location.href.indexOf("/en/") == -1) {
                    window.location.href = window.location.href.replace('/ja/', '/en/');
                }
            }
            else {
                set_cookie("cookie", "jn", "365", "jdarchive.org");
                if (window.location.href.indexOf("/ja/") == -1) {
                    window.location = window.location.href.replace('/en/', '/ja/');
                }
            }
        }

    });

    $('.jda-home-featured-collection').height(Math.max($(window).height() - 50, 600));

    $(window).resize(function () { $('.jda-home-featured-collection').height(Math.max($(window).height() - 50, 600)); });

    // Shorthand the application namespace
    //http://documentcloud.github.com/visualsearch/
    VisualSearch = VS.init({
        container: $('.visual_search'),
        query: '',
        callbacks: {

            loaded: function () {

                if ($(location).attr('href').indexOf('home') >= 0) {
                    $('.VS-search-box').css('width', '600px');
					$('.VS-search-box').css('margin-left', 'auto');
					$('.VS-search-box').css('margin-right', 'auto');
                    $('#VS-search input').css('width', '550px');
                } else {
                    $('.VS-search-box').css('width', '500px');
                    $('#VS-search input').css('width', '430px');
                }
                $("#jda-home-search-div, #search-bar").fadeTo('slow', 1);
                $('#VS-search input').attr('placeholder', 'Explore the Archive');

                $('#VS-search input').css('padding-top', '9px');
                $('#VS-search input').focus(function () {
                    //$(this).attr('placeholder', '');
                    $(this).css('width', '3px');
                });

                $('#jda-go-button').click(function () {
                    var query = VisualSearch.searchBox.value();
                    window.location = 'search#q=' + query;
                });
            },

            search: function () {

                var facets = VisualSearch.searchQuery.models;

                var tagQuery = "tag:";
                var textQuery = "";
                //var usernameQuery = "";

                _.each(facets, function (facet) {
                    console.log(facet.get('category'));
                    switch (facet.get('category')) {
                        case 'text':
                            textQuery = (textQuery.length > 0) ? textQuery + " AND " + facet.get('value') : facet.get('value');
                            textQuery = textQuery.replace(/^#/, '');
                            break;
                        case 'tag':
                            tagQuery = (tagQuery.length > 4) ? tagQuery + ", " + facet.get('value') : tagQuery + facet.get('value');
                            tagQuery = tagQuery.replace(/^#/, '');
                            break;
                            /*
                            case 'user':
                                usernameQuery = facet.get('value');
                                break;
                            */
                    }
                });

                var query = textQuery + (textQuery.length > 0 && tagQuery.length > 4 ? " " : "") + (tagQuery.length > 4 ? tagQuery : "");

                window.location = 'search#q=' + query;

            },

            clearSearch: function () { $('input').val(''); },
            // These are the facets that will be autocompleted in an empty input.
            facetMatches: function (callback) {
                callback([
					//'tag', 'keyword', 'text', 'data:time & place','collection','user'
					'tag', 'text'
                ]);
            },
            // These are the values that match specific categories, autocompleted
            // in a category's input field.  searchTerm can be used to filter the
            // list on the server-side, prior to providing a list to the widget.
            valueMatches: function (facet, searchTerm, callback) {
                switch (facet) {
                    case 'user':
                        callback([]);
                        break;
                    case 'tag':
                        callback([]);
                        break;
                    case 'keyword':
                        callback([]);
                        break;
                    case 'text':
                        callback([]);
                        break;
                    case 'data:time & place':
                        callback([]);
                        break;
                }
            }
        } //callbacks
    });

    $('#jda-go-button').click(function () {
        var e = jQuery.Event("keydown");
        e.which = 13;

        //For whatever reason there are two ways of telling VS to search
        //based on whether the facet has been created yet or not
        if ($(".search_facet_input_container input").length) {
            $(".search_facet_input_container input").trigger(e);
        } else {
            VisualSearch.searchBox.searchEvent(e);
        }

        return false;
    });

});
<|endoftext|>


<commit_before>/*
 * tst.context.js: tests that cause works with errors from different contexts.
 */

var mod_assert = require('assert');
var mod_verror = require('../lib/verror');
var mod_isError = require('core-util-is').isError;
var mod_vm = require('vm');

var VError = mod_verror.VError;
var WError = mod_verror.WError;

var err = new Error();
var verr = new VError(err);
mod_assert.ok(mod_isError(verr.cause()));

var context = mod_vm.createContext({
	'callback': function callback(err2) {
		mod_assert.ok(mod_isError(err2));
		var verr2 = new VError(err);
		mod_assert.ok(mod_isError(verr2.cause()));
	}
});
mod_vm.runInContext('callback(new Error())', context);
<commit_msg>joyent/node-verror#56 Add more tests to tst.context.js Reviewed by: David Pacheco <dap@joyent.com> Approved by: David Pacheco <dap@joyent.com><commit_after>/*
 * tst.context.js: tests that cause works with errors from different contexts.
 */

var mod_assert = require('assert');
var mod_verror = require('../lib/verror');
var mod_vm = require('vm');

var VError = mod_verror.VError;
var WError = mod_verror.WError;

var prog1 = 'callback(new Error(), "Error")';
var prog2 = 'var e = new Error(); e.name = "BarError"; callback(e, "BarError")';

function runTests(cerr, name) {
	var verr;

	/*
	 * The constructor should recognize the other context's Error as an
	 * error for wrapping, and not as an options object.
	 */
	verr = new VError(cerr);
	mod_assert.equal(verr.cause(), cerr);

	verr = new VError({ cause: cerr });
	mod_assert.equal(verr.cause(), cerr);

	/*
	 * The assertions done at each step while walking the cause chain
	 * should be okay with the other context's Error.
	 */
	mod_assert.deepEqual(
	    mod_verror.findCauseByName(cerr, 'FooError'), null);
	mod_assert.equal(
	    mod_verror.findCauseByName(verr, name), cerr);

	/*
	 * Verify that functions that take an Error as an argument
	 * accept the Error created in the other context.
	 */
	mod_assert.deepEqual(mod_verror.cause(cerr), null);
	mod_assert.deepEqual(mod_verror.info(cerr), {});
	mod_assert.equal(typeof (mod_verror.fullStack(cerr)), 'string');
}

var context = mod_vm.createContext({
	'callback': runTests
});

/*
 * We run the same set of tests using two different errors: one whose name is
 * the default "Error", and one whose name has been changed.
 *
 * Note that changing the name is not the same as having a constructor that
 * inherits from Error. Such Errors are not currently supported when
 * constructed in another context.
 */
mod_vm.runInContext(prog1, context);
mod_vm.runInContext(prog2, context);
<|endoftext|>


<commit_before>/**
 * .reel Unit Tests
 */
(function($){

  module('Issues', reel_test_module_routine);

  test( 'GH-4 Proper background positioning range for stitched non-looping panoramas', function(){
    /* Github issue 4 bugfix
     * http://github.com/pisi/Reel/issues/#issue/4
     */
    expect($.browser.msie ? 4 : 2);
    var
      stitched= 1652,
      $pano= $('#stitched_nonlooping').reel({ stitched: stitched, loops: false }),
      travel= stitched - parseInt($pano.css('width'))

    $pano.trigger('frameChange', 1);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), '0px', 'Frame 1 (min, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Frame 1 (min, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), '0px 0px', 'Frame 1 (min)');
    }
    $pano.trigger('frameChange', 36);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), -travel+'px', 'Frame 36 (max, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Frame 36 (max, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), -travel+'px 0px', 'Frame 36 (max)');
    }
  });

  test( 'GH-6 Proper background positioning range for stitched looping panoramas', function(){
    /* Github issue 6 bugfix
     * http://github.com/pisi/Reel/issues/#issue/6
     */
    expect($.browser.msie ? 4 : 2);
    var
      stitched= 1652,
      $pano= $('#stitched_looping').reel({ stitched: stitched, loops: true }),
      travel= stitched

    $pano.trigger('frameChange', 1);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), '0px', 'Looping - frame 1 (min, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Looping - frame 1 (min, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), '0px 0px', 'Looping - frame 1 (min)');
    }
    $pano.trigger('frameChange', 36);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), '0px', 'Looping - frame 36 (max, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Looping - frame 36 (max, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), '0px 0px', 'Looping - frame 36 (max)');
    }
  });

  asyncTest( 'GH-11 First frame disappears after image sequence loading is complete', function(){
    /* Github issue 11 bugfix
     * http://github.com/pisi/Reel/issues/#issue/11
     * Replacement of original image source with embedded transparent sprite
     * can not happen when using `images` option
     */
    expect(1);
    var
      $pano= $('#sequence').reel({
        footage:  10,
        cw:       true,
        orbital:  3,
        inversed: true,
        path:     'resources/phone/',
        images:   phone_frames(20)
      })

    $pano.one('loaded.test', function(){
      equal($pano.attr('src'), 'resources/phone/01.png', 'Image is from the sequence');
      start();
    });

    /*
      Borrowed from test/sampler.html
    */
    function phone_frames(frames){
      var every= 1, stack= []
      for(var i= 1; i <= frames; i+= every){
        var name= [i, '.png'].join('')
        while (name.length < 6) name= '0'+name
        stack.push(name)
      }
      return stack
    }
  });

  asyncTest( 'GH-30 Broken "play" in IE', function(){
    /* Github issue 30 bugfix
     * http://github.com/pisi/Reel/issues/#issue/30
     * First of all, private `slidable` boolean flag leaked into global scope
     * and also caused Reel to throw JS errors.
     * Then adaptive ticker timeout sometimes went sub-zero causing IE to invalidate such `setTimeout` call
     * and thus effectively ceised the timer completely.
     * Another IE issue: broken image overlay in IE 7 or lower was caused by no support for "data:" protocol URLs,
     * so to workaround it a CDN-served blank image is be used instead.
     */
    expect(4);
    var
      $pano= $('#image').reel(),
      ticks= 0

    equal(typeof slidable, 'undefined', '`slidable` is undefined in the global scope');
    equal(typeof window.slidable, 'undefined', '`window.slidable` is also undefined');

    $(document).bind('tick.reel.test', function(){
      ticks++;
      if (ticks == 100){
        ok(true, 'Ticked 100 times - ticker runs ;)');

        var
          protocol= $('#image').attr('src').split(':')[0]

        if ($.browser.msie && +$.browser.version <= 7) equal(protocol, 'http', 'CDN-served transparent image.')
        else equal(protocol, 'data', 'Embedded transparent image.');

        start();
      }
    });
  });

  asyncTest( '`stage_pool` private variable leaked into global scope', function()
  {
    expect(1);

    var
      $reel= $('#image').reel()

    setTimeout(function(){
      ok( typeof stage_pool === 'undefined', 'No leaked `stage_pool` accessible in the global scope');
      start();
    }, 100)
  });

  asyncTest( '`footage` private variable leaked into global scope', function()
  {
    expect(1);

    var
      $reel= $('#image').reel()

    setTimeout(function(){
      ok( typeof footage === 'undefined', 'No leaked `footage` accessible in the global scope');
      start();
    }, 100)
  });

  asyncTest( 'Teardown doesn\'t propagate the cloned original image down the chain', function(){
    /*
     * When Reel instance is torn down and `.reel()` is called again in the same chain,
     * the instance isn't properly initialized.
     * The cloned-back original `IMG` tag doesn't propagate as a proper target
     * for subsequent `.reel()` calls. These don't fail (as they are most probably
     * performed upon the old now detached DOM node. The extra selector evaluation
     * is therefore required in order to further manipulate the node.
     */
    expect( 3 );

    $('#image').reel().bind('click.test', function(){
      ok( true, 'Event binding is preserved');
    });

    setTimeout( function(){
      $('#image').trigger('teardown').reel();
      ok( $('#image').is('.reel'), 'IMG tag is flagged as a Reel instance');
      ok( $('#image').parent().is('.reel-overlay#image-reel'), 'and wrapped in overlay DIV');
      $('#image').click();
      start();
    }, 500 );
  });

  asyncTest( 'GH-46 Incorrect `row` to `frame` translation in multi-row movies', function(){
    /* Github issue 46 bugfix
     * http://github.com/pisi/Reel/issues/#issue/46
     * When topmost row has been reached with dragging, the instance freeze in that row
     * no matter the vertical direction of the drag. Instance then has to be dragged
     * left or right to restore the vertical movement. Unfortunately enough
     * this happens for all frames lying on the first row and especially the default value.
     *
     * This bug expresses itself by locking vertical reel in the topmost row
     * and preventing proper `row` > `frame` propagation unless horizontal drag
     * is performed.
     */
    var
      try_rows= [ 1, 2 ],
      done_rows= 0,
      try_frames= [ 1, 2, 3, 4, 5, 6, 7, /*8,*/ 9, 10, 11, 12, 13, 14, /*15,*/ 16, 17, 18, 19, 20,
                    21, 22, 23, 24, 25, 26, 27, 28, /*29,*/ 30, 31, 32, 33, 34, 35, 36 ]
                    /* The three commented-out frame values (8, 15 and 29)
                     * are known exceptions from the rule and the actual calculated value is
                     * always one less. Exactly why this happens and especially why it is
                     * independent on `frames` value is still a true mystery for me.
                     * Anyway, it yields 96.3% accuracy, which is as far as I could get it,
                     * is much better then before and I'm happy with it. At least for now.
                     */

    expect( try_rows * try_frames * 3 ); // 3 test for each combination

    for( var i= 0; i < try_rows.length; i++) setTimeout( function(){
      for( var ii= 0; ii < try_frames.length; ii++){
        $('#image').unreel();
        var
          frame= try_frames[ ii ],
          row= try_rows[ i ],
          rows= 2,
          frames= 36, // default
          $pano= $('#image').reel({
            frame: frame,
            snaps: false, // The default snapping is not desirable in this precision test
            rows: rows,
            row: row
          })

        // Click and drag long way down
        $pano.trigger('down', [ 100, 200 ]);
        $pano.trigger('pan', [ 100, 400 ]);
        deepEqual({ row: $pano.data('row'), frame: $pano.data('frame') },
                  { row: 1, frame: rows * frames - frames + frame },
                  'Drag way down on frame '+frame+' / '+frames+', row '+row+' / '+rows);

        // `tick` needs to be triggered manually between `pan`s in order to have the instance slidable again
        $pano.trigger('tick');

        // Then drag it all the way back up to reach the first row
        $pano.trigger('pan', [ 100, 1 ]);
        deepEqual({ row: $pano.data('row'), frame: $pano.data('frame') },
                  { row: 0, frame: frame },
                  '& drag way up');

        $pano.trigger('tick');

        // Then drag it back all the way down
        $pano.trigger('pan', [ 100, 400 ]);
        deepEqual({ row: $pano.data('row'), frame: $pano.data('frame') },
                  { row: 1, frame: rows * frames - frames + frame },
                  '& drag way down again.');
      }
      done_rows++;
      if (done_rows == rows) start();
    }, 5);
  });

  asyncTest( 'GH-62 Implicit teardown', function(){
    /*
     * Unable to switch Reels in a simple manner without a manual teardown.
     */
    expect( 1 );
    var
      image = undefined

    $('#image').reel().bind('loaded.test', function(){
      if (image === undefined){
        image= $(this).data('image');
        var
          new_instance= $(this).reel({
            image: 'resources/green-reel.jpg'
          });

        // Finish the test in case reel initialization fails
        if (!new_instance.length){
          ok( false, 'Unable to instantitate the same DOM node for the second time');
          start();
        }
      }else{
        ok( image !== $(this).data('image'), 'The second reel image is different than the starting one');
        start();
      }
    });
    $('#image').reel();
  });

})(jQuery);
<commit_msg>Fixing the multirow test to receive correct row index even when asynchronous by wrapping it function and passing in the index.<commit_after>/**
 * .reel Unit Tests
 */
(function($){

  module('Issues', reel_test_module_routine);

  test( 'GH-4 Proper background positioning range for stitched non-looping panoramas', function(){
    /* Github issue 4 bugfix
     * http://github.com/pisi/Reel/issues/#issue/4
     */
    expect($.browser.msie ? 4 : 2);
    var
      stitched= 1652,
      $pano= $('#stitched_nonlooping').reel({ stitched: stitched, loops: false }),
      travel= stitched - parseInt($pano.css('width'))

    $pano.trigger('frameChange', 1);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), '0px', 'Frame 1 (min, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Frame 1 (min, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), '0px 0px', 'Frame 1 (min)');
    }
    $pano.trigger('frameChange', 36);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), -travel+'px', 'Frame 36 (max, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Frame 36 (max, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), -travel+'px 0px', 'Frame 36 (max)');
    }
  });

  test( 'GH-6 Proper background positioning range for stitched looping panoramas', function(){
    /* Github issue 6 bugfix
     * http://github.com/pisi/Reel/issues/#issue/6
     */
    expect($.browser.msie ? 4 : 2);
    var
      stitched= 1652,
      $pano= $('#stitched_looping').reel({ stitched: stitched, loops: true }),
      travel= stitched

    $pano.trigger('frameChange', 1);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), '0px', 'Looping - frame 1 (min, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Looping - frame 1 (min, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), '0px 0px', 'Looping - frame 1 (min)');
    }
    $pano.trigger('frameChange', 36);
    if ($.browser.msie){
      // MSIE returns undefined backgroundPosition, so we need to check individual ones
      equiv($pano.css('backgroundPositionX'), '0px', 'Looping - frame 36 (max, X)');
      equiv($pano.css('backgroundPositionY'), '0px', 'Looping - frame 36 (max, Y)');
    }else{
      equiv($pano.css('backgroundPosition'), '0px 0px', 'Looping - frame 36 (max)');
    }
  });

  asyncTest( 'GH-11 First frame disappears after image sequence loading is complete', function(){
    /* Github issue 11 bugfix
     * http://github.com/pisi/Reel/issues/#issue/11
     * Replacement of original image source with embedded transparent sprite
     * can not happen when using `images` option
     */
    expect(1);
    var
      $pano= $('#sequence').reel({
        footage:  10,
        cw:       true,
        orbital:  3,
        inversed: true,
        path:     'resources/phone/',
        images:   phone_frames(20)
      })

    $pano.one('loaded.test', function(){
      equal($pano.attr('src'), 'resources/phone/01.png', 'Image is from the sequence');
      start();
    });

    /*
      Borrowed from test/sampler.html
    */
    function phone_frames(frames){
      var every= 1, stack= []
      for(var i= 1; i <= frames; i+= every){
        var name= [i, '.png'].join('')
        while (name.length < 6) name= '0'+name
        stack.push(name)
      }
      return stack
    }
  });

  asyncTest( 'GH-30 Broken "play" in IE', function(){
    /* Github issue 30 bugfix
     * http://github.com/pisi/Reel/issues/#issue/30
     * First of all, private `slidable` boolean flag leaked into global scope
     * and also caused Reel to throw JS errors.
     * Then adaptive ticker timeout sometimes went sub-zero causing IE to invalidate such `setTimeout` call
     * and thus effectively ceised the timer completely.
     * Another IE issue: broken image overlay in IE 7 or lower was caused by no support for "data:" protocol URLs,
     * so to workaround it a CDN-served blank image is be used instead.
     */
    expect(4);
    var
      $pano= $('#image').reel(),
      ticks= 0

    equal(typeof slidable, 'undefined', '`slidable` is undefined in the global scope');
    equal(typeof window.slidable, 'undefined', '`window.slidable` is also undefined');

    $(document).bind('tick.reel.test', function(){
      ticks++;
      if (ticks == 100){
        ok(true, 'Ticked 100 times - ticker runs ;)');

        var
          protocol= $('#image').attr('src').split(':')[0]

        if ($.browser.msie && +$.browser.version <= 7) equal(protocol, 'http', 'CDN-served transparent image.')
        else equal(protocol, 'data', 'Embedded transparent image.');

        start();
      }
    });
  });

  asyncTest( '`stage_pool` private variable leaked into global scope', function()
  {
    expect(1);

    var
      $reel= $('#image').reel()

    setTimeout(function(){
      ok( typeof stage_pool === 'undefined', 'No leaked `stage_pool` accessible in the global scope');
      start();
    }, 100)
  });

  asyncTest( '`footage` private variable leaked into global scope', function()
  {
    expect(1);

    var
      $reel= $('#image').reel()

    setTimeout(function(){
      ok( typeof footage === 'undefined', 'No leaked `footage` accessible in the global scope');
      start();
    }, 100)
  });

  asyncTest( 'Teardown doesn\'t propagate the cloned original image down the chain', function(){
    /*
     * When Reel instance is torn down and `.reel()` is called again in the same chain,
     * the instance isn't properly initialized.
     * The cloned-back original `IMG` tag doesn't propagate as a proper target
     * for subsequent `.reel()` calls. These don't fail (as they are most probably
     * performed upon the old now detached DOM node. The extra selector evaluation
     * is therefore required in order to further manipulate the node.
     */
    expect( 3 );

    $('#image').reel().bind('click.test', function(){
      ok( true, 'Event binding is preserved');
    });

    setTimeout( function(){
      $('#image').trigger('teardown').reel();
      ok( $('#image').is('.reel'), 'IMG tag is flagged as a Reel instance');
      ok( $('#image').parent().is('.reel-overlay#image-reel'), 'and wrapped in overlay DIV');
      $('#image').click();
      start();
    }, 500 );
  });

  asyncTest( 'GH-46 Incorrect `row` to `frame` translation in multi-row movies', function(){
    /* Github issue 46 bugfix
     * http://github.com/pisi/Reel/issues/#issue/46
     * When topmost row has been reached with dragging, the instance freeze in that row
     * no matter the vertical direction of the drag. Instance then has to be dragged
     * left or right to restore the vertical movement. Unfortunately enough
     * this happens for all frames lying on the first row and especially the default value.
     *
     * This bug expresses itself by locking vertical reel in the topmost row
     * and preventing proper `row` > `frame` propagation unless horizontal drag
     * is performed.
     */
    var
      try_rows= [ 1, 2 ],
      done_rows= 0,
      try_frames= [ 1, 2, 3, 4, 5, 6, 7, /*8,*/ 9, 10, 11, 12, 13, 14, /*15,*/ 16, 17, 18, 19, 20,
                    21, 22, 23, 24, 25, 26, 27, 28, /*29,*/ 30, 31, 32, 33, 34, 35, 36 ]
                    /* The three commented-out frame values (8, 15 and 29)
                     * are known exceptions from the rule and the actual calculated value is
                     * always one less. Exactly why this happens and especially why it is
                     * independent on `frames` value is still a true mystery for me.
                     * Anyway, it yields 96.3% accuracy, which is as far as I could get it,
                     * is much better then before and I'm happy with it. At least for now.
                     */

    expect( try_rows * try_frames * 3 ); // 3 test for each combination

    for( var i= 0; i < try_rows.length; i++) (function(ix){ setTimeout( function(){
      for( var ii= 0; ii < try_frames.length; ii++){
        $('#image').unreel();
        var
          frame= try_frames[ ii ],
          row= try_rows[ ix ],
          rows= 2,
          frames= 36, // default
          $pano= $('#image').reel({
            frame: frame,
            snaps: false, // The default snapping is not desirable in this precision test
            rows: rows,
            row: row
          })

        // Click and drag long way down
        $pano.trigger('down', [ 100, 200 ]);
        $pano.trigger('pan', [ 100, 400 ]);
        deepEqual({ row: $pano.data('row'), frame: $pano.data('frame') },
                  { row: 1, frame: rows * frames - frames + frame },
                  'Drag way down on frame '+frame+' / '+frames+', row '+row+' / '+rows);

        // `tick` needs to be triggered manually between `pan`s in order to have the instance slidable again
        $pano.trigger('tick');

        // Then drag it all the way back up to reach the first row
        $pano.trigger('pan', [ 100, 1 ]);
        deepEqual({ row: $pano.data('row'), frame: $pano.data('frame') },
                  { row: 0, frame: frame },
                  '& drag way up');

        $pano.trigger('tick');

        // Then drag it back all the way down
        $pano.trigger('pan', [ 100, 400 ]);
        deepEqual({ row: $pano.data('row'), frame: $pano.data('frame') },
                  { row: 1, frame: rows * frames - frames + frame },
                  '& drag way down again.');
      }
      done_rows++;
      if (done_rows == rows) start();
    }, 5) })(i)
  });

  asyncTest( 'GH-62 Implicit teardown', function(){
    /*
     * Unable to switch Reels in a simple manner without a manual teardown.
     */
    expect( 1 );
    var
      image = undefined

    $('#image').reel().bind('loaded.test', function(){
      if (image === undefined){
        image= $(this).data('image');
        var
          new_instance= $(this).reel({
            image: 'resources/green-reel.jpg'
          });

        // Finish the test in case reel initialization fails
        if (!new_instance.length){
          ok( false, 'Unable to instantitate the same DOM node for the second time');
          start();
        }
      }else{
        ok( image !== $(this).data('image'), 'The second reel image is different than the starting one');
        start();
      }
    });
    $('#image').reel();
  });

})(jQuery);
<|endoftext|>


<commit_before>module('Tests for the parser plugin');
test('Get attr href', function() {
  var url = 'https://github.com/AlekseyLeshko/testimonial.js';
  var $node = $('<a />', {
    href: url
  });
  var href = Parser.prototype.getAttrHrefOrDefault($node);
  ok(href === url, 'Received href is correct');
});

test('Get default href', function() {
  var defaultHref = '#';
  var $node = $('<a />');
  var href = Parser.prototype.getAttrHrefOrDefault($node);
  ok(href === defaultHref, 'Received href is correct');
});

test('Parse author node', function() {
  var $node = $('.author').first();
  var slideObj = Parser.prototype.parseAuthorNode($node);
  compareSlideObj(slideObj, expectedSlideObj);
});

test('Parse node', function() {
  var quote = 'Истинный путь идет по канату, который натянут не высоко, а над самой землей. ' +
    'Он предназначен, кажется, больше для того, чтобы о него спотыкаться, ' +
    'чем для того, чтобы идти по нему.';
  var $node = $('.slide').first();
  Parser.prototype.dataArr = [];
  Parser.prototype.parseNode($node);
  ok(Parser.prototype.dataArr.length === 1, 'Ыlide parsed correctly');

  var slideObj = Parser.prototype.dataArr[0];
  compareSlideObj(slideObj, expectedSlideObj);
  ok(slideObj.quote === quote, 'Quote is correct');
});

var expectedSlideObj = {
  fullName: 'Кафка Франц',
  authorHref: 'https://github.com/AlekseyLeshko',
  company: 'Company',
  companyHref: 'https://github.com',
  fotoSrc: '../resources/img/author_logo.png'
};

function compareSlideObj(x, y) {
  ok(x.fullName === y.fullName, 'Fullname is correct');
  ok(x.authorHref === y.authorHref, 'Author url is correct');
  ok(x.company === y.company, 'Company is correct');
  ok(x.companyHref === y.companyHref, 'Company url is correct');
  ok(x.fotoSrc === y.fotoSrc, 'Foto src is correct');
};
<commit_msg>Add test for plugin parser<commit_after>module('Tests for the parser plugin');
test('Get attr href', function() {
  var url = 'https://github.com/AlekseyLeshko/testimonial.js';
  var $node = $('<a />', {
    href: url
  });
  var href = Parser.prototype.getAttrHrefOrDefault($node);
  ok(href === url, 'Received href is correct');
});

test('Get default href', function() {
  var defaultHref = '#';
  var $node = $('<a />');
  var href = Parser.prototype.getAttrHrefOrDefault($node);
  ok(href === defaultHref, 'Received href is correct');
});

test('Parse author node', function() {
  var $node = $('.author').first();
  var slideObj = Parser.prototype.parseAuthorNode($node);
  compareSlideObj(slideObj, expectedSlideObj);
});

test('Parse node', function() {
  var quote = 'Истинный путь идет по канату, который натянут не высоко, а над самой землей. ' +
    'Он предназначен, кажется, больше для того, чтобы о него спотыкаться, ' +
    'чем для того, чтобы идти по нему.';
  var $node = $('.slide').first();
  Parser.prototype.dataArr = [];
  Parser.prototype.parseNode($node);
  ok(Parser.prototype.dataArr.length === 1, 'Slide parsed correctly');

  var slideObj = Parser.prototype.dataArr[0];
  compareSlideObj(slideObj, expectedSlideObj);
  ok(slideObj.quote === quote, 'Quote is correct');
});

test('Parser constructor', function() {
  var $nodeArr = $('.slide');
  var parser = new Parser($nodeArr);

  ok(parser.dataArr.length === 0);
  ok(parser.$nodeArr === $nodeArr);
});

var expectedSlideObj = {
  fullName: 'Кафка Франц',
  authorHref: 'https://github.com/AlekseyLeshko',
  company: 'Company',
  companyHref: 'https://github.com',
  fotoSrc: '../resources/img/author_logo.png'
};

function compareSlideObj(x, y) {
  ok(x.fullName === y.fullName, 'Fullname is correct');
  ok(x.authorHref === y.authorHref, 'Author url is correct');
  ok(x.company === y.company, 'Company is correct');
  ok(x.companyHref === y.companyHref, 'Company url is correct');
  ok(x.fotoSrc === y.fotoSrc, 'Foto src is correct');
};
<|endoftext|>


<commit_before>module.exports = {
  CUSTOMER: "customer",
  BETTEREZ_APP: "betterez-app",
  MOBILE_SCANNER: "btrz-mobile-scanner"
};<commit_msg>#3rr0ec6: Add API_CLIENT audience<commit_after>module.exports = {
  CUSTOMER: "customer",
  BETTEREZ_APP: "betterez-app",
  MOBILE_SCANNER: "btrz-mobile-scanner",
  API_CLIENT: "btrz-api-client"
};<|endoftext|>


<commit_before>//grab the synced data and create a map with it

var hash = window.location.hash.replace("#", "");
var coords = hash.split(",");
var lat = coords[0]
var lon = coords[1];

var mapillary_popup = $(".mapillary-image-viewer");
var mapillary_renderer = $("#mapillary-image");
var mapillary_close_button = $(".mapillary-quit");

var tabs = {
	satellite: $("[mode=satellite]"),
	map: $("[mode=regular]"),
}

var map = L.map('map-main').setView([lat, lon], 14);
var mapLayer = L.tileLayer('http://otile{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png', {
	maxZoom: 18,
	subdomains: '1234',
	attribution: 'Tiles Courtesy of MapQuest. © OpenStreetMap contributors (license)'
});

mapLayer.addTo(map);

var marker = L.marker([lat, lon]).addTo(map);

tabs.map.on("click", function () {
	if (satelliteLayer) {
		map.addLayer(mapLayer);
		map.removeLayer(satelliteLayer);
	}
	tabs.satellite.removeClass("selected");
	tabs.map.addClass("selected");
});

tabs.satellite.on("click", function () {
	if (!window.satelliteLayer) { //there isn't a satellite layer yet, create one
		window.satelliteLayer = L.tileLayer('http://otile{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.png', {
			maxZoom: 18,
			subdomains: '1234',
			attribution: 'Tiles Courtesy of MapQuest. Portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency'
		});
	}

	map.addLayer(satelliteLayer);
	map.removeLayer(mapLayer);
	tabs.satellite.addClass("selected");
	tabs.map.removeClass("selected");
});

map.on("click", function (e) {
	console.log(e);
	var lat = e.latlng.lat;
	var lon = e.latlng.lng;
	var maxDistance = (19 - map.getZoom()) * 12 + 15;
	console.log("distance is", maxDistance);
	$.ajax({
			url: "https://api.mapillary.com/v1/im/close",
			data: {
				lat: lat,
				lon: lon,
				distance: maxDistance,
				limit: 3,
			}
		})
		.done(function (data) {
			console.log(data);
			if (data.length > 0) {
				var image = data[0];
				var imagelat = image.lat;
				var imagelon = image.lon;
				var src = "https://d1cuyjsrcm0gby.cloudfront.net/" + image.key + "/thumb-640.jpg";
				var image = $("").attr("src", src)[0].outerHTML;
				var popup = L.popup({
						className: "mapillary-popup",
					})
					.setLatLng([imagelat, imagelon])
					.setContent(image + "
Imagery by Mapillary
")
					.openOn(map);
			} else {
				createToast("No ground imagery available for this location.");
			}

		});
});

mapillary_close_button.on("click", function () {
	mapillary_popup.attr("hidden", "true");
});

function enableMapillaryLayer() { //show where there are mapillary images. Not accessible through the UI, but useful for debugging.
	L.tileLayer("http://{s}.tiles.mapillary.com/{z}/{x}/{y}").addTo(map);
}<commit_msg>bug fix<commit_after>//grab the synced data and create a map with it

var hash = window.location.hash.replace("#", "");
var coords = hash.split(",");
var lat = coords[0]
var lon = coords[1];

var mapillary_popup = $(".mapillary-image-viewer");
var mapillary_renderer = $("#mapillary-image");
var mapillary_close_button = $(".mapillary-quit");

var tabs = {
	satellite: $("[mode=satellite]"),
	map: $("[mode=regular]"),
}

var map = L.map('map-main').setView([lat, lon], 14);
var mapLayer = L.tileLayer('http://otile{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png', {
	maxZoom: 18,
	subdomains: '1234',
	attribution: 'Tiles Courtesy of MapQuest. © OpenStreetMap contributors (license)'
});

mapLayer.addTo(map);

var marker = L.marker([lat, lon]).addTo(map);

tabs.map.on("click", function () {
	if (satelliteLayer) {
		map.addLayer(mapLayer);
		map.removeLayer(satelliteLayer);
	}
	tabs.satellite.removeClass("selected");
	tabs.map.addClass("selected");
});

tabs.satellite.on("click", function () {
	if (!window.satelliteLayer) { //there isn't a satellite layer yet, create one
		window.satelliteLayer = L.tileLayer('http://otile{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.png', {
			maxZoom: 18,
			subdomains: '1234',
			attribution: 'Tiles Courtesy of MapQuest. Portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency'
		});
	}

	map.addLayer(satelliteLayer);
	map.removeLayer(mapLayer);
	tabs.satellite.addClass("selected");
	tabs.map.removeClass("selected");
});

map.on("click", function (e) {
	console.log(e);
	var lat = e.latlng.lat;
	var lon = e.latlng.lng;
	var maxDistance = (19 - map.getZoom()) * 12 + 15;
	console.log("distance is", maxDistance);
	$.ajax({
			url: "https://api.mapillary.com/v1/im/close",
			data: {
				lat: lat,
				lon: lon,
				distance: maxDistance,
				limit: 3,
			}
		})
		.done(function (data) {
			console.log(data);
			if (data.length > 0) {
				var image = data[0];
				var imagelat = image.lat;
				var imagelon = image.lon;
				var src = "https://d1cuyjsrcm0gby.cloudfront.net/" + image.key + "/thumb-640.jpg";
				var image = $("").attr("src", src)[0].outerHTML;
				var popup = L.popup({
						className: "mapillary-popup",
					})
					.setLatLng([imagelat, imagelon])
					.setContent(image + "
Imagery by Mapillary
")
					.openOn(map);

				//recalculate the size of the popup when the image loads
				$(".mapillary-image-thumb").on("load", function () {
					popup.update();
				});
			} else {
				createToast("No ground imagery available for this location.");
			}

		});
});

mapillary_close_button.on("click", function () {
	mapillary_popup.attr("hidden", "true");
});

function enableMapillaryLayer() { //show where there are mapillary images. Not accessible through the UI, but useful for debugging.
	L.tileLayer("http://{s}.tiles.mapillary.com/{z}/{x}/{y}").addTo(map);
}<|endoftext|>


<commit_before>var SRC_DIR = 'src';
var GRUNT_TEST_DIR = 'grunt/test';
var ROOT_DIR = './';
var TEMPLATE_DIR = 'grunt/templates';

var exec = require("child_process").exec;

module.exports = function(grunt) {

  var modules = grunt.file.expand({cwd: SRC_DIR}, 'basic-*');

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    src_dir: 'src',
    build_dir: 'build',
    dist_dir: 'dist',

    clean: {
      build: '<%= build_dir %>',
      dist: '<%= dist_dir %>'
    },

    copy: {
      build: {
        expand: true,
        cwd: SRC_DIR,
        src: [
          'basic-*/+(basic-*).+(html|js)',
          'basic-shared/*.js',
          'basic-shared/resources/**',
          '!test/**'],
        dest: '<%= build_dir %>'
      },
      dist: {
        expand: true,
        cwd: '<%= build_dir %>',
        src: ['**/*.html', '**/*.js'],
        dest: '<%= dist_dir %>'
      },
      test: {
        expand: true,
        cwd: GRUNT_TEST_DIR,
        src: ['index.html'],
        dest: '<%= dist_dir %>'
      },
      bower_test: {
        expand: true,
        cwd: ROOT_DIR,
        src: ['bower_components/**'],
        dest: '<%= dist_dir %>'
      }
    },

    uglify: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= build_dir %>',
          src: ['basic-*/*.js', 'basic-shared/*.js'],
          dest: '<%= build_dir %>'
        }]
      }
    },

    hogan_static: {
      lib: {
        options:{
          data: {
            modules: modules,
            'basic-shared': grunt.file.expand({cwd: SRC_DIR})
          }
        },
        files: [{
          src: TEMPLATE_DIR + '/lib_template.html',
          dest: '<%= build_dir %>/<%= pkg.name %>.html'
        }]
      }
    },

    vulcanize: {
      options: {
        inline:true,
        'strip-excludes':true,

        // Comment out the following line for verbose output files
        //strip:true
      },
      'basic-shared': {
        files: [{
          expand: true,
          cwd: '<%= build_dir %>',
          src: ['basic-shared/**/*.html'],
          dest: '<%= build_dir %>'
        }]
      },
      modules: {
        options:{
          excludes: {
            imports: ['.*\.html']
          }
        },
        files: [{
          expand: true,
          cwd: '<%= build_dir %>',
          src: ['basic-*/basic-*.html'],
          dest: '<%= build_dir %>'
        }]
      },
      dist: {
        options:{
          excludes: {
            imports: ['polymer.html']
          }
        },
        files: {
          '<%= build_dir %>/<%= pkg.name %>.html' : '<%= build_dir %>/<%= pkg.name %>.html'
        }
      }
    },

    replace: {
      bower: {
        src: ['dist/**/*.html'],
        overwrite: true,
        replacements: [{
          from: 'bower_components',
          to: '..'
        }]
      }
    },

    banner: grunt.file.read('BANNER.txt'),

    usebanner: {
      jscss: {
        options: {
          banner: '/**\n<%= banner %>\n*/'
        },
        files: {
          src: [ 'src/**/*.js', 'src/**/*.scss' ]
        }
      },
      html: {
        options: {
          banner: '<!--\n<%= banner %>\n-->'
        },
        files: {
          src: [ 'src/basic-*/basic-*.html' ]
        }
      },
      dist: {
        options: {
          banner: '<!--\n<%= banner %>\n-->'
        },
        files: {
          src: [ 'build/basic-web-components.html' ]
        }
      }
    },

    bump: {
      options: {
        files: [ 'package.json', 'bower.json' ],
        commitFiles: [ 'package.json', 'bower.json', 'dist/*' ],
        updateConfigs: ['pkg'],
        push: true,
        pushTo: 'origin'
      }
    }

  });

  // Create HTML imports for basic-shared folders
  grunt.registerTask('basic-shared:imports', function() {
    var dirs = ['.'];

    for (var i = 0; i < dirs.length; i++) {
      var files = grunt.file.expand({cwd: SRC_DIR + '/basic-shared/' + dirs[i] + '/' }, '*.js');

      files.forEach(function(file) {
        var fileName = file.substr(0, file.lastIndexOf('.')) || file;
        grunt.file.write(grunt.config('build_dir') + '/basic-shared/' + dirs[i] + '/' + fileName.toLowerCase() + '.html', '<script src=\"' + file + '\"></script>');
      });
    }

    grunt.log.ok();
  });

  grunt.registerTask('build:dist', function(arg){
    grunt.task.run([
      'clean:build',
      'copy:build',
      'hogan_static:lib',
      'vulcanize:basic-shared',
      'vulcanize:modules',
      'vulcanize:dist',
      'usebanner:dist'
    ]);
  });

  grunt.registerTask('build:dev', function() {
    grunt.task.run([
      'clean:build',
      'copy:build',
      'hogan_static:lib'
    ]);
  });

  function execCmd(cmd, onExecuted) {
    exec( cmd, function(error, stdout, stderr) {
      error && console.error(error);
      stderr && console.error(stderr);
      stdout && console.log(stdout);
      onExecuted();
    });
  }

  grunt.registerTask('stage-release', 'Stage release files.', function() {
    execCmd('git add ' + grunt.config('dist_dir') + '/*', this.async() );
  });

  grunt.registerTask('default', ['build:dev']);

  grunt.registerTask('release', function(version){
    version = version || 'patch';
    grunt.task.run( 'bump-only:' + version, 'clean:dist', 'build:dist', 'copy:dist', 'replace:bower', 'build:docs', 'stage-release', 'bump-commit');
  });

  grunt.registerTask('build:test', function(version) {
    version = version || 'patch';
    grunt.task.run('clean:dist', 'build:dist', 'copy:dist', 'replace:bower', 'copy:test', 'copy:bower_test');
  });
};
<commit_msg>Clean up basic-shared grunt tasks that are not longer needed.<commit_after>var SRC_DIR = 'src';
var GRUNT_TEST_DIR = 'grunt/test';
var ROOT_DIR = './';
var TEMPLATE_DIR = 'grunt/templates';

var exec = require("child_process").exec;

module.exports = function(grunt) {

  var modules = grunt.file.expand({cwd: SRC_DIR}, 'basic-*');

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    src_dir: 'src',
    build_dir: 'build',
    dist_dir: 'dist',

    clean: {
      build: '<%= build_dir %>',
      dist: '<%= dist_dir %>'
    },

    copy: {
      build: {
        expand: true,
        cwd: SRC_DIR,
        src: [
          'basic-*/+(basic-*).+(html|js)',
          'basic-shared/*.js',
          'basic-shared/resources/**',
          '!test/**'],
        dest: '<%= build_dir %>'
      },
      dist: {
        expand: true,
        cwd: '<%= build_dir %>',
        src: ['**/*.html', '**/*.js'],
        dest: '<%= dist_dir %>'
      },
      test: {
        expand: true,
        cwd: GRUNT_TEST_DIR,
        src: ['index.html'],
        dest: '<%= dist_dir %>'
      },
      bower_test: {
        expand: true,
        cwd: ROOT_DIR,
        src: ['bower_components/**'],
        dest: '<%= dist_dir %>'
      }
    },

    uglify: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= build_dir %>',
          src: ['basic-*/*.js', 'basic-shared/*.js'],
          dest: '<%= build_dir %>'
        }]
      }
    },

    hogan_static: {
      lib: {
        options:{
          data: {
            modules: modules,
            'basic-shared': grunt.file.expand({cwd: SRC_DIR})
          }
        },
        files: [{
          src: TEMPLATE_DIR + '/lib_template.html',
          dest: '<%= build_dir %>/<%= pkg.name %>.html'
        }]
      }
    },

    vulcanize: {
      options: {
        inline:true,
        'strip-excludes':true,

        // Comment out the following line for verbose output files
        //strip:true
      },
      modules: {
        options:{
          excludes: {
            imports: ['.*\.html']
          }
        },
        files: [{
          expand: true,
          cwd: '<%= build_dir %>',
          src: ['basic-*/basic-*.html'],
          dest: '<%= build_dir %>'
        }]
      },
      dist: {
        options:{
          excludes: {
            imports: ['polymer.html']
          }
        },
        files: {
          '<%= build_dir %>/<%= pkg.name %>.html' : '<%= build_dir %>/<%= pkg.name %>.html'
        }
      }
    },

    replace: {
      bower: {
        src: ['dist/**/*.html'],
        overwrite: true,
        replacements: [{
          from: 'bower_components',
          to: '..'
        }]
      }
    },

    banner: grunt.file.read('BANNER.txt'),

    usebanner: {
      jscss: {
        options: {
          banner: '/**\n<%= banner %>\n*/'
        },
        files: {
          src: [ 'src/**/*.js', 'src/**/*.scss' ]
        }
      },
      html: {
        options: {
          banner: '<!--\n<%= banner %>\n-->'
        },
        files: {
          src: [ 'src/basic-*/basic-*.html' ]
        }
      },
      dist: {
        options: {
          banner: '<!--\n<%= banner %>\n-->'
        },
        files: {
          src: [ 'build/basic-web-components.html' ]
        }
      }
    },

    bump: {
      options: {
        files: [ 'package.json', 'bower.json' ],
        commitFiles: [ 'package.json', 'bower.json', 'dist/*' ],
        updateConfigs: ['pkg'],
        push: true,
        pushTo: 'origin'
      }
    }

  });

  grunt.registerTask('build:dist', function(arg){
    grunt.task.run([
      'clean:build',
      'copy:build',
      'hogan_static:lib',
      'vulcanize:modules',
      'vulcanize:dist',
      'usebanner:dist'
    ]);
  });

  grunt.registerTask('build:dev', function() {
    grunt.task.run([
      'clean:build',
      'copy:build',
      'hogan_static:lib'
    ]);
  });

  function execCmd(cmd, onExecuted) {
    exec( cmd, function(error, stdout, stderr) {
      error && console.error(error);
      stderr && console.error(stderr);
      stdout && console.log(stdout);
      onExecuted();
    });
  }

  grunt.registerTask('stage-release', 'Stage release files.', function() {
    execCmd('git add ' + grunt.config('dist_dir') + '/*', this.async() );
  });

  grunt.registerTask('default', ['build:dev']);

  grunt.registerTask('release', function(version){
    version = version || 'patch';
    grunt.task.run( 'bump-only:' + version, 'clean:dist', 'build:dist', 'copy:dist', 'replace:bower', 'build:docs', 'stage-release', 'bump-commit');
  });

  grunt.registerTask('build:test', function(version) {
    version = version || 'patch';
    grunt.task.run('clean:dist', 'build:dist', 'copy:dist', 'replace:bower', 'copy:test', 'copy:bower_test');
  });
};
<|endoftext|>


<commit_before>/*
  Retrieve useful information about OpenStack
  a dictionnary of instances
   * Id of instance
   * User
   * Creation date
   * Last time we see the instance
   * Last lease date
   * Lease expiration
*/
function instancesStatus() {
    return $.getJSON("/instances", function(data) {
        return data;
    });
}

/**/
function buildInstanceView(instance, details) {
    return '
' +
           '' + details.name + '	' +
           '' + details.project + '	' +
           '' + details.created_at + '	' +
           '' + details.lease_end + '' +
           '	' +
           '
';
}

/*
    buildInstancesView create a full display of Instance on div_name
*/
function buildInstancesView(instances, div_name){
    $(div_name).html('');
    $.each(instances, function(instance, details){
        $(buildInstanceView(instance, details)).appendTo(div_name);
    });
}

/*
    Update lease status on click
*/
function updateLease(instance) {
    return $.getJSON("/instances/" + instance, function(data){
        instancesStatus().then(function (data_instances){
            var INSTANCES = data_instances;
            buildInstancesView(INSTANCES, '#instances');
        });
    }).success(function(data){
        text = data['instance']['name']
        if (data['status'] == "success") {
            color = "teal-text"
            type = "check"
        } else {
            color = "red-text"
            type = "clear"
        }
        Materialize.toast(text + ' ' + type + '', 600, 'rounded')
    });
}<commit_msg>Fix some jshint issues<commit_after>/*
  Retrieve useful information about OpenStack
  a dictionnary of instances
   * Id of instance
   * User
   * Creation date
   * Last time we see the instance
   * Last lease date
   * Lease expiration
*/
function instancesStatus() {
    return $.getJSON("/instances", function(data) {
        return data;
    });
}

/**/
function buildInstanceView(instance, details) {
    return '
' +
           '' + details.name + '	' +
           '' + details.project + '	' +
           '' + details.created_at + '	' +
           '' + details.lease_end + '' +
           '	' +
           '
';
}

/*
    buildInstancesView create a full display of Instance on div_name
*/
function buildInstancesView(instances, div_name){
    $(div_name).html('');
    $.each(instances, function(instance, details){
        $(buildInstanceView(instance, details)).appendTo(div_name);
    });
}

/*
    Update lease status on click
*/
function updateLease(instance) {
    return $.getJSON("/instances/" + instance, function(data){
        instancesStatus().then(function (data_instances){
            var INSTANCES = data_instances;
            buildInstancesView(INSTANCES, '#instances');
        });
    }).success(function(data){
        text = data.instance.name;
        if (data.status == "success") {
            color = "teal-text";
            type = "check";
        } else {
            color = "red-text";
            type = "clear";
        }
        Materialize.toast(text + ' ' + type + '',
         600, 'rounded');
    });
}<|endoftext|>


<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft Corporation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
WScript.Flag("-wasmI64");

function* paramTypes() {
  while(true) {
    yield "i32";
    yield "i64";
    yield "f32";
    yield "f64";
  }
}

function* callArguments() {
  // 3 values to rotate which type will receive which arg
  while(true) {
    yield {value: -12345, i32: "(i32.const -12345)", i64: "(i64.const -12345)", f32: `(f32.const ${Math.fround(-12345)})`, f64: `(f64.const -12345.0)`};
    yield {value: "0xabcdef12345678", i32: "(i32.const 0)", i64: "(i64.const 0xabcdef12345678)", f32: "(f32.const 0)", f64: "(f64.const 0)"};
    yield {value: Math.PI, i32: `(i32.const ${Math.PI|0})`, i64: `(i64.const ${Math.PI|0})`, f32: `(f32.const ${Math.fround(Math.PI)})`, f64: `(f64.const ${Math.PI})`};
  }
}
const tested = {};
function test(n) {
  if (n in tested) {
    return tested[n];
  }
  print(`Test(${n})`)
  const typeGen = paramTypes();
  const argGen = callArguments();
  let params = [], wasmCallTxt = [], callArgs = [], verify = [];
  for (let i = 0; i < n; ++i) {
    const type = typeGen.next().value;
    const getLocal = `(get_local ${i|0})`;
    const arg = argGen.next().value;

    params.push(type);
    wasmCallTxt.push(getLocal);
    callArgs.push(arg.value);
    verify.push(`(${type}.ne ${getLocal} ${arg[type]}) (br_if 0 (i32.const 0)) (drop)`);
  }
  const paramsTxt = params.join(" ");
  const txt = `(module
    (func $verify (param ${paramsTxt}) (result i32)
      ${verify.join("\n      ")}
      (i32.const 1)
    )
    (func (export "foo") (param ${paramsTxt}) (result i32)
      (call $verify
        ${wasmCallTxt.join("\n        ")}
      )
    )
  )`;
  //print(txt);
  const buf = WebAssembly.wabt.convertWast2Wasm(txt);
  try {
    const module = new WebAssembly.Module(buf);
    const {exports: {foo}} = new WebAssembly.Instance(module);
    if (foo(...callArgs) !== 1) {
      print(`FAILED. Failed to validate with ${n} arguments`);
    }
    tested[n] = true;
    return true;
  } catch (e) {
  }
  tested[n] = false;
}

const [forceTest] = WScript.Arguments;
if (forceTest !== undefined) {
  const res = test(forceTest);
  print(res ? "Module is valid" : "Module is invalid");
  WScript.Quit(0);
}

let nParams = 9000;
let inc = 1000;
let direction = true;

while (inc !== 0) {
  if (test(nParams)) {
    if (direction) {
      nParams += inc;
    } else {
      direction = true;
      inc >>= 1;
      nParams += inc;
    }
  } else {
    if (!direction) {
      nParams -= inc;
    } else {
      direction = false;
      inc >>= 1;
      // make sure the last test is a passing one
      inc = inc || 1;
      nParams -= inc;
    }
  }

  if (nParams > 100000 || nParams < 0) {
    print(`FAILED. Params reached ${nParams} long. Expected an error by now`);
    break;
  }
}

print(`Support at most ${nParams} params`);
<commit_msg>Update params.js test to not kill the process during execution<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft Corporation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
WScript.Flag("-wasmI64");

function* paramTypes() {
  while(true) {
    yield "i32";
    yield "i64";
    yield "f32";
    yield "f64";
  }
}

function* callArguments() {
  // 3 values to rotate which type will receive which arg
  while(true) {
    yield {value: -12345, i32: "(i32.const -12345)", i64: "(i64.const -12345)", f32: `(f32.const ${Math.fround(-12345)})`, f64: `(f64.const -12345.0)`};
    yield {value: "0xabcdef12345678", i32: "(i32.const 0)", i64: "(i64.const 0xabcdef12345678)", f32: "(f32.const 0)", f64: "(f64.const 0)"};
    yield {value: Math.PI, i32: `(i32.const ${Math.PI|0})`, i64: `(i64.const ${Math.PI|0})`, f32: `(f32.const ${Math.fround(Math.PI)})`, f64: `(f64.const ${Math.PI})`};
  }
}
const tested = {};
function test(n) {
  if (n in tested) {
    return tested[n];
  }
  print(`Test(${n})`)
  const typeGen = paramTypes();
  const argGen = callArguments();
  let params = [], wasmCallTxt = [], callArgs = [], verify = [];
  for (let i = 0; i < n; ++i) {
    const type = typeGen.next().value;
    const getLocal = `(get_local ${i|0})`;
    const arg = argGen.next().value;

    params.push(type);
    wasmCallTxt.push(getLocal);
    callArgs.push(arg.value);
    verify.push(`(${type}.ne ${getLocal} ${arg[type]}) (br_if 0 (i32.const 0)) (drop)`);
  }
  const paramsTxt = params.join(" ");
  const txt = `(module
    (func $verify (param ${paramsTxt}) (result i32)
      ${verify.join("\n      ")}
      (i32.const 1)
    )
    (func (export "foo") (param ${paramsTxt}) (result i32)
      (call $verify
        ${wasmCallTxt.join("\n        ")}
      )
    )
  )`;
  //print(txt);
  const buf = WebAssembly.wabt.convertWast2Wasm(txt);
  try {
    const module = new WebAssembly.Module(buf);
    const {exports: {foo}} = new WebAssembly.Instance(module);
    if (foo(...callArgs) !== 1) {
      print(`FAILED. Failed to validate with ${n} arguments`);
    }
    tested[n] = true;
    return true;
  } catch (e) {
  }
  tested[n] = false;
}

const [forceTest] = WScript.Arguments;
if (forceTest !== undefined) {
  const res = test(forceTest);
  print(res ? "Module is valid" : "Module is invalid");
} else {
    let nParams = 9000;
    let inc = 1000;
    let direction = true;

    while (inc !== 0) {
      if (test(nParams)) {
        if (direction) {
          nParams += inc;
        } else {
          direction = true;
          inc >>= 1;
          nParams += inc;
        }
      } else {
        if (!direction) {
          nParams -= inc;
        } else {
          direction = false;
          inc >>= 1;
          // make sure the last test is a passing one
          inc = inc || 1;
          nParams -= inc;
        }
      }

      if (nParams > 100000 || nParams < 0) {
        print(`FAILED. Params reached ${nParams} long. Expected an error by now`);
        break;
      }
    }

    print(`Support at most ${nParams} params`);
}<|endoftext|>


<commit_before>Plugin.extend({
    _type: 'interactivevideo',
    _isContainer: false,
    _render: true,
    initPlugin: function(data) {
    	if (typeof(data.video) != 'string') {
    		console.log('Video not defined');
    		console.log(data.video);
    		return false;
    	}

    	if (typeof(data.questions) != 'object') {
    		console.log('Questions not defined');
    		console.log(data.questions);
    		return false;
    	}

		var parentDiv = document.getElementById(Renderer.divIds.gameArea);
        var div = document.getElementById("testDiv");
        div = document.createElement('div');
        div.style.width = "100%";
        var videohtml = [];
        videohtml.push('
');
        videohtml.push('<video style="position:relative; z-index:-1;" width="570" height="325" autoplay>');
        videohtml.push('<source src="'+data.video+'" type="video/mp4"/>');
        videohtml.push('</video>');
        videohtml.push('

');
        videohtml.push('
');
        div.innerHTML = videohtml.join('');

        parentDiv.insertBefore(div, parentDiv.childNodes[0]);
        this._self = new createjs.DOMElement(div);

        var timer = data.questions;

		for (var key in timer) {
			if (timer[key] == 'data') {
				timer.splice(key, 1);
			}
			if (timer[key] == 'identifier') {
				timer.splice(key, 1);
			}
		}

		var $oVideo = jQuery('video');
		var flag = false;
		var a = '';
        $oVideo.bind('timeupdate', function() {
			var video = $(this).get(0);
			var iNow = video.currentTime;
			jQuery.each(timer, function(key, value) {
				if (typeof(value.data.question) != 'string') {
					console.log("Invalid question identifier : " + identifier);
					return false;
				}

				if(a != Math.round(iNow))
				{
					flag =false;
				}

				if (Math.round(iNow) == value.sec && !flag) {
					jQuery("#interactivevideo-question-container").show();

			    	var html = [];
			    	html.push('

');
			    	html.push('
' + value.data.question + '
');
			    	html.push('
');
			    	jQuery.each(value.data.options, function(key, val) {
			    		html.push('
<input type="radio" id="option'+val.value.resindex+'" name="interactivevideo-question" value="'+val.value.resvalue+'">'+val.value.text+'

');
			    	});
			    	html.push('
');
			    	html.push('
<button id="videocover">Submit</button>
');
			    	html.push('

');

					jQuery('#interactivevideo-question-container').html(html.join(''));

					video.pause();
					var elem = document.getElementById('videocover');
					elem.addEventListener('click', function(event) {
						var video = $("video").get(0);
						video.play();
						jQuery("#interactivevideo-question-container").hide();

						flag = true;
						a = Math.round(iNow);
						return false;
					});
				}
			});
		});
    },

    _buildQuestion: function(question) {
    	console.log(question);
    	var html = [];
    	html.push('
');
    	html.push('
' + question.data.questions + '
');
    	html.push('
');
    	jQuery.each(question.data.options, function(key, val) {
    		html.push('
<input type="radio" name="question" value="'+val.value.resvalue+'" />' + val.value.resvalue + '
');
    	});
    	html.push('
');

    	html.push('
<button class="button">Submit</button>
');

    	return html.join('');
    },

    drawBorder: function() {

    }

});
<commit_msg>fix:show wrong/right answers<commit_after>Plugin.extend({
    _type: 'interactivevideo',
    _isContainer: false,
    _render: true,
    initPlugin: function(data) {
    	if (typeof(data.video) != 'string') {
    		console.log('Video not defined');
    		console.log(data.video);
    		return false;
    	}

    	if (typeof(data.questions) != 'object') {
    		console.log('Questions not defined');
    		console.log(data.questions);
    		return false;
    	}

		var parentDiv = document.getElementById(Renderer.divIds.gameArea);
        var div = document.getElementById("testDiv");
        div = document.createElement('div');
        div.style.width = "100%";
        var videohtml = [];
        videohtml.push('
');
        videohtml.push('<video style="position:relative; z-index:-1;" width="570" height="325" autoplay>');
        videohtml.push('<source src="'+data.video+'" type="video/mp4"/>');
        videohtml.push('</video>');
        videohtml.push('

');
        videohtml.push('
');
        div.innerHTML = videohtml.join('');

        parentDiv.insertBefore(div, parentDiv.childNodes[0]);
        this._self = new createjs.DOMElement(div);

        var timer = data.questions;

		for (var key in timer) {
			if (timer[key] == 'data') {
				timer.splice(key, 1);
			}
			if (timer[key] == 'identifier') {
				timer.splice(key, 1);
			}
		}

		var $oVideo = jQuery('video');
		var flag = false;
		var a = '';
        $oVideo.bind('timeupdate', function() {
			var video = $(this).get(0);
			var iNow = video.currentTime;
			jQuery.each(timer, function(key, value) {
				if (typeof(value.data.question) != 'string') {
					console.log("Invalid question identifier : " + identifier);
					return false;
				}

				if(a != Math.round(iNow))
				{
					flag =false;
				}

				if (Math.round(iNow) == value.sec && !flag) {
					jQuery('#interactivevideo-question-container').show();
					jQuery('#interactivevideo-wronganswer').hide();

			    	var html = [];
			    	html.push('

');
			    	html.push('
' + value.data.question + '
');
			    	html.push('
');
			    	jQuery.each(value.data.options, function(key, val) {
			    		console.log(val);
			    		html.push('
<input type="radio" id="option'+val.value.resindex+'" name="interactivevideo-question" value="'+ ((typeof(val.answer) != 'undefined') ? 1 : 0) +'">'+val.value.text+'

');
			    	});
			    	html.push('
');
			    	html.push('
<button id="interactivevideo-submit">Submit</button>
');
			    	html.push('
Wrong answer. Please try again
');
			    	html.push('

');

					jQuery('#interactivevideo-question-container').html(html.join(''));

					video.pause();
					//var elem = document.getElementById('videocover');
					jQuery('#interactivevideo-submit').on('click', function(event) {
						var video = $("video").get(0);
						var selected_answer = jQuery("input[name='interactivevideo-question']:checked").val();
						console.log(selected_answer);
						if (selected_answer == 1) {
							video.play();
							jQuery("#interactivevideo-question-container").hide();
						} else {
							jQuery('#interactivevideo-wronganswer').show();
						}

						flag = true;
						a = Math.round(iNow);
						return false;
					});
				}
			});
		});
    },

    _buildQuestion: function(question) {
    	console.log(question);
    	var html = [];
    	html.push('
');
    	html.push('
' + question.data.questions + '
');
    	html.push('
');
    	jQuery.each(question.data.options, function(key, val) {
    		html.push('
<input type="radio" name="question" value="'+val.value.resvalue+'" />' + val.value.resvalue + '
');
    	});
    	html.push('
');

    	html.push('
<button class="button">Submit</button>
');

    	return html.join('');
    },

    drawBorder: function() {

    }

});
<|endoftext|>


<commit_before>import after from 'lodash.after';
import assert from 'assert';
import {IntervalWorker} from '../lib/recurly/worker';

describe('IntervalWorker', () => {
  beforeEach(function () {
    const perform = this.perform = sinon.spy();
    this.valid = { perform };
    this.validShortPeriod = { perform, period: 5 };
  });

  afterEach(function () {
    if (this.worker) try { this.worker.destroy(); } catch (e) {}
  })

  it('requires a perform function', function () {
    assert.throws(() => new IntervalWorker(), Error, 'Invalid perform function');
    assert.throws(() => new IntervalWorker({ perform: 'invalid' }), Error, 'Invalid perform function');
  });

  it('has a default interval period of 10s', function () {
    this.worker = new IntervalWorker(this.valid);
    assert.strictEqual(this.worker.period, 10000);
  });

  it('accepts a custom interval period', function () {
    this.worker = new IntervalWorker(this.validShortPeriod);
    assert.strictEqual(this.worker.period, 5);
  });

  it('calls the perform function with a jobId', function (done) {
    const start = Date.now();
    this.worker = new IntervalWorker({ period: 1, perform: ({ jobId }) => {
      assert.strictEqual(jobId, 0);
      this.worker.destroy();
      done();
    }});
    this.worker.start();
  });

  it('calls the perform function at the period interval', function (done) {
    const then = Date.now();
    this.worker = new IntervalWorker({ period: 500, perform: () => {
      const lapse = Date.now() - then;
      assert(lapse >= 400);
      assert(lapse <= 600);
      this.worker.destroy();
      done();
    }});
    this.worker.start();
  });

  describe('#start', () => {
    it('enables the job', function (done) {
      this.worker = new IntervalWorker(this.validShortPeriod);
      assert.strictEqual(this.worker.active, false);
      assert.strictEqual(this.perform.called, false);
      this.worker.start();
      assert.strictEqual(this.worker.active, true);
      setTimeout(() => {
        assert.strictEqual(this.perform.calledOnce, true);
        done();
      }, 5);
    });
  });

  describe('#pause', () => {
    it('pauses the job', function (done) {
      const part = after(2, () => done());
      this.worker = new IntervalWorker(this.validShortPeriod);
      this.worker.start();
      assert.strictEqual(this.worker.active, true);

      setTimeout(() => {
        assert.strictEqual(this.perform.calledOnce, true);
        this.worker.pause();
        assert.strictEqual(this.worker.active, false);
        part();
      }, 5);

      setTimeout(() => {
        assert.strictEqual(this.perform.calledOnce, true);
        assert.strictEqual(this.worker.active, false);
        part();
      }, 15);
    });
  });

  describe('#destroy', () => {
    it('stops the worker', function () {
      const part = after(2, () => done());
      this.worker = new IntervalWorker(this.validShortPeriod);
      this.worker.start();

      setTimeout(() => {
        assert.strictEqual(this.perform.calledOnce, true);
        this.worker.destroy();
        assert.strictEqual(this.worker.active, false);
        assert.strictEqual(this.worker._intervalId, undefined);
        part();
      }, 5);

      setTimeout(() => {
        assert.strictEqual(this.perform.calledOnce, true);
        part();
      }, 15);
    });

    it('prevents further calls', function () {
      this.worker = new IntervalWorker(this.validShortPeriod);
      this.worker.start();
      this.worker.destroy();
      assert.throws(() => this.worker.start(), Error, 'destroyed');
      assert.throws(() => this.worker.pause(), Error, 'destroyed');
      assert.throws(() => this.worker.destroy(), Error, 'destroyed');
    });
  });
});
<commit_msg>Fixes worker specs<commit_after>import after from 'lodash.after';
import assert from 'assert';
import {IntervalWorker} from '../lib/recurly/worker';

describe('IntervalWorker', () => {
  beforeEach(function () {
    const perform = this.perform = sinon.spy();
    this.valid = { perform };
    this.validShortPeriod = { perform, period: 5 };
  });

  afterEach(function () {
    // Destroy any workers that have not already been destroyed
    if (this.worker && this.worker._intervalId) this.worker.destroy();
  })

  it('requires a perform function', function () {
    assert.throws(() => new IntervalWorker(), Error, 'Invalid perform function');
    assert.throws(() => new IntervalWorker({ perform: 'invalid' }), Error, 'Invalid perform function');
  });

  it('has a default interval period of 10s', function () {
    this.worker = new IntervalWorker(this.valid);
    assert.strictEqual(this.worker.period, 10000);
  });

  it('accepts a custom interval period', function () {
    this.worker = new IntervalWorker(this.validShortPeriod);
    assert.strictEqual(this.worker.period, 5);
  });

  it('calls the perform function with a jobId', function (done) {
    const start = Date.now();
    this.worker = new IntervalWorker({ period: 1, perform: ({ jobId }) => {
      assert.strictEqual(jobId, 0);
      this.worker.destroy();
      done();
    }});
    this.worker.start();
  });

  it('calls the perform function at the period interval', function (done) {
    const then = Date.now();
    this.worker = new IntervalWorker({ period: 500, perform: () => {
      const lapse = Date.now() - then;
      assert(lapse >= 400);
      assert(lapse <= 600);
      this.worker.destroy();
      done();
    }});
    this.worker.start();
  });

  describe('#start', () => {
    it('enables the job', function (done) {
      this.worker = new IntervalWorker(this.validShortPeriod);
      assert.strictEqual(this.worker.active, false);
      assert.strictEqual(this.perform.called, false);
      this.worker.start();
      assert.strictEqual(this.worker.active, true);
      setTimeout(() => {
        assert.strictEqual(this.perform.calledOnce, true);
        done();
      }, 5);
    });
  });

  describe('#pause', () => {
    it('pauses the job', function (done) {
      const part = after(2, () => done());
      this.worker = new IntervalWorker(this.validShortPeriod);
      this.worker.start();
      assert.strictEqual(this.worker.active, true);

      setTimeout(() => {
        assert.strictEqual(this.perform.calledOnce, true);
        this.worker.pause();
        assert.strictEqual(this.worker.active, false);
        part();
      }, 5);

      setTimeout(() => {
        assert.strictEqual(this.perform.calledOnce, true);
        assert.strictEqual(this.worker.active, false);
        part();
      }, 15);
    });
  });

  describe('#destroy', () => {
    it('stops the worker', function (done) {
      const part = after(2, () => done());
      this.worker = new IntervalWorker(this.validShortPeriod);
      this.worker.start();

      setTimeout(() => {
        assert.strictEqual(this.perform.calledOnce, true);
        this.worker.destroy();
        assert.strictEqual(this.worker.active, false);
        assert.strictEqual(this.worker._intervalId, undefined);
        part();
      }, 8);

      setTimeout(() => {
        assert.strictEqual(this.perform.calledOnce, true);
        part();
      }, 15);
    });

    it('prevents further calls', function () {
      this.worker = new IntervalWorker(this.validShortPeriod);
      this.worker.start();
      this.worker.destroy();
      assert.throws(() => this.worker.start(), Error);
      assert.throws(() => this.worker.pause(), Error);
      assert.throws(() => this.worker.destroy(), Error);
    });
  });
});
<|endoftext|>


<commit_before>require.config({
  baseUrl: 'js/lib',
  paths: {
    'test': '../../..',
    'mocha': 'mocha/mocha',
    'chai': 'chai/chai'
  },
  packages: [
    { name: 'md5', location: '../../../..', main: 'main' },
    { name: 'mocha-cloud', location: '../support', main: 'mocha-cloud' }
  ],
  shim: {
    'mocha': {
      exports: 'mocha'
    }
  }
});

require(['../suite']);
<commit_msg>Remove extraneous configuration in test setup.<commit_after>require.config({
  baseUrl: 'js/lib',
  paths: {
    'test': '../../..',
    'mocha': 'mocha/mocha',
    'chai': 'chai/chai'
  },
  packages: [
    { name: 'md5', location: '../../../..' },
    { name: 'mocha-cloud', location: '../support', main: 'mocha-cloud' }
  ],
  shim: {
    'mocha': {
      exports: 'mocha'
    }
  }
});

require(['../suite']);
<|endoftext|>