<commit_before>// https://github.com/kvz/phpjs/blob/master/functions/var/unserialize.js
function unserialize (data) {
    var that = this,
    utf8Overhead = function (chr) {
        // http://phpjs.org/functions/unserialize:571#comment_95906
        var code = chr.charCodeAt(0);
        if (code < 0x0080) {
            return 0;
        }
        if (code < 0x0800) {
            return 1;
        }
        return 2;
    },
    error = function (type, msg, filename, line) {
        throw new that.window[type](msg, filename, line);
    },
    read_until = function (data, offset, stopchr) {
        var i = 2, buf = [], chr = data.slice(offset, offset + 1);

        while (chr != stopchr) {
            if ((i + offset) > data.length) {
                error('Error', 'Invalid');
            }
            buf.push(chr);
            chr = data.slice(offset + (i - 1), offset + i);
            i += 1;
        }
        return [buf.length, buf.join('')];
    },
    read_chrs = function (data, offset, length) {
        var i, chr, buf;

        buf = [];
        for (i = 0; i < length; i++) {
            chr = data.slice(offset + (i - 1), offset + i);
            buf.push(chr);
            length -= utf8Overhead(chr);
        }
        return [buf.length, buf.join('')];
    },
    _unserialize = function (data, offset) {
        var dtype, dataoffset, keyandchrs, keys,
        readdata, readData, ccount, stringlength,
        i, key, kprops, kchrs, vprops, vchrs, value,
        chrs = 0,
        typeconvert = function (x) {
            return x;
        };

        if (!offset) {
            offset = 0;
        }
        dtype = (data.slice(offset, offset + 1)).toLowerCase();

        dataoffset = offset + 2;

        switch (dtype) {
            case 'i':
                typeconvert = function (x) {
                    return parseInt(x, 10);
                };
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
                break;
            case 'b':
                typeconvert = function (x) {
                    return parseInt(x, 10) !== 0;
                };
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
                break;
            case 'd':
                typeconvert = function (x) {
                    return parseFloat(x);
                };
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
                break;
            case 'n':
                readdata = null;
                break;
            case 's':
                ccount = read_until(data, dataoffset, ':');
                chrs = ccount[0];
                stringlength = ccount[1];
                dataoffset += chrs + 2;

                readData = read_chrs(data, dataoffset + 1, parseInt(stringlength, 10));
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 2;
                if (chrs != parseInt(stringlength, 10) && chrs != readdata.length) {
                    error('SyntaxError', 'String length mismatch');
                }
                break;
            case 'a':
                readdata = {};

                keyandchrs = read_until(data, dataoffset, ':');
                chrs = keyandchrs[0];
                keys = keyandchrs[1];
                dataoffset += chrs + 2;

                for (i = 0; i < parseInt(keys, 10); i++) {
                    kprops = _unserialize(data, dataoffset);
                    kchrs = kprops[1];
                    key = kprops[2];
                    dataoffset += kchrs;

                    vprops = _unserialize(data, dataoffset);
                    vchrs = vprops[1];
                    value = vprops[2];
                    dataoffset += vchrs;

                    readdata[key] = value;
                }

                dataoffset += 1;
                break;
            default:
                error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype);
                break;
        }
        return [dtype, dataoffset - offset, typeconvert(readdata)];
    }
    ;

    return _unserialize((data + ''), 0)[2];
}

jQuery(document).ready(function() {
	jQuery(".nav-main").naver();

    if ((jQuery('.cesta').length>0) && (fik_cart_name.length>0)) {
        if (typeof jQuery.cookie(fik_cart_name) != 'undefined') {
            var cart = unserialize(decodeURIComponent(jQuery.cookie(fik_cart_name)));
            var itemsQuantity = 0;
            jQuery.each( cart.items, function( key, value ) {
                itemsQuantity = itemsQuantity + cart.items[key].quantity * 1 ;
            });
            if (itemsQuantity > 0){
                jQuery('.cesta').append(' (' + itemsQuantity + ')');
            }
        }
    }

    jQuery("input[name='ns_widget_mailchimp_email']").attr("placeholder", "Email");

    jQuery(".dropdown-toggle").click(function(e){
        e.preventDefault();
    }
    );

    jQuery( ".closepopup" ).click(function() {
        jQuery('.popup').remove();
    });

});

<commit_msg>Add glide JS<commit_after>// https://github.com/kvz/phpjs/blob/master/functions/var/unserialize.js
function unserialize (data) {
    var that = this,
    utf8Overhead = function (chr) {
        // http://phpjs.org/functions/unserialize:571#comment_95906
        var code = chr.charCodeAt(0);
        if (code < 0x0080) {
            return 0;
        }
        if (code < 0x0800) {
            return 1;
        }
        return 2;
    },
    error = function (type, msg, filename, line) {
        throw new that.window[type](msg, filename, line);
    },
    read_until = function (data, offset, stopchr) {
        var i = 2, buf = [], chr = data.slice(offset, offset + 1);

        while (chr != stopchr) {
            if ((i + offset) > data.length) {
                error('Error', 'Invalid');
            }
            buf.push(chr);
            chr = data.slice(offset + (i - 1), offset + i);
            i += 1;
        }
        return [buf.length, buf.join('')];
    },
    read_chrs = function (data, offset, length) {
        var i, chr, buf;

        buf = [];
        for (i = 0; i < length; i++) {
            chr = data.slice(offset + (i - 1), offset + i);
            buf.push(chr);
            length -= utf8Overhead(chr);
        }
        return [buf.length, buf.join('')];
    },
    _unserialize = function (data, offset) {
        var dtype, dataoffset, keyandchrs, keys,
        readdata, readData, ccount, stringlength,
        i, key, kprops, kchrs, vprops, vchrs, value,
        chrs = 0,
        typeconvert = function (x) {
            return x;
        };

        if (!offset) {
            offset = 0;
        }
        dtype = (data.slice(offset, offset + 1)).toLowerCase();

        dataoffset = offset + 2;

        switch (dtype) {
            case 'i':
                typeconvert = function (x) {
                    return parseInt(x, 10);
                };
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
                break;
            case 'b':
                typeconvert = function (x) {
                    return parseInt(x, 10) !== 0;
                };
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
                break;
            case 'd':
                typeconvert = function (x) {
                    return parseFloat(x);
                };
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
                break;
            case 'n':
                readdata = null;
                break;
            case 's':
                ccount = read_until(data, dataoffset, ':');
                chrs = ccount[0];
                stringlength = ccount[1];
                dataoffset += chrs + 2;

                readData = read_chrs(data, dataoffset + 1, parseInt(stringlength, 10));
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 2;
                if (chrs != parseInt(stringlength, 10) && chrs != readdata.length) {
                    error('SyntaxError', 'String length mismatch');
                }
                break;
            case 'a':
                readdata = {};

                keyandchrs = read_until(data, dataoffset, ':');
                chrs = keyandchrs[0];
                keys = keyandchrs[1];
                dataoffset += chrs + 2;

                for (i = 0; i < parseInt(keys, 10); i++) {
                    kprops = _unserialize(data, dataoffset);
                    kchrs = kprops[1];
                    key = kprops[2];
                    dataoffset += kchrs;

                    vprops = _unserialize(data, dataoffset);
                    vchrs = vprops[1];
                    value = vprops[2];
                    dataoffset += vchrs;

                    readdata[key] = value;
                }

                dataoffset += 1;
                break;
            default:
                error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype);
                break;
        }
        return [dtype, dataoffset - offset, typeconvert(readdata)];
    }
    ;

    return _unserialize((data + ''), 0)[2];
}

jQuery(document).ready(function() {
	jQuery(".nav-main").naver();

    if ((jQuery('.cesta').length>0) && (fik_cart_name.length>0)) {
        if (typeof jQuery.cookie(fik_cart_name) != 'undefined') {
            var cart = unserialize(decodeURIComponent(jQuery.cookie(fik_cart_name)));
            var itemsQuantity = 0;
            jQuery.each( cart.items, function( key, value ) {
                itemsQuantity = itemsQuantity + cart.items[key].quantity * 1 ;
            });
            if (itemsQuantity > 0){
                jQuery('.cesta').append(' (' + itemsQuantity + ')');
            }
        }
    }

    jQuery("input[name='ns_widget_mailchimp_email']").attr("placeholder", "Email");

    jQuery(".dropdown-toggle").click(function(e){
        e.preventDefault();
    }
    );

    jQuery( ".closepopup" ).click(function() {
        jQuery('.popup').remove();
    });

    var glide = jQuery('.slider').glide({
        afterTransition: function() {
            var currentSlide = this.currentSlide;
        }
    }).data('api_glide');

});

<|endoftext|>


<commit_before>$(document).ready(function() {
    $('a.abstract').click(function() {
        $(this).parent().parent().find(".abstract.hidden").toggleClass('open');
    });
    $('a.bibtex').click(function() {
        $(this).parent().parent().find(".bibtex.hidden").toggleClass('open');
    });
});
<commit_msg>Delete common.js<commit_after><|endoftext|>


<commit_before>import domselect from 'dom-select'

const config = {

	BASE: '/',

	body: document.body,
	view: domselect('main'),

	width: window.innerWidth,
	height: window.innerHeight,

    infos: null
}

export default config<commit_msg>add commandHistory as empty array to config.js<commit_after>import domselect from 'dom-select'

const config = {

	BASE: '/',

	body: document.body,
	view: domselect('main'),

	width: window.innerWidth,
	height: window.innerHeight,

  infos: null,

	commandHistory: []
}

export default config
<|endoftext|>


<commit_before>/**
	* Template Name: Eventoz
	* Version: 1.0
	* Template Scripts
	* Author: MarkUps
	* Author URI: http://www.markups.io/

	Custom JS

	1. FIXED MENU
	2. EVENT TIME COUNTER
	3. MENU SMOOTH SCROLLING
	4. VIDEO POPUP
	5. SPEAKERS SLIDEER ( SLICK SLIDER )
	6. BOOTSTRAP ACCORDION
	7. MOBILE MENU CLOSE

**/

