<commit_before>// Initialize app
function showDivsConnect(){
    console.log(localStorage.logged_in);
    if(localStorage.logged_in=="true"){
        $(".login").show();
        $(".logout").hide();
        $(".names_user").html(localStorage.name+" "+localStorage.lastname);
    }else{
        $(".login").hide();
        $(".logout").show();
    }
}

function checkConnectionFB() {
    facebookConnectPlugin.getLoginStatus(function(response) {
        if (response.status == 'connected'&&response.authResponse.userID==localStorage.network) {
            localStorage.setItem("logged_in",true);
        } else {
            localStorage.setItem("logged_in",false);
        }
        showDivsConnect();
    });
}
function getUserData(id) {
    var data={id:id,table:"user"};
    $.ajax({
        url: "http://wisi.com.co/api/databyid",
        type: "get",
        data: data,
        success: function(d){
           $('input[name="name"]').val(d[0].name);
           $('input[name="last_name"]').val(d[0].lastname);
           $('input[name="email"]').val(d[0].email);
           $('input[name="birthday"]').val(d[0].birthday);
           $('input[name="phone"]').val(d[0].phone);
           $('input[name="celphone"]').val(d[0].celphone);
           $('select[name="genre"] option[value="'+d[0].genre+'"]').prop("selected", true);
           $('select[name="marital"] option[value="'+d[0].marital+'"]').attr("selected", "selected");
        }
    });
}
function getRechargedData(id) {
    var data={id:id};
    $.ajax({
        url: "http://wisi.com.co/api/rechargeds",
        type: "get",
        data: data,
        success: function(d){
           alert(JSON.stringify(d));
        }
    });
}

function randSlider() {
    var num= Math.floor((Math.random() * 5) + 1);
    $(".full-page-video").css('background-image','url("http://wisi.com.co/assets/img/sliders/slider'+num+'.jpg")');
}
function findElement(selector) {
    var box = null;
    return $(".page-on-center").length > 0 ? (box = $(".view-main").find(".page-on-center " + selector),
        0 === box.length && (box = $(".view-main").find(".page-on-center" + selector))) : box = $(".view-main").find(".page").find(selector),
    box;
}

function naxvarBg() {
    var navbar = $(".navbar-anim-on-scroll"), box = null, cls = "active";
    return 0 === navbar.length ? !1 : (box = navbar.next().find($(".page-on-center").length > 0 ? ".page-on-center .page-content" : ".page .page-content"),
        box.scrollTop() > 10 ? navbar.addClass(cls) : navbar.removeClass(cls), void box.scroll(function() {
            $(this).scrollTop() > 40 ? navbar.addClass(cls) : navbar.removeClass(cls);
        }));
}

function hidePreloader() {
    jQuery(".page-preloader").animate({
        opacity: 0
    }, function() {
        jQuery(this).hide();
    });
}

var myApp = new Framework7({
    swipeBackPage: !1,
    pushState: !0,
    swipePanel: "left",
    modalTitle: "Title"
}), $$ = Dom7;

var fbLoginSuccess = function (response) {
 if (response.authResponse) {
     facebookConnectPlugin.api('/me?fields=id,email,first_name,last_name,gender,picture', null,
         function(response) {
            var gender=38;
            if(response.gender=="male")gender=39;
            localStorage.setItem("network",response.id);
            localStorage.setItem("name",  response.first_name);
            localStorage.setItem("lastname",  response.last_name);
            localStorage.setItem("email",  response.email);
            localStorage.setItem("gender",  gender);
            localStorage.setItem("picture",  response.picture.data.url);
            localStorage.setItem("logged_in", true);
            showDivsConnect();
            var data=$.param({data:{id:response.id,first_name:response.first_name,last_name:response.last_name,email:response.email,gender:gender,picture:response.picture}});
            $.ajax({
                url: "http://wisi.com.co/api/social/sigin",
                type: "post",
                data: data,
                success: function(d){
                    var level="1";
                    if(localStorage.cont_started=="true")level="2";
                    showDivsConnect();
                    localStorage.setItem("cont_started",true);
                    localStorage.setItem("userid",d.userdata.id);
                    window.open("http://wisi.com.co/public/#/ad/"+level+"/"+d.userdata.id, "_system");
                }
            });
        });
 }

}

$$("body").on("click", ".button-facebook", function() {
    var terms=$('#chkTerm').is(':checked');
    if(terms){
        facebookConnectPlugin.login(["public_profile"],
            fbLoginSuccess,
            function (error) { myApp.alert("Problemas conectando con Facebook!", ""); }
            );
    }else{
        myApp.alert("Debe aceptar los términos y condiciones!", "");
    }
});

$$("body").on("click", ".pautar", function() {
    window.open("http://wisi.com.co/public/#/", "_system");
});
$$("body").on("click", ".free-navegate", function() {
    window.open("http://wisi.com.co/public/#/2/"+localStorage.userid, "_system");
});

$$("body").on("click", ".close_sesion", function() {
    localStorage.clear();
    window.location.href = "index.html";
});

var mainView = myApp.addView(".view-main", {
    dynamicNavbar: !0
});
$$(document).on("pageInit", function(e) {
    checkConnectionFB();
    var page = e.detail.page;
    var userid=localStorage.userid;
    if(page.name=="mydata")getUserData(userid);
    if(page.name=="rechargeds")getRechargedData(userid);

    myApp.calendar({
        input: "#ks-calendar-default"
    }), myApp.calendar({
        input: "#calendar-multiple",
        dateFormat: "M dd yyyy",
        multiple: !0
    }), myApp.calendar({
        input: "#calendar-range",
        dateFormat: "M dd yyyy",
        rangePicker: !0
    });
    var today = new Date(), weekLater = new Date().setDate(today.getDate() + 7);
    myApp.calendar({
        input: "#calendar-disabled",
        dateFormat: "M dd yyyy",
        disabled: {
            from: today,
            to: weekLater
        }
    }), myApp.calendar({
        container: "#calendar-inline-container",
        value: [ new Date() ]
    }), $$(".notification-default").on("click", function() {
        myApp.addNotification({
            title: "Framework7",
            message: "This is a simple notification message with title and message"
        });
    }), $$(".notification-full").on("click", function() {
        myApp.addNotification({
            title: "Framework7",
            subtitle: "Notification subtitle",
            message: "This is a simple notification message with custom icon and subtitle",
            media: ''
        });
    }), $$(".notification-custom").on("click", function() {
        myApp.addNotification({
            title: "My Awesome App",
            subtitle: "New message from John Doe",
            message: "Hello, how are you? Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut posuere erat. Pellentesque id elementum urna, a aliquam ante. Donec vitae volutpat orci. Aliquam sed molestie risus, quis tincidunt dui.",
            media: ''
        });
    }), $$(".notification-callback").on("click", function() {
        myApp.addNotification({
            title: "My Awesome App",
            subtitle: "New message from John Doe",
            message: "Hello, how are you? Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut posuere erat. Pellentesque id elementum urna, a aliquam ante. Donec vitae volutpat orci. Aliquam sed molestie risus, quis tincidunt dui.",
            media: '',
            onClose: function() {
                myApp.alert("Notification closed");
            }
        });
    }), $(".navbar").removeClass("navbar-clear"), ("index" === page.name || "dashboard-1" === page.name || "post" === page.name || "menu" === page.name || "login" === page.name || "registration" === page.name || "article" === page.name || "splash" === page.name) && $(".navbar").addClass("navbar-clear"),
    $(".twitter-content").length > 0 && $(".twitter-content").twittie({
        count: 10
    }), $(".tweet").length > 0 && $(".tweet").twittie({
        count: 1
    }), $(".flickr-content").length > 0 && $(".flickr-content").jflickrfeed({
        limit: 15,
        qstrings: {
            id: "44244432@N03"
        },
        itemTemplate: '

'
    }, function(data) {
        $(".flickr-content li a").swipebox();
    }), $(".owl-carousel").length > 0 && $(".owl-carousel").owlCarousel(), $(".featured-articles-slider").length > 0 && $(".featured-articles-slider").owlCarousel({
        singleItem: !0,
        navigation: !1,
        navigationText: [],
        pagination: !1,
        uniqueHistory: !0,
        loop: !0,
        autoPlay: 3e3,
        stopOnHover: !0
    }), $(".js-validate").length > 0 && $("body").on("click", "#register-button", function() {
        var form = $(this).parents("form"), valid = form.valid();
        if ("registration" === page.name && valid) {
            var data=$.param({data:form.serializeObject()});
            myApp.showPreloader(), $.post("http://wisi.com.co/api/register", data).done(function(data) {
                myApp.hidePreloader();
                var response = JSON.parse(data);
            if(!response.message){
                  window.location.href = 'login.html';
            }else{
                window.open("http://wisi.com.co/public/#/ad/1/"+response.userdata.id, "_system");
            }

            localStorage.setItem("cont_started",true);
        });
        }
    });
    // Conversation flag
    var conversationStarted = !1, myMessages = myApp.messages(".messages", {
        autoLayout: !0
    }), myMessagebar = myApp.messagebar(".messagebar");
    // Handle message
    $$(".messagebar .link").on("click", function() {
        var name_user="Invitado";
        if(localStorage.name!="")name_user=localStorage.name+" "+localStorage.lastname;
        $(".message-name").html(name_user);
        // Message text
        var messageText = myMessagebar.value().trim();
        // Exit if empy message
        if (0 !== messageText.length) {
            // Empty messagebar
            myMessagebar.clear();
            // Random message type
            var avatar, name, messageType = [ "sent", "received" ][Math.round(Math.random())];
            "received" === messageType && (avatar = "http://lorempixel.com/output/people-q-c-100-100-9.jpg",
            name = name_user), // Add message
            myMessages.addMessage({
                // Message text
                text: messageText,
                // Random message type
                type: messageType,
                // Avatar and name:
                avatar: avatar,
                name: name,
                // Day
                day: conversationStarted ? !1 : "Today",
                time: conversationStarted ? !1 : new Date().getHours() + ":" + new Date().getMinutes()
            }), // Update conversation flag
            conversationStarted = !0;
        }
    });
}), $(document).ready(function() {
    //randSlider();
    checkConnectionFB();
    showDivsConnect();

    if ((null === localStorage.getItem("newOptions") || localStorage.getItem("newOptions") === !0) && (myApp.popup(".popup-splash"),
        localStorage.setItem("newOptions", !0)), $(".chart-content").length > 0) {
        var obj = document.querySelector(".chart-content"), ctx = obj.getContext("2d");
    showLineChart(ctx);
}
naxvarBg(), $(".js-toggle-menu").on("click", function() {
    $(this).next().slideToggle(200), $(this).find("span").toggleClass("icon-chevron-down").toggleClass("icon-chevron-up");
}), $("body").on("click", ".js-gallery-col", function() {
    var cols = $(this).data("cols");
    $(".gallery-list").attr({
        "data-cols": cols
    }), $(".js-gallery-col").removeClass("active"), $(this).addClass("active");
});
}), $.fn.serializeObject = function() {
    var o = {}, a = this.serializeArray();
    return $.each(a, function() {
        void 0 !== o[this.name] ? (o[this.name].push || (o[this.name] = [ o[this.name] ]),
            o[this.name].push(this.value || "")) : o[this.name] = this.value || "";
    }), o;
};<commit_msg>cosole<commit_after>// Initialize app
function showDivsConnect(){
    console.log(localStorage.logged_in);
    if(localStorage.logged_in=="true"){
        $(".login").show();
        $(".logout").hide();
        $(".names_user").html(localStorage.name+" "+localStorage.lastname);
    }else{
        $(".login").hide();
        $(".logout").show();
    }
}

