<commit_before>/**
 * Created by Jameshwart Villarmea Lopez on 4/7/2015.
 */

var x = document.getElementById("map_holder");
var map;
var infowindow;
var latlng;
var request;
var selected;
var sortyby ="PROMINENCE";
var place_details_sortbyprominence=[];
var place_details_sorbydistance = [];
$(document).ready(function () {

    $(document).on("click",".add_review",function(){
        $("#frm_reviews").attr('andid','james');
    });
    $("#selecta").select2({
        placeholder: "Select Places...",
        allowClear: true,
        maximumSelectionLength: 3
    });

    $(document).on("change","#selecta",function(){
        selected = $("#selecta").select2("val");
        request = {
            location: latlng,
            radius:800,
            rankBy: google.maps.places.RankBy.PROMINENCE,
            types: selected
        };

    });

    $('#cmdSubmit').click(function () {
        $("#mnu_1,#your").css("display","block");
        place_details_sortbyprominence =[];
        place_details_sorbydistance = [];
        localStorage.removeItem("leloo_by_prominence");
        localStorage.removeItem("leloo_by_distance");
        if ($("#selecta").select2("val")) {
            $(this).hide();
            $("#noSubmit").show();

            getLocation();

            setTimeout(function () {
                $("#noSubmit").hide();
                $("#cmdSubmit").fadeIn();
            }, 2000)
        } else {
            $('#alert-msg').html("
 <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Ops! Please select place/s.
");

        }
    });

    $(".sortby").click(function(){
        $(".sortby").removeClass("active");
        $(this).addClass("active");

            if($(this).text() ==='Distance'){

                if("leloo_by_distance" in localStorage){
                    display_sorted_results(localStorage.getItem("leloo_by_distance"))
                }else{

                    if($("#selecta").select2("val")){
                        request.types=selected;
                        request.radius=null;
                        request.rankBy =google.maps.places.RankBy.DISTANCE;
                        getLocation();
                    }

                }

            }else if($(this).text() ==='Popularity'){

                if("leloo_by_prominence" in localStorage){

                    display_sorted_results(localStorage.getItem("leloo_by_prominence"))
                }else{
                    if($("#selecta").select2("val")){
                        request.types=selected;
                        request.radius=800;
                        request.rankBy =google.maps.places.RankBy.PROMINENCE;
                        getLocation();
                    }

                }
            }

    });
});

function getLocation() {
    //get current position
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {

    document.querySelector("#mapcanvas").style.height = '300px';
    latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

    var myOptions = {
        zoom: 15,
        center: latlng,
        mapTypeControl: false,
        navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL} ,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);

    var infowindowmain = new google.maps.InfoWindow({
        map: map,
        position: latlng,
        content: "You are here! (at least within a " + position.coords.accuracy + " meter radius)"
    });

    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: "You are here! (at least within a " + position.coords.accuracy + " meter radius)"
    });
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent("You are here! (at least within a " + position.coords.accuracy + " meter radius)");
        infowindow.open(map, this);
    });

    request.location = latlng;

    selected = $("#selecta").select2("val");
    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, callback);

    findhim(latlng);

}

function findhim(point) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({latLng: point}, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {

                var p_name = (results[0].name) ? "Place name: " + results[0].name + "
" : '';
                var p_address = (results[0].formatted_address) ? "
" + results[0].formatted_address + "
" : '';

                document.getElementById("location_container").innerHTML = p_name + p_address;
            }
        }
    });

}

function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        console.log(results);
        for (var i = 0; i < results.length; i++) {
            if(checkRadiusDistance(results[i],latlng,825)){
                createMarker(results[i]);
            }
        }

        $('#alert-msg').html("
 <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Returned " + results.length + " results
");

        $("#mnu_2,#about,#h_place,#btn-group-places").css("display","block");
        $("#btn-group-places").css("display","inline-block");
    }
    else
    {
        $('#alert-msg').html("
 <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Returned " + results.length + " results
");
        $("#mnu_2,#about,#h_place,#btn-group-places").css("display","none");

    }
}

function checkRadiusDistance(place,latlng,radius) {
    return google.maps.geometry.spherical.computeDistanceBetween(place.geometry.location, latlng) <= radius;
}

function createMarker(place) {

    var placeLoc = place.geometry.location;

    var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
    });

    var requestdata = {
        placeId: place.place_id
    };

    document.getElementById("placeres").innerHTML="";
    var service = new google.maps.places.PlacesService(map);
    service.getDetails(requestdata, function(placedata, status) {

        if (status == google.maps.places.PlacesServiceStatus.OK)
        {

            if(request.rankBy === google.maps.places.RankBy.PROMINENCE){
                place_details_sortbyprominence.push((placedata));
                localStorage.setItem("leloo_by_prominence",JSON.stringify(place_details_sortbyprominence));
                display_sorted_results(localStorage.getItem("leloo_by_prominence"));

            }else if(request.rankBy === google.maps.places.RankBy.DISTANCE){
                place_details_sorbydistance.push((placedata));
                localStorage.setItem("leloo_by_distance",JSON.stringify(place_details_sorbydistance));
                display_sorted_results(localStorage.getItem("leloo_by_distance"));

            }

        }
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(getPlace_contenet(place));
        infowindow.open(map, this);
    });

}
function display_sorted_results(localstorage_data){

    var data = localstorage_data.replace(/"\\"/g,"'").replace(/\\""/g,"'");

    data = JSON.parse(data);
    document.getElementById("places").innerHTML="";
    var str_container="";
    for(var i = 0 ; i < data.length ; i++){

        var placedata= data[i];

        var place_name = "
"+placedata.name+"
";
        var place_address = "
"+placedata.formatted_address+"
";
        var place_img_representation = "";
        var place_internationa_phonenuber =(typeof placedata.international_phone_number !=='undefined')?"
"+placedata.international_phone_number +"
":"";

        var place_rating =(typeof placedata.rating !=='undefined')? "
Rating based on aggregated user reviews:"+rating_display(placedata.rating)+"
":"";
        var place_website =(typeof placedata.website !== 'undefined')? "
VISIT WEBSITE":"";

        var user_reviews = "";
        if(typeof placedata.reviews !=='undefined'){
            for(var j = 0 ; j < placedata.reviews.length; j ++){

                var place_reviews = placedata.reviews[j];
                var review_author = "
"+place_reviews.author_name+"
";
                var review_authorlink = (typeof place_reviews.author_url !=='undefined')? ""+review_author+"":""+review_author+"";
                var review_rating ="
Rating:"+ rating_display(place_reviews.rating)+"
";
                var review_text = "
"+place_reviews.text+"
";

                 user_reviews +="
"+review_authorlink+review_rating+review_text+"
";
            }
        }

        var final_users_review = "
"+user_reviews+"
";
        str_container += "
 <button class='btn-primary add_review'  data-place_id= '"+placedata.place_id+"'> Add reviews</button></button>"+place_name+place_address+place_img_representation+place_internationa_phonenuber+place_rating+place_website + final_users_review +"
";
    }

    document.getElementById("placeres").innerHTML=str_container;
}

function getPlace_contenet(place) {
    var content = '';
    content += '
';
    content += '
';
    content += '	';
    var url=(typeof place.url !=='undefined')?place.url:'#';

    content += '' + place.name + '
';
    content += '
Address:	' + place.vicinity + '
';
    if (place.formatted_phone_number) {
        content += '
Telephone:	' + place.formatted_phone_number + '
';
    }

    if (place.rating) {
        rating_display(place.rating);
        content += '
Rating:	' +  rating_display(place.rating); + '
';

    }
    if (place.website) {
        var fullUrl = place.website;
        var website = hostnameRegexp.exec(place.website);
        if (website == null) {
            website = 'http://' + place.website + '/';
            fullUrl = website;
        }
        content += '
Website:	' + website + '
';
    }
    content += '
';
    return content;
}