(function( $ ){

	/* ----------------------------------------------------------- */
	/*  1. FIXED MENU
	/* ----------------------------------------------------------- */

	jQuery(window).bind('scroll', function () {
    if ($(window).scrollTop() > 150) {
        $('.mu-navbar').addClass('mu-nav-show');

	    } else {
	        $('.mu-navbar').removeClass('mu-nav-show');
	    }
	});

	/* ----------------------------------------------------------- */
	/*  2. EVENT TIME COUNTER
	/* ----------------------------------------------------------- */

	$('#mu-event-counter').countdown('2019/03/15').on('update.countdown', function(event) {
	  var $this = $(this).html(event.strftime(''
	    + '%D Days '
	    + '%H Hours '
	    + '%M Mins '
	    + '%S Secs'));
	});

    /* ----------------------------------------------------------- */
	/*  3. MENU SMOOTH SCROLLING
	/* ----------------------------------------------------------- */

	 //MENU SCROLLING WITH ACTIVE ITEM SELECTED

	// Cache selectors
	var lastId,
	topMenu = $(".mu-menu"),
	topMenuHeight = topMenu.outerHeight()+13,
	// All list items
	menuItems = topMenu.find('a[href^=\\#]'),
	// Anchors corresponding to menu items
	scrollItems = menuItems.map(function(){
	  var item = $($(this).attr("href"));
	  if (item.length) { return item; }
	});

	// Bind click handler to menu items
	// so we can get a fancy scroll animation
	menuItems.click(function(e){
	  var href = $(this).attr("href"),
	      offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+22;
	  jQuery('html, body').stop().animate({
	      scrollTop: offsetTop
	  }, 1500);
	  e.preventDefault();
	});

	// Bind to scroll
	jQuery(window).scroll(function(){
	   // Get container scroll position
	   var fromTop = $(this).scrollTop()+topMenuHeight;

	   // Get id of current scroll item
	   var cur = scrollItems.map(function(){
	     if ($(this).offset().top < fromTop)
	       return this;
	   });
	   // Get the id of the current element
	   cur = cur[cur.length-1];
	   var id = cur && cur.length ? cur[0].id : "";

	   if (lastId !== id) {
	       lastId = id;
	       // Set/remove active class
	       menuItems
	         .parent().removeClass("active")
	         .end().filter("[href=\\#"+id+"]").parent().addClass("active");
	   }
	})

	/* ----------------------------------------------------------- */
	/*  4. VIDEO POPUP
	/* ----------------------------------------------------------- */

   $('.mu-video-play-btn').on('click', function(event) {

        event.preventDefault();

        $('.mu-video-iframe-area').addClass('mu-video-iframe-display');

    });

    // when click the close btn

    // disappear iframe window

    $('.mu-video-close-btn').on('click', function(event) {

	    event.preventDefault();

		$('.mu-video-iframe-area').removeClass('mu-video-iframe-display');

    });

    // stop iframe if it is play while close the iframe window

    $('.mu-video-close-btn').click(function(){

        $('.mu-video-iframe').attr('src', $('.mu-video-iframe').attr('src'));

    });

    // when click overlay area

     $('.mu-video-iframe-area').on('click', function(event) {

	    event.preventDefault();

		$('.mu-video-iframe-area').removeClass('mu-video-iframe-display');

    });

	$('.mu-video-iframe-area, .mu-video-iframe').on('click', function(e){
	    e.stopPropagation();
	});

	/* ----------------------------------------------------------- */
	/*  5. SPEAKERS SLIDEER ( SLICK SLIDER )
	/* ----------------------------------------------------------- */

		$('.mu-speakers-slider').slick({
		  slidesToShow: 4,
		  responsive: [
		    {
		      breakpoint: 768,
		      settings: {
		        arrows: true,
		        slidesToShow: 4
		      }
		    },
		    {
		      breakpoint: 480,
		      settings: {
		        arrows: true,
		        slidesToShow: 4
		      }
		    }
		  ]
		});

	/* ----------------------------------------------------------- */
	/*  6. BOOTSTRAP ACCORDION
	/* ----------------------------------------------------------- */

		/* Start for accordion #1*/
		$('#accordion .panel-collapse').on('shown.bs.collapse', function () {
		$(this).prev().find(".fa").removeClass("fa-angle-up").addClass("fa-angle-down");
		});

		//The reverse of the above on hidden event:

		$('#accordion .panel-collapse').on('hidden.bs.collapse', function () {
		$(this).prev().find(".fa").removeClass("fa-angle-down").addClass("fa-angle-up");
		});

	/* ----------------------------------------------------------- */
	/*  7. MOBILE MENU CLOSE
	/* ----------------------------------------------------------- */

	jQuery('.mu-menu').on('click', 'li a', function() {
	  $('.mu-navbar .in').collapse('hide');
	});

})( jQuery );

	<commit_msg>increasing counter<commit_after>/**
	* Template Name: Eventoz
	* Version: 1.0
	* Template Scripts
	* Author: MarkUps
	* Author URI: http://www.markups.io/

	Custom JS

	1. FIXED MENU
	2. EVENT TIME COUNTER
	3. MENU SMOOTH SCROLLING
	4. VIDEO POPUP
	5. SPEAKERS SLIDEER ( SLICK SLIDER )
	6. BOOTSTRAP ACCORDION
	7. MOBILE MENU CLOSE

**/

(function( $ ){

	/* ----------------------------------------------------------- */
	/*  1. FIXED MENU
	/* ----------------------------------------------------------- */

	jQuery(window).bind('scroll', function () {
    if ($(window).scrollTop() > 150) {
        $('.mu-navbar').addClass('mu-nav-show');

	    } else {
	        $('.mu-navbar').removeClass('mu-nav-show');
	    }
	});

	/* ----------------------------------------------------------- */
	/*  2. EVENT TIME COUNTER
	/* ----------------------------------------------------------- */

	$('#mu-event-counter').countdown('2019/03/16').on('update.countdown', function(event) {
	  var $this = $(this).html(event.strftime(''
	    + '%D Days '
	    + '%H Hours '
	    + '%M Mins '
	    + '%S Secs'));
	});

    /* ----------------------------------------------------------- */
	/*  3. MENU SMOOTH SCROLLING
	/* ----------------------------------------------------------- */

	 //MENU SCROLLING WITH ACTIVE ITEM SELECTED

	// Cache selectors
	var lastId,
	topMenu = $(".mu-menu"),
	topMenuHeight = topMenu.outerHeight()+13,
	// All list items
	menuItems = topMenu.find('a[href^=\\#]'),
	// Anchors corresponding to menu items
	scrollItems = menuItems.map(function(){
	  var item = $($(this).attr("href"));
	  if (item.length) { return item; }
	});

	// Bind click handler to menu items
	// so we can get a fancy scroll animation
	menuItems.click(function(e){
	  var href = $(this).attr("href"),
	      offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+22;
	  jQuery('html, body').stop().animate({
	      scrollTop: offsetTop
	  }, 1500);
	  e.preventDefault();
	});

	// Bind to scroll
	jQuery(window).scroll(function(){
	   // Get container scroll position
	   var fromTop = $(this).scrollTop()+topMenuHeight;

	   // Get id of current scroll item
	   var cur = scrollItems.map(function(){
	     if ($(this).offset().top < fromTop)
	       return this;
	   });
	   // Get the id of the current element
	   cur = cur[cur.length-1];
	   var id = cur && cur.length ? cur[0].id : "";

	   if (lastId !== id) {
	       lastId = id;
	       // Set/remove active class
	       menuItems
	         .parent().removeClass("active")
	         .end().filter("[href=\\#"+id+"]").parent().addClass("active");
	   }
	})

	/* ----------------------------------------------------------- */
	/*  4. VIDEO POPUP
	/* ----------------------------------------------------------- */

   $('.mu-video-play-btn').on('click', function(event) {

        event.preventDefault();

        $('.mu-video-iframe-area').addClass('mu-video-iframe-display');

    });

    // when click the close btn

    // disappear iframe window

    $('.mu-video-close-btn').on('click', function(event) {

	    event.preventDefault();

		$('.mu-video-iframe-area').removeClass('mu-video-iframe-display');

    });

    // stop iframe if it is play while close the iframe window

    $('.mu-video-close-btn').click(function(){

        $('.mu-video-iframe').attr('src', $('.mu-video-iframe').attr('src'));

    });

    // when click overlay area

     $('.mu-video-iframe-area').on('click', function(event) {

	    event.preventDefault();

		$('.mu-video-iframe-area').removeClass('mu-video-iframe-display');

    });

	$('.mu-video-iframe-area, .mu-video-iframe').on('click', function(e){
	    e.stopPropagation();
	});

	/* ----------------------------------------------------------- */
	/*  5. SPEAKERS SLIDEER ( SLICK SLIDER )
	/* ----------------------------------------------------------- */

		$('.mu-speakers-slider').slick({
		  slidesToShow: 4,
		  responsive: [
		    {
		      breakpoint: 768,
		      settings: {
		        arrows: true,
		        slidesToShow: 4
		      }
		    },
		    {
		      breakpoint: 480,
		      settings: {
		        arrows: true,
		        slidesToShow: 4
		      }
		    }
		  ]
		});

	/* ----------------------------------------------------------- */
	/*  6. BOOTSTRAP ACCORDION
	/* ----------------------------------------------------------- */

		/* Start for accordion #1*/
		$('#accordion .panel-collapse').on('shown.bs.collapse', function () {
		$(this).prev().find(".fa").removeClass("fa-angle-up").addClass("fa-angle-down");
		});

		//The reverse of the above on hidden event:

		$('#accordion .panel-collapse').on('hidden.bs.collapse', function () {
		$(this).prev().find(".fa").removeClass("fa-angle-down").addClass("fa-angle-up");
		});

	/* ----------------------------------------------------------- */
	/*  7. MOBILE MENU CLOSE
	/* ----------------------------------------------------------- */

	jQuery('.mu-menu').on('click', 'li a', function() {
	  $('.mu-navbar .in').collapse('hide');
	});

})( jQuery );

	<|endoftext|>


<commit_before>var disqus_config = Object.assign({}, document.getElementById('#disqus_thread').dataset);

(function(key) {
  const thread = ;
  var d = document, s = d.createElement('script');

  s.src = 'https://' + key + '.disqus.com/embed.js';

  s.setAttribute('data-timestamp', +new Date());
  (d.head || d.body).appendChild(s);
})(disqus_config.key);
<commit_msg>fix: fix typo in disqus JS<commit_after>var disqus_config = Object.assign({}, document.getElementById('#disqus_thread').dataset);

(function(key) {
  var d = document, s = d.createElement('script');

  s.src = 'https://' + key + '.disqus.com/embed.js';

  s.setAttribute('data-timestamp', +new Date());
  (d.head || d.body).appendChild(s);
})(disqus_config.key);
<|endoftext|>


<commit_before>$(document).ready(function () {
	// *************scroll smooth*******************************//
	$('.navmobile a, .navfull a,.logomobile').on('click', function (event) {
		var target = $($(this).attr('href'));
		if (target.length) {

			event.preventDefault();

			var newScroll = target.position().top;

			$('html,body').animate({

				scrollTop: newScroll

			}, 1000);

		}
	});

	$('.navmobile a').on('click', function (event) {
		$('#toggle').click(); // close the mobile menu when click on links

	});

	// *************change menu link color and border*******************************//
	var headerOffset = (Math.floor(($('header').offset()).top));
	var acteursOffset = Math.floor(($('#Acteurs').offset()).top);
	var eventsOffset = Math.floor(($('#Events .background').offset()).top);
	var contactOffset = Math.floor(($('#Contact').offset()).top);
	var contactLinkOffset = Math.floor(($('#Contact a').offset()).top);
	console.log(contactLinkOffset);

    var menuLinks = $(".navfull .categories a");

    $('.navfull').show();
	$('.navmobile').hide();
	$('.backhome').css('z-index','100000');

	$(window).scroll(function () {
		console.log($(window).scrollTop(),contactLinkOffset)
        if(window.scrollY === 0){
            $('.navmobile').hide();
			$('.navfull').show();
			$('.backhome').css('z-index','100000');

		}
		else if($(window).scrollTop()  + $(window).height() > contactLinkOffset ){

          $('#Contact a').addClass('typeEffect');

        }

        else{
            $('.navfull').hide();
			$('.backhome').css('z-index','-100000');
            $('.navmobile').show();

        }

		var offsetLinks = $('.button_container').offset().top;

		if ((offsetLinks >= headerOffset && offsetLinks <= acteursOffset) /*|| offsetLinks >= contactOffset*/ ) {
			$('.navfull .categories a').removeClass('black');
			$('.navfull .categories a').addClass('white');
			$('.navfull .categories').removeClass('black-border');
			$('.navfull .categories').addClass('white-border');
			$('.button_container:not(.active) span').css('background-color','#F5F5F5');

		} else if (offsetLinks >= acteursOffset && offsetLinks <= eventsOffset) {
			$('.navfull .categories a').removeClass('white');
			$('.navfull .categories a').addClass('black');
			$('.navfull .categories').removeClass('white-border');
			$('.navfull .categories').addClass('black-border');
			$('.button_container:not(.active) span').css('background-color','#191919');

		} else if (offsetLinks >= eventsOffset && offsetLinks <= contactOffset) {
			$('.navfull .categories a').removeClass('black');
			$('.navfull .categories a').addClass('white');
			$('.navfull .categories').removeClass('black-border');
			$('.navfull .categories').addClass('white-border');
			$('.button_container:not(.active) span').css('background-color','#F5F5F5');

		} else if (offsetLinks >= contactOffset) {
			$('.navfull .categories a').removeClass('white');
			$('.navfull .categories a').addClass('black');
			$('.navfull .categories').removeClass('white-border');
			$('.navfull .categories').addClass('black-border');
			$('.button_container:not(.active) span').css('background-color','#191919');

		};
		/* change link colors when on view
		if (window.scrollY >= headerOffset && window.scrollY < acteursOffset) {
			$('.navfull .categories a').removeClass('sectionactive');
			menuLinks[0].classList.add('sectionactive');
		}

		if (window.scrollY >= acteursOffset && window.scrollY < eventsOffset) {
			$('.navfull .categories a').removeClass('sectionactive');
			menuLinks[1].classList.add('sectionactive');
		}

		if (window.scrollY >= eventsOffset && window.scrollY < contactOffset) {
			$('.navfull .categories a').removeClass('sectionactive');
			menuLinks[2].classList.add('sectionactive');
		}
		if (window.scrollY >= contactOffset) {
			$('.navfull .categories a').removeClass('sectionactive');
			menuLinks[3].classList.add('sectionactive');
		}*/

	})

})