function checkConnectionFB() {
    facebookConnectPlugin.getLoginStatus(function(response) {
        if (response.status == 'connected'&&response.authResponse.userID==localStorage.network) {
            localStorage.setItem("logged_in",true);
        } else {
            localStorage.setItem("logged_in",false);
        }
        showDivsConnect();
    });
}
function getUserData(id) {
    var data={id:id,table:"user"};
    $.ajax({
        url: "http://wisi.com.co/api/databyid",
        type: "get",
        data: data,
        success: function(d){
           $('input[name="name"]').val(d[0].name);
           $('input[name="last_name"]').val(d[0].lastname);
           $('input[name="email"]').val(d[0].email);
           $('input[name="birthday"]').val(d[0].birthday);
           $('input[name="phone"]').val(d[0].phone);
           $('input[name="celphone"]').val(d[0].celphone);
           $('select[name="genre"] option[value="'+d[0].genre+'"]').prop("selected", true);
           $('select[name="marital"] option[value="'+d[0].marital+'"]').attr("selected", "selected");
        }
    });
}
function getRechargedData(id) {
    var data={id:id};
    $.ajax({
        url: "http://wisi.com.co/api/rechargeds",
        type: "get",
        data: data,
        success: function(d){
           for each(var dat in d){
                console.log(d);
           }
        }
    });
}

function randSlider() {
    var num= Math.floor((Math.random() * 5) + 1);
    $(".full-page-video").css('background-image','url("http://wisi.com.co/assets/img/sliders/slider'+num+'.jpg")');
}
function findElement(selector) {
    var box = null;
    return $(".page-on-center").length > 0 ? (box = $(".view-main").find(".page-on-center " + selector),
        0 === box.length && (box = $(".view-main").find(".page-on-center" + selector))) : box = $(".view-main").find(".page").find(selector),
    box;
}

function naxvarBg() {
    var navbar = $(".navbar-anim-on-scroll"), box = null, cls = "active";
    return 0 === navbar.length ? !1 : (box = navbar.next().find($(".page-on-center").length > 0 ? ".page-on-center .page-content" : ".page .page-content"),
        box.scrollTop() > 10 ? navbar.addClass(cls) : navbar.removeClass(cls), void box.scroll(function() {
            $(this).scrollTop() > 40 ? navbar.addClass(cls) : navbar.removeClass(cls);
        }));
}

function hidePreloader() {
    jQuery(".page-preloader").animate({
        opacity: 0
    }, function() {
        jQuery(this).hide();
    });
}

var myApp = new Framework7({
    swipeBackPage: !1,
    pushState: !0,
    swipePanel: "left",
    modalTitle: "Title"
}), $$ = Dom7;

var fbLoginSuccess = function (response) {
 if (response.authResponse) {
     facebookConnectPlugin.api('/me?fields=id,email,first_name,last_name,gender,picture', null,
         function(response) {
            var gender=38;
            if(response.gender=="male")gender=39;
            localStorage.setItem("network",response.id);
            localStorage.setItem("name",  response.first_name);
            localStorage.setItem("lastname",  response.last_name);
            localStorage.setItem("email",  response.email);
            localStorage.setItem("gender",  gender);
            localStorage.setItem("picture",  response.picture.data.url);
            localStorage.setItem("logged_in", true);
            showDivsConnect();
            var data=$.param({data:{id:response.id,first_name:response.first_name,last_name:response.last_name,email:response.email,gender:gender,picture:response.picture}});
            $.ajax({
                url: "http://wisi.com.co/api/social/sigin",
                type: "post",
                data: data,
                success: function(d){
                    var level="1";
                    if(localStorage.cont_started=="true")level="2";
                    showDivsConnect();
                    localStorage.setItem("cont_started",true);
                    localStorage.setItem("userid",d.userdata.id);
                    window.open("http://wisi.com.co/public/#/ad/"+level+"/"+d.userdata.id, "_system");
                }
            });
        });
 }

}

$$("body").on("click", ".button-facebook", function() {
    var terms=$('#chkTerm').is(':checked');
    if(terms){
        facebookConnectPlugin.login(["public_profile"],
            fbLoginSuccess,
            function (error) { myApp.alert("Problemas conectando con Facebook!", ""); }
            );
    }else{
        myApp.alert("Debe aceptar los términos y condiciones!", "");
    }
});

$$("body").on("click", ".pautar", function() {
    window.open("http://wisi.com.co/public/#/", "_system");
});
$$("body").on("click", ".free-navegate", function() {
    window.open("http://wisi.com.co/public/#/2/"+localStorage.userid, "_system");
});

$$("body").on("click", ".close_sesion", function() {
    localStorage.clear();
    window.location.href = "index.html";
});

var mainView = myApp.addView(".view-main", {
    dynamicNavbar: !0
});
$$(document).on("pageInit", function(e) {
    checkConnectionFB();
    var page = e.detail.page;
    var userid=localStorage.userid;
    if(page.name=="mydata")getUserData(userid);
    if(page.name=="rechargeds")getRechargedData(userid);

    myApp.calendar({
        input: "#ks-calendar-default"
    }), myApp.calendar({
        input: "#calendar-multiple",
        dateFormat: "M dd yyyy",
        multiple: !0
    }), myApp.calendar({
        input: "#calendar-range",
        dateFormat: "M dd yyyy",
        rangePicker: !0
    });
    var today = new Date(), weekLater = new Date().setDate(today.getDate() + 7);
    myApp.calendar({
        input: "#calendar-disabled",
        dateFormat: "M dd yyyy",
        disabled: {
            from: today,
            to: weekLater
        }
    }), myApp.calendar({
        container: "#calendar-inline-container",
        value: [ new Date() ]
    }), $$(".notification-default").on("click", function() {
        myApp.addNotification({
            title: "Framework7",
            message: "This is a simple notification message with title and message"
        });
    }), $$(".notification-full").on("click", function() {
        myApp.addNotification({
            title: "Framework7",
            subtitle: "Notification subtitle",
            message: "This is a simple notification message with custom icon and subtitle",
            media: ''
        });
    }), $$(".notification-custom").on("click", function() {
        myApp.addNotification({
            title: "My Awesome App",
            subtitle: "New message from John Doe",
            message: "Hello, how are you? Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut posuere erat. Pellentesque id elementum urna, a aliquam ante. Donec vitae volutpat orci. Aliquam sed molestie risus, quis tincidunt dui.",
            media: ''
        });
    }), $$(".notification-callback").on("click", function() {
        myApp.addNotification({
            title: "My Awesome App",
            subtitle: "New message from John Doe",
            message: "Hello, how are you? Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut posuere erat. Pellentesque id elementum urna, a aliquam ante. Donec vitae volutpat orci. Aliquam sed molestie risus, quis tincidunt dui.",
            media: '',
            onClose: function() {
                myApp.alert("Notification closed");
            }
        });
    }), $(".navbar").removeClass("navbar-clear"), ("index" === page.name || "dashboard-1" === page.name || "post" === page.name || "menu" === page.name || "login" === page.name || "registration" === page.name || "article" === page.name || "splash" === page.name) && $(".navbar").addClass("navbar-clear"),
    $(".twitter-content").length > 0 && $(".twitter-content").twittie({
        count: 10
    }), $(".tweet").length > 0 && $(".tweet").twittie({
        count: 1
    }), $(".flickr-content").length > 0 && $(".flickr-content").jflickrfeed({
        limit: 15,
        qstrings: {
            id: "44244432@N03"
        },
        itemTemplate: '

'
    }, function(data) {
        $(".flickr-content li a").swipebox();
    }), $(".owl-carousel").length > 0 && $(".owl-carousel").owlCarousel(), $(".featured-articles-slider").length > 0 && $(".featured-articles-slider").owlCarousel({
        singleItem: !0,
        navigation: !1,
        navigationText: [],
        pagination: !1,
        uniqueHistory: !0,
        loop: !0,
        autoPlay: 3e3,
        stopOnHover: !0
    }), $(".js-validate").length > 0 && $("body").on("click", "#register-button", function() {
        var form = $(this).parents("form"), valid = form.valid();
        if ("registration" === page.name && valid) {
            var data=$.param({data:form.serializeObject()});
            myApp.showPreloader(), $.post("http://wisi.com.co/api/register", data).done(function(data) {
                myApp.hidePreloader();
                var response = JSON.parse(data);
            if(!response.message){
                  window.location.href = 'login.html';
            }else{
                window.open("http://wisi.com.co/public/#/ad/1/"+response.userdata.id, "_system");
            }

            localStorage.setItem("cont_started",true);
        });
        }
    });
    // Conversation flag
    var conversationStarted = !1, myMessages = myApp.messages(".messages", {
        autoLayout: !0
    }), myMessagebar = myApp.messagebar(".messagebar");
    // Handle message
    $$(".messagebar .link").on("click", function() {
        var name_user="Invitado";
        if(localStorage.name!="")name_user=localStorage.name+" "+localStorage.lastname;
        $(".message-name").html(name_user);
        // Message text
        var messageText = myMessagebar.value().trim();
        // Exit if empy message
        if (0 !== messageText.length) {
            // Empty messagebar
            myMessagebar.clear();
            // Random message type
            var avatar, name, messageType = [ "sent", "received" ][Math.round(Math.random())];
            "received" === messageType && (avatar = "http://lorempixel.com/output/people-q-c-100-100-9.jpg",
            name = name_user), // Add message
            myMessages.addMessage({
                // Message text
                text: messageText,
                // Random message type
                type: messageType,
                // Avatar and name:
                avatar: avatar,
                name: name,
                // Day
                day: conversationStarted ? !1 : "Today",
                time: conversationStarted ? !1 : new Date().getHours() + ":" + new Date().getMinutes()
            }), // Update conversation flag
            conversationStarted = !0;
        }
    });
}), $(document).ready(function() {
    //randSlider();
    checkConnectionFB();
    showDivsConnect();

    if ((null === localStorage.getItem("newOptions") || localStorage.getItem("newOptions") === !0) && (myApp.popup(".popup-splash"),
        localStorage.setItem("newOptions", !0)), $(".chart-content").length > 0) {
        var obj = document.querySelector(".chart-content"), ctx = obj.getContext("2d");
    showLineChart(ctx);
}
naxvarBg(), $(".js-toggle-menu").on("click", function() {
    $(this).next().slideToggle(200), $(this).find("span").toggleClass("icon-chevron-down").toggleClass("icon-chevron-up");
}), $("body").on("click", ".js-gallery-col", function() {
    var cols = $(this).data("cols");
    $(".gallery-list").attr({
        "data-cols": cols
    }), $(".js-gallery-col").removeClass("active"), $(this).addClass("active");
});
}), $.fn.serializeObject = function() {
    var o = {}, a = this.serializeArray();
    return $.each(a, function() {
        void 0 !== o[this.name] ? (o[this.name].push || (o[this.name] = [ o[this.name] ]),
            o[this.name].push(this.value || "")) : o[this.name] = this.value || "";
    }), o;
};<|endoftext|>