function showError(error) {
    switch (error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}

function ucfirst(str) {
    var firstLetter = str.substr(0, 1);
    return firstLetter.toUpperCase() + str.substr(1);
}

function rating_display(rating){
    var html_rating="";
    for (var i = 0; i < 5; i++) {
        if (rating < (i + 0.5)) {
            html_rating += '✩';
        } else {
            html_rating += '✭';
        }
    }

    return html_rating;
}

<commit_msg>change user login and add display user review<commit_after>/**
 * Created by Jameshwart Villarmea Lopez on 4/7/2015.
 */

var x = document.getElementById("map_holder");
var map;
var infowindow;
var latlng;
var request;
var selected;
var sortyby ="PROMINENCE";
var place_details_sortbyprominence=[];
var place_details_sorbydistance = [];
$(document).ready(function () {

    $(".navbar-brand").click(function(){
        var p_id = "ChIJZz1DaxqZqTMRYZcdlmHube0";
        $.post("public/userAction/getPlaceReview.php",{placeid:p_id},function(data){
            if(data){
                user_place_review = data;
                var user_review = JSON.parse(data);
                console.log(JSON.stringify(user_review));
            }
        });
    });

    $(document).on("click",".add_review",function(){
        $("#frm_reviews").attr('andid','james');
    });
    $("#selecta").select2({
        placeholder: "Select Places...",
        allowClear: true,
        maximumSelectionLength: 3
    });

    $(document).on("change","#selecta",function(){
        selected = $("#selecta").select2("val");
        request = {
            location: latlng,
            radius:800,
            rankBy: google.maps.places.RankBy.PROMINENCE,
            types: selected
        };

    });

    $('#cmdSubmit').click(function () {
        $("#mnu_1,#your").css("display","block");
        place_details_sortbyprominence =[];
        place_details_sorbydistance = [];
        localStorage.removeItem("leloo_by_prominence");
        localStorage.removeItem("leloo_by_distance");
        if ($("#selecta").select2("val")) {
            $(this).hide();
            $("#noSubmit").show();

            getLocation();

            setTimeout(function () {
                $("#noSubmit").hide();
                $("#cmdSubmit").fadeIn();
            }, 2000)
        } else {
            $('#alert-msg').html("
 <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Ops! Please select place/s.
");

        }
    });

    $(".sortby").click(function(){
        $(".sortby").removeClass("active");
        $(this).addClass("active");

            if($(this).text() ==='Distance'){

                if("leloo_by_distance" in localStorage){
                    display_sorted_results(localStorage.getItem("leloo_by_distance"))
                }else{

                    if($("#selecta").select2("val")){
                        request.types=selected;
                        request.radius=null;
                        request.rankBy =google.maps.places.RankBy.DISTANCE;
                        getLocation();
                    }

                }

            }else if($(this).text() ==='Popularity'){

                if("leloo_by_prominence" in localStorage){

                    display_sorted_results(localStorage.getItem("leloo_by_prominence"))
                }else{
                    if($("#selecta").select2("val")){
                        request.types=selected;
                        request.radius=800;
                        request.rankBy =google.maps.places.RankBy.PROMINENCE;
                        getLocation();
                    }

                }
            }

    });
});

function getLocation() {
    //get current position
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {

    document.querySelector("#mapcanvas").style.height = '300px';
    latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

    var myOptions = {
        zoom: 15,
        center: latlng,
        mapTypeControl: false,
        navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL} ,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);

    var infowindowmain = new google.maps.InfoWindow({
        map: map,
        position: latlng,
        content: "You are here! (at least within a " + position.coords.accuracy + " meter radius)"
    });

    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: "You are here! (at least within a " + position.coords.accuracy + " meter radius)"
    });
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent("You are here! (at least within a " + position.coords.accuracy + " meter radius)");
        infowindow.open(map, this);
    });

    request.location = latlng;

    selected = $("#selecta").select2("val");
    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, callback);

    findhim(latlng);

}

function findhim(point) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({latLng: point}, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {

                var p_name = (results[0].name) ? "Place name: " + results[0].name + "
" : '';
                var p_address = (results[0].formatted_address) ? "
" + results[0].formatted_address + "
" : '';

                document.getElementById("location_container").innerHTML = p_name + p_address;
            }
        }
    });

}

function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
            if(checkRadiusDistance(results[i],latlng,825)){
                createMarker(results[i]);
            }
        }

        $('#alert-msg').html("
 <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Returned " + results.length + " results
");

        $("#mnu_2,#about,#h_place,#btn-group-places").css("display","block");
        $("#btn-group-places").css("display","inline-block");
    }
    else
    {
        $('#alert-msg').html("
 <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Returned " + results.length + " results
");
        $("#mnu_2,#about,#h_place,#btn-group-places").css("display","none");

    }
}

function checkRadiusDistance(place,latlng,radius) {
    return google.maps.geometry.spherical.computeDistanceBetween(place.geometry.location, latlng) <= radius;
}

function createMarker(place) {

    var placeLoc = place.geometry.location;

    var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
    });

    var requestdata = {
        placeId: place.place_id
    };

    document.getElementById("placeres").innerHTML="";
    var service = new google.maps.places.PlacesService(map);
    service.getDetails(requestdata, function(placedata, status) {

        if (status == google.maps.places.PlacesServiceStatus.OK)
        {

            if(request.rankBy === google.maps.places.RankBy.PROMINENCE){
                place_details_sortbyprominence.push((placedata));
                localStorage.setItem("leloo_by_prominence",JSON.stringify(place_details_sortbyprominence));
                display_sorted_results(localStorage.getItem("leloo_by_prominence"));

            }else if(request.rankBy === google.maps.places.RankBy.DISTANCE){
                place_details_sorbydistance.push((placedata));
                localStorage.setItem("leloo_by_distance",JSON.stringify(place_details_sorbydistance));
                display_sorted_results(localStorage.getItem("leloo_by_distance"));

            }

        }
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(getPlace_contenet(place));
        infowindow.open(map, this);
    });

}
function display_sorted_results(localstorage_data){

    var data = localstorage_data.replace(/"\\"/g,"'").replace(/\\""/g,"'");

    data = JSON.parse(data);
    document.getElementById("places").innerHTML="";
    document.getElementById("p_user_review").innerHTML="";
    var str_container = "";
    var u_review = "";
    for(var i = 0 ; i < data.length ; i++){

        var placedata= data[i];

        var place_name = "
"+placedata.name+"
";
        var place_address = "
"+placedata.formatted_address+"
";
        var place_img_representation = "";
        var place_internationa_phonenuber =(typeof placedata.international_phone_number !=='undefined')?"
"+placedata.international_phone_number +"
":"";

        var place_rating =(typeof placedata.rating !=='undefined')? "
Rating based on aggregated user reviews:"+rating_display(placedata.rating)+"
":"";
        var place_website =(typeof placedata.website !== 'undefined')? "
VISIT WEBSITE":"";

        var user_reviews = "";
        if(typeof placedata.reviews !=='undefined'){
            for(var j = 0 ; j < placedata.reviews.length; j ++){

                var place_reviews = placedata.reviews[j];
                var review_author = "
"+place_reviews.author_name+"
";
                var review_authorlink = (typeof place_reviews.author_url !=='undefined')? ""+review_author+"":""+review_author+"";
                var review_rating ="
Rating:"+ rating_display(place_reviews.rating)+"
";
                var review_text = "
"+place_reviews.text+"
";

                 user_reviews +="
"+review_authorlink+review_rating+review_text+"
";
            }
        }

        u_review +=(getUser_Review(placedata.place_id,place_name,place_address));
        var final_users_review = "
"+user_reviews+"
";
        str_container += "
 <button class='btn-primary add_review'  data-place_id= '"+placedata.place_id+"'> Add reviews</button></button>"+place_name+place_address+place_img_representation+place_internationa_phonenuber+place_rating+place_website + final_users_review +"
";

    }
    document.getElementById("p_user_review").innerHTML=u_review;

    document.getElementById("placeres").innerHTML=str_container;
}

function getUser_Review(placeid,place_name,place_address){
    var p_id = placeid;
    var u_review = "";

    $.ajax({
        method:"POST",
        url:"public/userAction/getPlaceReview.php",
        data:"placeid="+p_id,
        success:function(data){
                if(data){
                    $("#p_user_review").html("");
                    var db_user_review = JSON.parse(data);
                    for(i = 0 ;i < db_user_review.length; i++ ){
                        var db_author_review =  "
"+db_user_review[i].full_name+"
";
                        var db_rating_review =  "
Rating:"+ rating_display(db_user_review[i].rating)+"
";
                        var db_text_review   =  "
"+db_user_review[i].reviewtext+"
";

                        u_review +="
"+db_author_review+db_rating_review+db_text_review+"
";

                    }
                   var db_review = "
"+place_name+place_address+"
"+u_review+"

";

                    u_review = db_review;
                }
        },
        async:false
    });

    return u_review;

}

function getPlace_contenet(place) {
    var content = '';
    content += '
';
    content += '
';
    content += '	';
    var url=(typeof place.url !=='undefined')?place.url:'#';

    content += '' + place.name + '
';
    content += '
Address:	' + place.vicinity + '
';
    if (place.formatted_phone_number) {
        content += '
Telephone:	' + place.formatted_phone_number + '
';
    }

    if (place.rating) {
        rating_display(place.rating);
        content += '
Rating:	' +  rating_display(place.rating); + '
';

    }
    if (place.website) {
        var fullUrl = place.website;
        var website = hostnameRegexp.exec(place.website);
        if (website == null) {
            website = 'http://' + place.website + '/';
            fullUrl = website;
        }
        content += '
Website:	' + website + '
';
    }
    content += '
';
    return content;
}