<commit_msg>fix menu<commit_after>$(document).ready(function () {
	// *************scroll smooth*******************************//
	$('.navmobile a, .navfull a,.logomobile').on('click', function (event) {
		var target = $($(this).attr('href'));
		if (target.length) {

			event.preventDefault();

			var newScroll = target.position().top;

			$('html,body').animate({

				scrollTop: newScroll

			}, 1000);

		}
	});

	$('.navmobile a').on('click', function (event) {
		$('#toggle').click(); // close the mobile menu when click on links

	});

	// *************change menu link color and border*******************************//
	var headerOffset = (Math.floor(($('header').offset()).top));
	var acteursOffset = Math.floor(($('#Acteurs').offset()).top);
	var eventsOffset = Math.floor(($('#Events .background').offset()).top);
	var contactOffset = Math.floor(($('#Contact').offset()).top);
	var contactLinkOffset = Math.floor(($('#Contact a').offset()).top);

	var menuLinks = $(".navfull .categories a");

	if ($(window).scrollTop() === 0){

    $('.navfull').show();
	$('.navmobile').hide();
	$('.backhome').css('z-index','100000');
	}
	else{
	$('.navfull').hide();
	$('.navmobile').show();

	}

	$(window).scroll(function () {

        if(window.scrollY === 0){
            $('.navmobile').hide();
			$('.navfull').show();
			$('.backhome').css('z-index','100000');

		}
		else if($(window).scrollTop()  + $(window).height() > contactLinkOffset ){

          $('#Contact a').addClass('typeEffect');

        }

        else{
            $('.navfull').hide();
			$('.backhome').css('z-index','-100000');
            $('.navmobile').show();

        }

		var offsetLinks = $('.button_container').offset().top;

		if ((offsetLinks >= headerOffset && offsetLinks <= acteursOffset) /*|| offsetLinks >= contactOffset*/ ) {
			$('.navfull .categories a').removeClass('black');
			$('.navfull .categories a').addClass('white');
			$('.navfull .categories').removeClass('black-border');
			$('.navfull .categories').addClass('white-border');
			$('.button_container:not(.active) span').css('background-color','#F5F5F5');

		} else if (offsetLinks >= acteursOffset && offsetLinks <= eventsOffset) {
			$('.navfull .categories a').removeClass('white');
			$('.navfull .categories a').addClass('black');
			$('.navfull .categories').removeClass('white-border');
			$('.navfull .categories').addClass('black-border');
			$('.button_container:not(.active) span').css('background-color','#191919');

		} else if (offsetLinks >= eventsOffset && offsetLinks <= contactOffset) {
			$('.navfull .categories a').removeClass('black');
			$('.navfull .categories a').addClass('white');
			$('.navfull .categories').removeClass('black-border');
			$('.navfull .categories').addClass('white-border');
			$('.button_container:not(.active) span').css('background-color','#F5F5F5');

		} else if (offsetLinks >= contactOffset) {
			$('.navfull .categories a').removeClass('white');
			$('.navfull .categories a').addClass('black');
			$('.navfull .categories').removeClass('white-border');
			$('.navfull .categories').addClass('black-border');
			$('.button_container:not(.active) span').css('background-color','#191919');

		};
		/* change link colors when on view
		if (window.scrollY >= headerOffset && window.scrollY < acteursOffset) {
			$('.navfull .categories a').removeClass('sectionactive');
			menuLinks[0].classList.add('sectionactive');
		}

		if (window.scrollY >= acteursOffset && window.scrollY < eventsOffset) {
			$('.navfull .categories a').removeClass('sectionactive');
			menuLinks[1].classList.add('sectionactive');
		}

		if (window.scrollY >= eventsOffset && window.scrollY < contactOffset) {
			$('.navfull .categories a').removeClass('sectionactive');
			menuLinks[2].classList.add('sectionactive');
		}
		if (window.scrollY >= contactOffset) {
			$('.navfull .categories a').removeClass('sectionactive');
			menuLinks[3].classList.add('sectionactive');
		}*/

	})

})

<|endoftext|>


<commit_before>;
(document => {
    const body = document.querySelector('body')
    const ageElement = document.querySelector('span.age')
    const daysElement = document.querySelector('.days')
    const hoursElement = document.querySelector('.hours')
    const minutesElement = document.querySelector('.minutes')
    const secondsElement = document.querySelector('.seconds')

    document.addEventListener('readystatechange', () => {
        if (document.readyState === 'complete') {
            function setAge() {
                const today = new Date();
                const birthDate = new Date(1985, 8, 6);
                const month = today.getMonth() - birthDate.getMonth();
                let age = today.getFullYear() - birthDate.getFullYear();

                age = (month < 0 || (month === 0 && today.getDate() < birthDate.getDate())) ? age - 1 : age;

                ageElement.innerHTML = age
            }

            function startCount() {
                let targetDate = new Date(2009, 0, 1);
                let onStart = () => {
                    document.querySelectorAll('.counter span').forEach(item => item.classList.add('show'))
                }
                let onTick = ({
                    days,
                    hours,
                    minutes,
                    seconds
                }) => {
                    daysElement.innerHTML = days;
                    hoursElement.innerHTML = hours;
                    minutesElement.innerHTML = minutes;
                    secondsElement.innerHTML = seconds;
                };
                let options = new LsCountupOptions({
                    targetDate,
                    onStart,
                    onTick
                });
                let countup = new LsCountup(options);

                countup.start();
                window.mycountup = countup;
            }

            setAge()
            startCount()

            body.classList.remove('loading')
        }
    })

    document.addEventListener('scroll', event => {
        const scrolled = window.pageYOffset;
        const background = document.querySelectorAll('.paralaxed-background')

        background.forEach(b => {
            const currentPositionY = b.offsetTop || 0;
            if (scrolled > b.offsetTop) b.style.backgroundPositionY = `${(scrolled - currentPositionY) * 0.5}px`
        })
    })
})(document || {});<commit_msg>paralax fast scrolling issue fixed<commit_after>;
(document => {
    const body = document.querySelector('body')
    const ageElement = document.querySelector('span.age')
    const daysElement = document.querySelector('.days')
    const hoursElement = document.querySelector('.hours')
    const minutesElement = document.querySelector('.minutes')
    const secondsElement = document.querySelector('.seconds')

    document.addEventListener('readystatechange', () => {
        if (document.readyState === 'complete') {
            function setAge() {
                const today = new Date();
                const birthDate = new Date(1985, 8, 6);
                const month = today.getMonth() - birthDate.getMonth();
                let age = today.getFullYear() - birthDate.getFullYear();

                age = (month < 0 || (month === 0 && today.getDate() < birthDate.getDate())) ? age - 1 : age;

                ageElement.innerHTML = age
            }

            function startCount() {
                let targetDate = new Date(2009, 0, 1);
                let onStart = () => {
                    document.querySelectorAll('.counter span').forEach(item => item.classList.add('show'))
                }
                let onTick = ({
                    days,
                    hours,
                    minutes,
                    seconds
                }) => {
                    daysElement.innerHTML = days;
                    hoursElement.innerHTML = hours;
                    minutesElement.innerHTML = minutes;
                    secondsElement.innerHTML = seconds;
                };
                let options = new LsCountupOptions({
                    targetDate,
                    onStart,
                    onTick
                });
                let countup = new LsCountup(options);

                countup.start();
                window.mycountup = countup;
            }

            setAge()
            startCount()

            body.classList.remove('loading')
        }
    })

    document.addEventListener('scroll', event => {
        const scrolled = window.pageYOffset;
        const background = document.querySelectorAll('.paralaxed-background')

        background.forEach(b => {
            const currentPositionY = b.offsetTop || 0;
            if (scrolled === 0) {
                b.style.backgroundPositionY = '0px'
            } else if (scrolled > b.offsetTop) {
                b.style.backgroundPositionY = `${(scrolled - currentPositionY) * 0.5}px`
            } else {
                b.style.backgroundPositionY = '0px'
            }
        })
    })
})(document || {});<|endoftext|>