<commit_before>define(["Tone/core/Tone", "Tone/core/Transport", "Tone/core/Buffer", "Tone/core/OfflineContext"], function(Tone){

	/**
	 * Because of a bug in iOS causing the currentTime to increment
	 * before the rendering is started, sometimes it takes multiple
	 * attemps to render the audio correctly.
	 * @private
	 */
	function attemptRender(callback, duration, sampleRate, tries){
		tries = Tone.defaultArg(tries, 0);
		var context = new Tone.OfflineContext(2, duration, sampleRate);
		Tone.context = context;

		var isPast = Tone.isPast;
		Tone.isPast = Tone.noOp;

		//invoke the callback/scheduling
		var response = callback(Tone.Transport);

		if (context.currentTime > 0 && tries < 1000){
			return attemptRender(callback, duration, sampleRate, ++tries);
		} else {
			Tone.isPast = isPast;
			return {
				"response" : response,
				"context" : context
			};
		}
	}

	/**
	 *  Generate a buffer by rendering all of the Tone.js code within the callback using the OfflineAudioContext.
	 *  The OfflineAudioContext is capable of rendering much faster than real time in many cases.
	 *  The callback function also passes in an offline instance of Tone.Transport which can be used
	 *  to schedule events along the Transport.
	 *  @param  {Function}  callback  All Tone.js nodes which are created and scheduled within this callback are recorded into the output Buffer.
	 *  @param  {Time}  duration     the amount of time to record for.
	 *  @return  {Promise}  The promise which is invoked with the Tone.Buffer of the recorded output.
	 *  @example
	 * //render 2 seconds of the oscillator
	 * Tone.Offline(function(){
	 * 	//only nodes created in this callback will be recorded
	 * 	var oscillator = new Tone.Oscillator().toMaster().start(0)
	 * 	//schedule their events
	 * }, 2).then(function(buffer){
	 * 	//do something with the output buffer
	 * })
	 * @example
	 * //can also schedule events along the Transport
	 * //using the passed in Offline Transport
	 * Tone.Offline(function(Transport){
	 * 	var osc = new Tone.Oscillator().toMaster()
	 * 	Transport.schedule(function(time){
	 * 		osc.start(time).stop(time + 0.1)
	 * 	}, 1)
	 * 	Transport.start(0.2)
	 * }, 4).then(function(buffer){
	 * 	//do something with the output buffer
	 * })
	 */
	Tone.Offline = function(callback, duration){
		//set the OfflineAudioContext
		var sampleRate = Tone.context.sampleRate;
		var originalContext = Tone.context;

		var renderRet = attemptRender(callback, duration, sampleRate);
		var response = renderRet.response;
		var context = renderRet.context;

		var ret;
		if (response instanceof Promise){
			//wait for the promise to resolve
			ret = response.then(function(){
				//then render the audio
				return context.render();
			});
		} else {
			//process the audio
			ret = context.render();
		}

		//return the original AudioContext
		Tone.context = originalContext;

		//return the audio
		return ret.then(function(buffer){
			//wrap it in a Tone.Buffer
			return new Tone.Buffer(buffer);
		});
	};

	return Tone.Offline;
});
<commit_msg>requiring Master in Offline<commit_after>define(["Tone/core/Tone", "Tone/core/Transport", "Tone/core/Buffer", "Tone/core/OfflineContext", "Tone/core/Master"], function(Tone){

	/**
	 * Because of a bug in iOS causing the currentTime to increment
	 * before the rendering is started, sometimes it takes multiple
	 * attempts to render the audio correctly.
	 * @private
	 */
	function attemptRender(callback, duration, sampleRate, tries){
		tries = Tone.defaultArg(tries, 0);
		var context = new Tone.OfflineContext(2, duration, sampleRate);
		Tone.context = context;

		//invoke the callback/scheduling
		var response = callback(Tone.Transport);

		if (context.currentTime > 0 && tries < 1000){
			return attemptRender(callback, duration, sampleRate, ++tries);
		} else {
			return {
				"response" : response,
				"context" : context
			};
		}
	}

	/**
	 *  Generate a buffer by rendering all of the Tone.js code within the callback using the OfflineAudioContext.
	 *  The OfflineAudioContext is capable of rendering much faster than real time in many cases.
	 *  The callback function also passes in an offline instance of Tone.Transport which can be used
	 *  to schedule events along the Transport.
	 *  @param  {Function}  callback  All Tone.js nodes which are created and scheduled within this callback are recorded into the output Buffer.
	 *  @param  {Time}  duration     the amount of time to record for.
	 *  @return  {Promise}  The promise which is invoked with the Tone.Buffer of the recorded output.
	 *  @example
	 * //render 2 seconds of the oscillator
	 * Tone.Offline(function(){
	 * 	//only nodes created in this callback will be recorded
	 * 	var oscillator = new Tone.Oscillator().toMaster().start(0)
	 * 	//schedule their events
	 * }, 2).then(function(buffer){
	 * 	//do something with the output buffer
	 * })
	 * @example
	 * //can also schedule events along the Transport
	 * //using the passed in Offline Transport
	 * Tone.Offline(function(Transport){
	 * 	var osc = new Tone.Oscillator().toMaster()
	 * 	Transport.schedule(function(time){
	 * 		osc.start(time).stop(time + 0.1)
	 * 	}, 1)
	 * 	Transport.start(0.2)
	 * }, 4).then(function(buffer){
	 * 	//do something with the output buffer
	 * })
	 */
	Tone.Offline = function(callback, duration){
		//set the OfflineAudioContext
		var sampleRate = Tone.context.sampleRate;
		var originalContext = Tone.context;

		var renderRet = attemptRender(callback, duration, sampleRate);
		var response = renderRet.response;
		var context = renderRet.context;

		var ret;
		if (response instanceof Promise){
			//wait for the promise to resolve
			ret = response.then(function(){
				//then render the audio
				return context.render();
			});
		} else {
			//process the audio
			ret = context.render();
		}

		//return the original AudioContext
		Tone.context = originalContext;

		//return the audio
		return ret.then(function(buffer){
			//wrap it in a Tone.Buffer
			return new Tone.Buffer(buffer);
		});
	};

	return Tone.Offline;
});
<|endoftext|>


<commit_before> import React from 'react'
 import { Link } from 'react-router'
 import { prefixLink } from 'gatsby-helpers'
 import Helmet from "react-helmet"
 import { config } from 'config'

 export default class Index extends React.Component {
   render () {
     return (

         <Helmet
           title={config.siteTitle}
           meta={[
             {"name": "description", "content": "Sample"},
             {"name": "keywords", "content": "sample, something"},
           ]}
         />

            Hello World!

Welcome to your new clean Gatsby site

Welcome to your new clean Gatsby site

      )
    }
 }
<commit_msg>Update index.js<commit_after> import React from 'react'
 import { Link } from 'react-router'
 import { prefixLink } from 'gatsby-helpers'
 import Helmet from "react-helmet"
 import { config } from 'config'

 export default class Index extends React.Component {
   render () {
     return (

         <Helmet
           title={config.siteTitle}
           meta={[
             {"name": "description", "content": "Sample"},
             {"name": "keywords", "content": "sample, something"},
           ]}
         />

            Hello World!

Welcome to your new clean Gatsby site

Welcome to your new clean Gatsby site

      ## Новый текст

      )
    }
 }
<|endoftext|>


<commit_before>// Initialize app
function showDivsConnect(){
    console.log(localStorage.getItem("logged_in"));
    if(localStorage.getItem("logged_in")=="true"){
        $(".login").show();
        $(".logout").hide();
        $(".names_user").html(localStorage.name+" "+localStorage.lastname);
    }else{
        $(".login").hide();
        $(".logout").show();
    }
}

function checkConnectionFB() {
    facebookConnectPlugin.getLoginStatus(function(response) {
        if (response.status == 'connected'&&response.authResponse.userID==localStorage.id) {
            localStorage.setItem("logged_in",true);
            showDivsConnect();
        } else {
            localStorage.setItem("logged_in",false);
        }
    });
}

function randSlider() {
    var num= Math.floor((Math.random() * 5) + 1);
    $(".full-page-video").css('background-image','url("http://wisi.com.co/assets/img/sliders/slider'+num+'.jpg")');
}
function findElement(selector) {
    var box = null;
    return $(".page-on-center").length > 0 ? (box = $(".view-main").find(".page-on-center " + selector),
        0 === box.length && (box = $(".view-main").find(".page-on-center" + selector))) : box = $(".view-main").find(".page").find(selector),
    box;
}

function naxvarBg() {
    var navbar = $(".navbar-anim-on-scroll"), box = null, cls = "active";
    return 0 === navbar.length ? !1 : (box = navbar.next().find($(".page-on-center").length > 0 ? ".page-on-center .page-content" : ".page .page-content"),
        box.scrollTop() > 10 ? navbar.addClass(cls) : navbar.removeClass(cls), void box.scroll(function() {
            $(this).scrollTop() > 40 ? navbar.addClass(cls) : navbar.removeClass(cls);
        }));
}

function hidePreloader() {
    jQuery(".page-preloader").animate({
        opacity: 0
    }, function() {
        jQuery(this).hide();
    });
}

var myApp = new Framework7({
    swipeBackPage: !1,
    pushState: !0,
    swipePanel: "left",
    modalTitle: "Title"
}), $$ = Dom7;

var fbLoginSuccess = function (response) {
   if (response.authResponse) {
       facebookConnectPlugin.api('/me?fields=id,email,first_name,last_name,gender,picture', null,
           function(response) {
            var gender=38;
            if(response.gender=="male")gender=39;
            localStorage.setItem("id",response.id);
            localStorage.setItem("name",  response.first_name);
            localStorage.setItem("lastname",  response.last_name);
            localStorage.setItem("email",  response.email);
            localStorage.setItem("gender",  gender);
            localStorage.setItem("picture",  response.picture.data.url);
            localStorage.setItem("logged_in", true);
            showDivsConnect();
            var data=$.param({data:{id:response.id,first_name:response.first_name,last_name:response.last_name,email:response.email,gender:gender,picture:response.picture}});
            $.ajax({
                url: "http://wisi.com.co/api/social/sigin",
                type: "post",
                data: data,
                success: function(d){
                    var level="1";
                    if(localStorage.cont_started=="true")level="2";
                    window.open("http://wisi.com.co/public/#/ad/"+level+"/"+d.userdata.id, "_system");
                    localStorage.setItem("cont_started",true);
                }
            });
           });
   }

}

$$("body").on("click", ".button-facebook", function() {
    var terms=$('#chkTerm').is(':checked');
    if(terms){
        facebookConnectPlugin.login(["public_profile"],
            fbLoginSuccess,
            function (error) { myApp.alert("Problemas conectando con Facebook!", ""); }
        );
    }else{
        myApp.alert("Debe aceptar los términos y condiciones!", "");
    }
});

$$("body").on("click", ".close_sesion", function() {
    localStorage.clear();
    location.reload();
});