function showError(error) {
    switch (error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}

function ucfirst(str) {
    var firstLetter = str.substr(0, 1);
    return firstLetter.toUpperCase() + str.substr(1);
}

function rating_display(rating){
    var html_rating="";
    for (var i = 0; i < 5; i++) {
        if (rating < (i + 0.5)) {
            html_rating += '✩';
        } else {
            html_rating += '✭';
        }
    }

    return html_rating;
}

<|endoftext|>


<commit_before>(function() {
    var showJSONDoc = function(studyContent){
        var doc = document, win = window,
            $ = function(id) { return doc.getElementById(id); },
            $$ = function(sel) { return doc.getElementsByTagName(sel); },
            $each = function(fn) { for (var i=0,len=this.length; i<len; i++) fn(i, this[i], this); };

        $.each = function(arr, fn) { $each.call(arr, fn); };

        var splitCase = function (t) { return typeof t != 'string' ? t : titleCase(t.replace(/([a-z0-9])([A-Z])/g, '$1 $2')); },
            titleCase = function (s) { return s.replace(/\w\S*/g, function (t) { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase(); }); },
            uniqueKeys = function(m){ var h={}; for (var i=0,len=m.length; i<len; i++) for (var k in m[i]) if (show(k)) h[k] = k; return h; },
            keys = function(o){ var a=[]; for (var k in o) if (show(k)) a.push(k); return a; };
        var tbls = [];

        function val(m) {
          if (m == null) return '';
          if (typeof m == 'number') return num(m);
          if (typeof m == 'string') return str(m);
          if (typeof m == 'boolean') return m ? 'true' : 'false';
          return m.length ? arr(m) : obj(m);
        };
        function num(m) { return m; };
        var sdfmt = location.hash.indexOf('show=') >=0 && location.hash.indexOf('fulldates') >= 0 ? dmft : dmfthm;
        function str(m){ return m.substr(0,6) == '/Date(' ? sdfmt(date(m)) : m.substr(0,4) == 'http' ? shref(m) : m; };
        function sfmt(s) { return humanize ? splitCase(s) : s; };
        function shref(s) { return humanize ? '' + s + '' : s; };
        function date(s) { return new Date(parseFloat(/Date\(([^)]+)\)/.exec(s)[1])); };
        function pad(d) { return d < 10 ? '0'+d : d; };
        function dmft(d) { return d.getFullYear() + '/' + pad(d.getMonth() + 1) + '/' + pad(d.getDate()); };
        function dmfthm(d) { return d.getFullYear() + '/' + pad(d.getMonth() + 1) + '/' + pad(d.getDate()) + ' ' + pad(d.getHours()) + ":" + pad(d.getMinutes()); };
        function show(k) { return typeof k != 'string' || k.substr(0,2) != '__'; };
        function obj(m) {
          var sb = '
';
          for (var k in m) if (show(k)) sb += '
' + sfmt(k) + '

' + val(m[k]) + '
';
          sb += '
';
          return sb;
        };
        function arr(m) {
          if (typeof m[0] == 'string' || typeof m[0] == 'number') return m.join(', ');
          var id=tbls.length, h=uniqueKeys(m);
          var sb = '

';
          tbls.push(m);
          var i=0;
          for (var k in h) sb += '' + sfmt(k) + '	';
          sb += '

' + makeRows(h,m) + '

';
          return sb;
        };

        function makeRows(h,m) {
          var sb = '';
          for (var r=0,len=m.length; r<len; r++) {
            sb += '
';
            var row = m[r];
            for (var k in h) if (show(k)) sb += '' + val(row[k]) + '	';
            sb += '
';
          }
          return sb;
        };

        var model = studyContent,
            txt = $$('TEXTAREA')[0],
            humanize = true && location.hash.indexOf('dehumanize') == -1,
            isIE = /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);

        $("content").innerHTML = val(model);
        txt.innerHTML=JSON.stringify(model);

        function showJson(){ doc.body.className='show-json'; txt.select(); txt.focus(); };

        doc.onclick = function(e) {
            e = e || window.event, el = e.target || e.srcElement, cls = el.className;
            if (el.tagName == 'B') el = el.parentNode;
            if (el.tagName != 'TH') return;
            el.className = cls == 'asc' ? 'desc' : (cls == 'desc' ? null : 'asc');
            $.each($$('TH'), function(i,th){ if (th == el) return; th.className = null; });
            clearSel();
            var ids=el.id.split('-'), tId=ids[1], cId=ids[2];
            if (!tbls[tId]) return;
            var tbl=tbls[tId].slice(0), h=uniqueKeys(tbl), col=keys(h)[cId], tbody=el.parentNode.parentNode.nextSibling;
            if (!el.className){ setTableBody(tbody, makeRows(h,tbls[tId])); return; }
            var d=el.className=='asc'?1:-1;
            tbl.sort(function(a,b){ return cmp(a[col],b[col]) * d; });
            setTableBody(tbody, makeRows(h,tbl));
        };

        function setTableBody(tbody, html) {
          if (!isIE) { tbody.innerHTML = html; return; }
          var temp = tbody.ownerDocument.createElement('div');
          temp.innerHTML = '
' + html + '
';
          tbody.parentNode.replaceChild(temp.firstChild.firstChild, tbody);
        };

        function clearSel() {
          if (doc.selection && doc.selection.empty) doc.selection.empty();
          else if(win.getSelection) {
            var sel=win.getSelection();
            if (sel && sel.removeAllRanges) sel.removeAllRanges();
          }
        };

        function cmp(v1, v2){
          var f1, f2, f1=parseFloat(v1), f2=parseFloat(v2);
          if (!isNaN(f1) && !isNaN(f2)) v1=f1, v2=f2;
          if (typeof v1 == 'string' && v1.substr(0,6) == '/Date(') v1=date(v1), v2=date(v2);
          if (v1 == v2) return 0;
          return v1 > v2 ? 1 : -1;
        };
    };
	var loadStudyForPosting = function(path){
		Stevenson.ui.Loader.display('Loading study ' +  path + ' for posting...', 500);
        Stevenson.log.info('Loading study ' +  path + ' for posting...');

        $.ajax({
            url: path,
            success: function (data){
                  var parts = data.split('---');
                if(parts.length == 3){
                    Stevenson.studyContent = parts[2];
                    Stevenson.ui.Loader.hide();
                    Stevenson.log.info('Study file: ' +  path + ' read.');
                    showJSONDoc(JSON.parse(Stevenson.studyContent));

               } else {
                    Stevenson.studyContent = parts[0];
                    Stevenson.log.warn('No YAML header found on study file');
                }
           },
            error: function (message){
						Stevenson.ui.Loader.hide();
						Stevenson.ui.Messages.displayError('Unable to load study file: ' + path + message);
					}
        });

        /*
		layoutsPathWOLastSlash = Stevenson.Account.layoutsPath.substring(0,Stevenson.Account.layoutsPath.lastIndexOf('/'));
		editorsPathWOLastSlash = Stevenson.Account.editorsPath.substring(0,Stevenson.Account.editorsPath.lastIndexOf('/'));
		schemasPathWOLastSlash = Stevenson.Account.schemasPath.substring(0,Stevenson.Account.schemasPath.lastIndexOf('/'));

		Stevenson.repo.getFiles({
			path: layoutsPathWOLastSlash, //'_layouts',
			success: function(layouts){
				$('#templates').html('');
				Stevenson.repo.getFiles({
					path: editorsPathWOLastSlash, //'_editors',
					success: function(editors){
						$.each(layouts, function(index, layout){
							if(layout.path.indexOf('_layouts') != -1 && layout.path != layoutsPathWOLastSlash){ //'_layouts'
								Stevenson.log.info('Adding layout: '+layout.path);
								var id = layout.path.replace('.html','').replace(Stevenson.Account.layoutsPath,'');
								layout.id = id;
								layout.templateurl = Stevenson.Account.siteBaseURL + '/cms/edit.html?editor=text#' + Stevenson.Account.layoutsPath + id + '.html';
								layout.editorurl = Stevenson.Account.siteBaseURL + '/cms/edit.html?new=true#' + Stevenson.Account.editorsPath + id + '.json'; //_editors/
								for(var i=0;i<editors.length;i++){
									if(editors[i].path ==Stevenson.Account.editorsPath + id+'.json'){ //'_editors/'
										layout.editorurl = Stevenson.Account.siteBaseURL + '/cms/edit.html#' + Stevenson.Account.editorsPath + id + '.json'; //_editors/
										break;
									}
								}

								layout.path = Stevenson.Account.siteBaseURL + '/' + layout.path;

								$('#templates').mustache('template', layout);
							}
						});
						Stevenson.ui.Loader.hide();
					},
					error: function(message){
						Stevenson.ui.Loader.hide();
						Stevenson.ui.Messages.displayError('Unable to load editors: ' + message);
					}
				});
			},
			error: function(message){
				Stevenson.ui.Loader.hide();
				Stevenson.ui.Messages.displayError('Unable to load templates: ' + message);
			}
		});

		Stevenson.repo.getFiles({
			path: Stevenson.Account.schemasPath, //'_schemas',
			success: function(schemas){
				$('#templates').html('');
				Stevenson.repo.getFiles({
					path: schemasPathWOLastSlash, //'_schemas',
					success: function(schemas){
						$.each(schemas, function(index, schema){
							if(schema.path.indexOf('_schemas') != -1 && schema.path != schemasPathWOLastSlash){ //'_schemas'
								Stevenson.log.info('Adding schema: '+schema.path);
								var id = schema.path.replace('.html','').replace(Stevenson.Account.schemasPath,''); //'_schemas/'
								schema.id = id;
								schema.schemaurl = Stevenson.Account.siteBaseURL + '/cms/edit.html?new=true#' + Stevenson.Account.schemasPath + id + '.json'; // _schemas/
								for(var i=0;i<schemas.length;i++){
									if(schemas[i].path == Stevenson.Account.schemasPath + id+'.json'){ //'_schemas/'
										schema.schemaurl = Stevenson.Account.siteBaseURL + '/cms/edit.html#' + Stevenson.Account.schemasPath + id + '.json'; //_schemas/
										break;
									}
								}

								schema.path = Stevenson.Account.siteBaseURL + '/' + schema.path;

								$('#templates').mustache('template', schema);
							}
						});
						Stevenson.ui.Loader.hide();
					},
					error: function(message){
						Stevenson.ui.Loader.hide();
						Stevenson.ui.Messages.displayError('Unable to load schemas: ' + message);
					}
				});
			},
			error: function(message){
				Stevenson.ui.Loader.hide();
				Stevenson.ui.Messages.displayError('Unable to load templates: ' + message);
			}
		});
        */
	};

	Stevenson.ext.beforeInit(function() {

		Stevenson.log.info('Initializing study file: ' + Stevenson.studyURL + ' for posting');
		loadStudyForPosting(Stevenson.studyURL);

	});
})(jQuery);