<commit_before>$(document).ready(function() {
  fetch((window.baseUrl || '') + '/assets/html/custombar.html').then(function(response) {
    return response.text()
  }).then(function(html) {
    html = html.replace(/assets\/img\//g, (window.baseUrl || '') + 'assets/img/')
    $('#custombar').before(html).remove()
    activate()
  })
})

function activate() {
  var el = {
    input:          $('#letters-input'),
    bagLetters:     $('.bag-letter-image'),
    letterTabs:     $('.tab-letter-color-letter'),
    letterTab1:     $('#tab-letter1'),
    letterTab2:     $('#tab-letter2'),
    lettersWrapper: $('.tab-letter-wrapper.active'),
    swatch:         $('.swatch-image-border'),
  }

  Object.keys(el).forEach(function(key) {
    if( !el[key].length ) { console.warn(`No element present for ${key}`); }
  })

  var bagContainerHeight = $(".main-bag-container").width() * .7
  $(".main-bag-container").height(bagContainerHeight)
  var bagContainerHeight = $(".main-letters-container").width() * .7
  $(".main-letters-container").height(bagContainerHeight)
  var letterTabHeight = $(".swatch-row").height() / 2
  $(".custom-letter-container").height(letterTabHeight)

  $(window).resize(function() {
    var newLetterHeight = $(".letters-wrapper ").height()
    $("#bagLetter1").css({ display: "block", height: newLetterHeight + "px" })
    $("#bagLetter2").css({ display: "block", height: newLetterHeight + "px" })
    bagContainerHeight = $(".main-bag-container").width() * .7
    $(".main-bag-container").height(bagContainerHeight)
    bagContainerHeight = $(".main-letters-container").width() * .7
    $(".main-letters-container").height(bagContainerHeight)
    letterTabHeight = $(".swatch-row").height() / 2
    $(".custom-letter-container").height(letterTabHeight)
  })

  var letter1Choice = "black"
  var letter2Choice = "black"

  el.letterTabs.on('click', function() {
    el.letterTabs.removeClass("active")
    el.lettersWrapper.removeClass('active')
    $(this).addClass("active")
    $(this).parent().addClass('active')
  })

  el.letterTab1.on('click', function() {
    el.swatch.removeClass('active')
    el.swatch.each(function() {
      if ($(this).data("material-swatch") == letter1Choice) {
        $(this).addClass("active")
      }
    })
  })

  el.letterTab2.on('click', function() {
    el.swatch.removeClass('active')
    el.swatch.each(function() {
      if ($(this).data("material-swatch") == letter2Choice) {
        $(this).addClass("active")
      }
    })
  })

  el.input.on("input", function() {
    var $inputText = $(this).val()

    if( $inputText.length > 0 ) {
      $("#bagLetter2").hide()
      renderLetter(1, $inputText.charAt(0), letter1Choice)
      if ($inputText.length > 1) {
        renderLetter(2, $inputText.charAt(1), letter2Choice)
        $("input").blur()
      }
      updateCustomInfo()
    } else {
      $("#tab-letter1").html("")
      $("#tab-letter2").html("")
      $("#bagLetter1").css({ display: "none" })
      $("#bagLetter2").css({ display: "none" })
    }
  })

  el.swatch.on('click', function() {
    el.swatch.removeClass("active")
    $(this).addClass("active")
    var text = el.input.val()

    if ($("#tab-letter1").hasClass("active")) {
      letter1Choice = $(this).data("material-swatch")
      renderLetter(1, text.charAt(0).toUpperCase(), letter1Choice)
    } else if ($("#tab-letter2").hasClass("active")) {
      letter2Choice = $(this).data("material-swatch")
      renderLetter(2, text.charAt(1).toUpperCase(), letter2Choice)
    } else {
      console.warn('Unknown letter active')
    }

    updateCustomInfo()
  })

  function renderLetter(index, letter, swatch) {
    var height     = $(".letters-wrapper").height()
    var letterPath = (window.baseUrl || "") + "assets/img/letters/" + letter.toUpperCase() + "-" + swatch + ".png"
    $("#tab-letter"+index).css({ background: "url(" + letterPath + ") no-repeat", backgroundSize: "contain", backgroundPosition: "center" })
    $("#bagLetter"+index).attr("src", letterPath)
    $("#bagLetter"+index).show().css({ height: height })
  }

  function updateCustomInfo() {
    var text = el.input.val()

    if( !text.length ) { return; }

    if (text.length > 1) {
      $("#custombar-custom-info").val("Danny-Black / " + text[0].toUpperCase() + "-" + letter1Choice + " / " + text[1].toUpperCase() + "-" + letter2Choice)
    } else {
      $("#custombar-custom-info").val("Danny-Black / " + text[0].toUpperCase() + "-" + letter1Choice)
    }
  }
}
<commit_msg>Remove unused selector<commit_after>$(document).ready(function() {
  fetch((window.baseUrl || '') + '/assets/html/custombar.html').then(function(response) {
    return response.text()
  }).then(function(html) {
    html = html.replace(/assets\/img\//g, (window.baseUrl || '') + 'assets/img/')
    $('#custombar').before(html).remove()
    activate()
  })
})

function activate() {
  var el = {
    input:          $('#letters-input'),
    letterTabs:     $('.tab-letter-color-letter'),
    letterTab1:     $('#tab-letter1'),
    letterTab2:     $('#tab-letter2'),
    lettersWrapper: $('.tab-letter-wrapper.active'),
    swatch:         $('.swatch-image-border'),
  }

  Object.keys(el).forEach(function(key) {
    if( !el[key].length ) { console.warn(`No element present for ${key}`); }
  })

  var bagContainerHeight = $(".main-bag-container").width() * .7
  $(".main-bag-container").height(bagContainerHeight)
  var bagContainerHeight = $(".main-letters-container").width() * .7
  $(".main-letters-container").height(bagContainerHeight)
  var letterTabHeight = $(".swatch-row").height() / 2
  $(".custom-letter-container").height(letterTabHeight)

  $(window).resize(function() {
    var newLetterHeight = $(".letters-wrapper ").height()
    $("#bagLetter1").css({ display: "block", height: newLetterHeight + "px" })
    $("#bagLetter2").css({ display: "block", height: newLetterHeight + "px" })
    bagContainerHeight = $(".main-bag-container").width() * .7
    $(".main-bag-container").height(bagContainerHeight)
    bagContainerHeight = $(".main-letters-container").width() * .7
    $(".main-letters-container").height(bagContainerHeight)
    letterTabHeight = $(".swatch-row").height() / 2
    $(".custom-letter-container").height(letterTabHeight)
  })

  var letter1Choice = "black"
  var letter2Choice = "black"

  el.letterTabs.on('click', function() {
    el.letterTabs.removeClass("active")
    el.lettersWrapper.removeClass('active')
    $(this).addClass("active")
    $(this).parent().addClass('active')
  })

  el.letterTab1.on('click', function() {
    el.swatch.removeClass('active')
    el.swatch.each(function() {
      if ($(this).data("material-swatch") == letter1Choice) {
        $(this).addClass("active")
      }
    })
  })

  el.letterTab2.on('click', function() {
    el.swatch.removeClass('active')
    el.swatch.each(function() {
      if ($(this).data("material-swatch") == letter2Choice) {
        $(this).addClass("active")
      }
    })
  })

  el.input.on("input", function() {
    var $inputText = $(this).val()

    if( $inputText.length > 0 ) {
      $("#bagLetter2").hide()
      renderLetter(1, $inputText.charAt(0), letter1Choice)
      if ($inputText.length > 1) {
        renderLetter(2, $inputText.charAt(1), letter2Choice)
        $("input").blur()
      }
      updateCustomInfo()
    } else {
      $("#tab-letter1").html("")
      $("#tab-letter2").html("")
      $("#bagLetter1").css({ display: "none" })
      $("#bagLetter2").css({ display: "none" })
    }
  })

  el.swatch.on('click', function() {
    el.swatch.removeClass("active")
    $(this).addClass("active")
    var text = el.input.val()

    if ($("#tab-letter1").hasClass("active")) {
      letter1Choice = $(this).data("material-swatch")
      renderLetter(1, text.charAt(0).toUpperCase(), letter1Choice)
    } else if ($("#tab-letter2").hasClass("active")) {
      letter2Choice = $(this).data("material-swatch")
      renderLetter(2, text.charAt(1).toUpperCase(), letter2Choice)
    } else {
      console.warn('Unknown letter active')
    }

    updateCustomInfo()
  })

  function renderLetter(index, letter, swatch) {
    var height     = $(".letters-wrapper").height()
    var letterPath = (window.baseUrl || "") + "assets/img/letters/" + letter.toUpperCase() + "-" + swatch + ".png"
    $("#tab-letter"+index).css({ background: "url(" + letterPath + ") no-repeat", backgroundSize: "contain", backgroundPosition: "center" })
    $("#bagLetter"+index).attr("src", letterPath)
    $("#bagLetter"+index).show().css({ height: height })
  }

  function updateCustomInfo() {
    var text = el.input.val()

    if( !text.length ) { return; }

    if (text.length > 1) {
      $("#custombar-custom-info").val("Danny-Black / " + text[0].toUpperCase() + "-" + letter1Choice + " / " + text[1].toUpperCase() + "-" + letter2Choice)
    } else {
      $("#custombar-custom-info").val("Danny-Black / " + text[0].toUpperCase() + "-" + letter1Choice)
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

var _ = require( 'lodash-node' );
var sinon = require( 'sinon' );

var getBase = function () {
    return require( '../relays/base' );
};

var getDefaultConfig = function () {
    return require( '../lib/default-config' );
};

var getUtil = function () {
    return require( '../lib/util' );
};

describe( 'Base Relay', function () {

    it( 'requires to be created with the `new` operator', function () {
        var BaseRelay = getBase();
        var myRelay   = null

        BaseRelay.should.be.a.Function;
        myRelay = new BaseRelay( { onLog: _.noop } );

        myRelay.should.be.an.Object;
        myRelay.should.not.be.an.instanceOf( BaseRelay );
    } );

    it( 'requires at least an `opts.onLog` callback function', function () {
        new getBase().bind( null ).should.throw( 'New relays must supply at least an `opts.onLog` callback function.' );
        new getBase().bind( null, { onLog: _.noop } ).should.not.throw();
    } );

    it( 'Supplies a log function to call when log events occur', function () {
        var onLogSpy = sinon.spy();
        var myRelay = new getBase()( { onLog: onLogSpy } );
        myRelay.log( {
                timestamp:  getUtil().getTimestamp(),
                level:      'error',
                rawArgs:    [ 'foo', 'bar', 'fizz', 'bang' ]
            },
            getDefaultConfig()
        );
        onLogSpy.calledOnce.should.be.ok;
    } );
} );
<commit_msg>Implement test for calling the onLog callback with a log event object<commit_after>'use strict';

var _ = require( 'lodash-node' );
var sinon = require( 'sinon' );

var getBase = function () {
    return require( '../relays/base' );
};

var getDefaultConfig = function () {
    return require( '../lib/default-config' );
};

var getUtil = function () {
    return require( '../lib/util' );
};

describe.only( 'Base Relay', function () {

    it( 'requires to be created with the `new` operator', function () {
        var BaseRelay = getBase();
        var myRelay   = null

        BaseRelay.should.be.a.Function;
        myRelay = new BaseRelay( { onLog: _.noop } );

        myRelay.should.be.an.Object;
        myRelay.should.not.be.an.instanceOf( BaseRelay );
    } );

    it( 'requires at least an `opts.onLog` callback function', function () {
        new getBase().bind( null ).should.throw( 'New relays must supply at least an `opts.onLog` callback function.' );
        new getBase().bind( null, { onLog: _.noop } ).should.not.throw();
    } );

    it( 'supplies a log function to call when log events occur', function () {
        var onLogSpy = sinon.spy();
        var myRelay = new getBase()( { onLog: onLogSpy } );
        myRelay.log( {
                timestamp:  getUtil().getTimestamp(),
                level:      'error',
                rawArgs:    [ 'foo', 'bar', 'fizz', 'bang' ]
            },
            getDefaultConfig()
        );
        onLogSpy.calledOnce.should.be.ok;
    } );

    it( 'calls the onLog callback with a log event', function ( done ) {
        var testTimestamp   = getUtil().getTimestamp();
        var testLevel       = 'error';
        var testRawArgs     = [ 'foo', 'bar', 'fizz', 'bang' ];
        var testPrefix      = 'myApp';
        var testMsgFmt      = ''

        var myRelay = new getBase()( {
            onLog: function ( logEvent ) {
                logEvent.should.have.properties( {
                    timestamp:  testTimestamp,
                    level:      testLevel,
                    prefix:     testPrefix,
                    rawArgs:    testRawArgs,
                    message:    ''
                } );
                done();
            }
        } );

        myRelay.log( {
                timestamp:  testTimestamp,
                level:      testLevel,
                rawArgs:    testRawArgs
            },
            {
                prefix:         testPrefix,
                messageFormat:  testMsgFmt
            }
        );
    } );

    it( 'respects minLevel config from relay config', function () {
        var onLogSpy = sinon.spy();
        var levels = getDefaultConfig().levels;

        var myRelay = new getBase()( {
            minLevel:   levels[ 1 ],
            onLog:      onLogSpy
        } );

        myRelay.log( {
                timestamp:  getUtil().getTimestamp(),
                level:      levels[ 0 ],
                rawArgs:    [ 'foo', 'bar', 'fizz', 'bang' ]
            },
            getDefaultConfig()
        );

        onLogSpy.called.should.not.be.ok;
    } );

    it( 'respects minLevel config from logger config', function () {
        var onLogSpy = sinon.spy();
        var levels = getDefaultConfig().levels;

        var myRelay = new getBase()( {
            onLog: onLogSpy
        } );

        myRelay.log( {
                timestamp:  getUtil().getTimestamp(),
                level:      levels[ 0 ],
                rawArgs:    [ 'foo', 'bar', 'fizz', 'bang' ]
            },
            _.assign( {}, getDefaultConfig(), { minLevel: levels[ 1 ] } )
        );

        onLogSpy.called.should.not.be.ok;
    } );
} );
<|endoftext|>


<commit_before>/**
 **/

if ($(window).width() <= 1280) {
  $('#sidebar').addClass('mobile')
}

// Variables
    tag1       = $('.pl__all'),
    tag2       = $('.Linux'),
    tag3       = $('.C语言'),
    tag4       = $('.PHP'),
    tag5       = $('.Python');
    tag6       = $('.岁月无声');
var sidebar    = $('#sidebar'),
    container  = $('#post'),
    content    = $('#pjax'),
    button     = $('#icon-arrow');

// Tags switcher
var clickHandler = function(k) {
  return function() {
    $(this).addClass('active').siblings().removeClass('active');
    tag1.hide();
    window['tag'+k].delay(50).fadeIn(350);
  }
};
for (var i = 1; i <= 5; i++) {
  $('#js-label' + i).on('click', clickHandler(i));
}

// If sidebar has class 'mobile', hide it after clicking.
tag1.on('click', function() {
  $(this).addClass('active').siblings().removeClass('active');
  if (sidebar.hasClass('mobile')) {
    $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
  }
});

// Enable fullscreen.
$('#js-fullscreen').on('click', function() {
  if (button.hasClass('fullscreen')) {
    sidebar.removeClass('fullscreen');
    button.removeClass('fullscreen');
    content.delay(300).queue(function(){
      $(this).removeClass('fullscreen').dequeue();
    });
  } else {
    sidebar.addClass('fullscreen');
    button.addClass('fullscreen');
    content.delay(200).queue(function(){
      $(this).addClass('fullscreen').dequeue();
    });
  }
});

$('#mobile-avatar').on('click', function(){
  $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
});

// Pjax
$(document).pjax('#avatar, #mobile-avatar, .pl__all', '#pjax', { fragment: '#pjax', timeout: 10000 });
$(document).on({
  'pjax:click': function() {
    content.removeClass('fadeIn').addClass('fadeOut');
    NProgress.start();
  },
  'pjax:start': function() {
    content.css({'opacity':0});
  },
  'pjax:end': function() {
    NProgress.done();
    container.scrollTop(0);
    content.css({'opacity':1}).removeClass('fadeOut').addClass('fadeIn');
    afterPjax();
  }
});

// Re-run scripts for post content after pjax
function afterPjax() {
  // Open links in new tab
  $('#post__content a').attr('target','_blank');

  // Generate post TOC for h1 h2 and h3
  var toc = $('#post__toc-ul');
  // Empty TOC and generate an entry for h1
  toc.empty().append('
' + $('#post__title').text() + '
');

  // Generate entries for h2 and h3
  $('#post__content').children('h2,h3').each(function() {
    // Generate random ID for each heading
    $(this).attr('id', function() {
      var ID = "",
          alphabet = "abcdefghijklmnopqrstuvwxyz";

      for(var i=0; i < 5; i++) {
        ID += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
      }
      return ID;
    });

    if ($(this).prop("tagName") == 'H2') {
      toc.append('
' + $(this).text() + '
');
    } else {
      toc.append('
' + $(this).text() + '
');
    }
  });

  // Smooth scrolling
  $('.js-anchor-link').on('click', function() {
    var target = $(this.hash);
    container.animate({scrollTop: target.offset().top + container.scrollTop() - 70}, 500, function() {
      target.addClass('flash').delay(700).queue(function() {
        $(this).removeClass('flash').dequeue();
      });
    });
  });

  // Lazy Loading Disqus
  // http://jsfiddle.net/dragoncrew/SHGwe/1/

  if($('#disqus_thread').length > 0){
    var top = $('#disqus_thread').offset().top;
    var ds_loaded = false;
    var identifier = $('#post__title').data('identifier');
    window.disqus_shortname = 'koalaxiaot';
    window.disqus_identifier = identifier;
	}

  function check() {
    if ( !ds_loaded && container.scrollTop() + container.height() > top ) {
      $.ajax({
        type: 'GET',
        url: 'http://' + disqus_shortname + '.disqus.com/embed.js',
        dataType: 'script',
        cache: true
      });
      ds_loaded = true;
    }
  }check();
  container.scroll(check);
}afterPjax();

<commit_msg>change 5 to 6<commit_after>/**
 **/

if ($(window).width() <= 1280) {
  $('#sidebar').addClass('mobile')
}

// Variables
    tag1       = $('.pl__all'),
    tag2       = $('.Linux'),
    tag3       = $('.C语言'),
    tag4       = $('.PHP'),
    tag5       = $('.Python');
    tag6       = $('.岁月无声');
var sidebar    = $('#sidebar'),
    container  = $('#post'),
    content    = $('#pjax'),
    button     = $('#icon-arrow');

// Tags switcher
var clickHandler = function(k) {
  return function() {
    $(this).addClass('active').siblings().removeClass('active');
    tag1.hide();
    window['tag'+k].delay(50).fadeIn(350);
  }
};
for (var i = 1; i <= 6; i++) {
  $('#js-label' + i).on('click', clickHandler(i));
}

// If sidebar has class 'mobile', hide it after clicking.
tag1.on('click', function() {
  $(this).addClass('active').siblings().removeClass('active');
  if (sidebar.hasClass('mobile')) {
    $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
  }
});

// Enable fullscreen.
$('#js-fullscreen').on('click', function() {
  if (button.hasClass('fullscreen')) {
    sidebar.removeClass('fullscreen');
    button.removeClass('fullscreen');
    content.delay(300).queue(function(){
      $(this).removeClass('fullscreen').dequeue();
    });
  } else {
    sidebar.addClass('fullscreen');
    button.addClass('fullscreen');
    content.delay(200).queue(function(){
      $(this).addClass('fullscreen').dequeue();
    });
  }
});

$('#mobile-avatar').on('click', function(){
  $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
});

// Pjax
$(document).pjax('#avatar, #mobile-avatar, .pl__all', '#pjax', { fragment: '#pjax', timeout: 10000 });
$(document).on({
  'pjax:click': function() {
    content.removeClass('fadeIn').addClass('fadeOut');
    NProgress.start();
  },
  'pjax:start': function() {
    content.css({'opacity':0});
  },
  'pjax:end': function() {
    NProgress.done();
    container.scrollTop(0);
    content.css({'opacity':1}).removeClass('fadeOut').addClass('fadeIn');
    afterPjax();
  }
});

// Re-run scripts for post content after pjax
function afterPjax() {
  // Open links in new tab
  $('#post__content a').attr('target','_blank');

  // Generate post TOC for h1 h2 and h3
  var toc = $('#post__toc-ul');
  // Empty TOC and generate an entry for h1
  toc.empty().append('
' + $('#post__title').text() + '
');

  // Generate entries for h2 and h3
  $('#post__content').children('h2,h3').each(function() {
    // Generate random ID for each heading
    $(this).attr('id', function() {
      var ID = "",
          alphabet = "abcdefghijklmnopqrstuvwxyz";

      for(var i=0; i < 5; i++) {
        ID += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
      }
      return ID;
    });

    if ($(this).prop("tagName") == 'H2') {
      toc.append('
' + $(this).text() + '
');
    } else {
      toc.append('
' + $(this).text() + '
');
    }
  });

  // Smooth scrolling
  $('.js-anchor-link').on('click', function() {
    var target = $(this.hash);
    container.animate({scrollTop: target.offset().top + container.scrollTop() - 70}, 500, function() {
      target.addClass('flash').delay(700).queue(function() {
        $(this).removeClass('flash').dequeue();
      });
    });
  });

  // Lazy Loading Disqus
  // http://jsfiddle.net/dragoncrew/SHGwe/1/

  if($('#disqus_thread').length > 0){
    var top = $('#disqus_thread').offset().top;
    var ds_loaded = false;
    var identifier = $('#post__title').data('identifier');
    window.disqus_shortname = 'koalaxiaot';
    window.disqus_identifier = identifier;
	}

  function check() {
    if ( !ds_loaded && container.scrollTop() + container.height() > top ) {
      $.ajax({
        type: 'GET',
        url: 'http://' + disqus_shortname + '.disqus.com/embed.js',
        dataType: 'script',
        cache: true
      });
      ds_loaded = true;
    }
  }check();
  container.scroll(check);
}afterPjax();

<|endoftext|>


<commit_before>/*
## Get the search term from submit named 'search'.
*/
function getQueryVariable (variable) {
  var query = window.location.search.substring(1);
  var vars = query.splits('&');

  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');

    if (pair[0] === varibale) {
      return decodeURIComponent(pair[1].replace(/\+/g, '%20'));
    }
  }
}

var searchTerm = getQueryVariable ('query');

/*
## Peform the search
*/

if (searchTerm) {
  document.getElementById('search-box').setAttribute("value", searchTerm);

  // Initalize lunr with the fields it will be searching on. I've given title
  // a bost of 10 to indeicate matches on this field are more important.

  var idex_item = lunr(function () {
    this.field('id');
    this.field('title', { boost: 10 });
    this.field('author');
    this.field('category');
    this.field('content');
  });

  for (var key in window.store) {
    idex_item.add({
      'id': key,
      'title': window.store[key].title,
      'author': window.store[key].author,
      'category': window.store[key].category,
      'content': window.store[key].content
    });

  var results = idex_item.search (searchTerm);
  displaySearchResults (results, window.store);
  }
}

<commit_msg>Display the results.<commit_after>/*
## Get the search term from submit named 'search'.
*/
function getQueryVariable (variable) {
  var query = window.location.search.substring(1);
  var vars = query.splits('&');

  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');

    if (pair[0] === varibale) {
      return decodeURIComponent(pair[1].replace(/\+/g, '%20'));
    }
  }
}

var searchTerm = getQueryVariable ('query');

/*
## Peform the search
*/

if (searchTerm) {
  document.getElementById('search-box').setAttribute("value", searchTerm);

  // Initalize lunr with the fields it will be searching on. I've given title
  // a bost of 10 to indeicate matches on this field are more important.

  var idex_item = lunr(function () {
    this.field('id');
    this.field('title', { boost: 10 });
    this.field('author');
    this.field('category');
    this.field('content');
  });

  for (var key in window.store) {
    idex_item.add({
      'id': key,
      'title': window.store[key].title,
      'author': window.store[key].author,
      'category': window.store[key].category,
      'content': window.store[key].content
    });

  var results = idex_item.search (searchTerm);
  displaySearchResults (results, window.store);
  }
}

/*
## Display the results
*/

function displaySearchResults (results, store) {
  var searchResults = document.getElementById ('search-results');

  if (results.length) {
    var appendString = '';

    for (var i = 0; i < results.length; i++) {
      var item = store[results[i].ref];
      appendString += '

' + item.title + '
';
      appendString += '
' + item.content.substring(0, 150) + ' ...

';
    }

    searchResults.innerHTML = appendString;
  }
  else {
    searchResults.innerHTML = '
Khong co ket qua nao.
';
  }
}
<|endoftext|>


<commit_before>
const fs = require('fs')

const moo = require('../moo')

function reEscape(pat) {
  if (typeof pat === 'string') {
    pat = pat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
  }
  return pat
}

function randomChoice(array) {
  return array[Math.floor(Math.random() * array.length)]
}

const chevrotain = require('chevrotain')
function chevrotainFromMoo(lexer) {
  const tokens = []
  lexer.groups.forEach(group => {
    var options = group.match.map(pat => typeof pat === 'string' ? reEscape(pat) : pat.source)
    var pat = new RegExp(options.join('|'))
    tokens.push(chevrotain.createToken({name: group.tokenType, pattern: pat}))
  })
  // "onlyStart" will track startOffset, startLine, startColumn.
  // By default endOffset, endLine and endColumn will also be tracked at the cost of a few % points in performance.
  return new chevrotain.Lexer(tokens, {positionTracking:"onlyStart"})
}

suite('startup', () => {

  benchmark('moo.compileStates', () => {
    moo.states({
      main: {
        strstart: {match: '`', push: 'lit'},
        ident:    /\w+/,
        lbrace:   {match: '{', push: 'main'},
        rbrace:   {match: '}', pop: 1},
        colon:    ':',
        space:    {match: /\s+/, lineBreaks: true},
      },
      lit: {
        interp:   {match: '${', push: 'main'},
        escape:   /\\./,
        strend:   {match: '`', pop: 1},
        const:    {match: /(?:[^$`]|\$(?!\{))+/, lineBreaks: true},
      },
    })
  })

})

suite('keywords', () => {

  const keywords = 'cow moo bovine udder hoof cheese milk cud grass moo moo bull calf friesian jersey alderney angus beef highland cattle'.split(' ')
  const words = keywords.concat('orange fruit apple pear kiwi fire pineapple pirahna kale kumquat starfruit dragonfruit passion sharon physalis gooseberry'.split(' '))
  var source = ''
  for (var i=2000; i--; ) {
    source += randomChoice(words) + ' '
  }

  const lexer = moo.compile({
    name: {match: /[a-z]+/, keywords: {cowword: keywords}},
    space: {match: /\s+/, lineBreaks: true},
  })
  lexer.reset(source)

  // test
  for (let tok in lexer) {
    switch (tok.type) {
      case 'space': continue
      case 'cowword': expect(keywords.indexOf(tok.value)).not.toBe(-1); continue
      case 'name': expect(keywords.indexOf(tok.value)).toBe(-1); continue
    }
  }

  benchmark('🐮 ', () => {
    lexer.reset(source)
    var count = 0
    while (tok = lexer.next()) { count++ }
  })

})

suite('json', () => {

  let jsonFile = fs.readFileSync('test/sample1k.json', 'utf-8')
  let jsonCount = 4557

  const manual = require('./manual')
  benchmark('hand-written', function() {
    // TODO don't decode JSON strings; only recognise them
    let next = manual(jsonFile)
    var count = 0
    while (tok = next()) { count++ }
    if (count !== jsonCount) { throw 'fail' }
  })

  const jsonLexer = require('./json')
  benchmark('🐮 ', function() {
    jsonLexer.reset(jsonFile)
    var count = 0
    while (tok = jsonLexer.next()) { count++ }
    if (count !== jsonCount) { throw 'fail' }
  })

  const jsonChev = chevrotainFromMoo(jsonLexer)
  benchmark('chevrotain', function() {
    let count = jsonChev.tokenize(jsonFile).tokens.length
    if (count !== jsonCount) { throw 'fail' }
  })

  const Syntax = require('./json-syntax')
  benchmark('syntax-cli', function() {
    Syntax.initString(jsonFile)
    var count = 0
    while (Syntax.getNextToken().type !== '$') { count++ }
    if (count !== jsonCount) throw 'fail'
  })

})

suite('tosh', () => {

  const tosh = require('./tosh')
  let toshFile = ''
  for (var i=5; i--; ) { toshFile += tosh.exampleFile }

  benchmark('🐮 ', function() {
    tosh.tokenize(toshFile)
  })

  benchmark('tosh', function() {
    let oldTokens = tosh.oldTokenizer(toshFile)
  })

})

suite('python', () => {

  const pythonLexer = require('./python').lexer
  let kurtFile = fs.readFileSync('test/kurt.py', 'utf-8')

  let pythonGroups = []
  for (let options of pythonLexer.groups) {
    let name = options.tokenType
    let match = options.match
    if (typeof match[0] === 'string') {
      var regexp = new RegExp(match.map(reEscape).join('|'))
    } else {
      var regexp = new RegExp(match.map(re => re.source).join('|'))
    }
    pythonGroups.push({name, regexp})
  }

  benchmark('🐮 ', function() {
    pythonLexer.reset(kurtFile)
    while (pythonLexer.next()) {}
  })

  /* ReMix
   * not strictly a tokenizer, but definitely interesting
  const ReMix = require('remix').ReMix
  let rm = new ReMix
  for (let group of pythonGroups) {
    rm.add({ [group.name]: new RegExp(group.regexp) })
  }
  benchmark('remix', function() {
    var count = 0
    var token
    while (token = rm.exec(kurtFile)) { count++ }
    if (count !== 14513) throw 'fail'
  })
   */

  /* lex
   * I do not know why this one is so slow
  const Lexer = require('lex')
  var lexer = new Lexer
  for (let group of pythonGroups) {
    lexer.addRule(new RegExp(group.regexp), () => group.name)
  }
  benchmark('lex', function() {
    lexer.setInput(kurtFile)
    var count = 0
    var token
    while (token = lexer.lex()) { count++ }
    if (count !== 14513) throw 'fail'
  })
   */

  /* tokenizer2
   * wrong output. Does not seem to use regexes in the way I expect
  const core = require('tokenizer2/core')
  var t2count
  var t = core(token => {
    // console.log(token)
    t2count++
  })
  for (let group of pythonGroups) {
    t.addRule(new RegExp('^' + group.regexp + '$'), group.name)
  }
  benchmark('tokenizer2', function() {
    t2count = 0
    t.onText(kurtFile)
    t.end()
    // if (t2count !== 14513) throw 'fail'
  })
   */

  /* chevrotain's lexer
   */
  let chevLexer = chevrotainFromMoo(pythonLexer)
  benchmark('chevrotain', function() {
    let count = chevLexer.tokenize(kurtFile).tokens.length
    if (count !== 14513) throw 'fail'
  })

  /* lexing
   *
   * wrong output -- I don't think it likes our triple-quoted strings?
   * Does pretty well considering, though!
  const lexing = require('lexing')
  let lexingRules = [
    [/^$/, function(match) { return { type: 'EOF' } }],
  ]
  for (let group of pythonGroups) {
    lexingRules.push([new RegExp('^' + group.regexp), function(match) {
      return { type: group.name, value: match[1] || match[0] }
    }])
  }
  const lexingTokenizer = new lexing.Tokenizer(lexingRules)
  benchmark('lexing', function() {
    let input = new lexing.StringIterator(kurtFile);
    let output = lexingTokenizer.map(input)
    var count = 0
    var token
    while ((token = output.next()).type !== 'EOF') {
      // console.log(token.type, JSON.stringify(token.value))
      count++
    }
    // if (count !== 14513) throw 'fail'
  })
   */

})
<commit_msg>Benchmark full Python tokenizer<commit_after>
const fs = require('fs')

const moo = require('../moo')

function reEscape(pat) {
  if (typeof pat === 'string') {
    pat = pat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
  }
  return pat
}

function randomChoice(array) {
  return array[Math.floor(Math.random() * array.length)]
}

const chevrotain = require('chevrotain')
function chevrotainFromMoo(lexer) {
  const tokens = []
  lexer.groups.forEach(group => {
    var options = group.match.map(pat => typeof pat === 'string' ? reEscape(pat) : pat.source)
    var pat = new RegExp(options.join('|'))
    tokens.push(chevrotain.createToken({name: group.tokenType, pattern: pat}))
  })
  // "onlyStart" will track startOffset, startLine, startColumn.
  // By default endOffset, endLine and endColumn will also be tracked at the cost of a few % points in performance.
  return new chevrotain.Lexer(tokens, {positionTracking:"onlyStart"})
}

suite('startup', () => {

  benchmark('moo.compileStates', () => {
    moo.states({
      main: {
        strstart: {match: '`', push: 'lit'},
        ident:    /\w+/,
        lbrace:   {match: '{', push: 'main'},
        rbrace:   {match: '}', pop: 1},
        colon:    ':',
        space:    {match: /\s+/, lineBreaks: true},
      },
      lit: {
        interp:   {match: '${', push: 'main'},
        escape:   /\\./,
        strend:   {match: '`', pop: 1},
        const:    {match: /(?:[^$`]|\$(?!\{))+/, lineBreaks: true},
      },
    })
  })

})

suite('keywords', () => {

  const keywords = 'cow moo bovine udder hoof cheese milk cud grass moo moo bull calf friesian jersey alderney angus beef highland cattle'.split(' ')
  const words = keywords.concat('orange fruit apple pear kiwi fire pineapple pirahna kale kumquat starfruit dragonfruit passion sharon physalis gooseberry'.split(' '))
  var source = ''
  for (var i=2000; i--; ) {
    source += randomChoice(words) + ' '
  }

  const lexer = moo.compile({
    name: {match: /[a-z]+/, keywords: {cowword: keywords}},
    space: {match: /\s+/, lineBreaks: true},
  })
  lexer.reset(source)

  // test
  for (let tok in lexer) {
    switch (tok.type) {
      case 'space': continue
      case 'cowword': expect(keywords.indexOf(tok.value)).not.toBe(-1); continue
      case 'name': expect(keywords.indexOf(tok.value)).toBe(-1); continue
    }
  }

  benchmark('🐮 ', () => {
    lexer.reset(source)
    var count = 0
    while (tok = lexer.next()) { count++ }
  })

})

suite('json', () => {

  let jsonFile = fs.readFileSync('test/sample1k.json', 'utf-8')
  let jsonCount = 4557

  const manual = require('./manual')
  benchmark('hand-written', function() {
    // TODO don't decode JSON strings; only recognise them
    let next = manual(jsonFile)
    var count = 0
    while (tok = next()) { count++ }
    if (count !== jsonCount) { throw 'fail' }
  })

  const jsonLexer = require('./json')
  benchmark('🐮 ', function() {
    jsonLexer.reset(jsonFile)
    var count = 0
    while (tok = jsonLexer.next()) { count++ }
    if (count !== jsonCount) { throw 'fail' }
  })

  const jsonChev = chevrotainFromMoo(jsonLexer)
  benchmark('chevrotain', function() {
    let count = jsonChev.tokenize(jsonFile).tokens.length
    if (count !== jsonCount) { throw 'fail' }
  })

  const Syntax = require('./json-syntax')
  benchmark('syntax-cli', function() {
    Syntax.initString(jsonFile)
    var count = 0
    while (Syntax.getNextToken().type !== '$') { count++ }
    if (count !== jsonCount) throw 'fail'
  })

})

suite('tosh', () => {

  const tosh = require('./tosh')
  let toshFile = ''
  for (var i=5; i--; ) { toshFile += tosh.exampleFile }

  benchmark('🐮 ', function() {
    tosh.tokenize(toshFile)
  })

  benchmark('tosh', function() {
    let oldTokens = tosh.oldTokenizer(toshFile)
  })

})

suite('python', () => {

  const pythonLexer = require('./python').lexer
  const pythonTokenize = require('./python').tokenize
  let kurtFile = fs.readFileSync('test/kurt.py', 'utf-8')

  benchmark('🐮 lex', function() {
    pythonLexer.reset(kurtFile)
    while (pythonLexer.next()) {}
  })

  benchmark('🐮 full tokenize', function() {
    pythonTokenize(kurtFile, () => {
    })
  })

  /* chevrotain's lexer
   */
  /*
  let chevLexer = chevrotainFromMoo(pythonLexer)
  benchmark('chevrotain', function() {
    let count = chevLexer.tokenize(kurtFile).tokens.length
    if (count !== 14513) throw 'fail'
  })
  */

  /*
  let pythonGroups = []
  for (let options of pythonLexer.groups) {
    let name = options.tokenType
    let match = options.match
    if (typeof match[0] === 'string') {
      var regexp = new RegExp(match.map(reEscape).join('|'))
    } else {
      var regexp = new RegExp(match.map(re => re.source).join('|'))
    }
    pythonGroups.push({name, regexp})
  }

  // ReMix
  // not strictly a tokenizer, but definitely interesting
  const ReMix = require('remix').ReMix
  let rm = new ReMix
  for (let group of pythonGroups) {
    rm.add({ [group.name]: new RegExp(group.regexp) })
  }
  benchmark('remix', function() {
    var count = 0
    var token
    while (token = rm.exec(kurtFile)) { count++ }
    if (count !== 14513) throw 'fail'
  })

  // lex
  // I do not know why this one is so slow
  const Lexer = require('lex')
  var lexer = new Lexer
  for (let group of pythonGroups) {
    lexer.addRule(new RegExp(group.regexp), () => group.name)
  }
  benchmark('lex', function() {
    lexer.setInput(kurtFile)
    var count = 0
    var token
    while (token = lexer.lex()) { count++ }
    if (count !== 14513) throw 'fail'
  })
  */

  /* tokenizer2
   * wrong output. Does not seem to use regexes in the way I expect
  const core = require('tokenizer2/core')
  var t2count
  var t = core(token => {
    // console.log(token)
    t2count++
  })
  for (let group of pythonGroups) {
    t.addRule(new RegExp('^' + group.regexp + '$'), group.name)
  }
  benchmark('tokenizer2', function() {
    t2count = 0
    t.onText(kurtFile)
    t.end()
    // if (t2count !== 14513) throw 'fail'
  })
   */

  /* lexing
   *
   * wrong output -- I don't think it likes our triple-quoted strings?
   * Does pretty well considering, though!
  const lexing = require('lexing')
  let lexingRules = [
    [/^$/, function(match) { return { type: 'EOF' } }],
  ]
  for (let group of pythonGroups) {
    lexingRules.push([new RegExp('^' + group.regexp), function(match) {
      return { type: group.name, value: match[1] || match[0] }
    }])
  }
  const lexingTokenizer = new lexing.Tokenizer(lexingRules)
  benchmark('lexing', function() {
    let input = new lexing.StringIterator(kurtFile);
    let output = lexingTokenizer.map(input)
    var count = 0
    var token
    while ((token = output.next()).type !== 'EOF') {
      // console.log(token.type, JSON.stringify(token.value))
      count++
    }
    // if (count !== 14513) throw 'fail'
  })
   */

})
<|endoftext|>


<commit_before>
var VIEWER = function() {
  var mesh, renderer, scene, camera, controls;
  var currentObjects = []; // Holds all of the objects that we are rendering
  var currentEdges = []; // Holds all of the edges for the objects that were are rendering
  var centroid;
  var navBarHeight = 50; //px
  var settings = {
      initialView: 'ISO',
      clearColor: 0x696969,
      containerId: ""
  };
  // material
  var material = new THREE.MeshPhongMaterial( {
      color: 0x00ffff,
      shading: THREE.FlatShading,
      transparent: true,
      opacity: 0.7,
  } );

  // Sets the main 3D scene and the origin scene up
  function init() {
      // renderer
      renderer = new THREE.WebGLRenderer();
      var width = $('#modelview').width();
      renderer.setSize(width, width * 0.8);
      renderer.setClearColor(settings.clearColor, 1);

      // Keeps our 3D view properly sized
      $(window).resize(function() {
          renderer.setSize(window.innerWidth, window.innerHeight - navBarHeight);
      });

      document.getElementById(settings.containerId).appendChild(renderer.domElement);

      // scene
      scene = new THREE.Scene();

      // camera
      camera = new THREE.PerspectiveCamera(40, window.innerWidth / (window.innerHeight - navBarHeight), 1, 10000);
      camera.position.set(60, 60, 60);
      camera.up.set( 0, 0, 1 );

      // controls
      controls = new THREE.OrbitControls(camera);
      controls.addEventListener('change', render); // use if there is no animation loop

      // ambient
      scene.add(new THREE.AmbientLight( 0x222222 ));

      // light
      var light = new THREE.DirectionalLight(0xffffff, 1);
      light.position.set( 20, 20, 0 );
      scene.add( light );

      // Set up the origin indicator
      originContainer = document.getElementById('indicator');
      originRenderer = new THREE.WebGLRenderer({
              antialias   : true, // to get smoother output
              preserveDrawingBuffer : true  // to allow screenshot
          });
      originRenderer.setClearColor(0xf0f0f0, 1);
      originRenderer.setSize(100.0, 100.0);
      originRenderer.setClearColor(settings.clearColor, 1);
      originContainer.appendChild(originRenderer.domElement);
      originScene = new THREE.Scene();
      originCamera = new THREE.PerspectiveCamera(35, 100.0 / 100.0, 1, 1000);
      originCamera.up = camera.up;

      // Set up the axes for the origin indicator
      var dirX = new THREE.Vector3(100, 0, 0);
      var dirY = new THREE.Vector3(0, 100, 0);
      var dirZ = new THREE.Vector3(0, 0, 100);
      var origin = new THREE.Vector3(0, 0, 0);
      var length = 75;
      var xAxisColor = 0xff0000;
      var yAxisColor = 0x00ff00;
      var zAxisColor = 0x0000ff;

      var arrowHelperX = new THREE.ArrowHelper(dirX, origin, length, xAxisColor, 20, 15);
      var arrowHelperY = new THREE.ArrowHelper(dirY, origin, length, yAxisColor, 20, 15);
      var arrowHelperZ = new THREE.ArrowHelper(dirZ, origin, length, zAxisColor, 20, 15);
      originScene.add(arrowHelperX);
      originScene.add(arrowHelperY);
      originScene.add(arrowHelperZ);

      // Base grid helps us orient ourselves
      var baseGrid = new THREE.GridHelper(30, 1);
      baseGrid.geometry.rotateX( Math.PI / 2 );
      scene.add(baseGrid);

      render();
  }

  // Loads the JSON geometry data into the main scene
  function loadGeometry(data) {
      // Make sure that we remove all objects from the scene
      if (currentObjects.length > 0) {
          for (var i = 0; i < currentObjects.length; i++) {
              scene.remove(currentObjects[i]);
              scene.remove(currentEdges[i]);
          }
      }

      // Step through all the results and render them
      for(var j = 0; j < data.allResults.length; j++){
          //load new model
          var loader = new THREE.JSONLoader();
          var model = loader.parse(data.allResults[j]);

          var mesh  = new THREE.Mesh(model.geometry, material);
          var edges = new THREE.EdgesHelper(mesh, 0x000000);

          scene.add(mesh);
          scene.add(edges);

          // We need to track all objects and lines added to the scene so that we can remove them later
          currentObjects[j] = mesh;
          currentEdges[j] = edges;

          // We only want to do these things for the first object
          if(j === 0) {
              //compute center
              model.geometry.computeBoundingBox();
              var bb = model.geometry.boundingBox;
              var centerX = 0.5 * (bb.max.x - bb.min.x);
              var centerY = 0.5 * (bb.max.y - bb.min.y);
              var centerZ = 0.5 * (bb.max.z - bb.min.z);
              centroid = new THREE.Vector3(centerX, centerY, centerZ);
          }
      }

      render();
      zoomAll();
  }

  // Shows what has been loaded into the scene
  function render() {
      // Main scene
      renderer.render(scene, camera);

      // Origin scene
      originCamera.position.copy(camera.position);
      originCamera.lookAt(originScene.position);
      originCamera.position.setLength(300);
      originRenderer.render(originScene, originCamera);
  }

  // Makes sure we are not too close to the object when setting a view camera position
  function safeDistance() {
      // Get the first object so that we can set the safe distance
      var bBox = currentObjects[0].geometry.boundingBox;
      if (bBox === undefined) {
          console.log("bBox Undefined");
          return;
      }

      // Calculate the safe distance that we should be away from the object to get a good view
      var sphereSize = bBox.size().length() * 0.75;
      return sphereSize / Math.sin(Math.PI / 180.0 * camera.fov * 0.5);
  }

  // Allows us to reset the camera position to any point in space
  function setCameraPosition(x, y, z) {
      rotateObjects(0);
      camera.position.x = x;
      camera.position.y = y;
      camera.position.z = z;
  }

  // Allows us to reset the rotation angle of the objects in the scene
  function rotateObjects(angle) {
      for(var i = 0; i < scene.children.length; i ++){
          scene.children[ i ].rotation.y = angle;
      }
  }

  // Allows the GUI to pass named views to get the desired camera position
  function setCameraView(viewName) {
      // If there are no objects rendered, don't mess with moving the camera around
      if (currentObjects.length === 0) return;

      var d = safeDistance();
      controls.reset();

      if(viewName === 'ISO') {
          // Move the camera to show us an isometric view
          setCameraPosition(d, -d, d);
      }
      else if(viewName === 'TOP') {
          // Move the camera to show us a top view
          setCameraPosition(0, 0, d);
      }
      else if(viewName === 'BOTTOM') {
          // Move the camera to show us a bottom view
          setCameraPosition(0, 0, -d);
      }
      else if(viewName === 'LEFT') {
          // Move the camera to show us a left side view
          setCameraPosition(d, 0, 0);
      }
      else if(viewName === 'RIGHT') {
          // Move the camera to show us a right side view
          setCameraPosition(-d, 0, 0);
      }
      else if(viewName === 'FRONT') {
          // Move the camera to show us a front view
          setCameraPosition(0, d, 0);
      }
      else if(viewName === 'BACK') {
          // Move the camera to show us a back view
          setCameraPosition(0, -d, 0);
      }
      else if(viewName === 'BOTTOM_LEFT') {
          // Move the camera to show us a bottom left
          setCameraPosition(d, d, -d);
      }
      else if(viewName === 'BOTTOM_RIGHT') {
          // Move the camera to show us a back view
          setCameraPosition(-d, d, -d);
      }
      else if(viewName === 'TOP_LEFT') {
          // Move the camera to show us a bottom left
          setCameraPosition(d, d, d);
      }
      else if(viewName === 'TOP_RIGHT') {
          // Move the camera to show us a back view
          setCameraPosition(-d, d, d);
      }

      // Make sure everything fits in the view
      zoomAll();
  }

  // Allows a UI to re-center the object in the view and zoom to the proper distance
  function fitAll() {
    controls.reset();

    zoomAll();
  }

  // Zooms the main object(s) in the scene to to the proper distance
  function zoomAll() {
      var distToCenter = safeDistance();

      // Move the camera backward
      var target = controls.target;
      var vec = new THREE.Vector3();
      vec.subVectors(camera.position, target);
      vec.setLength(distToCenter);
      camera.position.addVectors(vec, target);
      camera.updateProjectionMatrix();

      controls.update();
  }

  //exported functions
  return {
      init: function(opts) {
          $.extend(settings, opts);
          init();
      },
      loadGeometry : loadGeometry,
      setView : setCameraView,
      zoomAll : zoomAll,
      fitAll: fitAll,
      setCameraPosition: setCameraPosition
      // setZoom : function(factor){
      //     camera.position.multiplyScalar(factor);
      // },
      // captureImage: function(){
      //     return renderer.domElement.toDataURL("image/png");
      // }
  };
}();
<commit_msg>Changed the default color of the model and made it opaque. Also started playing with lighting.<commit_after>
var VIEWER = function() {
  var mesh, renderer, scene, camera, controls;
  var currentObjects = []; // Holds all of the objects that we are rendering
  var currentEdges = []; // Holds all of the edges for the objects that were are rendering
  var centroid;
  var navBarHeight = 50; //px
  var settings = {
      initialView: 'ISO',
      clearColor: 0x696969,
      containerId: ""
  };
  // material
  var material = new THREE.MeshPhongMaterial( {
      color: 0xCCCCCC,
      shading: THREE.FlatShading,
      transparent: true,
      opacity: 1.0
  } );

  // Sets the main 3D scene and the origin scene up
  function init() {
      // renderer
      renderer = new THREE.WebGLRenderer();
      var width = $('#modelview').width();
      renderer.setSize(width, width * 0.8);
      renderer.setClearColor(settings.clearColor, 1);

      // Keeps our 3D view properly sized
      $(window).resize(function() {
          renderer.setSize(window.innerWidth, window.innerHeight - navBarHeight);
      });

      document.getElementById(settings.containerId).appendChild(renderer.domElement);

      // scene
      scene = new THREE.Scene();

      // camera
      camera = new THREE.PerspectiveCamera(40, window.innerWidth / (window.innerHeight - navBarHeight), 1, 10000);
      camera.position.set(60, 60, 60);
      camera.up.set( 0, 0, 1 );

      // controls
      controls = new THREE.OrbitControls(camera);
      controls.addEventListener('change', render); // use if there is no animation loop

      // ambient
      scene.add(new THREE.AmbientLight( 0x222222 ));

      // light
      var light = new THREE.DirectionalLight(0xffffff, 1);
      light.position.set(60, 60, 60);
      scene.add(light);
      var light2 = new THREE.DirectionalLight(0xffffff, 1);
      light.position.set(-60, -60, -60);
      scene.add(light2);

      // Set up the origin indicator
      originContainer = document.getElementById('indicator');
      originRenderer = new THREE.WebGLRenderer({
              antialias   : true, // to get smoother output
              preserveDrawingBuffer : true  // to allow screenshot
          });
      originRenderer.setClearColor(0xf0f0f0, 1);
      originRenderer.setSize(100.0, 100.0);
      originRenderer.setClearColor(settings.clearColor, 1);
      originContainer.appendChild(originRenderer.domElement);
      originScene = new THREE.Scene();
      originCamera = new THREE.PerspectiveCamera(35, 100.0 / 100.0, 1, 1000);
      originCamera.up = camera.up;

      // Set up the axes for the origin indicator
      var dirX = new THREE.Vector3(100, 0, 0);
      var dirY = new THREE.Vector3(0, 100, 0);
      var dirZ = new THREE.Vector3(0, 0, 100);
      var origin = new THREE.Vector3(0, 0, 0);
      var length = 75;
      var xAxisColor = 0xff0000;
      var yAxisColor = 0x00ff00;
      var zAxisColor = 0x0000ff;

      var arrowHelperX = new THREE.ArrowHelper(dirX, origin, length, xAxisColor, 20, 15);
      var arrowHelperY = new THREE.ArrowHelper(dirY, origin, length, yAxisColor, 20, 15);
      var arrowHelperZ = new THREE.ArrowHelper(dirZ, origin, length, zAxisColor, 20, 15);
      originScene.add(arrowHelperX);
      originScene.add(arrowHelperY);
      originScene.add(arrowHelperZ);

      // Base grid helps us orient ourselves
      var baseGrid = new THREE.GridHelper(30, 1);
      baseGrid.geometry.rotateX( Math.PI / 2 );
      scene.add(baseGrid);

      render();
  }

  // Loads the JSON geometry data into the main scene
  function loadGeometry(data) {
      // Make sure that we remove all objects from the scene
      if (currentObjects.length > 0) {
          for (var i = 0; i < currentObjects.length; i++) {
              scene.remove(currentObjects[i]);
              scene.remove(currentEdges[i]);
          }
      }

      // Step through all the results and render them
      for(var j = 0; j < data.allResults.length; j++){
          //load new model
          var loader = new THREE.JSONLoader();
          var model = loader.parse(data.allResults[j]);

          var mesh  = new THREE.Mesh(model.geometry, material);
          var edges = new THREE.EdgesHelper(mesh, 0x000000);

          scene.add(mesh);
          scene.add(edges);

          // We need to track all objects and lines added to the scene so that we can remove them later
          currentObjects[j] = mesh;
          currentEdges[j] = edges;

          // We only want to do these things for the first object
          if(j === 0) {
              //compute center
              model.geometry.computeBoundingBox();
              var bb = model.geometry.boundingBox;
              var centerX = 0.5 * (bb.max.x - bb.min.x);
              var centerY = 0.5 * (bb.max.y - bb.min.y);
              var centerZ = 0.5 * (bb.max.z - bb.min.z);
              centroid = new THREE.Vector3(centerX, centerY, centerZ);
          }
      }

      render();
      zoomAll();
  }

  // Shows what has been loaded into the scene
  function render() {
      // Main scene
      renderer.render(scene, camera);

      // Origin scene
      originCamera.position.copy(camera.position);
      originCamera.lookAt(originScene.position);
      originCamera.position.setLength(300);
      originRenderer.render(originScene, originCamera);
  }

  // Makes sure we are not too close to the object when setting a view camera position
  function safeDistance() {
      // Get the first object so that we can set the safe distance
      var bBox = currentObjects[0].geometry.boundingBox;
      if (bBox === undefined) {
          console.log("bBox Undefined");
          return;
      }

      // Calculate the safe distance that we should be away from the object to get a good view
      var sphereSize = bBox.size().length() * 0.75;
      return sphereSize / Math.sin(Math.PI / 180.0 * camera.fov * 0.5);
  }

  // Allows us to reset the camera position to any point in space
  function setCameraPosition(x, y, z) {
      rotateObjects(0);
      camera.position.x = x;
      camera.position.y = y;
      camera.position.z = z;
  }

  // Allows us to reset the rotation angle of the objects in the scene
  function rotateObjects(angle) {
      for(var i = 0; i < scene.children.length; i ++){
          scene.children[ i ].rotation.y = angle;
      }
  }

  // Allows the GUI to pass named views to get the desired camera position
  function setCameraView(viewName) {
      // If there are no objects rendered, don't mess with moving the camera around
      if (currentObjects.length === 0) return;

      var d = safeDistance();
      controls.reset();

      if(viewName === 'ISO') {
          // Move the camera to show us an isometric view
          setCameraPosition(d, -d, d);
      }
      else if(viewName === 'TOP') {
          // Move the camera to show us a top view
          setCameraPosition(0, 0, d);
      }
      else if(viewName === 'BOTTOM') {
          // Move the camera to show us a bottom view
          setCameraPosition(0, 0, -d);
      }
      else if(viewName === 'LEFT') {
          // Move the camera to show us a left side view
          setCameraPosition(d, 0, 0);
      }
      else if(viewName === 'RIGHT') {
          // Move the camera to show us a right side view
          setCameraPosition(-d, 0, 0);
      }
      else if(viewName === 'FRONT') {
          // Move the camera to show us a front view
          setCameraPosition(0, d, 0);
      }
      else if(viewName === 'BACK') {
          // Move the camera to show us a back view
          setCameraPosition(0, -d, 0);
      }
      else if(viewName === 'BOTTOM_LEFT') {
          // Move the camera to show us a bottom left
          setCameraPosition(d, d, -d);
      }
      else if(viewName === 'BOTTOM_RIGHT') {
          // Move the camera to show us a back view
          setCameraPosition(-d, d, -d);
      }
      else if(viewName === 'TOP_LEFT') {
          // Move the camera to show us a bottom left
          setCameraPosition(d, d, d);
      }
      else if(viewName === 'TOP_RIGHT') {
          // Move the camera to show us a back view
          setCameraPosition(-d, d, d);
      }

      // Make sure everything fits in the view
      zoomAll();
  }

  // Allows a UI to re-center the object in the view and zoom to the proper distance
  function fitAll() {
    controls.reset();

    zoomAll();
  }

  // Zooms the main object(s) in the scene to to the proper distance
  function zoomAll() {
      var distToCenter = safeDistance();

      // Move the camera backward
      var target = controls.target;
      var vec = new THREE.Vector3();
      vec.subVectors(camera.position, target);
      vec.setLength(distToCenter);
      camera.position.addVectors(vec, target);
      camera.updateProjectionMatrix();

      controls.update();
  }

  //exported functions
  return {
      init: function(opts) {
          $.extend(settings, opts);
          init();
      },
      loadGeometry : loadGeometry,
      setView : setCameraView,
      zoomAll : zoomAll,
      fitAll: fitAll,
      setCameraPosition: setCameraPosition
      // setZoom : function(factor){
      //     camera.position.multiplyScalar(factor);
      // },
      // captureImage: function(){
      //     return renderer.domElement.toDataURL("image/png");
      // }
  };
}();
<|endoftext|>


<commit_before>var common = require('./common')
var DHT = require('../')
var test = require('tape')

// https://github.com/webtorrent/bittorrent-dht/pull/36
test('bootstrap and listen to custom port', function (t) {
  t.plan(4)

  var dht = new DHT({ bootstrap: [ '1.2.3.4:1000' ] })
  common.failOnWarningOrError(t, dht)

  var port = Math.floor(Math.random() * 60000) + 1024

  t.ok(!dht.listening)
  dht.listen(port)
  t.ok(!dht.listening)

  // bootstrapping should wait until next tick, so user has a chance to
  // listen to a custom port
  dht.on('listening', function () {
    t.ok(dht.listening)
    t.equal(dht.address().port, port)
  })

  dht.on('ready', function () {
    dht.destroy()
  })
})
<commit_msg>standard<commit_after>var common = require('./common')
var DHT = require('../')
var test = require('tape')

// https://github.com/webtorrent/bittorrent-dht/pull/36
test('bootstrap and listen to custom port', function (t) {
  t.plan(4)

  var dht = new DHT({ bootstrap: ['1.2.3.4:1000'] })
  common.failOnWarningOrError(t, dht)

  var port = Math.floor(Math.random() * 60000) + 1024

  t.ok(!dht.listening)
  dht.listen(port)
  t.ok(!dht.listening)

  // bootstrapping should wait until next tick, so user has a chance to
  // listen to a custom port
  dht.on('listening', function () {
    t.ok(dht.listening)
    t.equal(dht.address().port, port)
  })

  dht.on('ready', function () {
    dht.destroy()
  })
})
<|endoftext|>


<commit_before>(function prep() {
    "use strict";
    var node  = {
            child: require("child_process").exec
        },
        msg   = "",
        delay = function prep_delay() {
            setTimeout(function prep_delay_timeout() {
                if (msg === "") {
                    console.log("Waiting...");
                    prep_delay();
                } else {
                    console.log(msg);
                }
            }, 1000);
        };
    node.child("git clone https://github.com/prettydiff/biddle.git", function prep_clone(cer, stdcout, stdcer) {
        if (cer !== null) {
            msg = cer;
            return console.log(cer);
        }
        if (stdcer !== null && stdcer !== "") {
            msg = stdcer;
            return console.log(stdcer);
        }
        console.log("biddle clone complete!");
        node.child("node biddle global", {cwd:"biddle"}, function prep_clone_global(ger, stdgout, stdger) {
            if (ger !== null) {
                msg = ger;
                return console.log(ger);
            }
            if (stdger !== null && stdger !== "") {
                msg = stdger;
                return console.log(stdger);
            }
            console.log("biddle global complete!");
            node.child("biddle install http://prettydiff.com/downloads/jslint/jslint_latest.zip", function prep_clone_global_install(ier, stdiout, stdier) {
                var test = require("./lint.js");
                if (ier !== null) {
                    msg = ier;
                    return console.log(ier);
                }
                if (stdier !== null && stdier !== "") {
                    msg = stdier;
                    return console.log(stdier);
                }
                msg = "jslint installed by biddle";
                console.log("Pretty Diff test execute!");
                test();
                return [stdcout, stdgout, stdiout];
            });
        });
    });
    delay();
}());<commit_msg>debugging travis build<commit_after>(function prep() {
    "use strict";
    var node  = {
            child: require("child_process").exec
        },
        msg   = "",
        delay = function prep_delay() {
            setTimeout(function prep_delay_timeout() {
                if (msg === "") {
                    console.log("Waiting...");
                    prep_delay();
                } else {
                    console.log(msg);
                }
            }, 1000);
        };
    node.child("git clone https://github.com/prettydiff/biddle.git", function prep_clone(cer, stdcout, stdcer) {
        if (cer !== null && cer.toString().indexOf("Cloning into 'biddle'...") < 0) {
            msg = cer;
            return console.log(cer);
        }
        if (stdcer !== null && stdcer !== "") {
            msg = stdcer;
            return console.log(stdcer);
        }
        console.log("biddle clone complete!");
        node.child("node biddle global", {cwd:"biddle"}, function prep_clone_global(ger, stdgout, stdger) {
            if (ger !== null) {
                msg = ger;
                return console.log(ger);
            }
            if (stdger !== null && stdger !== "") {
                msg = stdger;
                return console.log(stdger);
            }
            console.log("biddle global complete!");
            node.child("biddle install http://prettydiff.com/downloads/jslint/jslint_latest.zip", function prep_clone_global_install(ier, stdiout, stdier) {
                var test = require("./lint.js");
                if (ier !== null) {
                    msg = ier;
                    return console.log(ier);
                }
                if (stdier !== null && stdier !== "") {
                    msg = stdier;
                    return console.log(stdier);
                }
                msg = "jslint installed by biddle";
                console.log("Pretty Diff test execute!");
                test();
                return [stdcout, stdgout, stdiout];
            });
        });
    });
    delay();
}());<|endoftext|>