var mainView = myApp.addView(".view-main", {
    dynamicNavbar: !0
});
$$(document).on("pageInit", function(e) {
    checkConnectionFB();
    var page = e.detail.page;

    myApp.calendar({
        input: "#ks-calendar-default"
    }), myApp.calendar({
        input: "#calendar-multiple",
        dateFormat: "M dd yyyy",
        multiple: !0
    }), myApp.calendar({
        input: "#calendar-range",
        dateFormat: "M dd yyyy",
        rangePicker: !0
    });
    var today = new Date(), weekLater = new Date().setDate(today.getDate() + 7);
    myApp.calendar({
        input: "#calendar-disabled",
        dateFormat: "M dd yyyy",
        disabled: {
            from: today,
            to: weekLater
        }
    }), myApp.calendar({
        container: "#calendar-inline-container",
        value: [ new Date() ]
    }), $$(".notification-default").on("click", function() {
        myApp.addNotification({
            title: "Framework7",
            message: "This is a simple notification message with title and message"
        });
    }), $$(".notification-full").on("click", function() {
        myApp.addNotification({
            title: "Framework7",
            subtitle: "Notification subtitle",
            message: "This is a simple notification message with custom icon and subtitle",
            media: ''
        });
    }), $$(".notification-custom").on("click", function() {
        myApp.addNotification({
            title: "My Awesome App",
            subtitle: "New message from John Doe",
            message: "Hello, how are you? Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut posuere erat. Pellentesque id elementum urna, a aliquam ante. Donec vitae volutpat orci. Aliquam sed molestie risus, quis tincidunt dui.",
            media: ''
        });
    }), $$(".notification-callback").on("click", function() {
        myApp.addNotification({
            title: "My Awesome App",
            subtitle: "New message from John Doe",
            message: "Hello, how are you? Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut posuere erat. Pellentesque id elementum urna, a aliquam ante. Donec vitae volutpat orci. Aliquam sed molestie risus, quis tincidunt dui.",
            media: '',
            onClose: function() {
                myApp.alert("Notification closed");
            }
        });
    }), $(".navbar").removeClass("navbar-clear"), ("index" === page.name || "dashboard-1" === page.name || "post" === page.name || "menu" === page.name || "login" === page.name || "registration" === page.name || "article" === page.name || "splash" === page.name) && $(".navbar").addClass("navbar-clear"),
    $(".twitter-content").length > 0 && $(".twitter-content").twittie({
        count: 10
    }), $(".tweet").length > 0 && $(".tweet").twittie({
        count: 1
    }), $(".flickr-content").length > 0 && $(".flickr-content").jflickrfeed({
        limit: 15,
        qstrings: {
            id: "44244432@N03"
        },
        itemTemplate: '

'
    },  $(".owl-carousel").length > 0 && $(".owl-carousel").owlCarousel(), $(".featured-articles-slider").length > 0 && $(".featured-articles-slider").owlCarousel({
        singleItem: !0,
        navigation: !1,
        navigationText: [],
        pagination: !1,
        uniqueHistory: !0,
        loop: !0,
        autoPlay: 3e3,
        stopOnHover: !0
    }), $(".js-validate").length > 0 && $("body").on("click", ".js-form-submit", function() {
        var form = $(this).parents("form"), valid = form.valid();
        if ("contact" === page.name && valid) {
            var data = form.serializeObject();
            myApp.showPreloader(), $.post("/email.php", data).done(function(data) {
                myApp.hidePreloader();
                var response = JSON.parse(data);
                response.error ? myApp.alert(response.msg, "") : (myApp.alert(response.msg, ""),
                    form.find("input[type=text], input[type=email], textarea").val(""));
            });
        }
    });
    // Conversation flag
    var conversationStarted = !1, myMessages = myApp.messages(".messages", {
        autoLayout: !0
    }), myMessagebar = myApp.messagebar(".messagebar");
    // Handle message
    $$(".messagebar .link").on("click", function() {
        // Message text
        var messageText = myMessagebar.value().trim();
        // Exit if empy message
        if (0 !== messageText.length) {
            // Empty messagebar
            myMessagebar.clear();
            // Random message type
            var avatar, name, messageType = [ "sent", "received" ][Math.round(Math.random())];
            "received" === messageType && (avatar = "http://lorempixel.com/output/people-q-c-100-100-9.jpg",
            name = "Kate"), // Add message
            myMessages.addMessage({
                // Message text
                text: messageText,
                // Random message type
                type: messageType,
                // Avatar and name:
                avatar: avatar,
                name: name,
                // Day
                day: conversationStarted ? !1 : "Today",
                time: conversationStarted ? !1 : new Date().getHours() + ":" + new Date().getMinutes()
            }), // Update conversation flag
            conversationStarted = !0;
        }
    });
}), $(document).ready(function() {
    //randSlider();
    checkConnectionFB();

    if ((null === localStorage.getItem("newOptions") || localStorage.getItem("newOptions") === !0) && (myApp.popup(".popup-splash"),
        localStorage.setItem("newOptions", !0)), $(".chart-content").length > 0) {
        var obj = document.querySelector(".chart-content"), ctx = obj.getContext("2d");
    showLineChart(ctx);
}
naxvarBg(), $(".js-toggle-menu").on("click", function() {
    $(this).next().slideToggle(200), $(this).find("span").toggleClass("icon-chevron-down").toggleClass("icon-chevron-up");
}), $("body").on("click", ".js-gallery-col", function() {
    var cols = $(this).data("cols");
    $(".gallery-list").attr({
        "data-cols": cols
    }), $(".js-gallery-col").removeClass("active"), $(this).addClass("active");
});
}), $.fn.serializeObject = function() {
    var o = {}, a = this.serializeArray();
    return $.each(a, function() {
        void 0 !== o[this.name] ? (o[this.name].push || (o[this.name] = [ o[this.name] ]),
            o[this.name].push(this.value || "")) : o[this.name] = this.value || "";
    }), o;
};<commit_msg>Changes<commit_after>// Initialize app
function showDivsConnect(){
    console.log(localStorage.logged_in));
    if(localStorage.logged_in=="true"){
        $(".login").show();
        $(".logout").hide();
        $(".names_user").html(localStorage.name+" "+localStorage.lastname);
    }else{
        $(".login").hide();
        $(".logout").show();
    }
}

function checkConnectionFB() {
    facebookConnectPlugin.getLoginStatus(function(response) {
        if (response.status == 'connected'&&response.authResponse.userID==localStorage.id) {
            localStorage.setItem("logged_in",true);
            showDivsConnect();
        } else {
            localStorage.setItem("logged_in",false);
        }
    });
}

function randSlider() {
    var num= Math.floor((Math.random() * 5) + 1);
    $(".full-page-video").css('background-image','url("http://wisi.com.co/assets/img/sliders/slider'+num+'.jpg")');
}
function findElement(selector) {
    var box = null;
    return $(".page-on-center").length > 0 ? (box = $(".view-main").find(".page-on-center " + selector),
        0 === box.length && (box = $(".view-main").find(".page-on-center" + selector))) : box = $(".view-main").find(".page").find(selector),
    box;
}

function naxvarBg() {
    var navbar = $(".navbar-anim-on-scroll"), box = null, cls = "active";
    return 0 === navbar.length ? !1 : (box = navbar.next().find($(".page-on-center").length > 0 ? ".page-on-center .page-content" : ".page .page-content"),
        box.scrollTop() > 10 ? navbar.addClass(cls) : navbar.removeClass(cls), void box.scroll(function() {
            $(this).scrollTop() > 40 ? navbar.addClass(cls) : navbar.removeClass(cls);
        }));
}

function hidePreloader() {
    jQuery(".page-preloader").animate({
        opacity: 0
    }, function() {
        jQuery(this).hide();
    });
}

var myApp = new Framework7({
    swipeBackPage: !1,
    pushState: !0,
    swipePanel: "left",
    modalTitle: "Title"
}), $$ = Dom7;

var fbLoginSuccess = function (response) {
   if (response.authResponse) {
       facebookConnectPlugin.api('/me?fields=id,email,first_name,last_name,gender,picture', null,
           function(response) {
            var gender=38;
            if(response.gender=="male")gender=39;
            localStorage.setItem("id",response.id);
            localStorage.setItem("name",  response.first_name);
            localStorage.setItem("lastname",  response.last_name);
            localStorage.setItem("email",  response.email);
            localStorage.setItem("gender",  gender);
            localStorage.setItem("picture",  response.picture.data.url);
            localStorage.setItem("logged_in", true);
            showDivsConnect();
            var data=$.param({data:{id:response.id,first_name:response.first_name,last_name:response.last_name,email:response.email,gender:gender,picture:response.picture}});
            $.ajax({
                url: "http://wisi.com.co/api/social/sigin",
                type: "post",
                data: data,
                success: function(d){
                    var level="1";
                    if(localStorage.cont_started=="true")level="2";
                    window.open("http://wisi.com.co/public/#/ad/"+level+"/"+d.userdata.id, "_system");
                    localStorage.setItem("cont_started",true);
                }
            });
           });
   }

}

$$("body").on("click", ".button-facebook", function() {
    var terms=$('#chkTerm').is(':checked');
    if(terms){
        facebookConnectPlugin.login(["public_profile"],
            fbLoginSuccess,
            function (error) { myApp.alert("Problemas conectando con Facebook!", ""); }
        );
    }else{
        myApp.alert("Debe aceptar los términos y condiciones!", "");
    }
});

$$("body").on("click", ".close_sesion", function() {
    localStorage.clear();
    location.reload();
});