<commit_msg>- Try to use as function to make visible from html<commit_after>(function() {
    Stevenson.ext.showJSONDoc (function(studyContent){
        var doc = document, win = window,
            $ = function(id) { return doc.getElementById(id); },
            $$ = function(sel) { return doc.getElementsByTagName(sel); },
            $each = function(fn) { for (var i=0,len=this.length; i<len; i++) fn(i, this[i], this); };

        $.each = function(arr, fn) { $each.call(arr, fn); };

        var splitCase = function (t) { return typeof t != 'string' ? t : titleCase(t.replace(/([a-z0-9])([A-Z])/g, '$1 $2')); },
            titleCase = function (s) { return s.replace(/\w\S*/g, function (t) { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase(); }); },
            uniqueKeys = function(m){ var h={}; for (var i=0,len=m.length; i<len; i++) for (var k in m[i]) if (show(k)) h[k] = k; return h; },
            keys = function(o){ var a=[]; for (var k in o) if (show(k)) a.push(k); return a; };
        var tbls = [];

        function val(m) {
          if (m == null) return '';
          if (typeof m == 'number') return num(m);
          if (typeof m == 'string') return str(m);
          if (typeof m == 'boolean') return m ? 'true' : 'false';
          return m.length ? arr(m) : obj(m);
        };
        function num(m) { return m; };
        var sdfmt = location.hash.indexOf('show=') >=0 && location.hash.indexOf('fulldates') >= 0 ? dmft : dmfthm;
        function str(m){ return m.substr(0,6) == '/Date(' ? sdfmt(date(m)) : m.substr(0,4) == 'http' ? shref(m) : m; };
        function sfmt(s) { return humanize ? splitCase(s) : s; };
        function shref(s) { return humanize ? '' + s + '' : s; };
        function date(s) { return new Date(parseFloat(/Date\(([^)]+)\)/.exec(s)[1])); };
        function pad(d) { return d < 10 ? '0'+d : d; };
        function dmft(d) { return d.getFullYear() + '/' + pad(d.getMonth() + 1) + '/' + pad(d.getDate()); };
        function dmfthm(d) { return d.getFullYear() + '/' + pad(d.getMonth() + 1) + '/' + pad(d.getDate()) + ' ' + pad(d.getHours()) + ":" + pad(d.getMinutes()); };
        function show(k) { return typeof k != 'string' || k.substr(0,2) != '__'; };
        function obj(m) {
          var sb = '
';
          for (var k in m) if (show(k)) sb += '
' + sfmt(k) + '

' + val(m[k]) + '
';
          sb += '
';
          return sb;
        };
        function arr(m) {
          if (typeof m[0] == 'string' || typeof m[0] == 'number') return m.join(', ');
          var id=tbls.length, h=uniqueKeys(m);
          var sb = '

';
          tbls.push(m);
          var i=0;
          for (var k in h) sb += '' + sfmt(k) + '	';
          sb += '

' + makeRows(h,m) + '

';
          return sb;
        };

        function makeRows(h,m) {
          var sb = '';
          for (var r=0,len=m.length; r<len; r++) {
            sb += '
';
            var row = m[r];
            for (var k in h) if (show(k)) sb += '' + val(row[k]) + '	';
            sb += '
';
          }
          return sb;
        };

        var model = studyContent,
            txt = $$('TEXTAREA')[0],
            humanize = true && location.hash.indexOf('dehumanize') == -1,
            isIE = /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);

        $("content").innerHTML = val(model);
        txt.innerHTML=JSON.stringify(model);

        function showJson(){ doc.body.className='show-json'; txt.select(); txt.focus(); };

        doc.onclick = function(e) {
            e = e || window.event, el = e.target || e.srcElement, cls = el.className;
            if (el.tagName == 'B') el = el.parentNode;
            if (el.tagName != 'TH') return;
            el.className = cls == 'asc' ? 'desc' : (cls == 'desc' ? null : 'asc');
            $.each($$('TH'), function(i,th){ if (th == el) return; th.className = null; });
            clearSel();
            var ids=el.id.split('-'), tId=ids[1], cId=ids[2];
            if (!tbls[tId]) return;
            var tbl=tbls[tId].slice(0), h=uniqueKeys(tbl), col=keys(h)[cId], tbody=el.parentNode.parentNode.nextSibling;
            if (!el.className){ setTableBody(tbody, makeRows(h,tbls[tId])); return; }
            var d=el.className=='asc'?1:-1;
            tbl.sort(function(a,b){ return cmp(a[col],b[col]) * d; });
            setTableBody(tbody, makeRows(h,tbl));
        };

        function setTableBody(tbody, html) {
          if (!isIE) { tbody.innerHTML = html; return; }
          var temp = tbody.ownerDocument.createElement('div');
          temp.innerHTML = '
' + html + '
';
          tbody.parentNode.replaceChild(temp.firstChild.firstChild, tbody);
        };

        function clearSel() {
          if (doc.selection && doc.selection.empty) doc.selection.empty();
          else if(win.getSelection) {
            var sel=win.getSelection();
            if (sel && sel.removeAllRanges) sel.removeAllRanges();
          }
        };

        function cmp(v1, v2){
          var f1, f2, f1=parseFloat(v1), f2=parseFloat(v2);
          if (!isNaN(f1) && !isNaN(f2)) v1=f1, v2=f2;
          if (typeof v1 == 'string' && v1.substr(0,6) == '/Date(') v1=date(v1), v2=date(v2);
          if (v1 == v2) return 0;
          return v1 > v2 ? 1 : -1;
        };
    });
	var loadStudyForPosting = function(path){
		Stevenson.ui.Loader.display('Loading study ' +  path + ' for posting...', 500);
        Stevenson.log.info('Loading study ' +  path + ' for posting...');

        $.ajax({
            url: path,
            success: function (data){
                  var parts = data.split('---');
                if(parts.length == 3){
                    Stevenson.studyContent = parts[2];
                    Stevenson.ui.Loader.hide();
                    Stevenson.log.info('Study file: ' +  path + ' read.');
                    Stevenson.ext.showJSONDoc(JSON.parse(Stevenson.studyContent));

               } else {
                    Stevenson.studyContent = parts[0];
                    Stevenson.log.warn('No YAML header found on study file');
                }
           },
            error: function (message){
						Stevenson.ui.Loader.hide();
						Stevenson.ui.Messages.displayError('Unable to load study file: ' + path + message);
					}
        });

        /*
		layoutsPathWOLastSlash = Stevenson.Account.layoutsPath.substring(0,Stevenson.Account.layoutsPath.lastIndexOf('/'));
		editorsPathWOLastSlash = Stevenson.Account.editorsPath.substring(0,Stevenson.Account.editorsPath.lastIndexOf('/'));
		schemasPathWOLastSlash = Stevenson.Account.schemasPath.substring(0,Stevenson.Account.schemasPath.lastIndexOf('/'));

		Stevenson.repo.getFiles({
			path: layoutsPathWOLastSlash, //'_layouts',
			success: function(layouts){
				$('#templates').html('');
				Stevenson.repo.getFiles({
					path: editorsPathWOLastSlash, //'_editors',
					success: function(editors){
						$.each(layouts, function(index, layout){
							if(layout.path.indexOf('_layouts') != -1 && layout.path != layoutsPathWOLastSlash){ //'_layouts'
								Stevenson.log.info('Adding layout: '+layout.path);
								var id = layout.path.replace('.html','').replace(Stevenson.Account.layoutsPath,'');
								layout.id = id;
								layout.templateurl = Stevenson.Account.siteBaseURL + '/cms/edit.html?editor=text#' + Stevenson.Account.layoutsPath + id + '.html';
								layout.editorurl = Stevenson.Account.siteBaseURL + '/cms/edit.html?new=true#' + Stevenson.Account.editorsPath + id + '.json'; //_editors/
								for(var i=0;i<editors.length;i++){
									if(editors[i].path ==Stevenson.Account.editorsPath + id+'.json'){ //'_editors/'
										layout.editorurl = Stevenson.Account.siteBaseURL + '/cms/edit.html#' + Stevenson.Account.editorsPath + id + '.json'; //_editors/
										break;
									}
								}

								layout.path = Stevenson.Account.siteBaseURL + '/' + layout.path;

								$('#templates').mustache('template', layout);
							}
						});
						Stevenson.ui.Loader.hide();
					},
					error: function(message){
						Stevenson.ui.Loader.hide();
						Stevenson.ui.Messages.displayError('Unable to load editors: ' + message);
					}
				});
			},
			error: function(message){
				Stevenson.ui.Loader.hide();
				Stevenson.ui.Messages.displayError('Unable to load templates: ' + message);
			}
		});

		Stevenson.repo.getFiles({
			path: Stevenson.Account.schemasPath, //'_schemas',
			success: function(schemas){
				$('#templates').html('');
				Stevenson.repo.getFiles({
					path: schemasPathWOLastSlash, //'_schemas',
					success: function(schemas){
						$.each(schemas, function(index, schema){
							if(schema.path.indexOf('_schemas') != -1 && schema.path != schemasPathWOLastSlash){ //'_schemas'
								Stevenson.log.info('Adding schema: '+schema.path);
								var id = schema.path.replace('.html','').replace(Stevenson.Account.schemasPath,''); //'_schemas/'
								schema.id = id;
								schema.schemaurl = Stevenson.Account.siteBaseURL + '/cms/edit.html?new=true#' + Stevenson.Account.schemasPath + id + '.json'; // _schemas/
								for(var i=0;i<schemas.length;i++){
									if(schemas[i].path == Stevenson.Account.schemasPath + id+'.json'){ //'_schemas/'
										schema.schemaurl = Stevenson.Account.siteBaseURL + '/cms/edit.html#' + Stevenson.Account.schemasPath + id + '.json'; //_schemas/
										break;
									}
								}

								schema.path = Stevenson.Account.siteBaseURL + '/' + schema.path;

								$('#templates').mustache('template', schema);
							}
						});
						Stevenson.ui.Loader.hide();
					},
					error: function(message){
						Stevenson.ui.Loader.hide();
						Stevenson.ui.Messages.displayError('Unable to load schemas: ' + message);
					}
				});
			},
			error: function(message){
				Stevenson.ui.Loader.hide();
				Stevenson.ui.Messages.displayError('Unable to load templates: ' + message);
			}
		});
        */
	};

	Stevenson.ext.beforeInit(function() {

		Stevenson.log.info('Initializing study file: ' + Stevenson.studyURL + ' for posting');
		loadStudyForPosting(Stevenson.studyURL);

	});
})(jQuery);