var mainView = myApp.addView(".view-main", {
    dynamicNavbar: !0
});
$$(document).on("pageInit", function(e) {
    checkConnectionFB();
    var page = e.detail.page;

    myApp.calendar({
        input: "#ks-calendar-default"
    }), myApp.calendar({
        input: "#calendar-multiple",
        dateFormat: "M dd yyyy",
        multiple: !0
    }), myApp.calendar({
        input: "#calendar-range",
        dateFormat: "M dd yyyy",
        rangePicker: !0
    });
    var today = new Date(), weekLater = new Date().setDate(today.getDate() + 7);
    myApp.calendar({
        input: "#calendar-disabled",
        dateFormat: "M dd yyyy",
        disabled: {
            from: today,
            to: weekLater
        }
    }), myApp.calendar({
        container: "#calendar-inline-container",
        value: [ new Date() ]
    }), $$(".notification-default").on("click", function() {
        myApp.addNotification({
            title: "Framework7",
            message: "This is a simple notification message with title and message"
        });
    }), $$(".notification-full").on("click", function() {
        myApp.addNotification({
            title: "Framework7",
            subtitle: "Notification subtitle",
            message: "This is a simple notification message with custom icon and subtitle",
            media: ''
        });
    }), $$(".notification-custom").on("click", function() {
        myApp.addNotification({
            title: "My Awesome App",
            subtitle: "New message from John Doe",
            message: "Hello, how are you? Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut posuere erat. Pellentesque id elementum urna, a aliquam ante. Donec vitae volutpat orci. Aliquam sed molestie risus, quis tincidunt dui.",
            media: ''
        });
    }), $$(".notification-callback").on("click", function() {
        myApp.addNotification({
            title: "My Awesome App",
            subtitle: "New message from John Doe",
            message: "Hello, how are you? Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut posuere erat. Pellentesque id elementum urna, a aliquam ante. Donec vitae volutpat orci. Aliquam sed molestie risus, quis tincidunt dui.",
            media: '',
            onClose: function() {
                myApp.alert("Notification closed");
            }
        });
    }), $(".zoom").swipebox(), $(".navbar").removeClass("navbar-clear"), ("index" === page.name || "dashboard-1" === page.name || "post" === page.name || "menu" === page.name || "login" === page.name || "registration" === page.name || "article" === page.name || "splash" === page.name) && $(".navbar").addClass("navbar-clear"),
    $(".twitter-content").length > 0 && $(".twitter-content").twittie({
        count: 10
    }), $(".tweet").length > 0 && $(".tweet").twittie({
        count: 1
    }), $(".flickr-content").length > 0 && $(".flickr-content").jflickrfeed({
        limit: 15,
        qstrings: {
            id: "44244432@N03"
        },
        itemTemplate: '

'
    }, function(data) {
        $(".flickr-content li a").swipebox();
    }), $(".owl-carousel").length > 0 && $(".owl-carousel").owlCarousel(), $(".featured-articles-slider").length > 0 && $(".featured-articles-slider").owlCarousel({
        singleItem: !0,
        navigation: !1,
        navigationText: [],
        pagination: !1,
        uniqueHistory: !0,
        loop: !0,
        autoPlay: 3e3,
        stopOnHover: !0
    }), $(".js-validate").length > 0 && $("body").on("click", ".js-form-submit", function() {
        var form = $(this).parents("form"), valid = form.valid();
        if ("contact" === page.name && valid) {
            var data = form.serializeObject();
            myApp.showPreloader(), $.post("/email.php", data).done(function(data) {
                myApp.hidePreloader();
                var response = JSON.parse(data);
                response.error ? myApp.alert(response.msg, "") : (myApp.alert(response.msg, ""),
                    form.find("input[type=text], input[type=email], textarea").val(""));
            });
        }
    });
    // Conversation flag
    var conversationStarted = !1, myMessages = myApp.messages(".messages", {
        autoLayout: !0
    }), myMessagebar = myApp.messagebar(".messagebar");
    // Handle message
    $$(".messagebar .link").on("click", function() {
        // Message text
        var messageText = myMessagebar.value().trim();
        // Exit if empy message
        if (0 !== messageText.length) {
            // Empty messagebar
            myMessagebar.clear();
            // Random message type
            var avatar, name, messageType = [ "sent", "received" ][Math.round(Math.random())];
            "received" === messageType && (avatar = "http://lorempixel.com/output/people-q-c-100-100-9.jpg",
            name = "Kate"), // Add message
            myMessages.addMessage({
                // Message text
                text: messageText,
                // Random message type
                type: messageType,
                // Avatar and name:
                avatar: avatar,
                name: name,
                // Day
                day: conversationStarted ? !1 : "Today",
                time: conversationStarted ? !1 : new Date().getHours() + ":" + new Date().getMinutes()
            }), // Update conversation flag
            conversationStarted = !0;
        }
    });
}), $(document).ready(function() {
    //randSlider();
    checkConnectionFB();

    if ((null === localStorage.getItem("newOptions") || localStorage.getItem("newOptions") === !0) && (myApp.popup(".popup-splash"),
        localStorage.setItem("newOptions", !0)), $(".chart-content").length > 0) {
        var obj = document.querySelector(".chart-content"), ctx = obj.getContext("2d");
    showLineChart(ctx);
}
naxvarBg(), $(".js-toggle-menu").on("click", function() {
    $(this).next().slideToggle(200), $(this).find("span").toggleClass("icon-chevron-down").toggleClass("icon-chevron-up");
}), $("body").on("click", ".js-gallery-col", function() {
    var cols = $(this).data("cols");
    $(".gallery-list").attr({
        "data-cols": cols
    }), $(".js-gallery-col").removeClass("active"), $(this).addClass("active");
});
}), $.fn.serializeObject = function() {
    var o = {}, a = this.serializeArray();
    return $.each(a, function() {
        void 0 !== o[this.name] ? (o[this.name].push || (o[this.name] = [ o[this.name] ]),
            o[this.name].push(this.value || "")) : o[this.name] = this.value || "";
    }), o;
};<|endoftext|>


<commit_before>//* @protected
/**
	_moon.DataListSpotlightSupport_ a mixin that provides spotlight handling code for use by
	_moon.DataList_ and _moon.DataGridList_.  Since those each extend from their respective
	enyo counterparts, this mixin provides common add-on code needed for proper spotlight handling.
*/
moon.DataListSpotlightSupport = {
	didRender: function () {
		// Since we delay rendering (potentially spottable) children by default, spotlight on the list is
		// true by default; once we render, we check if the list was focused and if so, transfer
		// focus to the first spottable child inside
		var spot = enyo.Spotlight.getCurrent();
		this.spotlight = false;
		if (spot && (spot === this || spot.isDescendantOf(this))) {
			enyo.Spotlight.spot(this);
		}
	},
	didScroll: enyo.inherit(function (sup) {
		return function () {
			// When scrolling in pointer mode, we unspot the last focused child, to prevent it from
			// looping as new pages come up
			var spot;
			if (enyo.Spotlight.getPointerMode() &&
				((spot = enyo.Spotlight.getCurrent()) && (spot === this || spot.isDescendantOf(this)))) {
				enyo.Spotlight.unspot();
				this._unspotSinceSpot = true;
			}
			return sup.apply(this, arguments);
		};
	}),
	previewDomEvent: function(inEvent) {
		// When spotlight is being applied back to the list after being unspotted, check that the child being
		// focused is visible and if not, spot the first visible child that is
		if ((inEvent.type == "onSpotlightFocus") && this._unspotSinceSpot && (!enyo.Spotlight.getPointerMode())) {
			var target = inEvent.originator;
			if (target != this) {
				// Calculate the target bounds, relative to the scrollBounds
				var tb = target.getBounds();
				var p = target.isDescendantOf(this.$.page1) ? this.$.page1 : this.$.page2;
				var pb = p.getBounds();
				// Need to add page offset to target bounds
				tb.top += pb.top;
				tb.left += pb.left;
				var sb = this.$.scroller.getScrollBounds();
				// Check if target is inside the current scrollBounds
				if ((tb.top < sb.top) ||
					(tb.left < sb.left) ||
					((tb.top + tb.height) > (sb.top + sb.clientHeight)) ||
					((tb.left + tb.width) > (sb.left + sb.clientWidth))) {
					// Not in view, so find and spot the first visible child
					var vc = this.getFirstVisibleChild(sb);
					if (vc) {
						this._unspotSinceSpot = false;
						enyo.Spotlight.spot(vc);
					}
					return true;
				} else {
					this._unspotSinceSpot = false;
				}
			}
		}
	},
	getFirstVisibleChild: function(inScrollBounds) {
		// Loop through the pages in top-down order
		var pages = (this.$.page1.index < this.$.page2.index) ?
			[this.$.page1, this.$.page2] :
			[this.$.page2, this.$.page1];
		for (var p in pages) {
			var page = pages[p];
			var pb = page.getBounds();
			// Loop through children in each pange top-down
			for (var i=0; i<page.children.length; i++) {
				var c = page.children[i];
				var cb = c.getBounds();
				// Need to add page offset to target bounds
				cb.top += pb.top;
				cb.left += pb.left;
				// Return the first spottable child whose top/left are inside the viewport
				if ((cb.top >= inScrollBounds.top) && (cb.left >= inScrollBounds.left)) {
					if (enyo.Spotlight.isSpottable(c)) {
						return c;
					}
					c = enyo.Spotlight.getFirstChild(c);
					if (c) {
						return c;
					}
				}
			}
		}
		return null;
	}
};

//* @public

/**
	_moon.DataList_ is an [enyo.DataList](#enyo.DataList) with Moonstone styling
	applied.  It uses [moon.Scroller](#moon.Scroller) as its default scroller.
*/
enyo.kind({
	name: "moon.DataList",
	kind: "enyo.DataList",
	//* @protected
	mixins: ["moon.DataListSpotlightSupport"],
	noDefer: true,
	allowTransitions: false,
	spotlight: true,
	scrollerOptions: { kind: "moon.Scroller", horizontal: "hidden" }
});
//* @protected
/**
	Overload the delegate strategy to incorporate measurements for our scrollers
	when they are visible.
*/
(function (enyo, moon) {
	moon.DataList.delegates.vertical   = enyo.clone(moon.DataList.delegates.vertical);
	moon.DataList.delegates.horizontal = enyo.clone(moon.DataList.delegates.horizontal);
	var exts = {
		refresh: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				list.$.scroller.resized();
			};
		}),
		scrollToIndex: function (list, i) {
			// This function recurses, so make sure we are scrolling to a valid index,
			// otherwise childForIndex will never return a control
			if ((i < 0) || (i >= list.collection.length)) {
				return;
			}
				// first see if the child is already available to scroll to
			var c = this.childForIndex(list, i),
				// but we also need the page so we can find its position
				p = this.pageForIndex(list, i);
			// if there is no page then the index is bad
			if (p < 0 || p > this.pageCount(list)) { return; }
			// if there isn't one, then we know we need to go ahead and
			// update, otherwise we should be able to use the scroller's
			// own methods to find it
			if (c) {
				// force a synchronous scroll to the control so it won't dupe and
				// re-animate over positions it has already crossed
				list.$.scroller.scrollToControl(c, false, false);
			} else {
				var idx = list.$.page1.index;

				// attempting to line them up in a useful order
				// given the direction from where our current index is
				if (idx < p) {
					list.$.page1.index = p - 1;
					list.$.page2.index = p;
				} else {
					list.$.page1.index = p;
					list.$.page2.index = p + 1;
				}
				list.refresh();

				this.scrollToIndex(list, i);
			}
		}
	};
	enyo.kind.extendMethods(moon.DataList.delegates.vertical, exts, true);
	enyo.kind.extendMethods(moon.DataList.delegates.vertical, {
		reset: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				if (list.$.scroller.getVertical() != "scroll") {
					this.updateBounds(list);
					list.refresh();
				}
			};
		}),
		updateBounds: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				var w = list.boundsCache.width,
					b = list.$.scroller.getScrollBounds(),
					n = list.$.scroller.$.strategy.$.vColumn.hasNode();
				if (list.$.scroller.getVertical() == "scroll" || (b.height > b.clientHeight)) {
					list.boundsCache.width = w-n.offsetWidth;
				}
			};
		})
	}, true);
	enyo.kind.extendMethods(moon.DataList.delegates.horizontal, exts, true);
	enyo.kind.extendMethods(moon.DataList.delegates.horizontal, {
		reset: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				if (list.$.scroller.getHorizontal() != "scroll") {
					this.updateBounds(list);
					list.refresh();
				}
				list.$.scroller.scrollTo(0, 0);
			};
		}),
		updateBounds: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				var w = list.boundsCache.height,
					b = list.$.scroller.getScrollBounds(),
					n = list.$.scroller.$.strategy.$.hColumn.hasNode();
				if (list.$.scroller.getVertical() == "scroll" || (b.width > b.clientWidth)) {
					list.boundsCache.height = w-n.offsetHeight;
				}
			};
		})
	}, true);
})(enyo, moon);
<commit_msg>Reset _unspotSinceSpot when getting a pointer focus. DCO-1.1-Signed-Off-By: Kevin Schaaf <kevin.schaaf@lge.com><commit_after>//* @protected
/**
	_moon.DataListSpotlightSupport_ a mixin that provides spotlight handling code for use by
	_moon.DataList_ and _moon.DataGridList_.  Since those each extend from their respective
	enyo counterparts, this mixin provides common add-on code needed for proper spotlight handling.
*/
moon.DataListSpotlightSupport = {
	didRender: function () {
		// Since we delay rendering (potentially spottable) children by default, spotlight on the list is
		// true by default; once we render, we check if the list was focused and if so, transfer
		// focus to the first spottable child inside
		var spot = enyo.Spotlight.getCurrent();
		this.spotlight = false;
		if (spot && (spot === this || spot.isDescendantOf(this))) {
			enyo.Spotlight.spot(this);
		}
	},
	didScroll: enyo.inherit(function (sup) {
		return function () {
			// When scrolling in pointer mode, we unspot the last focused child, to prevent it from
			// looping as new pages come up
			var spot;
			if (enyo.Spotlight.getPointerMode() &&
				((spot = enyo.Spotlight.getCurrent()) && (spot === this || spot.isDescendantOf(this)))) {
				enyo.Spotlight.unspot();
				this._unspotSinceSpot = true;
			}
			return sup.apply(this, arguments);
		};
	}),
	previewDomEvent: function(inEvent) {
		// When spotlight is being applied back to the list after being unspotted, check that the child being
		// focused is visible and if not, spot the first visible child that is
		if ((inEvent.type == "onSpotlightFocus") && this._unspotSinceSpot) {
			if (enyo.Spotlight.getPointerMode()) {
				this._unspotSinceSpot = false;
			} else {
				var target = inEvent.originator;
				if (target != this) {
					// Calculate the target bounds, relative to the scrollBounds
					var tb = target.getBounds();
					var p = target.isDescendantOf(this.$.page1) ? this.$.page1 : this.$.page2;
					var pb = p.getBounds();
					// Need to add page offset to target bounds
					tb.top += pb.top;
					tb.left += pb.left;
					var sb = this.$.scroller.getScrollBounds();
					// Check if target is inside the current scrollBounds
					if ((tb.top < sb.top) ||
						(tb.left < sb.left) ||
						((tb.top + tb.height) > (sb.top + sb.clientHeight)) ||
						((tb.left + tb.width) > (sb.left + sb.clientWidth))) {
						// Not in view, so find and spot the first visible child
						var vc = this.getFirstVisibleChild(sb);
						if (vc) {
							this._unspotSinceSpot = false;
							enyo.Spotlight.spot(vc);
						}
						return true;
					} else {
						this._unspotSinceSpot = false;
					}
				}
			}
		}
	},
	getFirstVisibleChild: function(inScrollBounds) {
		// Loop through the pages in top-down order
		var pages = (this.$.page1.index < this.$.page2.index) ?
			[this.$.page1, this.$.page2] :
			[this.$.page2, this.$.page1];
		for (var p in pages) {
			var page = pages[p];
			var pb = page.getBounds();
			// Loop through children in each pange top-down
			for (var i=0; i<page.children.length; i++) {
				var c = page.children[i];
				var cb = c.getBounds();
				// Need to add page offset to target bounds
				cb.top += pb.top;
				cb.left += pb.left;
				// Return the first spottable child whose top/left are inside the viewport
				if ((cb.top >= inScrollBounds.top) && (cb.left >= inScrollBounds.left)) {
					if (enyo.Spotlight.isSpottable(c)) {
						return c;
					}
					c = enyo.Spotlight.getFirstChild(c);
					if (c) {
						return c;
					}
				}
			}
		}
		return null;
	}
};

//* @public

/**
	_moon.DataList_ is an [enyo.DataList](#enyo.DataList) with Moonstone styling
	applied.  It uses [moon.Scroller](#moon.Scroller) as its default scroller.
*/
enyo.kind({
	name: "moon.DataList",
	kind: "enyo.DataList",
	//* @protected
	mixins: ["moon.DataListSpotlightSupport"],
	noDefer: true,
	allowTransitions: false,
	spotlight: true,
	scrollerOptions: { kind: "moon.Scroller", horizontal: "hidden" }
});
//* @protected
/**
	Overload the delegate strategy to incorporate measurements for our scrollers
	when they are visible.
*/
(function (enyo, moon) {
	moon.DataList.delegates.vertical   = enyo.clone(moon.DataList.delegates.vertical);
	moon.DataList.delegates.horizontal = enyo.clone(moon.DataList.delegates.horizontal);
	var exts = {
		refresh: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				list.$.scroller.resized();
			};
		}),
		scrollToIndex: function (list, i) {
			// This function recurses, so make sure we are scrolling to a valid index,
			// otherwise childForIndex will never return a control
			if ((i < 0) || (i >= list.collection.length)) {
				return;
			}
				// first see if the child is already available to scroll to
			var c = this.childForIndex(list, i),
				// but we also need the page so we can find its position
				p = this.pageForIndex(list, i);
			// if there is no page then the index is bad
			if (p < 0 || p > this.pageCount(list)) { return; }
			// if there isn't one, then we know we need to go ahead and
			// update, otherwise we should be able to use the scroller's
			// own methods to find it
			if (c) {
				// force a synchronous scroll to the control so it won't dupe and
				// re-animate over positions it has already crossed
				list.$.scroller.scrollToControl(c, false, false);
			} else {
				var idx = list.$.page1.index;

				// attempting to line them up in a useful order
				// given the direction from where our current index is
				if (idx < p) {
					list.$.page1.index = p - 1;
					list.$.page2.index = p;
				} else {
					list.$.page1.index = p;
					list.$.page2.index = p + 1;
				}
				list.refresh();

				this.scrollToIndex(list, i);
			}
		}
	};
	enyo.kind.extendMethods(moon.DataList.delegates.vertical, exts, true);
	enyo.kind.extendMethods(moon.DataList.delegates.vertical, {
		reset: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				if (list.$.scroller.getVertical() != "scroll") {
					this.updateBounds(list);
					list.refresh();
				}
			};
		}),
		updateBounds: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				var w = list.boundsCache.width,
					b = list.$.scroller.getScrollBounds(),
					n = list.$.scroller.$.strategy.$.vColumn.hasNode();
				if (list.$.scroller.getVertical() == "scroll" || (b.height > b.clientHeight)) {
					list.boundsCache.width = w-n.offsetWidth;
				}
			};
		})
	}, true);
	enyo.kind.extendMethods(moon.DataList.delegates.horizontal, exts, true);
	enyo.kind.extendMethods(moon.DataList.delegates.horizontal, {
		reset: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				if (list.$.scroller.getHorizontal() != "scroll") {
					this.updateBounds(list);
					list.refresh();
				}
				list.$.scroller.scrollTo(0, 0);
			};
		}),
		updateBounds: enyo.inherit(function (sup) {
			return function (list) {
				sup.apply(this, arguments);
				var w = list.boundsCache.height,
					b = list.$.scroller.getScrollBounds(),
					n = list.$.scroller.$.strategy.$.hColumn.hasNode();
				if (list.$.scroller.getVertical() == "scroll" || (b.width > b.clientWidth)) {
					list.boundsCache.height = w-n.offsetHeight;
				}
			};
		})
	}, true);
})(enyo, moon);
<|endoftext|>