<|endoftext|>


<commit_before>import Router from 'next/router';
import styled, { keyframes, css } from 'react-emotion';

import * as React from 'react';
import * as Utilities from '~/common/utilities';
import * as Constants from '~/common/constants';
import * as WindowUtils from '~/common/window';
import { VERSIONS, LATEST_VERSION } from '~/common/versions';

import navigation from '~/common/navigation';

import DocumentationHeader from '~/components/DocumentationHeader';
import DocumentationFooter from '~/components/DocumentationFooter';
import DocumentationPageLayout from '~/components/DocumentationPageLayout';
import DocumentationSidebar from '~/components/DocumentationSidebar';
import DocumentationNestedScrollLayout from '~/components/DocumentationNestedScrollLayout';
import Head from '~/components/Head';
import { H1 } from '~/components/base/headings';

const STYLES_DOCUMENT = css`
  padding: 24px 24px 24px 32px;

  hr {
    border-top: 1px solid ${Constants.colors.border};
    border-bottom: 0px;
  }

  @media screen and (max-width: ${Constants.breakpoints.mobile}) {
    padding: 32px 16px 48px 16px;
  }
`;

const STYLES_ALERT = css`
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 24px;
  line-height: 1.4;
  color: ${Constants.colors.white};
  background: ${Constants.colors.black};
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
`;

const STYLES_ALERT_BOLD = css`
  color: ${Constants.colors.white};
  font-family: ${Constants.fontFamilies.demi};
`;

const mutateRouteDataForRender = data => {
  data.forEach(element => {
    if (element.href) {
      element.as = Utilities.replaceVersionInUrl(element.href, 'latest');
    }

    if (element.posts) {
      mutateRouteDataForRender(element.posts);
    }
  });
};

export default class DocumentationPage extends React.Component {
  state = {
    isMenuActive: false,
  };

  componentDidMount() {
    Router.onRouteChangeStart = () => {
      if (this.refs.layout) {
        window.__sidebarScroll = this.refs.layout.getSidebarScrollTop();
      }
      window.NProgress.start();
    };

    Router.onRouteChangeComplete = () => {
      window.NProgress.done();
    };

    Router.onRouteChangeError = () => {
      window.NProgress.done();
    };

    window.addEventListener('resize', this._handleResize);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this._handleResize);
  }

  _handleResize = () => {
    // NOTE(jim): Handles switching between web and mobile layouts.
    const scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

    if (WindowUtils.getViewportSize().width >= Constants.breakpoints.mobileValue) {
      window.scrollTo(0, 0);
    }
  };

  _handleSetVersion = version => {
    this._version = version;
    let newPath = '/versions/' + version;

    // TODO: Find what's stripping trailing slashes from these
    if (version.startsWith('v')) {
      newPath += '/'
    }

    Router.push(newPath + '/');
  };

  _handleShowMenu = () => {
    this.setState({
      isMenuActive: true,
    });
  };

  _handleHideMenu = () => {
    this.setState({
      isMenuActive: false,
    });
  };

  render() {
    const sidebarScrollPosition = process.browser ? window.__sidebarScroll : 0;
    const canonicalUrl = `https://docs.expo.io${Utilities.replaceVersionInUrl(
      this.props.url.pathname,
      'latest'
    )}`;

    let version = (this.props.asPath || this.props.url.pathname).split(`/`)[2];
    if (!version || VERSIONS.indexOf(version) === -1) {
      version = VERSIONS[0];
    }
    this._version = version;

    const routes = navigation[version];

    const headerElement = (
      <DocumentationHeader
        pathname={this.props.url.pathname}
        version={this._version}
        isMenuActive={this.state.isMenuActive}
        isAlogiaSearchHidden={this.state.isMenuActive}
        onSetVersion={this._handleSetVersion}
        onShowMenu={this._handleShowMenu}
        onHideMenu={this._handleHideMenu}
      />
    );

    const sidebarElement = (
      <DocumentationSidebar url={this.props.url} asPath={this.props.asPath} routes={routes} />
    );

    console.log(this.props.title);

    return (
      <DocumentationNestedScrollLayout
        ref="layout"
        header={headerElement}
        sidebar={sidebarElement}
        isMenuActive={this.state.isMenuActive}
        sidebarScrollPosition={sidebarScrollPosition}>
        <Head title={`${this.props.title} - Expo Documentation`}>
          {version === 'unversioned' && <meta name="robots" content="noindex" />}
          {version !== 'unversioned' && <link rel="canonical" href={canonicalUrl} />}

        {!this.state.isMenuActive ? (

              Hey friend! We are co-hosting a
              conference with Software Mansion,{' '}

                learn more
              .

{this.props.title}

            {this.props.children}
            <DocumentationFooter />

        ) : (
          <DocumentationSidebar url={this.props.url} asPath={this.props.asPath} routes={routes} />
        )}
      </DocumentationNestedScrollLayout>
    );
  }
}
<commit_msg>[docs] Remove spurious console.log and unused imports<commit_after>import Router from 'next/router';
import { css } from 'react-emotion';

import * as React from 'react';
import * as Utilities from '~/common/utilities';
import * as Constants from '~/common/constants';
import * as WindowUtils from '~/common/window';
import { VERSIONS } from '~/common/versions';

import navigation from '~/common/navigation';

import DocumentationHeader from '~/components/DocumentationHeader';
import DocumentationFooter from '~/components/DocumentationFooter';
import DocumentationSidebar from '~/components/DocumentationSidebar';
import DocumentationNestedScrollLayout from '~/components/DocumentationNestedScrollLayout';
import Head from '~/components/Head';
import { H1 } from '~/components/base/headings';

const STYLES_DOCUMENT = css`
  padding: 24px 24px 24px 32px;

  hr {
    border-top: 1px solid ${Constants.colors.border};
    border-bottom: 0px;
  }

  @media screen and (max-width: ${Constants.breakpoints.mobile}) {
    padding: 32px 16px 48px 16px;
  }
`;

const STYLES_ALERT = css`
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 24px;
  line-height: 1.4;
  color: ${Constants.colors.white};
  background: ${Constants.colors.black};
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
`;

const STYLES_ALERT_BOLD = css`
  color: ${Constants.colors.white};
  font-family: ${Constants.fontFamilies.demi};
`;

const mutateRouteDataForRender = data => {
  data.forEach(element => {
    if (element.href) {
      element.as = Utilities.replaceVersionInUrl(element.href, 'latest');
    }

    if (element.posts) {
      mutateRouteDataForRender(element.posts);
    }
  });
};

export default class DocumentationPage extends React.Component {
  state = {
    isMenuActive: false,
  };

  componentDidMount() {
    Router.onRouteChangeStart = () => {
      if (this.refs.layout) {
        window.__sidebarScroll = this.refs.layout.getSidebarScrollTop();
      }
      window.NProgress.start();
    };

    Router.onRouteChangeComplete = () => {
      window.NProgress.done();
    };

    Router.onRouteChangeError = () => {
      window.NProgress.done();
    };

    window.addEventListener('resize', this._handleResize);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this._handleResize);
  }

  _handleResize = () => {
    // NOTE(jim): Handles switching between web and mobile layouts.
    const scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

    if (WindowUtils.getViewportSize().width >= Constants.breakpoints.mobileValue) {
      window.scrollTo(0, 0);
    }
  };

  _handleSetVersion = version => {
    this._version = version;
    let newPath = '/versions/' + version;

    // TODO: Find what's stripping trailing slashes from these
    if (version.startsWith('v')) {
      newPath += '/'
    }

    Router.push(newPath + '/');
  };

  _handleShowMenu = () => {
    this.setState({
      isMenuActive: true,
    });
  };

  _handleHideMenu = () => {
    this.setState({
      isMenuActive: false,
    });
  };

  render() {
    const sidebarScrollPosition = process.browser ? window.__sidebarScroll : 0;
    const canonicalUrl = `https://docs.expo.io${Utilities.replaceVersionInUrl(
      this.props.url.pathname,
      'latest'
    )}`;

    let version = (this.props.asPath || this.props.url.pathname).split(`/`)[2];
    if (!version || VERSIONS.indexOf(version) === -1) {
      version = VERSIONS[0];
    }
    this._version = version;

    const routes = navigation[version];

    const headerElement = (
      <DocumentationHeader
        pathname={this.props.url.pathname}
        version={this._version}
        isMenuActive={this.state.isMenuActive}
        isAlogiaSearchHidden={this.state.isMenuActive}
        onSetVersion={this._handleSetVersion}
        onShowMenu={this._handleShowMenu}
        onHideMenu={this._handleHideMenu}
      />
    );

    const sidebarElement = (
      <DocumentationSidebar url={this.props.url} asPath={this.props.asPath} routes={routes} />
    );

    return (
      <DocumentationNestedScrollLayout
        ref="layout"
        header={headerElement}
        sidebar={sidebarElement}
        isMenuActive={this.state.isMenuActive}
        sidebarScrollPosition={sidebarScrollPosition}>
        <Head title={`${this.props.title} - Expo Documentation`}>
          {version === 'unversioned' && <meta name="robots" content="noindex" />}
          {version !== 'unversioned' && <link rel="canonical" href={canonicalUrl} />}

        {!this.state.isMenuActive ? (

              Hey friend! We are co-hosting a
              conference with Software Mansion,{' '}

                learn more
              .

{this.props.title}

            {this.props.children}
            <DocumentationFooter />

        ) : (
          <DocumentationSidebar url={this.props.url} asPath={this.props.asPath} routes={routes} />
        )}
      </DocumentationNestedScrollLayout>
    );
  }
}
<|endoftext|>


<commit_before>/// <autosync enabled="true" />
/// <reference path="application/app.js" />
/// <reference path="application/controllers/bookaddctrl.js" />
/// <reference path="application/controllers/bookdetailsctrl.js" />
/// <reference path="application/controllers/bookeditctrl.js" />
/// <reference path="application/controllers/booklistctrl.js" />
/// <reference path="application/controllers/loginctrl.js" />
/// <reference path="application/controllers/profilectrl.js" />
/// <reference path="application/controllers/rootctrl.js" />
/// <reference path="application/controllers/studentaddctrl.js" />
/// <reference path="application/controllers/studentdetailsctrl.js" />
/// <reference path="application/controllers/studentlistctrl.js" />
/// <reference path="application/directives/directives.js" />
/// <reference path="application/services/api-service.js" />
/// <reference path="application/services/notifier-service.js" />
/// <reference path="jquery.raty.js" />
/// <reference path="application/controllers/homectrl.js" />
/// <reference path="morris.js" />
/// <reference path="raphael.js" />
/// <reference path="raphael-min.js" />
/// <reference path="jquery-2.1.0.js" />
/// <reference path="application/controllers/categoryctrl.js" />
/// <reference path="application/controllers/transactionctrl.js" />
/// <reference path="application/services/identity-service.js" />
/// <reference path="application/services/shared-service.js" />
/// <reference path="modernizr-2.7.2.js" />
/// <reference path="respond.matchmedia.addlistener.js" />
/// <reference path="respond.js" />
/// <reference path="angular-route.js" />
/// <reference path="angular.js" />
/// <reference path="angular-animate.js" />
/// <reference path="foundation.js" />
/// <reference path="foundation.offcanvas.js" />
/// <reference path="foundation.abide.js" />
/// <reference path="foundation.topbar.js" />
/// <reference path="foundation.reveal.js" />
/// <reference path="toastr.js" />
<commit_msg>_references.js updated<commit_after>/// <autosync enabled="true" />
/// <reference path="angular-animate.js" />
/// <reference path="angular-route.js" />
/// <reference path="angular.js" />
/// <reference path="foundation.abide.js" />
/// <reference path="foundation.js" />
/// <reference path="foundation.offcanvas.js" />
/// <reference path="foundation.reveal.js" />
/// <reference path="foundation.topbar.js" />
/// <reference path="jquery-2.1.0.js" />
/// <reference path="jquery.raty.js" />
/// <reference path="modernizr-2.7.2.js" />
/// <reference path="morris.js" />
/// <reference path="raphael-min.js" />
/// <reference path="raphael.js" />
/// <reference path="respond.js" />
/// <reference path="respond.matchmedia.addlistener.js" />
/// <reference path="toastr.js" />
/// <reference path="application/app.js" />
/// <reference path="application/controllers/bookaddctrl.js" />
/// <reference path="application/controllers/bookdetailsctrl.js" />
/// <reference path="application/controllers/bookeditctrl.js" />
/// <reference path="application/controllers/booklistctrl.js" />
/// <reference path="application/controllers/categoryctrl.js" />
/// <reference path="application/controllers/homectrl.js" />
/// <reference path="application/controllers/loginctrl.js" />
/// <reference path="application/controllers/profilectrl.js" />
/// <reference path="application/controllers/rootctrl.js" />
/// <reference path="application/controllers/studentaddctrl.js" />
/// <reference path="application/controllers/studentdetailsctrl.js" />
/// <reference path="application/controllers/studentlistctrl.js" />
/// <reference path="application/controllers/transactionctrl.js" />
/// <reference path="application/directives/directives.js" />
/// <reference path="application/services/api-service.js" />
/// <reference path="application/services/identity-service.js" />
/// <reference path="application/services/notifier-service.js" />
/// <reference path="application/services/shared-service.js" />
<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2018 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var Class = require('../../../utils/Class');
var Components = require('../../components');
var GameObject = require('../../GameObject');
var GetBitmapTextSize = require('../GetBitmapTextSize');
var Render = require('./DynamicBitmapTextRender');

/**
 * @callback DisplayCallback
 *
 * @param {object} display - [description]
 * @param {{topLeft:number,topRight:number,bottomLeft:number,bottomRight:number}} display.tint - [description]
 * @param {number} display.index - [description]
 * @param {number} display.charCode - [description]
 * @param {number} display.x - [description]
 * @param {number} display.y - [description]
 * @param {number} display.scale - [description]
 * @param {number} display.rotation - [description]
 * @param {[type]} display.data - [description]
 */