<commit_before>/* Javascript for StaffGradedAssignmentXBlock. */
function StaffGradedAssignmentXBlock(runtime, element)
{
    function xblock($, _)
    {
        var uploadUrl = runtime.handlerUrl(element, 'student_upload_file');
        var studentDownloadUrl = runtime.handlerUrl(element, 'student_download_file');
        var studentDownloadZippedUrl = runtime.handlerUrl(element, 'student_download_zipped')
        var submitUrl = runtime.handlerUrl(element, 'student_submit');
        var deleteSubmissionFileUrl = runtime.handlerUrl(element, 'student_delete_file')

        var staffDownloadUrl = runtime.handlerUrl(element, 'staff_download_file');
        var staffDownloadZippedUrl = runtime.handlerUrl(element, 'staff_download_zipped');

        var annotatedUploadUrl = runtime.handlerUrl(element, 'staff_upload_annotated');
        var studentAnnotationDownloadUrl = runtime.handlerUrl(element, 'student_download_annotated');
        var studentAnnotationDownloadZippedUrl = runtime.handlerUrl(element, 'student_download_annotated_zipped');
        var deleteAnnotationFileUrl = runtime.handlerUrl(element, 'staff_delete_annotated');

        var staffDownloadAnnotatedUrl = runtime.handlerUrl(element, 'staff_download_annotated');
        var staffDownloadAnnotatedZippedUrl = runtime.handlerUrl(element, 'staff_download_annotated_zipped');

        var getStaffGradingUrl = runtime.handlerUrl(element, 'get_staff_grading_data');
        var enterGradeUrl = runtime.handlerUrl(element, 'staff_enter_grade');
        var removeGradeUrl = runtime.handlerUrl(element, 'staff_remove_grade');

        var reopenSubmissionUrl = runtime.handlerUrl(element, 'staff_reopen_submission');
        var removeSubmissionUrl = runtime.handlerUrl(element, 'staff_remove_submission')
        var reopenAllSubmissionsUrl = runtime.handlerUrl(element, 'staff_reopen_all_submissions');
        var removeAllSubmissionsUrl = runtime.handlerUrl(element, 'staff_remove_all_submissions');

        var template = _.template($(element).find("#sga-tmpl").text());
        var uploadTemplate = _.template($(element).find("#sga-upload-tmpl").text());
        var filelistTemplate = _.template($(element).find("#sga-filelist-tmpl").text());
        var gradingTemplate;

        function render(state)
        {
            state.error = state.error ? state.error : false;

            // Render template
            var content = $(element).find("#sga-content").html(template(state));

            var uploadData = {
                filelist:          state.uploaded,
                uploadUrl:         uploadUrl,
                downloadZippedUrl: studentDownloadZippedUrl,
                downloadUrl: function(hash)
                {
                    return studentDownloadUrl + '/' + hash;
                },
                deleteUrl: function(hash)
                {
                    return deleteSubmissionFileUrl +'/' + hash;
                },
                upload_allowed:    state.upload_allowed
            };

            var annotatedData = {
                filelist:          state.annotated,
                downloadZippedUrl: studentAnnotationDownloadZippedUrl,
                downloadUrl: function(hash)
                {
                    return studentDownloadUrl + '/' + hash;
                },
                deleteUrl: function(hash)
                {
                    return "";
                },
                upload_allowed:    false
            };

            handleUpload($('#student-upload'), uploadData);
            handleFilelist($('#student-annotated'), annotatedData);

            //submit assignment for marking.
            $(content).find(".assingmentsubmit").click(function(e)
            {
                $.get(submitUrl).success(function () {
                    state.submitted = true;
                    state.upload_allowed = false;
                    render(state);
                });
            });
        }

        function renderStaffGrading(data)
        {
            $(".grade-modal").hide();
            //$(".annotated-modal").hide();

            var allStudentData = data;

            // Add download urls to template context
            data.downloadUrl = staffDownloadUrl;
            data.downloadZippedUrl = staffDownloadZippedUrl;            //data.removeSubmissionUrl = removeSubmissionUrl;

            // Render template
            $(element).find("#grade-info")
                .html(gradingTemplate(data))
                .data(data);

            // Map data to table rows
            data.assignments.map(function(assignment) {
                $(element).find("#grade-info #row-" + assignment.module_id)
                    .data(assignment);
            });

            // Set up grade entry modal
            $(element).find(".enter-grade-button")
                .leanModal({closeButton: "#enter-grade-cancel"})
                .on("click", handleGradeEntry);

            //set up annotated file submision modal
            $(element).find(".manage-annotated-button")
                .leanModal({closeButton: "#manage-annotated-exit"})
                .on("click", handleManageAnnotated);

            //all submission control
            $(element).find(".remove-all-submissions-button")
                .on("click", function()
                {
                    var url = removeAllSubmissionsUrl;

                    $.get(url).success(function() {
                        allStudentData.assignments.each(
                            removeSubmission(this)
                        );

                        renderStaffGrading(allStudentData);
                    });
                });

            //reopen all submissions for the asingment.
            $(element).find(".reopen-all-submissions-button")
                .on("click", function()
                {
                    var url = reopenAllSubmissionsUrl;

                    $.get(url).success(function() {
                        allStudentData.assignments.each(function() {
                            this.submitted = false;
                        });

                        renderStaffGrading(allStudentData);
                    });
                });

            //Remove a submission, including grades and files.
            $(element).find(".remove-submission-button")
                .on("click", function()
                {
                    var module_id = $(this).parents("tr").data("module_id");
                    var url = removeSubmissionUrl + "?module_id=" + module_id;

                    $.get(url).success(function() {
                        removeSubmission($.grep(allStudentData.assignments, function(e) {
                            return e.module_id == module_id;
                        })[0]);

                        renderStaffGrading(allStudentData);
                    });
                });

            //reopens a submission for a student.  Clears previous grade.
            $(element).find(".reopen-submission-button")
                .on("click", function()
                {
                    var module_id = $(this).parents("tr").data("module_id");
                    var url = reopenSubmissionUrl + "?module_id=" + module_id;

                    $.get(url).success(function() {
                        $.grep(allStudentData.assignments, function(e) {
                            return e.module_id == module_id;
                        })[0].submitted = false;

                        renderStaffGrading(allStudentData);
                    });
                });

            //All upload, download and delete for annotated files
            function handleManageAnnotated()
            {
                var row = $(this).parents("tr");
                var module_id = row.data("module_id")

                var studentData =
                    $.grep(allStudentData.assignments, function(e){
                        return e.module_id == module_id;
                    })[0];

                $('#student-name-annotations').text(studentData.fullname);

                //Object containing data needed for rendering file list
                //and upload button.
                var fileData = {
                    filelist:          studentData.annotated,
                    uploadUrl:         annotatedUploadUrl + "?module_id="
                                       + studentData.module_id,
                    downloadZippedUrl: staffDownloadAnnotatedZippedUrl
                                       + "?module_id=" + studentData.module_id,
                    downloadUrl: function(hash)
                    {
                        return staffDownloadAnnotatedUrl + '/' + hash
                        + "?module_id=" + studentData.module_id;
                    },
                    deleteUrl: function(hash)
                    {
                        return deleteAnnotationFileUrl +'/' + hash
                        + "?module_id=" + studentData.module_id;
                    },
                    upload_allowed:    true
                };

                var form = $(element).find("#manage-annotations-form");

                handleUpload(form, fileData);

                form.find("#manage-annotated-exit").on("click", function() {
                    setTimeout(function() {
                        $("#grade-submissions-button").click();
                    }, 225);
                });
            }

            /* Click event handler for "enter grade" */
            function handleGradeEntry()
            {
                var row = $(this).parents("tr");
                var module_id = row.data("module_id")

                var studentData =
                    $.grep(allStudentData.assignments, function(e){
                        return e.module_id == module_id;
                    })[0];

                var form = $(element).find("#enter-grade-form");
                $(element).find("#student-name").text(studentData.fullname);

                form.find("#module_id-input").val(studentData.module_id);
                form.find("#grade-input").val(studentData.score);
                form.find("#comment-input").text(studentData.comment);

                form.off("submit").on("submit", function(event) {
                    var max_score = allStudentdata.max_score;//row.parents("#grade-info").data("max_score");
                    var score = Number(form.find("#grade-input").val());
                    event.preventDefault();

                    if (isNaN(score)) //entered score not integer
                    {
                        form.find(".error").html("
Grade must be a number.");
                    }
                    else if (score < 0) //entered score not positive
                    {
                        form.find(".error").html("
Grade must be positive.");
                    }
                    else if (score > max_score) //entered score too large.
                    {
                        form.find(".error").html("
Maximum score is " + max_score);
                    }
                    else
                    {
                        // No errors
                        studentData.score = score;
                        studentData.comment = form.find("#comment-input").text();

                        $.post(enterGradeUrl, form.serialize())
                            .success(function() {
                                renderStaffGrading(allStudentData);
                            });
                    }
                });

                //Remove the grade from the student's assignment.
                form.find("#remove-grade").on("click", function() {
                    var url = removeGradeUrl + "?module_id=" + module_id;
                    $.get(url).success(renderStaffGrading);
                });

                //leave the grading pane.
                form.find("#enter-grade-cancel").on("click", function() {
                    /* We're kind of stretching the limits of leanModal, here,
                     * by nesting modals one on top of the other.  One side effect
                     * is that when the enter grade modal is closed, it hides
                     * the overlay for itself and for the staff grading modal,
                     * so the overlay is no longer present to click on to close
                     * the staff grading modal.  Since leanModal uses a fade out
                     * time of 200ms to hide the overlay, our work around is to
                     * wait 225ms and then just "click" the 'Grade Submissions'
                     * button again.  It would also probably be pretty
                     * straightforward to submit a patch to leanModal so that it
                     * would work properly with nested modals.
                     *
                     * See: https://github.com/mitodl/edx-sga/issues/13
                     */
                    setTimeout(function() {
                        $("#grade-submissions-button").click();
                    }, 225);
                });
            }
        }

        //reset a submission, removing all files and grades.
        function removeSubmission(submission)
        {
            submission.uploaded = [];
            submission.annotated = [];
            submission.submitted = false;

            removeGrade(submission);
        }

        //remove a grade from a submission
        function removeGrade(submission)
        {
            submission.score = null;
            submission.comment = '';
            submission.published = false;
            submission.approved = false;
        }

        function handleUpload(parent, state)
        {
            //look into removing
            //var state = data;
            if (typeof state.error === undefined)
            {
                state.error = "";
            }

            //var parent = e;
            var fileuploadDiv = parent.find('.upload');
            var filelistDiv = parent.find('.filelist');

            handleFilelist(filelistDiv, state)

/*            var renderFileList = function(element)
            {
                return function(){
                    handleFilelist(element, state);
                };
            }(parent.find('.filelist'));*/

            //renderFileList();
            fileuploadDiv.html(uploadTemplate(state));

            fileuploadDiv.find(".fileupload").fileupload({
                url: state.uploadUrl,
                add: function(e, data)
                {
                    var do_upload = fileuploadDiv.html('');
                    $('<button/>')
                        .text('Upload ' + data.files[0].name)
                        .appendTo(do_upload)
                        .click(function() {
                            do_upload.text("Uploading...");
                            data.submit();
                        });
                },
                progressall: function(e, data)
                {
                    var percent = parseInt(data.loaded / data.total * 100, 10);
                    fileuploadDiv.text("Uploading... " + percent + "%");
                },
                fail: function(e, data)
                {
                    var error = "";
                    if (data.jqXHR.status == 413)
                    {
                        state.error = "The file you are trying to upload is too large."
                    }
                    else
                    {
                        // Suitably vague
                        state.error = "There was an error uploading your file.";

                        console.log("There was an error with file upload.");
                        console.log("event: ", e);
                        console.log("data: ", data);
                    }
                    handleUpload(parent, state);
                },
                done: function(e, data)
                {
                    if (data.result.success !== undefined)
                    {
                        // Actually, this is an error
                        state.error = data.result.success;
                    }
                    else
                    {
                        // The happy path, no errors
                        state.filelist.push(data.result);
                        state.error = "";
                    }
                    //reset the upload field.
                    handleUpload(parent, state);

                }
            });
        }

        function handleFilelist(fileListDiv, state)
        {
            fileListDiv.html(filelistTemplate(state));

            //attach download url
            //would do this with a template, but I am unsure how
            //to use the downloadUrl function in an underscore.js
            //template.
            fileListDiv.find(".fileDownload").each(function() {
                var pos = $(this).attr('value');
                url = state.downloadUrl(state.filelist[pos].sha1);
                $(this).attr("href", url);
            });

            //bind file delete command to url.
            fileListDiv.find(".fileDelete").on("click", function() {
                var url = state.deleteUrl(state.filelist[this.value].sha1);
                var pos = this.value;

                $.get(url).success(function(data) {
                    if (pos < state.filelist.length)
                    {
                        state.filelist.splice(pos, 1);
                    }

                    handleFilelist(fileListDiv, state)
                });
            });
        }

        $(function($) { // onLoad
            var block = $(element).find(".sga-block");
            var state = block.attr("data-state");
            render(JSON.parse(state));

            var is_staff = block.attr("data-staff") == "True";
            if (is_staff) {
                gradingTemplate = _.template(
                    $(element).find("#sga-grading-tmpl").text());

                block.find("#grade-submissions-button")
                    .leanModal()
                    .on("click", function() {
                        $.ajax({
                            url: getStaffGradingUrl,
                            success: renderStaffGrading
                        });
                    });
                block.find("#staff-debug-info-button")
                    .leanModal();
            }
        });
    }

    if (require === undefined) {
        /**
         * The LMS does not use require.js (although it loads it...) and
         * does not already load jquery.fileupload.  (It looks like it uses
         * jquery.ajaxfileupload instead.  But our XBlock uses
         * jquery.fileupload.
         */
        function loadjs(url) {
            $("


<commit_before>import { Dependencies } from 'constitute';
import { UnsupportedOperationException } from './../exceptions';
import Redis from './redis';
import DI from './../di';
import Config from './config';
import ServiceInterface from './interface';

export class Store {
  getInstance() {
    return this;
  }

  has() {
    return Promise.resolve(false);
  }

  get() {
    return Promise.resolve(null);
  }

  set() {
    return Promise.resolve(this);
  }

  flush() {
    return Promise.resolve(true);
  }

  tags() {
    throw new UnsupportedOperationException('Not support tag feature');
  }
}

export class NullStore extends Store {
  namespace() {
    return this;
  }

  tags() {
    return this;
  }
}

export class RedisNamespaceStore extends Store {
  constructor(prefix, namespace, redis) {
    super();
    this.prefix = prefix;
    this.namespace = namespace;
    this.redis = redis;
  }

  getInstance() {
    return this.redis;
  }

  has(key) {
    return this.redis.exists(this.key(key)).then(res => res > 0);
  }

  key(key) {
    return this.prefix ? [this.prefix, this.namespace, key].join(':') : key;
  }

  get(key) {
    return this.redis.get(this.key(key)).then(res => JSON.parse(res));
  }

  set(key, value, minutes, mutex) {
    const args = [
      this.key(key),
      JSON.stringify(value)
    ];
    if (minutes) {
      args.push('ex', minutes * 60);
    }
    if (mutex) {
      const m = mutex.toUpperCase();
      if (m === 'NX' || m === 'XX') {
        args.push(m);
      }
    }
    return this.redis.set(...args);
  }

  flush() {
    return this.redis.keys([this.prefix, this.namespace, '*'].join(':'))
      .then((keys) => {
        if (keys.length > 0) {
          return this.redis.del(keys);
        }
        return 1;
      });
  }
}

export class RedisStore extends Store {
  constructor(prefix, redis) {
    super();
    this.prefix = prefix;
    this.namespaceHandler = {};
    this.redis = redis || DI.get('redis').getInstance();
  }

  getInstance() {
    return this.redis;
  }

  namespace(namespace) {
    if ({}.hasOwnProperty.call(this.namespaceHandler, namespace)) {
      return this.namespaceHandler[namespace];
    }
    this.namespaceHandler[namespace] = new RedisNamespaceStore(this.prefix, namespace, this.redis);
    return this.namespaceHandler[namespace];
  }

  has(key) {
    return this.redis.exists(this.key(key));
  }

  key(key) {
    return this.prefix ? [this.prefix, key].join(':') : key;
  }

  get(key) {
    return this.redis.get(this.key(key)).then(res => JSON.parse(res));
  }

  set(key, value, minutes, mutex) {
    const args = [
      this.key(key),
      JSON.stringify(value)
    ];
    if (minutes) {
      args.push('ex', minutes * 60);
    }
    if (mutex) {
      const m = mutex.toUpperCase();
      if (m === 'NX' || m === 'XX') {
        args.push(m);
      }
    }
    return this.redis.set(...args);
  }

  flush() {
    return this.redis.flushall();
  }
}

@Dependencies(Config, Redis) //eslint-disable-line new-cap
export default class Cache extends ServiceInterface {
  constructor(config) {
    super();
    this.config = config.get('cache');
    this.prefix = this.config.prefix || 'eva';
    this.driver = this.config.driver;
    this.store = null;
  }

  setStore(store) {
    this.store = store;
    return this;
  }

  /**
   * @returns {Store}
   */
  getStore() {
    if (this.store) {
      return this.store;
    }
    this.store = this.driver === 'redis' ?
      new RedisStore(this.prefix) : new NullStore(this.prefix);
    return this.store;
  }

  setPrefix(prefix) {
    this.prefix = prefix;
  }

  getPrefix() {
    return this.prefix;
  }

  namespace(...args) {
    return this.getStore().namespace(...args);
  }

  has(key) {
    return this.getStore().has(key);
  }

  get(key) {
    return this.getStore().get(key);
  }

  set(...args) {
    return this.getStore().set(...args);
  }

  flush() {
    return this.getStore().flush();
  }
}

<commit_msg>fix cache flush bug<commit_after>import { Dependencies } from 'constitute';
import { UnsupportedOperationException } from './../exceptions';
import Redis from './redis';
import DI from './../di';
import Config from './config';
import ServiceInterface from './interface';

export class Store {
  getInstance() {
    return this;
  }

  has() {
    return Promise.resolve(false);
  }

  get() {
    return Promise.resolve(null);
  }

  set() {
    return Promise.resolve(this);
  }

  flush() {
    return Promise.resolve(true);
  }

  tags() {
    throw new UnsupportedOperationException('Not support tag feature');
  }
}

export class NullStore extends Store {
  namespace() {
    return this;
  }

  tags() {
    return this;
  }
}

export class RedisNamespaceStore extends Store {
  constructor(prefix, namespace, redis) {
    super();
    this.prefix = prefix;
    this.namespace = namespace;
    this.redis = redis;
  }

  getInstance() {
    return this.redis;
  }

  has(key) {
    return this.redis.exists(this.key(key)).then(res => res > 0);
  }

  key(key) {
    return this.prefix ? [this.prefix, this.namespace, key].join(':') : key;
  }

  get(key) {
    return this.redis.get(this.key(key)).then(res => JSON.parse(res));
  }

  set(key, value, minutes, mutex) {
    const args = [
      this.key(key),
      JSON.stringify(value)
    ];
    if (minutes) {
      args.push('ex', minutes * 60);
    }
    if (mutex) {
      const m = mutex.toUpperCase();
      if (m === 'NX' || m === 'XX') {
        args.push(m);
      }
    }
    return this.redis.set(...args);
  }

  flush() {
    return this.redis.keys([this.prefix, this.namespace, '*'].join(':'))
      .then((keys) => {
        if (keys.length) {
          return this.redis.del(keys);
        }
        return 1;
      });
  }
}

export class RedisStore extends Store {
  constructor(prefix, redis) {
    super();
    this.prefix = prefix;
    this.namespaceHandler = {};
    this.redis = redis || DI.get('redis').getInstance();
  }

  getInstance() {
    return this.redis;
  }

  namespace(namespace) {
    if ({}.hasOwnProperty.call(this.namespaceHandler, namespace)) {
      return this.namespaceHandler[namespace];
    }
    this.namespaceHandler[namespace] = new RedisNamespaceStore(this.prefix, namespace, this.redis);
    return this.namespaceHandler[namespace];
  }

  has(key) {
    return this.redis.exists(this.key(key));
  }

  key(key) {
    return this.prefix ? [this.prefix, key].join(':') : key;
  }

  get(key) {
    return this.redis.get(this.key(key)).then(res => JSON.parse(res));
  }

  set(key, value, minutes, mutex) {
    const args = [
      this.key(key),
      JSON.stringify(value)
    ];
    if (minutes) {
      args.push('ex', minutes * 60);
    }
    if (mutex) {
      const m = mutex.toUpperCase();
      if (m === 'NX' || m === 'XX') {
        args.push(m);
      }
    }
    return this.redis.set(...args);
  }

  flush() {
    return this.redis.flushall();
  }
}

@Dependencies(Config, Redis) //eslint-disable-line new-cap
export default class Cache extends ServiceInterface {
  constructor(config) {
    super();
    this.config = config.get('cache');
    this.prefix = this.config.prefix || 'eva';
    this.driver = this.config.driver;
    this.store = null;
  }

  setStore(store) {
    this.store = store;
    return this;
  }

  /**
   * @returns {Store}
   */
  getStore() {
    if (this.store) {
      return this.store;
    }
    this.store = this.driver === 'redis' ?
      new RedisStore(this.prefix) : new NullStore(this.prefix);
    return this.store;
  }

  setPrefix(prefix) {
    this.prefix = prefix;
  }

  getPrefix() {
    return this.prefix;
  }

  namespace(...args) {
    return this.getStore().namespace(...args);
  }

  has(key) {
    return this.getStore().has(key);
  }

  get(key) {
    return this.getStore().get(key);
  }

  set(...args) {
    return this.getStore().set(...args);
  }

  flush() {
    return this.getStore().flush();
  }
}

<|endoftext|>


<commit_before>import React, { Component } from 'react'
import styled, { css } from 'styled-components'
import { LiveProvider, LivePreview, LiveEditor } from 'react-live'
import fetch from 'isomorphic-fetch'
import StarIcon from 'react-octicons-svg/dist/StarIcon'
import HeartIcon from 'react-octicons-svg/dist/HeartIcon'

import rem from '../utils/rem'
import { headerFont } from '../utils/fonts'
import { violetRed, gold } from '../utils/colors'
import { editorMixin, StyledError } from '../components/LiveEdit'
import Code from '../components/Code'
import Link from '../components/Link'
import { Content } from '../components/Layout'
import HomepageGettingStarted from '../components/homepage-getting-started'
import captureScroll from '../components/CaptureScroll'

const headerCode = (`
const Tagline = styled.h1\`
  font-weight: 600;
  font-size: 1.3rem;
\`

const SupportingTagline = styled.h2\`
  font-size: 1.1rem;
  font-weight: 400;
\`

render(

    <Tagline>Visual primitives for the component age.</Tagline>
    <SupportingTagline>
      Use the best bits of ES6 and CSS to style your apps without stress 💅
    </SupportingTagline>

)`).trim()

const Title = styled.div`
  margin: 2rem 0;

  h1,
  h2 {
    margin: 0;
  }
`

const Logo = styled.img.attrs({
  alt: 'styled-components Logo',
  src: '/static/logo.png'
})`
  width: ${rem(125)};
  height: ${rem(125)};
`;

const UsersWrapper = styled.section`
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  padding: 0.5rem;
  margin-bottom: 2rem;
`

const UsersHeading = styled.p`
  text-transform: uppercase;
  color: #000;
  font-size: 0.8rem;
  font-weight: 600;
  margin: 2.5rem 0 0.5rem;
`

const CompanyLogo = styled.img`
  position: relative;
  height: ${p => p.height || '2rem'};
  margin: 0.5rem;
  bottom: ${p => p.bottom || 0};
  opacity: 0.6;

  &:hover {
    opacity: 1;
  }
`

const Wrapper = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  color: white;

  background: linear-gradient(20deg, ${violetRed}, ${gold});
  box-shadow: 0px 2px 20px rgba(0, 0, 0, 0.17);
  box-sizing: border-box;
  min-height: 100vh;
`

const HeroContent = Content.extend`
  font-family: ${headerFont};
  width: 75rem;
`

const EditorContainer = styled.div`
  display: inline-block;
  box-shadow: ${rem(1)} ${rem(1)} ${rem(20)} rgba(20, 20, 20, 0.27);
  margin: ${rem(35)} 0;
  text-align: left;
`

const Editor = captureScroll(styled(LiveEditor)`
  ${editorMixin}
  height: 24rem;
`)

const Links = styled.div`
  margin: ${rem(36)} 0;
`

const Button = styled.a`
  display: inline-block;
  border-radius: ${rem(3)};
  padding: ${rem(6)} 0;
  margin: ${rem(5)} ${rem(16)};
  text-decoration: none;
  text-align: center;
  width: ${rem(175)};
  font-family: ${headerFont};

  background: transparent;
  color: white;
  border: ${rem(2)} solid white;

  ${p => p.primary && css`
    background: white;
    color: palevioletred;
  `}
`

const InternalButton = Button.withComponent(Link);

const Star = styled(StarIcon).attrs({
  width: null,
  height: null
})`
  position: relative;
  display: inline;
  width: ${rem(15)};
  color: ${violetRed};
  bottom: ${rem(2)};
`

const Footer = styled.footer`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  color: white;

  background: ${violetRed};
  box-shadow: 0px -2px 20px rgba(0, 0, 0, 0.17);
  box-sizing: border-box;
  margin-top: ${rem(50)};
`

const Heart = styled(HeartIcon).attrs({
  width: null,
  height: null
})`
  display: inline-block;
  width: ${rem(17)};
`

class Index extends Component {
  render() {
    return (

        <Wrapper>
          <HeroContent>
            <LiveProvider
              code={headerCode}
              noInline
              mountStylesheet={false}
              scope={{ styled, css, rem }}>

              <Logo />

              <Title>
                <LivePreview />
              </Title>

              <Links>
                <Button
                  href="https://github.com/styled-components/styled-components"
                  target="_blank"
                  rel="noopener"
                  primary
                >
                  GitHub
                </Button>

                <InternalButton href="/docs" prefetch>
                  Documentation
                </InternalButton>
              </Links>

              <EditorContainer>
                <Editor />