/**
 * @classdesc
 * [description]
 *
 * @class DynamicBitmapText
 * @extends Phaser.GameObjects.GameObject
 * @memberOf Phaser.GameObjects
 * @constructor
 * @since 3.0.0
 *
 * @extends Phaser.GameObjects.Components.Alpha
 * @extends Phaser.GameObjects.Components.BlendMode
 * @extends Phaser.GameObjects.Components.Depth
 * @extends Phaser.GameObjects.Components.Origin
 * @extends Phaser.GameObjects.Components.Pipeline
 * @extends Phaser.GameObjects.Components.ScrollFactor
 * @extends Phaser.GameObjects.Components.Texture
 * @extends Phaser.GameObjects.Components.Tint
 * @extends Phaser.GameObjects.Components.Transform
 * @extends Phaser.GameObjects.Components.Visible
 *
 * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. It can only belong to one Scene at any given time.
 * @param {number} x - The x coordinate of this Game Object in world space.
 * @param {number} y - The y coordinate of this Game Object in world space.
 * @param {string} font - [description]
 * @param {(string|string[])} [text] - [description]
 * @param {number} [size] - [description]
 */
var DynamicBitmapText = new Class({

    Extends: GameObject,

    Mixins: [
        Components.Alpha,
        Components.BlendMode,
        Components.Depth,
        Components.Origin,
        Components.Pipeline,
        Components.ScrollFactor,
        Components.Texture,
        Components.Tint,
        Components.Transform,
        Components.Visible,
        Render
    ],

    initialize:

    function DynamicBitmapText (scene, x, y, font, text, size)
    {
        if (text === undefined) { text = ''; }

        GameObject.call(this, scene, 'DynamicBitmapText');

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#font
         * @type {string}
         * @since 3.0.0
         */
        this.font = font;

        var entry = this.scene.sys.cache.bitmapFont.get(font);

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#fontData
         * @type {object}
         * @since 3.0.0
         */
        this.fontData = entry.data;

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#text
         * @type {string}
         * @since 3.0.0
         */
        this.text = (Array.isArray(text)) ? text.join('\n') : text;

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#fontSize
         * @type {number}
         * @since 3.0.0
         */
        this.fontSize = size || this.fontData.size;

        this.setTexture(entry.texture, entry.frame);
        this.setPosition(x, y);
        this.setOrigin(0, 0);
        this.initPipeline('TextureTintPipeline');

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#_bounds
         * @type {TextBounds}
         * @private
         * @since 3.0.0
         */
        this._bounds = this.getTextBounds();

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#scrollX
         * @type {number}
         * @default 0
         * @since 3.0.0
         */
        this.scrollX = 0;

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#scrollY
         * @type {number}
         * @default 0
         * @since 3.0.0
         */
        this.scrollY = 0;

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#cropWidth
         * @type {number}
         * @default 0
         * @since 3.0.0
         */
        this.cropWidth = 0;

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#cropHeight
         * @type {number}
         * @default 0
         * @since 3.0.0
         */
        this.cropHeight = 0;

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#displayCallback;
         * @type {DisplayCallback}
         * @since 3.0.0
         */
        this.displayCallback;
    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#setSize
     * @since 3.0.0
     *
     * @param {number} width - [description]
     * @param {number} height - [description]
     *
     * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object.
     */
    setSize: function (width, height)
    {
        this.cropWidth = width;
        this.cropHeight = height;

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#setDisplayCallback
     * @since 3.0.0
     *
     * @param {DisplayCallback} callback - [description]
     *
     * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object.
     */
    setDisplayCallback: function (callback)
    {
        this.displayCallback = callback;

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#setFontSize
     * @since 3.0.0
     *
     * @param {number} size - [description]
     *
     * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object.
     */
    setFontSize: function (size)
    {
        this.fontSize = size;

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#setText
     * @since 3.0.0
     *
     * @param {(string|string[])} value - The string, or array of strings, to be set as the content of this BitmapText.
     *
     * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object.
     */
    setText: function (value)
    {
        if (!value && value !== 0)
        {
            value = '';
        }

        if (Array.isArray(value))
        {
            value = value.join('\n');
        }

        if (value !== this.text)
        {
            this.text = value.toString();

            this.updateDisplayOrigin();
        }

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#setScrollX
     * @since 3.0.0
     *
     * @param {number} value - [description]
     *
     * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object.
     */
    setScrollX: function (value)
    {
        this.scrollX = value;

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#setScrollY
     * @since 3.0.0
     *
     * @param {number} value - [description]
     *
     * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object.
     */
    setScrollY: function (value)
    {
        this.scrollY = value;

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#getTextBounds
     * @since 3.0.0
     *
     * @param {boolean} round - [description]
     *
     * @return {TextBounds} [description]
     */
    getTextBounds: function (round)
    {
        //  local = the BitmapText based on fontSize and 0x0 coords
        //  global = the BitmapText, taking into account scale and world position

        this._bounds = GetBitmapTextSize(this, round);

        return this._bounds;
    },

    /**
     * [description]
     *
     * @name Phaser.GameObjects.DynamicBitmapText#width
     * @type {number}
     * @since 3.0.0
     */
    width: {

        get: function ()
        {
            this.getTextBounds(false);
            return this._bounds.global.width;
        }

    },

    /**
     * [description]
     *
     * @name Phaser.GameObjects.DynamicBitmapText#height
     * @type {number}
     * @since 3.0.0
     */
    height: {

        get: function ()
        {
            this.getTextBounds(false);
            return this._bounds.global.height;
        }

    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#toJSON
     * @since 3.0.0
     *
     * @return {JSONGameObject.<JSONBitmapText>} [description]
     */
    toJSON: function ()
    {
        var out = Components.ToJSON(this);

        //  Extra data is added here

        var data = {
            font: this.font,
            text: this.text,
            fontSize: this.fontSize
        };

        out.data = data;

        return out;
    }

});

module.exports = DynamicBitmapText;
<commit_msg>Add missing letterSpacing to DynamicBitmapText<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2018 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var Class = require('../../../utils/Class');
var Components = require('../../components');
var GameObject = require('../../GameObject');
var GetBitmapTextSize = require('../GetBitmapTextSize');
var Render = require('./DynamicBitmapTextRender');

/**
 * @callback DisplayCallback
 *
 * @param {object} display - [description]
 * @param {{topLeft:number,topRight:number,bottomLeft:number,bottomRight:number}} display.tint - [description]
 * @param {number} display.index - [description]
 * @param {number} display.charCode - [description]
 * @param {number} display.x - [description]
 * @param {number} display.y - [description]
 * @param {number} display.scale - [description]
 * @param {number} display.rotation - [description]
 * @param {[type]} display.data - [description]
 */

/**
 * @classdesc
 * [description]
 *
 * @class DynamicBitmapText
 * @extends Phaser.GameObjects.GameObject
 * @memberOf Phaser.GameObjects
 * @constructor
 * @since 3.0.0
 *
 * @extends Phaser.GameObjects.Components.Alpha
 * @extends Phaser.GameObjects.Components.BlendMode
 * @extends Phaser.GameObjects.Components.Depth
 * @extends Phaser.GameObjects.Components.Origin
 * @extends Phaser.GameObjects.Components.Pipeline
 * @extends Phaser.GameObjects.Components.ScrollFactor
 * @extends Phaser.GameObjects.Components.Texture
 * @extends Phaser.GameObjects.Components.Tint
 * @extends Phaser.GameObjects.Components.Transform
 * @extends Phaser.GameObjects.Components.Visible
 *
 * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. It can only belong to one Scene at any given time.
 * @param {number} x - The x coordinate of this Game Object in world space.
 * @param {number} y - The y coordinate of this Game Object in world space.
 * @param {string} font - [description]
 * @param {(string|string[])} [text] - [description]
 * @param {number} [size] - [description]
 */
var DynamicBitmapText = new Class({

    Extends: GameObject,

    Mixins: [
        Components.Alpha,
        Components.BlendMode,
        Components.Depth,
        Components.Origin,
        Components.Pipeline,
        Components.ScrollFactor,
        Components.Texture,
        Components.Tint,
        Components.Transform,
        Components.Visible,
        Render
    ],

    initialize:

    function DynamicBitmapText (scene, x, y, font, text, size)
    {
        if (text === undefined) { text = ''; }

        GameObject.call(this, scene, 'DynamicBitmapText');

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#font
         * @type {string}
         * @since 3.0.0
         */
        this.font = font;

        var entry = this.scene.sys.cache.bitmapFont.get(font);

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#fontData
         * @type {object}
         * @since 3.0.0
         */
        this.fontData = entry.data;

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#text
         * @type {string}
         * @since 3.0.0
         */
        this.text = (Array.isArray(text)) ? text.join('\n') : text;

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#fontSize
         * @type {number}
         * @since 3.0.0
         */
        this.fontSize = size || this.fontData.size;

        /**
         * Adds/Removes spacing between characters
         * Can be a negative or positive number
         *
         * @name Phaser.GameObjects.DynamicBitmapText#letterSpacing
         * @type {number}
         * @since 3.4.1
         */
        this.letterSpacing = 0;

        this.setTexture(entry.texture, entry.frame);
        this.setPosition(x, y);
        this.setOrigin(0, 0);
        this.initPipeline('TextureTintPipeline');

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#_bounds
         * @type {TextBounds}
         * @private
         * @since 3.0.0
         */
        this._bounds = this.getTextBounds();

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#scrollX
         * @type {number}
         * @default 0
         * @since 3.0.0
         */
        this.scrollX = 0;

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#scrollY
         * @type {number}
         * @default 0
         * @since 3.0.0
         */
        this.scrollY = 0;

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#cropWidth
         * @type {number}
         * @default 0
         * @since 3.0.0
         */
        this.cropWidth = 0;

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#cropHeight
         * @type {number}
         * @default 0
         * @since 3.0.0
         */
        this.cropHeight = 0;

        /**
         * [description]
         *
         * @name Phaser.GameObjects.DynamicBitmapText#displayCallback;
         * @type {DisplayCallback}
         * @since 3.0.0
         */
        this.displayCallback;
    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#setSize
     * @since 3.0.0
     *
     * @param {number} width - [description]
     * @param {number} height - [description]
     *
     * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object.
     */
    setSize: function (width, height)
    {
        this.cropWidth = width;
        this.cropHeight = height;

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#setDisplayCallback
     * @since 3.0.0
     *
     * @param {DisplayCallback} callback - [description]
     *
     * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object.
     */
    setDisplayCallback: function (callback)
    {
        this.displayCallback = callback;

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#setFontSize
     * @since 3.0.0
     *
     * @param {number} size - [description]
     *
     * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object.
     */
    setFontSize: function (size)
    {
        this.fontSize = size;

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#setText
     * @since 3.0.0
     *
     * @param {(string|string[])} value - The string, or array of strings, to be set as the content of this BitmapText.
     *
     * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object.
     */
    setText: function (value)
    {
        if (!value && value !== 0)
        {
            value = '';
        }

        if (Array.isArray(value))
        {
            value = value.join('\n');
        }

        if (value !== this.text)
        {
            this.text = value.toString();

            this.updateDisplayOrigin();
        }

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#setScrollX
     * @since 3.0.0
     *
     * @param {number} value - [description]
     *
     * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object.
     */
    setScrollX: function (value)
    {
        this.scrollX = value;

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#setScrollY
     * @since 3.0.0
     *
     * @param {number} value - [description]
     *
     * @return {Phaser.GameObjects.DynamicBitmapText} This Game Object.
     */
    setScrollY: function (value)
    {
        this.scrollY = value;

        return this;
    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#getTextBounds
     * @since 3.0.0
     *
     * @param {boolean} round - [description]
     *
     * @return {TextBounds} [description]
     */
    getTextBounds: function (round)
    {
        //  local = the BitmapText based on fontSize and 0x0 coords
        //  global = the BitmapText, taking into account scale and world position

        this._bounds = GetBitmapTextSize(this, round);

        return this._bounds;
    },

    /**
     * [description]
     *
     * @name Phaser.GameObjects.DynamicBitmapText#width
     * @type {number}
     * @since 3.0.0
     */
    width: {

        get: function ()
        {
            this.getTextBounds(false);
            return this._bounds.global.width;
        }

    },

    /**
     * [description]
     *
     * @name Phaser.GameObjects.DynamicBitmapText#height
     * @type {number}
     * @since 3.0.0
     */
    height: {

        get: function ()
        {
            this.getTextBounds(false);
            return this._bounds.global.height;
        }

    },

    /**
     * [description]
     *
     * @method Phaser.GameObjects.DynamicBitmapText#toJSON
     * @since 3.0.0
     *
     * @return {JSONGameObject.<JSONBitmapText>} [description]
     */
    toJSON: function ()
    {
        var out = Components.ToJSON(this);

        //  Extra data is added here

        var data = {
            font: this.font,
            text: this.text,
            fontSize: this.fontSize
        };

        out.data = data;

        return out;
    }

});

module.exports = DynamicBitmapText;
<|endoftext|>


<commit_before>class ExDate {
    now() {
        return Date.now();
    }
}

class Engine {
    constructor(date) {
        var now = date.now();
        this.Date = date;
        this.count = 0;
        this.FPS = 60;
        this.instanciated_at = now;
        this.last_updated_at = now;
        this.callback = null;
    }

    start() {
        var lag = 0;
        const MPU = 1000 / this.FPS;
        const LIMIT_LAG = 1000 * MPU;
        var loop = function(){
            if(0 <= this.count){
                setTimeout(loop, MPU);
                this.count++;
            }
            var now = this.Date.now();
            var elapsed = now - this.lastUpdated_at;
            this.lastUpdated_at = now;
            lag += elapsed;
            if(LIMIT_LAG < lag){
                lag = 0;
                return;
            }
            while(MPU <= lag){
                this.update();
                lag -= MPU;
            }
            this.render(lag / MPU);
            if (this.count % this.FPS === 0) {
                this.callback(this);
            }
        }.bind(this);
        loop();
    }

    update() {
    }

    render(delta) {
    }

    add_callback(callback) {
        this.callback = callback;
    }

}

class TokenBucket {
    constructor(max_token) {
        this.b = max_token;
        this.token = max_token;
    }

    add_token() {
        if (this.token < this.b) {
            this.token += 1;
            return true;
        }
        return false;
    }

    remove_token(n) {
        if (0 <= this.token - n) {
            this.token -= n;
            return true;
        }
        return false;
    }

    update() {
        return this.add_token();
    }
}

// main
var h1 = document.createElement("h1")
document.body.appendChild(h1);

var engine = new Engine(new ExDate());
engine.add_callback(function(engine){
    var value = this.lastUpdated_at - this.instanciated_at;
    h1.innerText = "time:" + value;
});
engine.start();
<commit_msg>Update<commit_after>class ExDate {
    now() {
        return Date.now();
    }
}

class Engine {
    constructor(date) {
        var now = date.now();
        this.Date = date;
        this.count = 0;
        this.FPS = 60;
        this.instanciated_at = now;
        this.last_updated_at = now;
        this.callback = null;
    }

    start() {
        var lag = 0;
        const MPU = 1000 / this.FPS;
        const LIMIT_LAG = 1000 * MPU;
        var loop = function(){
            if(0 <= this.count){
                setTimeout(loop, MPU);
                this.count++;
            }
            var now = this.Date.now();
            var elapsed = now - this.lastUpdated_at;
            this.lastUpdated_at = now;
            lag += elapsed;
            if(LIMIT_LAG < lag){
                lag = 0;
                return;
            }
            while(MPU <= lag){
                this.update();
                lag -= MPU;
            }
            this.render(lag / MPU);
            if (this.count % this.FPS === 0) {
                this.callback(this);
            }
        }.bind(this);
        loop();
    }

    update() {
    }

    render(delta) {
    }

    add_callback(callback) {
        this.callback = callback;
    }

}

class TokenBucket {
    constructor(max_token) {
        this.b = max_token;
        this.token = max_token;
    }

    add_token() {
        if (this.token < this.b) {
            this.token += 1;
            return true;
        }
        return false;
    }

    remove_token(n) {
        if (0 <= this.token - n) {
            this.token -= n;
            return true;
        }
        return false;
    }
}

var h1 = document.createElement("h1")
document.body.appendChild(h1);

var engine = new Engine(new ExDate());
engine.add_callback(function(engine){
    var value = this.lastUpdated_at - this.instanciated_at;
    h1.innerText = "time:" + value;
});
engine.start();
<|endoftext|>


<commit_before>const axios = require("axios");

exports.handler = async (event, context) => {
  const MP_KEY = process.env
  const email = event.queryStringParameters.email

  Promise.all([
    axios.get(`https://www.mountainproject.com/data/get-ticks?email=${email}&key=${MP_KEY}`),
    axios.get(`https://www.mountainproject.com/data/get-user?email=${email}&key=${MP_KEY}`)
  ]).then(([ticksResponse, userResponse]) => {
    return { statusCode: 200, body: JSON.stringify({ name: userResponse.data.name, ticks:  ticksResponse.data.ticks }) }
  }, (error) => {
    return { statusCode: 500, body: JSON.stringify({ error: error}) }
  });
}
<commit_msg>Fix get-mp-ticks function<commit_after>const axios = require("axios");

exports.handler = async (event, context) => {
  try {
    const MP_KEY = process.env
    const email = event.queryStringParameters.email || ""

    if(email) {
      const [ticksResponse, userResponse] = await Promise.all([
        axios.get(`https://www.mountainproject.com/data/get-ticks?email=${email}&key=${MP_KEY}`),
        axios.get(`https://www.mountainproject.com/data/get-user?email=${email}&key=${MP_KEY}`)
      ])
      if(userResponse.data) {
        return { statusCode: 200, body: JSON.stringify({ name: userResponse.data.name, ticks: ticksResponse.data }) }
      } else {
        return { statusCode: 500, body: JSON.stringify({ error: 'Email not found'}) }
      }
    } else {
      return { statusCode: 500, body: JSON.stringify({ error: 'Email not specified'}) }
    }
  } catch (err) {
    return { statusCode: 500, body: err.toString() }
  }
}
<|endoftext|>