text:
(function($) {
	$.fn.fullpage = function(options) {
		// Create some defaults, extending them with any options that were provided
		options = $.extend({
			"verticalCentered" : false,
			'resize' : true,
			'slidesColor' : [],
			'anchors':[],
			'scrollingSpeed': 500,
			'easing': 'easeInQuart',
			'menu': false,
			'navigation': false,
			'navigationPosition': 'right',
			'navigationColor': '#333',
			'navigationTooltips': [],
			'slidesNavigation': false,
			'slidesNavPosition': 'bottom',
			'controlArrowColor': '#ccc',
			'loopBottom': false,
			'loopTop': false,
			'loopHorizontal': false,
			'autoScrolling': true,
			'scrollOverflow': false,
			'css3': false,
			'paddingTop': 0,
			'paddingBottom': 0,
			'fixedElements': null,
			'normalScrollElements': null,
			'keyboardScrolling': true,
			'touchSensitivity': 5,

			//events
			'afterLoad': null,
			'onLeave': null,
			'afterRender': null,
			'afterSlideLoad': null,
			'onSlideLeave': null
		}, options);

		//Defines the delay to take place before being able to scroll to the next section
		//BE CAREFUL! Not recommened to change it under 400 for a good behavior in laptops and
		//Apple devices (laptops, mouses...)
		var scrollDelay = 600;

		$.fn.fullpage.setAutoScrolling = function(value){
			options.autoScrolling = value;

			var element = $('.section.active');

			if(options.autoScrolling){
				$('html, body').css({
					'overflow' : 'hidden',
					'height' : '100%'
				});

				if(element.length){
					//moving the container up
					if(options.css3){
						var translate3d = 'translate3d(0px, -' + element.position().top + 'px, 0px)';
						transformContainer(translate3d, false);
					}else{
						//deleting the possible negative top
						$('#superContainer').css('top', '-'  + element.position().top + 'px');
					}
				}

			}else{
				$('html, body').css({
					'overflow' : 'auto',
					'height' : 'auto'
				});

				if(options.css3){
					//moving the container up
					var translate3d = 'translate3d(0px, 0px, 0px)';
					transformContainer(translate3d, false);
				}else{
					//deleting the possible negative top
					$('#superContainer').css('top', '0px');
				}

				//scrolling the page to the section with no animation
				$('html, body').scrollTop(element.position().top);
			}

		};

		/**
		* Adds or remove the possiblity of scrolling through sections by using the mouse wheel or the trackpad.
		*/
		$.fn.fullpage.setMouseWheelScrolling = function (value){
			if(value){
				addMouseWheelHandler();
			}else{
				removeMouseWheelHandler();
			}
		};

		//flag to avoid very fast sliding for landscape sliders
		var slideMoving = false;

		var isTablet = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|Windows Phone)/);

		var windowsHeight = $(window).height();
		var isMoving = false;
		var isResizing = false;
		var lastScrolledDestiny;
		var lastScrolledSlide;

		$.fn.fullpage.setMouseWheelScrolling(true);

		//if css3 is not supported, it will use jQuery animations
		if(options.css3){
			options.css3 = support3d();
		}

		$('body').wrapInner('
');

		//creating the navigation dots
		if (options.navigation) {
			$('body').append('

');
			var nav = $('#fullPage-nav');

			nav.css('color', options.navigationColor);
			nav.addClass(options.navigationPosition);
		}

		$('.section').each(function(index){
			var slides = $(this).find('.slide');
			var numSlides = slides.length;

			if(!index){
				$(this).addClass('active');
			}

			$(this).css('height', windowsHeight + 'px');

			if(options.paddingTop || options.paddingBottom){
				$(this).css('padding', options.paddingTop  + ' 0 ' + options.paddingBottom + ' 0');
			}

			if (typeof options.slidesColor[index] !==  'undefined') {
				$(this).css('background-color', options.slidesColor[index]);
			}

			if (typeof options.anchors[index] !== 'undefined') {
				$(this).attr('data-anchor', options.anchors[index]);
			}

			if (options.navigation) {
				var link = '';
				if(options.anchors.length){
					link = options.anchors[index];
				}
				var tooltip = options.navigationTooltips[index];
				if(typeof tooltip === 'undefined'){
					tooltip = '';
				}

				nav.find('ul').append('

');
			}

			// if there's any slide
			if (numSlides > 0) {
				var sliderWidth = numSlides * 100;
				var slideWidth = 100 / numSlides;

				slides.wrapAll('
');
				slides.parent().wrap('
');

				$(this).find('.slidesContainer').css('width', sliderWidth + '%');
				$(this).find('.slides').after('

');
				$(this).find('.controlArrow.next').css('border-color', 'transparent transparent transparent '+options.controlArrowColor);
				$(this).find('.controlArrow.prev').css('border-color', 'transparent '+ options.controlArrowColor + ' transparent transparent');

				if(!options.loopHorizontal){
					$(this).find('.controlArrow.prev').hide();
				}

				if(options.slidesNavigation){
					addSlidesNavigation($(this), numSlides);
				}

				slides.each(function(index) {
					if(!index){
						$(this).addClass('active');
					}

					$(this).css('width', slideWidth + '%');

					if(options.verticalCentered){
						addTableClass($(this));
					}
				});
			}else{
				if(options.verticalCentered){
					addTableClass($(this));
				}
			}

		}).promise().done(function(){
			$.fn.fullpage.setAutoScrolling(options.autoScrolling);

			$.isFunction( options.afterRender ) && options.afterRender.call( this);

			//fixed elements need to be moved out of the plugin container due to problems with CSS3.
			if(options.fixedElements && options.css3){
				$(options.fixedElements).appendTo('body');
			}

			//vertical centered of the navigation + first bullet active
			if(options.navigation){
				nav.css('margin-top', '-' + (nav.height()/2) + 'px');
				nav.find('li').first().find('a').addClass('active');
			}

			//moving the menu outside the main container (avoid problems with fixed positions when using CSS3 tranforms)
			if(options.menu && options.css3){
				$(options.menu).appendTo('body');
			}

			if(options.scrollOverflow){
				//after DOM and images are loaded
				$(window).on('load', function() {

					$('.section').each(function(){
						var slides = $(this).find('.slide');

						if(slides.length){
							slides.each(function(){
								createSlimScrolling($(this));
							});
						}else{
							createSlimScrolling($(this));
						}

					});
				});
			}

			$(window).on('load', function() {
				scrollToAnchor();
			});

		});

		var scrollId;
		var isScrolling = false;

		//when scrolling...
		$(window).scroll(function(e){

			if(!options.autoScrolling){
				var currentScroll = $(window).scrollTop();

				var scrolledSections = $('.section').map(function(){
					if ($(this).offset().top < (currentScroll + 100)){
						return $(this);
					}
				});

				//geting the last one, the current one on the screen
				var currentSection = scrolledSections[scrolledSections.length-1];

				//executing only once the first time we reach the section
				if(!currentSection.hasClass('active')){
					isScrolling = true;

					var yMovement = getYmovement(currentSection);

					$('.section.active').removeClass('active');
					currentSection.addClass('active');

					var anchorLink  = currentSection.data('anchor');
					$.isFunction( options.onLeave ) && options.onLeave.call( this, currentSection.index('.section'), yMovement);

					$.isFunction( options.afterLoad ) && options.afterLoad.call( this, anchorLink, (currentSection.index('.section') + 1));

					activateMenuElement(anchorLink);
					activateNavDots(anchorLink, 0);

					if(options.anchors.length && !isMoving){
						//needed to enter in hashChange event when using the menu with anchor links
						lastScrolledDestiny = anchorLink;

						location.hash = anchorLink;
					}

					//small timeout in order to avoid entering in hashChange event when scrolling is not finished yet
					clearTimeout(scrollId);
					scrollId = setTimeout(function(){
						isScrolling = false;
					}, 100);
				}

			}
		});

		var touchStartY = 0;
		var touchStartX = 0;
		var touchEndY = 0;
		var touchEndX = 0;

		/* Detecting touch events

		* As we are changing the top property of the page on scrolling, we can not use the traditional way to detect it.
		* This way, the touchstart and the touch moves shows an small difference between them which is the
		* used one to determine the direction.
		*/
		$(document).on('touchmove MSPointerMove', function(event){
			if(options.autoScrolling){
				//preventing the easing on iOS devices
				event.preventDefault();
				var e = event.originalEvent;
				var touchMoved = false;
				var activeSection = $('.section.active');
				var scrollable;

				if (!isMoving && !slideMoving) { //if theres any #

					touchEndY = e.touches[0].pageY;
					touchEndX = e.touches[0].pageX;

					//if movement in the X axys is greater than in the Y and the currect section has slides...
					if (activeSection.find('.slides').length && Math.abs(touchStartX - touchEndX) > (Math.abs(touchStartY - touchEndY))) {

					    //is the movement greater than the minimum resistance to scroll?
					    if (Math.abs(touchStartX - touchEndX) > ($(window).width() / 100 * options.touchSensitivity)) {
					        if (touchStartX > touchEndX) {
					             activeSection.find('.controlArrow.next:visible').trigger('click');

					        } else {
					            activeSection.find('.controlArrow.prev:visible').trigger('click');
					        }
					    }
					}

					//vertical scrolling
					else{
						//if there are landscape slides, we check if the scrolling bar is in the current one or not
						if(activeSection.find('.slides').length){
							scrollable= activeSection.find('.slide.active').find('.scrollable');
						}else{
							scrollable = activeSection.find('.scrollable');
						}

						//is the movement greater than the minimum resistance to scroll?
						if (Math.abs(touchStartY - touchEndY) > ($(window).height() / 100 * options.touchSensitivity)) {
							if (touchStartY > touchEndY) {
								if(scrollable.length > 0 ){
									//is the scrollbar at the end of the scroll?
									if(isScrolled('bottom', scrollable)){
										$.fn.fullpage.moveSectionDown();
									}else{
										return true;
									}
								}else{
									// moved down
									$.fn.fullpage.moveSectionDown();
								}
							} else if (touchEndY > touchStartY) {

								if(scrollable.length > 0){
									//is the scrollbar at the start of the scroll?
									if(isScrolled('top', scrollable)){
										$.fn.fullpage.moveSectionUp();
									}
									else{
										return true;
									}
								}else{
									// moved up
									$.fn.fullpage.moveSectionUp();
								}
							}
						}
					}
				}
			}
		});

		$(document).on('touchstart MSPointerDown', function(event){

			if(options.autoScrolling){
				var e = event.originalEvent;
				touchStartY = e.touches[0].pageY;
				touchStartX = e.touches[0].pageX;
			}
		});

		/**
		 * Detecting mousewheel scrolling
		 *
		 * http://blogs.sitepointstatic.com/examples/tech/mouse-wheel/index.html
		 * http://www.sitepoint.com/html5-javascript-mouse-wheel/
		 */
		function MouseWheelHandler(e) {
			if(options.autoScrolling){
				// cross-browser wheel delta
				e = window.event || e;
				var delta = Math.max(-1, Math.min(1,
						(e.wheelDelta || -e.detail)));
				var scrollable;
				var activeSection = $('.section.active');

				if (!isMoving) { //if theres any #

					//if there are landscape slides, we check if the scrolling bar is in the current one or not
					if(activeSection.find('.slides').length){
						scrollable= activeSection.find('.slide.active').find('.scrollable');
					}else{
						scrollable = activeSection.find('.scrollable');
					}

					//scrolling down?
					if (delta < 0) {
						if(scrollable.length > 0 ){
							//is the scrollbar at the end of the scroll?
							if(isScrolled('bottom', scrollable)){
								$.fn.fullpage.moveSectionDown();
							}else{
								return true; //normal scroll
							}
						}else{
							$.fn.fullpage.moveSectionDown();
						}
					}

					//scrolling up?
					else {
						if(scrollable.length > 0){
							//is the scrollbar at the start of the scroll?
							if(isScrolled('top', scrollable)){
								$.fn.fullpage.moveSectionUp();
							}else{
								return true; //normal scroll
							}
						}else{
							$.fn.fullpage.moveSectionUp();
						}
					}
				}

				return false;
			}
		}

		$.fn.fullpage.moveSectionUp = function(){
			var prev = $('.section.active').prev('.section');

			//looping to the bottom if there's no more sections above
			if(options.loopTop && !prev.length){
				prev = $('.section').last();
			}

			if (prev.length > 0 || (!prev.length && options.loopTop)){
				scrollPage(prev);
			}
		};

		$.fn.fullpage.moveSectionDown = function (){
			var next = $('.section.active').next('.section');

			//looping to the top if there's no more sections below
			if(options.loopBottom && !next.length){
				next = $('.section').first();
			}

			if (next.length > 0 || (!next.length && options.loopBottom)){
				scrollPage(next);
			}
		};

		$.fn.fullpage.moveTo = function (section, slide){
			var destiny = '';

			if(isNaN(section)){
				destiny = $('[data-anchor="'+section+'"]');
			}else{
				destiny = $('.section').eq( (section -1) );
			}

			if (slide !== 'undefined'){
				scrollPageAndSlide(section, slide);
			}else if(destiny.length > 0){
				scrollPage(destiny);
			}
		};

		function scrollPage(element, callback) {
			var scrollOptions = {}, scrolledElement;
			var dest = element.position();
			var dtop = dest !== null ? dest.top : null;
			var yMovement = getYmovement(element);
			var anchorLink  = element.data('anchor');
			var sectionIndex = element.index('.section');
			var activeSlide = element.find('.slide.active');

			if(activeSlide.length){
				var slideAnchorLink = activeSlide.data('anchor');
				var slideIndex = activeSlide.index();
			}

			var leavingSection = $('.section.active').index('.section') + 1;

			element.addClass('active').siblings().removeClass('active');

			//preventing from activating the MouseWheelHandler event
			//more than once if the page is scrolling
			isMoving = true;

			if(typeof anchorLink !== 'undefined'){
				setURLHash(slideIndex, slideAnchorLink, anchorLink);
			}

			if(options.autoScrolling){
				scrollOptions['top'] = -dtop;
				scrolledElement = '#superContainer';
			}else{
				scrollOptions['scrollTop'] = dtop;
				scrolledElement = 'html, body';
			}

			if(options.css3 && options.autoScrolling){

				$.isFunction( options.onLeave ) && options.onLeave.call( this, leavingSection, yMovement);

				var translate3d = 'translate3d(0px, -' + dtop + 'px, 0px)';
				transformContainer(translate3d, true);

				setTimeout(function(){
					$.isFunction( options.afterLoad ) && options.afterLoad.call( this, anchorLink, (sectionIndex + 1));

						setTimeout(function(){
							isMoving = false;
							$.isFunction( callback ) && callback.call( this);
						}, scrollDelay);
				}, options.scrollingSpeed);
			}else{
				$.isFunction( options.onLeave ) && options.onLeave.call( this, leavingSection, yMovement);

				$(scrolledElement).animate(
					scrollOptions
				, options.scrollingSpeed, options.easing, function() {
					//callback
					$.isFunction( options.afterLoad ) && options.afterLoad.call( this, anchorLink, (sectionIndex + 1));

					setTimeout(function(){
						isMoving = false;
						$.isFunction( callback ) && callback.call( this);
					}, scrollDelay);
				});
			}

			//flag to avoid callingn `scrollPage()` twice in case of using anchor links
			lastScrolledDestiny = anchorLink;

			//avoid firing it twice (as it does also on scroll)
			if(options.autoScrolling){
				activateMenuElement(anchorLink);
				activateNavDots(anchorLink, sectionIndex);
			}
		}

		function scrollToAnchor(){
			//getting the anchor link in the URL and deleting the `#`
			var value =  window.location.hash.replace('#', '').split('/');
			var section = value[0];
			var slide = value[1];

			if(section){  //if theres any #
				scrollPageAndSlide(section, slide);
			}
		}

		//detecting any change on the URL to scroll to the given anchor link
		//(a way to detect back history button as we play with the hashes on the URL)
		$(window).on('hashchange',function(){
			if(!isScrolling){
				var value =  window.location.hash.replace('#', '').split('/');
				var section = value[0];
				var slide = value[1];

				//when moving to a slide in the first section for the first time (first time to add an anchor to the URL)
				var isFirstSlideMove =  (typeof lastScrolledDestiny === 'undefined');
				var isFirstScrollMove = (typeof lastScrolledDestiny === 'undefined' && typeof slide === 'undefined');

				/*in order to call scrollpage() only once for each destination at a time
				It is called twice for each scroll otherwise, as in case of using anchorlinks `hashChange`
				event is fired on every scroll too.*/
				if ((section && section !== lastScrolledDestiny) && !isFirstSlideMove || isFirstScrollMove || (typeof slide !== 'undefined' && !slideMoving && lastScrolledSlide != slide ))  {
					scrollPageAndSlide(section, slide);
				}
			}

		});

		/**
		 * Sliding with arrow keys, both, vertical and horizontal
		 */
		$(document).keydown(function(e) {
			//Moving the main page with the keyboard arrows if keyboard scrolling is enabled
			if (options.keyboardScrolling && !isMoving) {
				switch (e.which) {
				//up
				case 38:
				case 33:
					$.fn.fullpage.moveSectionUp();
					break;

				//down
				case 40:
				case 34:
					$.fn.fullpage.moveSectionDown();
					break;

				//left
				case 37:
					$('.section.active').find('.controlArrow.prev:visible').trigger('click');
					break;

				//right
				case 39:
					$('.section.active').find('.controlArrow.next:visible').trigger('click');
					break;

				default:
					return; // exit this handler for other keys
				}
			}
		});

		//navigation action
		$(document).on('click', '#fullPage-nav a', function(e){
			e.preventDefault();
			var index = $(this).parent().index();
			scrollPage($('.section').eq(index));
		});

		//navigation tooltips
		$(document).on({
			mouseenter: function(){
				var tooltip = $(this).data('tooltip');
				$('
' + tooltip + '
').hide().appendTo($(this)).fadeIn(200);
			},
			mouseleave: function(){
				$(this).find('.fullPage-tooltip').fadeOut().remove();
			}
		}, '#fullPage-nav li');

		if(options.normalScrollElements){
			$(document).on('mouseover', options.normalScrollElements, function () {
				$.fn.fullpage.setMouseWheelScrolling(false);
			});

			$(document).on('mouseout', options.normalScrollElements, function(){
				$.fn.fullpage.setMouseWheelScrolling(true);
			});
		}

		/**
		 * Scrolling horizontally when clicking on the slider controls.
		 */
		$('.section').on('click', '.controlArrow', function() {
			//not that fast my friend! :)
			if (slideMoving) {
				return;
			}
			slideMoving = true;

			var slides = $(this).closest('.section').find('.slides');
			var currentSlide = slides.find('.slide.active');
			var destiny = null;

			if ($(this).hasClass('prev')) {
				destiny = currentSlide.prev('.slide');
			} else {
				destiny = currentSlide.next('.slide');
			}

			//is there isn't a next slide in the secuence?
			if(!destiny.length) {
				//to the last
				if ($(this).hasClass('prev')) {
					destiny = currentSlide.siblings(':last');
				} else {
					destiny = currentSlide.siblings(':first');
				}
			}

			landscapeScroll(slides, destiny);
		});

		/**
		 * Scrolling horizontally when clicking on the slider controls.
		 */
		$('.section').on('click', '.toSlide', function(e) {
			e.preventDefault();

			var slides = $(this).closest('.section').find('.slides');
			var currentSlide = slides.find('.slide.active');
			var destiny = null;

			destiny = slides.find('.slide').eq( ($(this).data('index') -1) );

			if(destiny.length > 0){
				landscapeScroll(slides, destiny);
			}
		});

		/**
		* Scrolls horizontal sliders.
		*/
		function landscapeScroll(slides, destiny){
			var destinyPos = destiny.position();
			var slidesContainer = slides.find('.slidesContainer').parent();
			var slideIndex = destiny.index();
			var section = slides.closest('.section');
			var sectionIndex = section.index('.section');
			var anchorLink = section.data('anchor');
			var slidesNav = section.find('.fullPage-slidesNav');
			var slideAnchor = destiny.data('anchor');

			//caching the value of isResizing at the momment the function is called
			//because it will be checked later inside a setTimeout and the value might change
			var localIsResizing = isResizing;

			if(options.onSlideLeave){
				var prevSlideIndex = section.find('.slide.active').index();
				var xMovement = getXmovement(prevSlideIndex, slideIndex);

				//if the site is not just resizing and readjusting the slides
				if(!localIsResizing){
					$.isFunction( options.onSlideLeave ) && options.onSlideLeave.call( this, anchorLink, (sectionIndex + 1), prevSlideIndex, xMovement);
				}
			}
			//slide trigger
			//string convert array
			if(destiny.data("margin")){
				var newH=$(".place-warp").height();
				//console.log($(".place-warp").length);
				// var imgW=388;
				// var imgH=800;
				// var newW=Number(newH)*imgW/imgH;
				// console.log(newH);
				// console.log(newW)
				var rate=Number(newH)/995;

				var arrMargin=destiny.data("margin").split(",");
				$(".circle").css({

						opacity:0.8,
					    margin:(arrMargin[0]*rate)+"px 0 0 "+ (arrMargin[1]*rate)+ "px",
					    transform: "scale("+rate+","+rate+")",
						"-ms-transform": "scale("+rate+","+rate+")", /* IE 9 */
						"-webkit-transform": "scale("+rate+","+rate+")" /* Safari and Chrome */
					     });

			}else{
				$(".circle").css({

					opacity:0,
					margin:{}
				});

			}

			destiny.addClass('active').siblings().removeClass('active');

			if(typeof slideAnchor === 'undefined'){
				slideAnchor = slideIndex;
			}

			//only changing the URL if the slides are in the current section (not for resize re-adjusting)
			if(section.hasClass('active')){

				if(!options.loopHorizontal){
					//hidding it for the fist slide, showing for the rest
					section.find('.controlArrow.prev').toggle(slideIndex!=0);

					//hidding it for the last slide, showing for the rest
					section.find('.controlArrow.next').toggle(!destiny.is(':last-child'));
				}

				setURLHash(slideIndex, slideAnchor, anchorLink);
			}

			if(options.css3){
				var translate3d = 'translate3d(-' + destinyPos.left + 'px, 0px, 0px)';

				slides.find('.slidesContainer').addClass('easing').css({
					'-webkit-transform': translate3d,
					'-moz-transform': translate3d,
					'-ms-transform':translate3d,
					'transform': translate3d
				});
				setTimeout(function(){
					//if the site is not just resizing and readjusting the slides
					if(!localIsResizing){
						$.isFunction( options.afterSlideLoad ) && options.afterSlideLoad.call( this, anchorLink, (sectionIndex + 1), slideAnchor, slideIndex );
					}

					slideMoving = false;
				}, options.scrollingSpeed);
			}else{
				slidesContainer.animate({
					scrollLeft : destinyPos.left
				}, options.scrollingSpeed, function() {

					//if the site is not just resizing and readjusting the slides
					if(!localIsResizing){
						$.isFunction( options.afterSlideLoad ) && options.afterSlideLoad.call( this, anchorLink, (sectionIndex + 1), slideAnchor, slideIndex);
					}
					//letting them slide again
					slideMoving = false;
				});
			}

			slidesNav.find('.active').removeClass('active');
			slidesNav.find('li').eq(slideIndex).find('a').addClass('active');
		}

		if (!isTablet) {
			var resizeId;

			//when resizing the site, we adjust the heights of the sections
			$(window).resize(function() {
				//in order to call the functions only when the resize is finished
				//http://stackoverflow.com/questions/4298612/jquery-how-to-call-resize-event-only-once-its-finished-resizing
				clearTimeout(resizeId);
				resizeId = setTimeout(doneResizing, 500);
			});

		}
		$(window).bind('orientationchange', function() {
			doneResizing();
		});

		/**
		 * When resizing is finished, we adjust the slides sizes and positions
		 */
		function doneResizing() {
			isResizing = true;

			var windowsWidth = $(window).width();
			windowsHeight = $(window).height();

			//text and images resizing
			if (options.resize) {
				resizeMe(windowsHeight, windowsWidth);
			}

			$('.section').each(function(){
				var scrollHeight = windowsHeight - parseInt($(this).css('padding-bottom')) - parseInt($(this).css('padding-top'));

				//resizing the scrolling divs
				if(options.scrollOverflow){
					var slides = $(this).find('.slide');

					if(slides.length){
						slides.each(function(){
							createSlimScrolling($(this));
						});
					}else{
						createSlimScrolling($(this));
					}

				}

				//adjusting the height of the table-cell for IE and Firefox
				if(options.verticalCentered){
					$(this).find('.tableCell').css('height', getTableHeight($(this)) + 'px');
				}

				$(this).css('height', windowsHeight + 'px');

				//adjusting the position fo the FULL WIDTH slides...
				var slides = $(this).find('.slides');
				if (slides.length) {
					landscapeScroll(slides, slides.find('.slide.active'));
				}
			});

			//adjusting the position for the current section
			var destinyPos = $('.section.active').position();

			var activeSection = $('.section.active');

			//isn't it the first section?
			if(activeSection.index('.section')){
				scrollPage(activeSection);
			}

			isResizing = false;
		}

		/**
		 * Resizing of the font size depending on the window size as well as some of the images on the site.
		 */
		function resizeMe(displayHeight, displayWidth) {
			//Standard height, for which the body font size is correct
			var preferredHeight = 825;
			var windowSize = displayHeight;

			/* Problem to be solved

			if (displayHeight < 825) {
				var percentage = (windowSize * 100) / preferredHeight;
				var newFontSize = percentage.toFixed(2);

				$("img").each(function() {
					var newWidth = ((80 * percentage) / 100).toFixed(2);
					$(this).css("width", newWidth + '%');
				});
			} else {
				$("img").each(function() {
					$(this).css("width", '');
				});
			}*/

			if (displayHeight < 825 || displayWidth < 900) {
				if (displayWidth < 900) {
					windowSize = displayWidth;
					preferredHeight = 900;
				}
				var percentage = (windowSize * 100) / preferredHeight;
				var newFontSize = percentage.toFixed(2);

				$("body").css("font-size", newFontSize + '%');
			} else {
				$("body").css("font-size", '100%');
			}
		}

		/**
		 * Activating the website navigation dots according to the given slide name.
		 */
		function activateNavDots(name, sectionIndex){
			if(options.navigation){
				$('#fullPage-nav').find('.active').removeClass('active');
				if(name){
					$('#fullPage-nav').find('a[href="#' + name + '"]').addClass('active');
				}else{
					$('#fullPage-nav').find('li').eq(sectionIndex).find('a').addClass('active');
				}
			}
		}

		/**
		 * Activating the website main menu elements according to the given slide name.
		 */
		function activateMenuElement(name){
			if(options.menu){
				$(options.menu).find('.active').removeClass('active');
				$(options.menu).find('[data-menuanchor="'+name+'"]').addClass('active');
			}
		}

		/**
		* Return a boolean depending on whether the scrollable element is at the end or at the start of the scrolling
		* depending on the given type.
		*/
		function isScrolled(type, scrollable){
			if(type === 'top'){
				return !scrollable.scrollTop();
			}else if(type === 'bottom'){
				return scrollable.scrollTop() + scrollable.innerHeight() >= scrollable[0].scrollHeight;
			}
		}

		/**
		* Retuns `up` or `down` depending on the scrolling movement to reach its destination
		* from the current section.
		*/
		function getYmovement(destiny){
			var fromIndex = $('.section.active').index('.section');
			var toIndex = destiny.index('.section');

			if(fromIndex > toIndex){
				return 'up';
			}
			return 'down';
		}

		/**
		* Retuns `right` or `left` depending on the scrolling movement to reach its destination
		* from the current slide.
		*/
		function getXmovement(fromIndex, toIndex){
			if(fromIndex > toIndex){
				return 'left';
			}
			return 'right';
		}

		function createSlimScrolling(element){
			//needed to make `scrollHeight` work under Opera 12
			element.css('overflow', 'hidden');

			//in case element is a slide
			var section = element.closest('.section');
			var scrollable = element.find('.scrollable');

			//if there was scroll, the contentHeight will be the one in the scrollable section
			if(scrollable.length){
				var contentHeight = element.find('.scrollable').get(0).scrollHeight;
			}else{
				var contentHeight = element.get(0).scrollHeight;
				if(options.verticalCentered){
					contentHeight = element.find('.tableCell').get(0).scrollHeight;
				}
			}

			var scrollHeight = windowsHeight - parseInt(section.css('padding-bottom')) - parseInt(section.css('padding-top'));

			//needs scroll?
			if ( contentHeight > scrollHeight) {
				//was there already an scroll ? Updating it
				if(scrollable.length){
					scrollable.css('height', scrollHeight + 'px').parent().css('height', scrollHeight + 'px');
				}
				//creating the scrolling
				else{
					if(options.verticalCentered){
						element.find('.tableCell').wrapInner('
');
					}else{
						element.wrapInner('
');
					}

					element.find('.scrollable').slimScroll({
						height: scrollHeight + 'px',
						size: '10px',
						alwaysVisible: true
					});
				}
			}

			//removing the scrolling when it is not necessary anymore
			else{
				element.find('.scrollable').children().first().unwrap().unwrap();
				element.find('.slimScrollBar').remove();
				element.find('.slimScrollRail').remove();
			}

			//undo
			element.css('overflow', '');
		}

		function addTableClass(element){
			element.addClass('table').wrapInner('
');
		}

		function getTableHeight(element){
			var sectionHeight = windowsHeight;

			if(options.paddingTop || options.paddingBottom){
				var section = element;
				if(!section.hasClass('section')){
					section = element.closest('.section');
				}

				var paddings = parseInt(section.css('padding-top')) + parseInt(section.css('padding-bottom'));
				sectionHeight = (windowsHeight - paddings);
			}

			return sectionHeight;
		}

		/**
		* Adds a css3 transform property to the container class with or without animation depending on the animated param.
		*/
		function transformContainer(translate3d, animated){
			$('#superContainer').toggleClass('easing', animated);

			$('#superContainer').css({
				'-webkit-transform': translate3d,
				'-moz-transform': translate3d,
				'-ms-transform':translate3d,
				'transform': translate3d
			});
		}

		/**
		* Scrolls to the given section and slide
		*/
		function scrollPageAndSlide(destiny, slide){
			if (typeof slide === 'undefined') {
			    slide = 0;
			}

			if(isNaN(destiny)){
				var section = $('[data-anchor="'+destiny+'"]');
			}else{
				var section = $('.section').eq( (destiny -1) );
			}

			//we need to scroll to the section and then to the slide
			if (destiny !== lastScrolledDestiny && !section.hasClass('active')){
				scrollPage(section, function(){
					scrollSlider(section, slide)
				});
			}
			//if we were already in the section
			else{
				scrollSlider(section, slide);
			}

		}

		/**
		* Scrolls the slider to the given slide destination for the given section
		*/
		function scrollSlider(section, slide){
			if(typeof slide != 'undefined'){
				var slides = section.find('.slides');
				var destiny =  slides.find('[data-anchor="'+slide+'"]');

				if(!destiny.length){
					destiny = slides.find('.slide').eq(slide);
				}

				if(destiny.length){
					landscapeScroll(slides, destiny);
				}
			}
		}

		/**
		* Creates a landscape navigation bar with dots for horizontal sliders.
		*/
		function addSlidesNavigation(section, numSlides){
			section.append('

');
			var nav = section.find('.fullPage-slidesNav');

			//top or bottom
			nav.addClass(options.slidesNavPosition);

			for(var i=0; i< numSlides; i++){
				nav.find('ul').append('

');
			}

			//centering it
			nav.css('margin-left', '-' + (nav.width()/2) + 'px');

			nav.find('li').first().find('a').addClass('active');
		}

		/**
		* Sets the URL hash for a section with slides
		*/
		function setURLHash(slideIndex, slideAnchor, anchorLink){
			var sectionHash = '';

			if(options.anchors.length){

				//isn't it the first slide?
				if(slideIndex){
					if(typeof anchorLink !== 'undefined'){
						sectionHash = anchorLink;
					}

					//slide without anchor link? We take the index instead.
					if(typeof slideAnchor === 'undefined'){
						slideAnchor = slideIndex;
					}

					lastScrolledSlide = slideAnchor;
					location.hash = sectionHash + '/' + slideAnchor;

				//first slide won't have slide anchor, just the section one
				}else if(typeof slideIndex !== 'undefined'){
					location.hash = anchorLink;
				}

				//section without slides
				else{
					location.hash = anchorLink;
				}
			}
		}

		/**
		* Scrolls the slider to the given slide destination for the given section
		*/
		$(document).on('click', '.fullPage-slidesNav a', function(e){
			e.preventDefault();
			var slides = $(this).closest('.section').find('.slides');
			var destiny = slides.find('.slide').eq($(this).closest('li').index());

			landscapeScroll(slides, destiny);
		});

		/**
		* Checks for translate3d support
		* @return boolean
		* http://stackoverflow.com/questions/5661671/detecting-transform-translate3d-support
		*/
		function support3d() {
			var el = document.createElement('p'),
				has3d,
				transforms = {
					'webkitTransform':'-webkit-transform',
					'OTransform':'-o-transform',
					'msTransform':'-ms-transform',
					'MozTransform':'-moz-transform',
					'transform':'transform'
				};

			// Add it to the body to get the computed style.
			document.body.insertBefore(el, null);

			for (var t in transforms) {
				if (el.style[t] !== undefined) {
					el.style[t] = "translate3d(1px,1px,1px)";
					has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
				}
			}

			document.body.removeChild(el);

			return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
		}

		/**
		* Removes the auto scrolling action fired by the mouse wheel and tackpad.
		* After this function is called, the mousewheel and trackpad movements won't scroll through sections.
		*/
		function removeMouseWheelHandler(){
			if (document.addEventListener) {
				document.removeEventListener('mousewheel', MouseWheelHandler, false); //IE9, Chrome, Safari, Oper
				document.removeEventListener('DOMMouseScroll', MouseWheelHandler, false); //Firefox
			} else {
				document.detachEvent("onmousewheel", MouseWheelHandler); //IE 6/7/8
			}
		}

		/**
		* Adds the auto scrolling action for the mouse wheel and tackpad.
		* After this function is called, the mousewheel and trackpad movements will scroll through sections
		*/
		function addMouseWheelHandler(){
			if (document.addEventListener) {
				document.addEventListener("mousewheel", MouseWheelHandler, false); //IE9, Chrome, Safari, Oper
				document.addEventListener("DOMMouseScroll", MouseWheelHandler, false); //Firefox
			} else {
				document.attachEvent("onmousewheel", MouseWheelHandler); //IE 6/7/8
			}
		}

	};
})(jQuery);


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />

        <link rel="stylesheet" type="text/css" href="css/jquery.mobile-1.4.2.css" />
        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <title>Homebrew Buddy</title>

Homebrew Buddy

90

:

00

                        Start
                        Stop

Add

Delete?

                    Delete
                    Cancel

Add Ingredient

                    Name<input type="text" name="name" id="ingredientName" placeholder="Citra" data-clear-btn="true"/>

                    Amount (oz)<input type="text" name="amount" id="ingredientAmount" placeholder=".25" data-clear-btn="true"/>

                    Drop Time (mm:ss)<input type="text" name="time" id="ingredientDropTime" placeholder="60:00, 20:00, etc" data-clear-btn="true"/>

                Add
                Cancel

        </script>

redpajama_set_name: RedPajamaGithub


text:
package com.tuenti.voice.example.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import android.content.Context;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;

public class WakeLockManager {

	private final static String LOG_TAG = "WakeLockManager";
	private PowerManager mPowerManager;

	private WakeLock mPartialLock;
	private WakeLock mFullLock;
	private WakeLock mProximityLock;
	private Method mPowerManagerReleaseIntMethod;
	private final static int WAIT_FOR_PROXIMITY_NEGATIVE = 1;
	private final static int WAKE_UP_IMMEDIATELY = 0;

	public WakeLockManager(Context context){
		mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
		mFullLock = mPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK
											  | PowerManager.ACQUIRE_CAUSES_WAKEUP
											  | PowerManager.ON_AFTER_RELEASE, LOG_TAG);
		mPartialLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOG_TAG);

		// Check if PROXIMITY_SCREEN_OFF_WAKE_LOCK is implemented, not part of public api.
		try {
			Method method = mPowerManager.getClass().getDeclaredMethod("getSupportedWakeLockFlags");
			int supportedWakeLockFlags = (Integer) method.invoke(mPowerManager);
			Field field = PowerManager.class.getDeclaredField("PROXIMITY_SCREEN_OFF_WAKE_LOCK");
			int proximityScreenOffWakeLock = (Integer) field.get(null);
			if ((supportedWakeLockFlags & proximityScreenOffWakeLock) != 0x0) {
				mProximityLock = mPowerManager.newWakeLock(proximityScreenOffWakeLock, LOG_TAG);
			}
		} catch (Exception e){
			Log.e(LOG_TAG, "Failed to get proximity wake lock.");
		}

		if( mProximityLock != null ){
			try {
				mPowerManagerReleaseIntMethod = mProximityLock.getClass().getDeclaredMethod("release", int.class);
			}catch (Exception e) {
				Log.e(LOG_TAG, "Failed to get release method.");
			}
		}
	}

	public boolean isProximityWakeLockEnabled() {
		return mProximityLock != null;
	}

	public void setProximityWakeLock(boolean enable, boolean screenOnImmediately ){
		if (isProximityWakeLockEnabled()){
			synchronized (mProximityLock){
				if ( enable ){
					if ( !mProximityLock.isHeld() ) {
						mProximityLock.acquire();
					}
				} else {
					if ( mProximityLock.isHeld()){
						if (mPowerManagerReleaseIntMethod != null){
							try {
								int flags = screenOnImmediately ? WAKE_UP_IMMEDIATELY : WAIT_FOR_PROXIMITY_NEGATIVE;
								mPowerManagerReleaseIntMethod.invoke(mProximityLock, flags);
							} catch (Exception e){
								Log.e(LOG_TAG, "Wake lock release failed");
							}
						}
					}
				}
			}
		}
	}

	public void setWakeLock(boolean enabled, boolean screenOn ) {
		synchronized (this ) {
			if ( enabled ) {
				if ( screenOn) {
					if (!mFullLock.isHeld()){
						mFullLock.acquire();
					}
					if (mPartialLock.isHeld()){
						mPartialLock.release();
					}
				} else {
					if (!mPartialLock.isHeld()){
						mPartialLock.acquire();
					}
					if (mFullLock.isHeld()){
						mFullLock.release();
					}
				}
			} else {
				if (mFullLock.isHeld()){
					mFullLock.release();
				}
				if (mPartialLock.isHeld()){
					mPartialLock.release();
				}
			}
		}
	}

	public void releaseWakeLock() {
		setWakeLock(false, false);
		setProximityWakeLock(false, false);
	}
}


text:
package bart.model.errorgenerator.operator;

import bart.BartConstants;
import bart.IInitializableOperator;
import bart.OperatorFactory;
import bart.model.EGTask;
import bart.model.NumberOfChanges;
import bart.model.VioGenQueryConfiguration;
import speedy.model.algebra.IAlgebraOperator;
import speedy.model.algebra.Limit;
import speedy.model.database.TableAlias;
import speedy.model.database.Tuple;
import speedy.model.database.operators.IRunQuery;
import bart.model.dependency.ComparisonAtom;
import bart.model.dependency.CrossProductFormulas;
import bart.model.errorgenerator.CellChanges;
import bart.model.errorgenerator.ISampleStrategy;
import bart.model.errorgenerator.SampleParameters;
import bart.model.errorgenerator.VioGenQuery;
import bart.model.errorgenerator.operator.valueselectors.INewValueSelectorStrategy;
import bart.utility.AlgebraUtility;
import bart.utility.BartUtility;
import bart.utility.DependencyUtility;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import speedy.utility.PrintUtility;

public class ExecuteVioGenQueryInequalityRAMRandomCP implements IVioGenQueryExecutor, IInitializableOperator {

    private static Logger logger = LoggerFactory.getLogger(ExecuteVioGenQueryInequalityRAMRandomCP.class);

    private GenerateChangesAndContexts changesGenerator = new GenerateChangesAndContexts();
    private ISampleStrategy sampleStrategy;
    private IRunQuery queryRunner;
    private INewValueSelectorStrategy valueSelector;

    private void checkConditions(VioGenQuery vioGenQuery, EGTask task) {
        if (!DependencyUtility.hasOnlyVariableInequalities(vioGenQuery.getFormula())) {
            throw new IllegalArgumentException("VioGenQuery with equalities is not supported.\n" + vioGenQuery);
        }
        if (vioGenQuery.getFormula().getCrossProductFormulas().getTableAliasInCrossProducts().size() != 2) {
            throw new IllegalArgumentException("ExecuteVioGenQueryInequalityCrossProducts operator supports only cross products between two queries.\n" + vioGenQuery);
        }
        if (task.getConfiguration().isGenerateAllChanges()) {
            throw new IllegalArgumentException("ExecuteVioGenQueryInequalityCrossProducts requires a random execution. Please set generateAllChanges to false.");
        }
    }

    @Override
    public int execute(VioGenQuery vioGenQuery, CellChanges allCellChanges, EGTask task) {
        if (task.getConfiguration().isPrintLog()) System.out.println("--- VioGen Query: " + vioGenQuery.toShortString());
        intitializeOperators(task);
        checkConditions(vioGenQuery, task);
        long start = new Date().getTime();
        int sampleSize = ExecuteVioGenQueryUtility.computeSampleSize(vioGenQuery, task);
        if (sampleSize == 0) {
            if (task.getConfiguration().isPrintLog()) System.out.println("No changes required");
            return 0;
        }
        if (!task.getConfiguration().isGenerateAllChanges() && task.getConfiguration().isPrintLog()) {
            PrintUtility.printInformation("Error percentage: " + vioGenQuery.getConfiguration().getPercentage());
            PrintUtility.printInformation(sampleSize + " changes required");
        }
        if (logger.isInfoEnabled()) logger.info("Error percentage: " + vioGenQuery.getConfiguration().getPercentage());
        if (logger.isInfoEnabled()) logger.info(sampleSize + " changes required");
        Set<CrossProductTuplePair> discardedTuples = new HashSet<CrossProductTuplePair>();
        NumberOfChanges numberOfChanges = new NumberOfChanges();
        Set<Tuple> usedTuples = new HashSet<Tuple>();
        findVioGenQueries(vioGenQuery, allCellChanges, numberOfChanges, sampleSize, discardedTuples, usedTuples, start, task);
        if (!ExecuteVioGenQueryUtility.checkIfFinished(numberOfChanges.getChanges(), sampleSize)) {
            if (logger.isInfoEnabled()) logger.info("After first iteration there are " + (sampleSize - numberOfChanges.getChanges()) + " remaining changes to perform!");
            executeDiscardedPairs(vioGenQuery, allCellChanges, discardedTuples, usedTuples, numberOfChanges, sampleSize, start, task);
        }
        if (task.getConfiguration().isPrintLog()) PrintUtility.printSuccess("Executed changes: " + numberOfChanges.getChanges());
        return numberOfChanges.getChanges();
    }

    private void findVioGenQueries(VioGenQuery vioGenQuery, CellChanges allCellChanges, NumberOfChanges numberOfChanges, int sampleSize, Set<CrossProductTuplePair> discardedTuples, Set<Tuple> usedTuples, long start, EGTask task) {
        int offset = computeOffset(vioGenQuery, task);
        if (logger.isInfoEnabled()) logger.info("Random p: " + vioGenQuery.getConfiguration().getProbabilityFactorForInequalityQueries());
        CrossProductFormulas crossProduct = vioGenQuery.getFormula().getCrossProductFormulas();
        List<ComparisonAtom> inequalityComparisons = crossProduct.getInequalityComparisons();
        if (logger.isDebugEnabled()) logger.debug("Inequality Comparisons: " + inequalityComparisons);
        List<TableAlias> tableAliasInCrossProducts = crossProduct.getTableAliasInCrossProducts();
        TableAlias firstTableAlias = tableAliasInCrossProducts.get(0);
        IAlgebraOperator firstOperator = crossProduct.getCrossProductAlgebraOperator(firstTableAlias);
        firstOperator = addLimit(firstOperator, firstTableAlias, vioGenQuery, offset, task);
        if (logger.isDebugEnabled()) logger.debug("First operator\n" + firstOperator);
        List<Tuple> firstExtractedTuples = ExecuteVioGenQueryUtility.materializeTuples(firstOperator, queryRunner, task);
        if (logger.isDebugEnabled()) logger.debug("Tuples for alias " + firstTableAlias + ": " + firstExtractedTuples.size());
        TableAlias secondTableAlias = tableAliasInCrossProducts.get(1);
        IAlgebraOperator secondOperator = crossProduct.getCrossProductAlgebraOperator(secondTableAlias);
        secondOperator = addLimit(secondOperator, secondTableAlias, vioGenQuery, offset, task);
        if (logger.isDebugEnabled()) logger.debug("Second operator\n" + secondOperator);
        List<Tuple> secondExtractedTuples = ExecuteVioGenQueryUtility.materializeTuples(secondOperator, queryRunner, task);
        if (logger.isDebugEnabled()) logger.debug("Tuples for alias " + secondTableAlias + ": " + secondExtractedTuples.size());
        for (Tuple firstTuple : firstExtractedTuples) {
            if (BartUtility.isTimeout(start, task)) {
                logger.warn("Timeout for vioGenQuery " + vioGenQuery);
                discardedTuples.clear();
                return;
            }
            if (usedTuples.contains(firstTuple)) {
                continue;
            }
            for (Tuple secondTuple : secondExtractedTuples) {
                if (BartUtility.isTimeout(start, task)) {
                    logger.warn("Timeout for vioGenQuery " + vioGenQuery);
                    discardedTuples.clear();
                    return;
                }
                if (usedTuples.contains(firstTuple) || usedTuples.contains(secondTuple)) {
                    continue;
                }
                CrossProductTuplePair tuplePair = new CrossProductTuplePair(firstTuple, firstTableAlias, secondTuple, secondTableAlias);
                if (discardedTuples.size() < offset) {
                    discardedTuples.add(tuplePair);
                    continue;
                }
                if (!BartUtility.pickRandom(vioGenQuery.getConfiguration().getProbabilityFactorForInequalityQueries())) {
                    discardedTuples.add(tuplePair);
                    continue;
                }
                boolean verified = AlgebraUtility.verifyComparisonsOnTuplePair(tuplePair.getFirstTuple(), tuplePair.getSecondTuple(), vioGenQuery.getFormula(), task);
                if (!verified) {
                    continue;
                }
                if (logger.isDebugEnabled()) logger.debug("Tuple pair to handle " + tuplePair);
                changesGenerator.handleTuplePair(tuplePair.getFirstTuple(), tuplePair.getSecondTuple(), vioGenQuery, allCellChanges, numberOfChanges, usedTuples, valueSelector, task);
                if (ExecuteVioGenQueryUtility.checkIfFinished(numberOfChanges.getChanges(), sampleSize)) {
                    if (logger.isInfoEnabled()) logger.info("All changes generated!");
                    return;
                }
            }
        }
    }

    private void executeDiscardedPairs(VioGenQuery vioGenQuery, CellChanges allCellChanges, Set<CrossProductTuplePair> discardedTuples, Set<Tuple> usedTuples, NumberOfChanges numberOfChanges, int sampleSize, long start, EGTask task) {
        Iterator<CrossProductTuplePair> it = discardedTuples.iterator();
        while (it.hasNext()) {
            if (BartUtility.isTimeout(start, task)) {
                logger.warn("Timeout for vioGenQuery " + vioGenQuery);
                return;
            }
            CrossProductTuplePair tuplePair = it.next();
            if (usedTuples.contains(tuplePair.getFirstTuple()) || usedTuples.contains(tuplePair.getSecondTuple())) {
                continue;
            }
            boolean verified = AlgebraUtility.verifyComparisonsOnTuplePair(tuplePair.getFirstTuple(), tuplePair.getSecondTuple(), vioGenQuery.getFormula(), task);
            if (!verified) {
                continue;
            }
            changesGenerator.handleTuplePair(tuplePair.getFirstTuple(), tuplePair.getSecondTuple(), vioGenQuery, allCellChanges, numberOfChanges, usedTuples, valueSelector, task);
            if (ExecuteVioGenQueryUtility.checkIfFinished(numberOfChanges.getChanges(), sampleSize)) {
                return;
            }
        }
    }

    private int computeOffset(VioGenQuery vioGenQuery, EGTask task) {
        if (!vioGenQuery.getConfiguration().isUseOffsetInInequalityQueries()) {
            return 0;
        }
        int sampleSize = ExecuteVioGenQueryUtility.computeSampleSize(vioGenQuery, task);
        Set<TableAlias> tableInFormula = DependencyUtility.extractTableAliasInFormula(vioGenQuery.getFormula());
        SampleParameters sampleParameters = sampleStrategy.computeParameters(vioGenQuery.getQuery(), tableInFormula, BartConstants.INEQUALITY_QUERY_TYPE, sampleSize, vioGenQuery.getConfiguration(), task);
        int offset = sampleParameters.getOffset();
        if (logger.isInfoEnabled()) logger.info("Offset: " + offset);
        return offset;
    }

    private IAlgebraOperator addLimit(IAlgebraOperator operator, TableAlias tableAlias, VioGenQuery vioGenQuery, int offset, EGTask task) {
        VioGenQueryConfiguration queryConfiguration = vioGenQuery.getConfiguration();
        if (queryConfiguration.isUseLimitInInequalityQueries()) {
            int sampleSize = ExecuteVioGenQueryUtility.computeSampleSize(vioGenQuery, task);
            Set<TableAlias> tablesInFormula = new HashSet<TableAlias>();
            tablesInFormula.add(tableAlias);
            SampleParameters sampleParameters = sampleStrategy.computeParameters(operator, tablesInFormula, BartConstants.INEQUALITY_QUERY_TYPE, sampleSize, queryConfiguration, task);
            int limitValue = sampleParameters.getLimit() + offset;
            Limit limit = new Limit(limitValue);
            limit.addChild(operator);
            operator = limit;
        }
        if (logger.isDebugEnabled()) logger.debug("Operator:\n" + operator);
        return operator;
    }

    public void intitializeOperators(EGTask task) {
        queryRunner = OperatorFactory.getInstance().getQueryRunner(task);
        valueSelector = OperatorFactory.getInstance().getValueSelector(task);
        String strategy = task.getConfiguration().getSampleStrategyForInequalityQueries();
        sampleStrategy = OperatorFactory.getInstance().getSampleStrategy(strategy, task);
    }

}

class CrossProductTuplePair {

    Tuple firstTuple;
    TableAlias firstTableAlias;
    Tuple secondTuple;
    TableAlias secondTableAlias;

    public CrossProductTuplePair(Tuple firstTuple, TableAlias firstTableAlias, Tuple secondTuple, TableAlias secondTableAlias) {
        this.firstTuple = firstTuple;
        this.firstTableAlias = firstTableAlias;
        this.secondTuple = secondTuple;
        this.secondTableAlias = secondTableAlias;
    }

    public Tuple getFirstTuple() {
        return firstTuple;
    }

    public TableAlias getFirstTableAlias() {
        return firstTableAlias;
    }

    public Tuple getSecondTuple() {
        return secondTuple;
    }

    public TableAlias getSecondTableAlias() {
        return secondTableAlias;
    }

    @Override
    public String toString() {
        return "CrossProductTuplePair{" + "firstTuple=" + firstTuple.toStringWithOIDAndAlias() + ", firstTableAlias=" + firstTableAlias + "\n\tsecondTuple=" + secondTuple.toStringWithOIDAndAlias() + ", secondTableAlias=" + secondTableAlias + '}';
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>javax.management.loading (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<meta name="keywords" content="javax.management.loading package">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

javax.management.loading

Interfaces

ClassLoaderRepository

MLetMBean

PrivateClassLoader

Classes

DefaultLoaderRepository

MLet

MLetContent

PrivateMLet


text:
#region Foreign-License

#endregion
using System;
namespace Tcl.Lang
{

    ///  This class implements the binary data object type in Tcl.
    public class TclByteArray : IInternalRep
    {

        ///  The number of bytes used in the byte array.
        /// The following structure is the internal rep for a ByteArray object.
        /// Keeps track of how much memory has been used. This can be different from
        /// how much has been allocated for the byte array to enable growing and
        /// shrinking of the ByteArray object with fewer allocations.
        ///
        private int used;

        ///  Internal representation of the binary data.
        private byte[] bytes;

        ///  Create a new empty Tcl binary data.
        private TclByteArray()
        {
            used = 0;
            bytes = new byte[0];
        }

        ///  Create a new Tcl binary data.
        private TclByteArray(byte[] b)
        {
            used = b.Length;
            bytes = new byte[used];
            Array.Copy(b, 0, bytes, 0, used);
        }

        ///  Create a new Tcl binary data.
        private TclByteArray(byte[] b, int position, int length)
        {
            used = length;
            bytes = new byte[used];
            Array.Copy(b, position, bytes, 0, used);
        }

        ///  Create a new Tcl binary data.
        private TclByteArray(char[] c)
        {
            used = c.Length;
            bytes = new byte[used];
            for (int ix = 0; ix < used; ix++)
            {
                bytes[ix] = (byte)c[ix];
            }
        }

        ///  Returns a duplicate of the current object.
        ///
        ///
        /// <param name="obj">the TclObject that contains this internalRep.
        /// </param>
        public IInternalRep Duplicate()
        {
            return new TclByteArray(bytes, 0, used);
        }

        ///  Implement this no-op for the InternalRep interface.

        public void Dispose()
        {
        }

        ///  Called to query the string representation of the Tcl object. This
        /// method is called only by TclObject.toString() when
        /// TclObject.stringRep is null.
        ///
        ///
        /// <returns> the string representation of the Tcl object.
        /// </returns>
        public override string ToString()
        {
            char[] c = new char[used];
            for (int ix = 0; ix < used; ix++)
            {
                c[ix] = (char)(bytes[ix] & 0xff);
            }
            return new string(c);
        }

        ///  Creates a new instance of a TclObject with a TclByteArray internal
        /// rep.
        ///
        ///
        /// <returns> the TclObject with the given byte array value.
        /// </returns>

        public static TclObject NewInstance(byte[] b, int position, int length)
        {
            return new TclObject(new TclByteArray(b, position, length));
        }

        ///  Creates a new instance of a TclObject with a TclByteArray internal
        /// rep.
        ///
        ///
        /// <returns> the TclObject with the given byte array value.
        /// </returns>

        public static TclObject NewInstance(byte[] b)
        {
            return new TclObject(new TclByteArray(b));
        }

        ///  Creates a new instance of a TclObject with an empty TclByteArray
        /// internal rep.
        ///
        ///
        /// <returns> the TclObject with the empty byte array value.
        /// </returns>

        public static TclObject NewInstance()
        {
            return new TclObject(new TclByteArray());
        }

        ///  Called to convert the other object's internal rep to a ByteArray.
        ///
        ///
        /// <param name="interp">current interpreter.
        /// </param>
        /// <param name="tobj">the TclObject to convert to use the ByteArray internal rep.
        /// </param>
        /// <exception cref=""> TclException if the object doesn't contain a valid ByteArray.
        /// </exception>
        internal static void setByteArrayFromAny(Interp interp, TclObject tobj)
        {
            IInternalRep rep = tobj.InternalRep;

            if (!(rep is TclByteArray))
            {

                char[] c = tobj.ToString().ToCharArray();
                tobj.InternalRep = new TclByteArray(c);
            }
        }

        ///
        /// This method changes the length of the byte array for this
        /// object.  Once the caller has set the length of the array, it
        /// is acceptable to directly modify the bytes in the array up until
        /// Tcl_GetStringFromObj() has been called on this object.
        ///
        /// Results:
        /// The new byte array of the specified length.
        ///
        /// Side effects:
        /// Allocates enough memory for an array of bytes of the requested
        /// size.  When growing the array, the old array is copied to the
        /// new array; new bytes are undefined.  When shrinking, the
        /// old array is truncated to the specified length.
        ///

        public static byte[] SetLength(Interp interp, TclObject tobj, int length)
        {
            if (tobj.Shared)
            {
                throw new TclRuntimeError("TclByteArray.setLength() called with shared object");
            }
            setByteArrayFromAny(interp, tobj);
            TclByteArray tbyteArray = (TclByteArray)tobj.InternalRep;

            if (length > tbyteArray.bytes.Length)
            {
                byte[] newBytes = new byte[length];
                Array.Copy(tbyteArray.bytes, 0, newBytes, 0, tbyteArray.used);
                tbyteArray.bytes = newBytes;
            }
            tobj.invalidateStringRep();
            tbyteArray.used = length;
            return tbyteArray.bytes;
        }

        ///  Queries the length of the byte array. If tobj is not a byte array
        /// object, an attempt will be made to convert it to a byte array.
        ///
        ///
        /// <param name="interp">current interpreter.
        /// </param>
        /// <param name="tobj">the TclObject to use as a byte array.
        /// </param>
        /// <returns> the length of the byte array.
        /// </returns>
        /// <exception cref=""> TclException if tobj is not a valid byte array.
        /// </exception>
        public static int getLength(Interp interp, TclObject tobj)
        {
            setByteArrayFromAny(interp, tobj);

            TclByteArray tbyteArray = (TclByteArray)tobj.InternalRep;
            return tbyteArray.used;
        }

        ///  Returns the bytes of a ByteArray object.  If tobj is not a ByteArray
        /// object, an attempt will be made to convert it to a ByteArray.

        ///
        ///
        /// <param name="interp">the current interpreter.
        /// </param>
        /// <param name="tobj">the byte array object.
        /// </param>
        /// <returns> a byte array.
        /// </returns>
        /// <exception cref=""> TclException if tobj is not a valid ByteArray.
        /// </exception>
        public static byte[] getBytes(Interp interp, TclObject tobj)
        {
            setByteArrayFromAny(interp, tobj);
            TclByteArray tbyteArray = (TclByteArray)tobj.InternalRep;
            return tbyteArray.bytes;
        }
    }
}


text:
package com.twitter.inject

import com.twitter.concurrent.NamedPoolThreadFactory
import com.twitter.util.ExecutorServiceFuturePool
import java.util.concurrent.Executors

object PoolUtils {

  def newUnboundedPool(name: String): ExecutorServiceFuturePool = {
    new ExecutorServiceFuturePool(Executors.newCachedThreadPool(new NamedPoolThreadFactory(name)))
  }

  def newFixedPool(name: String, size: Int = 1): ExecutorServiceFuturePool = {
    new ExecutorServiceFuturePool(
      Executors.newFixedThreadPool(size, new NamedPoolThreadFactory(name))
    )
  }
}


text:
package com.leocardz.link.preview.library;

import android.os.AsyncTask;

import org.jsoup.nodes.Document;

import java.util.HashMap;
import java.util.List;

/**
 * ImagePickingStrategy that mimics the original behavior of TextCrawler.  If a meta image tag exists,
 * it is used, if not, the document is scraped to find other images.
 */
class DefaultImagePickingStrategy extends BaseImagePickingStrategy {

    /**
     * Gets images from the html code
     */
    @Override
    public List<String> getImages(AsyncTask asyncTask, Document document, HashMap<String, String> metaTags) {
        List<String> images = getMetaImage(metaTags);

        if (images.isEmpty()) {
            images.addAll(getImagesFromImgTags(asyncTask, document));
        }
        return images;
    }
}


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <memory>

#include "base/memory/weak_ptr.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "chrome/renderer/subresource_redirect/robots_rules_parser.h"
#include "components/subresource_redirect/proto/robots_rules.pb.h"
#include "components/subresource_redirect/subresource_redirect_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"

namespace subresource_redirect {

constexpr char kTestOrigin[] = "https://test.com";

class CheckResultReceiver {
 public:
  void OnCheckRobotsRulesResult(RobotsRulesParser::CheckResult check_result) {
    EXPECT_FALSE(did_receive_result_);
    did_receive_result_ = true;
    check_result_ = check_result;
  }
  RobotsRulesParser::CheckResultCallback GetCallback() {
    return base::BindOnce(&CheckResultReceiver::OnCheckRobotsRulesResult,
                          weak_ptr_factory_.GetWeakPtr());
  }
  RobotsRulesParser::CheckResult check_result() const { return check_result_; }
  bool did_receive_result() const { return did_receive_result_; }

 private:
  RobotsRulesParser::CheckResult check_result_;
  bool did_receive_result_ = false;
  base::WeakPtrFactory<CheckResultReceiver> weak_ptr_factory_{this};
};

const int kRenderFrameID = 1;

class SubresourceRedirectRobotsRulesParserTest : public testing::Test {
 public:
  SubresourceRedirectRobotsRulesParserTest()
      : task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME),
        robots_rules_parser_(base::Seconds(1)) {}
  void SetUp() override {
    scoped_feature_list_.InitWithFeaturesAndParameters(
        {{blink::features::kSubresourceRedirect, {{}}}}, {});
  }

  void SetUpRobotsRules(const std::vector<RobotsRule>& patterns) {
    robots_rules_parser_.UpdateRobotsRules(GetRobotsRulesProtoString(patterns));
    VerifyRulesReceiveState(RobotsRulesParser::RulesReceiveState::kSuccess);
  }

  // Verify robots rules check result is received synchronously with the
  // expected result.
  void CheckRobotsRules(const std::string& url_path_with_query,
                        RobotsRulesParser::CheckResult expected_result,
                        int render_frame_id = kRenderFrameID) {
    CheckResultReceiver result_receiver;
    auto result = robots_rules_parser_.CheckRobotsRules(
        render_frame_id, GURL(kTestOrigin + url_path_with_query),
        result_receiver.GetCallback());
    EXPECT_FALSE(result_receiver.did_receive_result());
    EXPECT_EQ(expected_result, result);
  }

  // Verify robots rules check result is received asynchronously, and returns
  // the receiver that can be used to check the result.
  std::unique_ptr<CheckResultReceiver> CheckRobotsRulesAsync(
      const std::string& url_path_with_query,
      int render_frame_id = kRenderFrameID) {
    auto result_receiver = std::make_unique<CheckResultReceiver>();
    EXPECT_FALSE(robots_rules_parser_.CheckRobotsRules(
        render_frame_id, GURL(kTestOrigin + url_path_with_query),
        result_receiver->GetCallback()));
    return result_receiver;
  }

  void VerifyRulesReceiveState(
      RobotsRulesParser::RulesReceiveState expected_rules_receive_state) {
    EXPECT_EQ(robots_rules_parser_.rules_receive_state_,
              expected_rules_receive_state);
  }

  void VerifyRobotsRulesReceiveResultHistogram(
      RobotsRulesParser::SubresourceRedirectRobotsRulesReceiveResult result) {
    histogram_tester().ExpectUniqueSample(
        "SubresourceRedirect.RobotRulesDecider.ReceiveResult", result, 1);
  }

  void VerifyReceivedRobotsRulesCountHistogram(size_t count) {
    histogram_tester().ExpectUniqueSample(
        "SubresourceRedirect.RobotRulesDecider.Count", count, 1);
  }

  void VerifyTotalRobotsRulesApplyHistograms(size_t total) {
    histogram_tester().ExpectTotalCount(
        "SubresourceRedirect.RobotRulesDecider.ApplyDuration", total);
  }

  const base::HistogramTester& histogram_tester() { return histogram_tester_; }

 protected:
  base::test::ScopedFeatureList scoped_feature_list_;
  base::test::TaskEnvironment task_environment_;
  base::HistogramTester histogram_tester_;
  RobotsRulesParser robots_rules_parser_;
};

TEST_F(SubresourceRedirectRobotsRulesParserTest,
       InvalidProtoParseErrorDisallowsAllPaths) {
  VerifyRulesReceiveState(RobotsRulesParser::RulesReceiveState::kTimerRunning);
  robots_rules_parser_.UpdateRobotsRules("INVALID PROTO");
  VerifyRulesReceiveState(RobotsRulesParser::RulesReceiveState::kParseFailed);
  VerifyRobotsRulesReceiveResultHistogram(
      RobotsRulesParser::SubresourceRedirectRobotsRulesReceiveResult::
          kParseError);
  histogram_tester().ExpectTotalCount(
      "SubresourceRedirect.RobotRulesDecider.Count", 0);

  // All url paths should be disallowed.
  CheckRobotsRules("", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/foo.jpg", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/foo/bar.jpg", RobotsRulesParser::CheckResult::kDisallowed);
  VerifyTotalRobotsRulesApplyHistograms(0);
}

TEST_F(SubresourceRedirectRobotsRulesParserTest, EmptyRulesAllowsAllPaths) {
  VerifyRulesReceiveState(RobotsRulesParser::RulesReceiveState::kTimerRunning);
  SetUpRobotsRules({});
  VerifyRobotsRulesReceiveResultHistogram(
      RobotsRulesParser::SubresourceRedirectRobotsRulesReceiveResult::kSuccess);
  VerifyReceivedRobotsRulesCountHistogram(0);

  // All url paths should be allowed.
  CheckRobotsRules("", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/foo.jpg", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/foo/bar.jpg", RobotsRulesParser::CheckResult::kAllowed);
  VerifyTotalRobotsRulesApplyHistograms(4);
}

TEST_F(SubresourceRedirectRobotsRulesParserTest,
       RulesReceiveTimeoutDisallowsAllPaths) {
  // Let the rule fetch timeout.
  VerifyRulesReceiveState(RobotsRulesParser::RulesReceiveState::kTimerRunning);
  task_environment_.FastForwardBy(base::Seconds(10));
  VerifyRobotsRulesReceiveResultHistogram(
      RobotsRulesParser::SubresourceRedirectRobotsRulesReceiveResult::kTimeout);
  VerifyRulesReceiveState(RobotsRulesParser::RulesReceiveState::kTimeout);

  // All url paths should be disallowed due to timeout.
  CheckRobotsRules("", RobotsRulesParser::CheckResult::kDisallowedAfterTimeout);
  CheckRobotsRules("/",
                   RobotsRulesParser::CheckResult::kDisallowedAfterTimeout);
  CheckRobotsRules("/foo.jpg",
                   RobotsRulesParser::CheckResult::kDisallowedAfterTimeout);
  CheckRobotsRules("/foo/bar.jpg",
                   RobotsRulesParser::CheckResult::kDisallowedAfterTimeout);
  VerifyTotalRobotsRulesApplyHistograms(0);
}

TEST_F(SubresourceRedirectRobotsRulesParserTest,
       CheckResultCallbackAfterRulesReceived) {
  auto receiver1 = CheckRobotsRulesAsync("/foo.jpg");
  auto receiver2 = CheckRobotsRulesAsync("/bar");
  EXPECT_FALSE(receiver1->did_receive_result());
  EXPECT_FALSE(receiver2->did_receive_result());
  VerifyTotalRobotsRulesApplyHistograms(0);

  // Once the rules are received the callback should get called with the result.
  VerifyRulesReceiveState(RobotsRulesParser::RulesReceiveState::kTimerRunning);
  SetUpRobotsRules({{kRuleTypeAllow, "/foo"}, {kRuleTypeDisallow, "/"}});
  VerifyRobotsRulesReceiveResultHistogram(
      RobotsRulesParser::SubresourceRedirectRobotsRulesReceiveResult::kSuccess);
  VerifyReceivedRobotsRulesCountHistogram(2);

  EXPECT_TRUE(receiver1->did_receive_result());
  EXPECT_TRUE(receiver2->did_receive_result());
  EXPECT_EQ(RobotsRulesParser::CheckResult::kAllowed,
            receiver1->check_result());
  EXPECT_EQ(RobotsRulesParser::CheckResult::kDisallowed,
            receiver2->check_result());
  VerifyTotalRobotsRulesApplyHistograms(2);

  CheckRobotsRules("/foo.png", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/bar", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/baz", RobotsRulesParser::CheckResult::kDisallowed);
  VerifyTotalRobotsRulesApplyHistograms(5);
}

// Verify if the callback is called before the decider gets destroyed.
TEST_F(SubresourceRedirectRobotsRulesParserTest,
       VerifyCallbackCalledBeforeDeciderDestroy) {
  auto robots_rules_parser =
      std::make_unique<RobotsRulesParser>(base::Seconds(1));
  auto receiver1 = std::make_unique<CheckResultReceiver>();
  auto receiver2 = std::make_unique<CheckResultReceiver>();

  robots_rules_parser->CheckRobotsRules(kRenderFrameID,
                                        GURL("https://test.com/foo.jpg"),
                                        receiver1->GetCallback());
  robots_rules_parser->CheckRobotsRules(
      kRenderFrameID, GURL("https://test.com/bar"), receiver2->GetCallback());
  EXPECT_FALSE(receiver1->did_receive_result());
  EXPECT_FALSE(receiver2->did_receive_result());
  VerifyTotalRobotsRulesApplyHistograms(0);

  robots_rules_parser->UpdateRobotsRules(GetRobotsRulesProtoString(
      {{kRuleTypeAllow, "/foo"}, {kRuleTypeDisallow, "/"}}));

  // Destroying the decider should trigger the callbacks.
  robots_rules_parser.reset();

  EXPECT_TRUE(receiver1->did_receive_result());
  EXPECT_TRUE(receiver2->did_receive_result());
  EXPECT_EQ(RobotsRulesParser::CheckResult::kAllowed,
            receiver1->check_result());
  EXPECT_EQ(RobotsRulesParser::CheckResult::kDisallowed,
            receiver2->check_result());
  VerifyTotalRobotsRulesApplyHistograms(2);
}

TEST_F(SubresourceRedirectRobotsRulesParserTest,
       CheckResultCallbackAfterRulesReceiveTimeout) {
  auto receiver1 = CheckRobotsRulesAsync("/foo.jpg");
  auto receiver2 = CheckRobotsRulesAsync("/bar");
  EXPECT_FALSE(receiver1->did_receive_result());
  EXPECT_FALSE(receiver2->did_receive_result());
  VerifyTotalRobotsRulesApplyHistograms(0);

  // Once the rule fetch timesout,the callback should get called with the
  // result.
  task_environment_.FastForwardBy(base::Seconds(10));
  VerifyRobotsRulesReceiveResultHistogram(
      RobotsRulesParser::SubresourceRedirectRobotsRulesReceiveResult::kTimeout);
  VerifyRulesReceiveState(RobotsRulesParser::RulesReceiveState::kTimeout);

  EXPECT_TRUE(receiver1->did_receive_result());
  EXPECT_TRUE(receiver2->did_receive_result());
  EXPECT_EQ(RobotsRulesParser::CheckResult::kTimedout,
            receiver1->check_result());
  EXPECT_EQ(RobotsRulesParser::CheckResult::kTimedout,
            receiver2->check_result());
  VerifyTotalRobotsRulesApplyHistograms(0);

  SetUpRobotsRules({{kRuleTypeAllow, "/foo"}, {kRuleTypeDisallow, "/"}});

  CheckRobotsRules("/foo.png", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/bar", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/baz", RobotsRulesParser::CheckResult::kDisallowed);
  VerifyTotalRobotsRulesApplyHistograms(3);
}

TEST_F(SubresourceRedirectRobotsRulesParserTest, FullAllowRule) {
  SetUpRobotsRules({{kRuleTypeAllow, "*"}});
  VerifyRobotsRulesReceiveResultHistogram(
      RobotsRulesParser::SubresourceRedirectRobotsRulesReceiveResult::kSuccess);
  VerifyReceivedRobotsRulesCountHistogram(1);

  // All url paths should be allowed.
  CheckRobotsRules("", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/foo.jpg", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/foo/bar.jpg", RobotsRulesParser::CheckResult::kAllowed);
  VerifyTotalRobotsRulesApplyHistograms(4);
}

TEST_F(SubresourceRedirectRobotsRulesParserTest, FullDisallowRule) {
  SetUpRobotsRules({{kRuleTypeDisallow, "*"}});
  VerifyRobotsRulesReceiveResultHistogram(
      RobotsRulesParser::SubresourceRedirectRobotsRulesReceiveResult::kSuccess);
  VerifyReceivedRobotsRulesCountHistogram(1);

  // All url paths should be disallowed.
  CheckRobotsRules("", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/foo.jpg", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/foo/bar.jpg", RobotsRulesParser::CheckResult::kDisallowed);
  VerifyTotalRobotsRulesApplyHistograms(4);
}

TEST_F(SubresourceRedirectRobotsRulesParserTest, TwoAllowRules) {
  SetUpRobotsRules({{kRuleTypeAllow, "/foo"},
                    {kRuleTypeAllow, "/bar$"},
                    {kRuleTypeDisallow, "*"}});
  VerifyRobotsRulesReceiveResultHistogram(
      RobotsRulesParser::SubresourceRedirectRobotsRulesReceiveResult::kSuccess);
  VerifyReceivedRobotsRulesCountHistogram(3);

  CheckRobotsRules("", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/foo.jpg", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/foo/baz.jpg", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/bar", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/bar.jpg", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/baz", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("foo", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("bar", RobotsRulesParser::CheckResult::kDisallowed);
  VerifyTotalRobotsRulesApplyHistograms(9);
}

// When the URL path matches multiple allow and disallow rules, whichever rule
// that comes first in the list should take precedence.
TEST_F(SubresourceRedirectRobotsRulesParserTest,
       FirstAllowRuleMatchOverridesLaterDisallowRule) {
  SetUpRobotsRules({{kRuleTypeAllow, "/foo"}, {kRuleTypeDisallow, "/foo"}});
  VerifyRobotsRulesReceiveResultHistogram(
      RobotsRulesParser::SubresourceRedirectRobotsRulesReceiveResult::kSuccess);
  VerifyReceivedRobotsRulesCountHistogram(2);

  CheckRobotsRules("/foo", RobotsRulesParser::CheckResult::kAllowed);

  SetUpRobotsRules({{kRuleTypeDisallow, "/foo"}, {kRuleTypeAllow, "/foo"}});
  CheckRobotsRules("/foo", RobotsRulesParser::CheckResult::kDisallowed);

  SetUpRobotsRules({{kRuleTypeAllow, "/foo.jpg"}, {kRuleTypeDisallow, "/foo"}});
  CheckRobotsRules("/foo.jpg", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/foo", RobotsRulesParser::CheckResult::kDisallowed);

  SetUpRobotsRules({{kRuleTypeDisallow, "/foo.jpg"}, {kRuleTypeAllow, "/foo"}});
  CheckRobotsRules("/foo.jpg", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/foo", RobotsRulesParser::CheckResult::kAllowed);

  VerifyTotalRobotsRulesApplyHistograms(6);
}

TEST_F(SubresourceRedirectRobotsRulesParserTest, TestURLWithArguments) {
  SetUpRobotsRules({{kRuleTypeAllow, "/*.jpg$"},
                    {kRuleTypeDisallow, "/*.png?*arg_disallowed"},
                    {kRuleTypeAllow, "/*.png"},
                    {kRuleTypeDisallow, "/*.gif?*arg_disallowed"},
                    {kRuleTypeAllow, "/*.gif"},
                    {kRuleTypeDisallow, "/"}});
  VerifyRobotsRulesReceiveResultHistogram(
      RobotsRulesParser::SubresourceRedirectRobotsRulesReceiveResult::kSuccess);
  VerifyReceivedRobotsRulesCountHistogram(6);

  CheckRobotsRules("/allowed.jpg", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/allowed.png", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/allowed.gif", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/disallowed.jpg?arg",
                   RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/allowed.png?arg",
                   RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/allowed.png?arg_allowed",
                   RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/allowed.png?arg_allowed&arg_allowed2",
                   RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/allowed.png?arg_disallowed",
                   RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/allowed.png?arg_disallowed&arg_disallowed2",
                   RobotsRulesParser::CheckResult::kDisallowed);

  VerifyTotalRobotsRulesApplyHistograms(9);
}

TEST_F(SubresourceRedirectRobotsRulesParserTest, TestRulesAreCaseSensitive) {
  SetUpRobotsRules({{kRuleTypeAllow, "/allowed"},
                    {kRuleTypeAllow, "/CamelCase"},
                    {kRuleTypeAllow, "/CAPITALIZE"},
                    {kRuleTypeDisallow, "/"}});
  VerifyReceivedRobotsRulesCountHistogram(4);

  CheckRobotsRules("/allowed.jpg", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/CamelCase.jpg", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/CAPITALIZE.jpg", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/Allowed.jpg", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/camelcase.jpg",
                   RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/capitalize.jpg",
                   RobotsRulesParser::CheckResult::kDisallowed);

  VerifyTotalRobotsRulesApplyHistograms(6);
}

TEST_F(SubresourceRedirectRobotsRulesParserTest,
       TestRulesHandleSpecialGlobSymbols) {
  SetUpRobotsRules({
      {kRuleTypeAllow, "/allo?ed"},
      {kRuleTypeAllow, "/foo"},
      {kRuleTypeAllow, "/bar$"},
      {kRuleTypeAllow, "/boo$$"},
      {kRuleTypeAllow, "/baz*"},
      {kRuleTypeAllow, "/bop*$"},
      {kRuleTypeAllow, "*startwithstar"},
      {kRuleTypeAllow, "*anchoredtoend$"},
      {kRuleTypeDisallow, "/"},
  });
  VerifyReceivedRobotsRulesCountHistogram(9);

  // The '?' character is *not* treated as a special globbing symbol.
  CheckRobotsRules("/allo?ed.jpg", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/allowed.jpg", RobotsRulesParser::CheckResult::kDisallowed);

  // A pattern without a final '$' is not anchored to the end of the string.
  CheckRobotsRules("/foo", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/foo.jpg", RobotsRulesParser::CheckResult::kAllowed);

  // A pattern with a final '$' is anchored to the end of the string.
  CheckRobotsRules("/bar", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/bar.jpg", RobotsRulesParser::CheckResult::kDisallowed);

  // When a pattern ends with two '$' characters, the first '$' is a literal,
  // and the second matches the end of the string.
  CheckRobotsRules("/boo$", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/boo$$", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/boo", RobotsRulesParser::CheckResult::kDisallowed);
  CheckRobotsRules("/boo$.jpg", RobotsRulesParser::CheckResult::kDisallowed);

  // A trailing '*' has no effect, and it is compatible with '$'.
  CheckRobotsRules("/baz", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/bazfoo", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/bop", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/bopfoo", RobotsRulesParser::CheckResult::kAllowed);

  // Patterns with leading '*' are not anchored to the beginning of the string.
  CheckRobotsRules("/startwithstar", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/ZZZstartwithstar",
                   RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/ZZZstartwithstarbar",
                   RobotsRulesParser::CheckResult::kAllowed);

  // Patterns with leading '*' correctly interact with trailing '$'.
  CheckRobotsRules("/ZZZanchoredtoend",
                   RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/ZZZanchoredtoendZZZ",
                   RobotsRulesParser::CheckResult::kDisallowed);

  VerifyTotalRobotsRulesApplyHistograms(19);
}

TEST_F(SubresourceRedirectRobotsRulesParserTest,
       TestInvalidatePendingRequests) {
  auto receiver1 = CheckRobotsRulesAsync("/allowed.jpg", 1 /*render_frame_id*/);
  auto receiver2 =
      CheckRobotsRulesAsync("/disallowed.jpg", 1 /*render_frame_id*/);
  auto receiver3 = CheckRobotsRulesAsync("/allowed.jpg", 2 /*render_frame_id*/);
  auto receiver4 =
      CheckRobotsRulesAsync("/disallowed.jpg", 2 /*render_frame_id*/);

  // Invalidate should cancel requests for that render frame ID.
  robots_rules_parser_.InvalidatePendingRequests(1 /*render_frame_id*/);
  EXPECT_TRUE(receiver1->did_receive_result());
  EXPECT_TRUE(receiver2->did_receive_result());
  EXPECT_EQ(RobotsRulesParser::CheckResult::kInvalidated,
            receiver1->check_result());
  EXPECT_EQ(RobotsRulesParser::CheckResult::kInvalidated,
            receiver2->check_result());
  EXPECT_FALSE(receiver3->did_receive_result());
  EXPECT_FALSE(receiver4->did_receive_result());
  VerifyTotalRobotsRulesApplyHistograms(0);

  // When robots rules are retrieved, the
  SetUpRobotsRules({{kRuleTypeAllow, "/allow*"}, {kRuleTypeDisallow, "/*"}});
  EXPECT_TRUE(receiver3->did_receive_result());
  EXPECT_TRUE(receiver4->did_receive_result());
  EXPECT_EQ(RobotsRulesParser::CheckResult::kAllowed,
            receiver3->check_result());
  EXPECT_EQ(RobotsRulesParser::CheckResult::kDisallowed,
            receiver4->check_result());
  VerifyTotalRobotsRulesApplyHistograms(2);

  CheckRobotsRules("/allowed.jpg", RobotsRulesParser::CheckResult::kAllowed);
  CheckRobotsRules("/disallowed.jpg",
                   RobotsRulesParser::CheckResult::kDisallowed);
  VerifyTotalRobotsRulesApplyHistograms(4);
}

}  // namespace subresource_redirect


text:
require 'helper'

describe Twitter::Trend do

  describe "#==" do
    it "returns false for empty objects" do
      trend = Twitter::Trend.new
      other = Twitter::Trend.new
      expect(trend == other).to be_false
    end
    it "returns true when objects names are the same" do
      trend = Twitter::Trend.new(:name => "#sevenwordsaftersex", :query => "foo")
      other = Twitter::Trend.new(:name => "#sevenwordsaftersex", :query => "bar")
      expect(trend == other).to be_true
    end
    it "returns false when objects names are different" do
      trend = Twitter::Trend.new(:name => "#sevenwordsaftersex")
      other = Twitter::Trend.new(:name => "#sixwordsaftersex")
      expect(trend == other).to be_false
    end
    it "returns false when classes are different" do
      trend = Twitter::Trend.new(:name => "#sevenwordsaftersex")
      other = Twitter::Base.new(:name => "#sevenwordsaftersex")
      expect(trend == other).to be_false
    end
    it "returns true when objects non-name attributes are the same" do
      trend = Twitter::Trend.new(:query => "foo")
      other = Twitter::Trend.new(:query => "foo")
      expect(trend == other).to be_true
    end
    it "returns false when objects non-name attributes are different" do
      trend = Twitter::Trend.new(:query => "foo")
      other = Twitter::Trend.new(:query => "bar")
      expect(trend == other).to be_false
    end
  end

  describe "#uri" do
    it "returns a URI when the url is set" do
      trend = Twitter::Trend.new(:url => "http://twitter.com/search/?q=%23sevenwordsaftersex")
      expect(trend.uri).to be_a URI
      expect(trend.uri.to_s).to eq("http://twitter.com/search/?q=%23sevenwordsaftersex")
    end
    it "returns nil when the url is not set" do
      trend = Twitter::Trend.new
      expect(trend.uri).to be_nil
    end
  end

  describe "#uri?" do
    it "returns true when the url is set" do
      trend = Twitter::Trend.new(:url => "https://api.twitter.com/1.1/geo/id/247f43d441defc03.json")
      expect(trend.uri?).to be_true
    end
    it "returns false when the url is not set" do
      trend = Twitter::Trend.new
      expect(trend.uri?).to be_false
    end
  end

end


text:
<?php

require_once dirname(dirname(__DIR__)) . '/vendor/autoload.php';

use Cspray\DeliveryService;
use Cspray\DeliveryService\Amp\ReceiptPromisorFactory;
use Cspray\DeliveryService\Amp\Mediator;

$reactor = new Amp\NativeReactor();
$promisorFactory = new ReceiptPromisorFactory();
$transmitter = new DeliveryService\StandardTransmitter($promisorFactory);
$receiver = new DeliveryService\StandardReceiver();
$mediator = new Mediator($reactor, $transmitter, $receiver);

$listener = function($type, $payload) {
    $payload = $payload[0];
    echo "{$type}{$payload}\n";
};
$receiver->listen('generic', $listener);

$transmitter->send('generic', [1]);
$transmitter->send('generic', [2]);

$mediator->startSendingMessages();

$reactor->tick(); # dequeue first message and schedule listener callbacks
$reactor->tick(); # invoke first listener callbacks, dequeue next message and schedule second listener callbacks
$reactor->tick(); #
--EXPECT--
generic1
generic2


text:
/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package dk.statsbiblioteket.summa.common.configuration;

import dk.statsbiblioteket.util.qa.QAInfo;

import java.io.IOException;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * An abstraction of a storage backend for a {@link Configuration}.
 *

 *
Important: Any implementation of this interface should be
 * threadsafe.
 */
@QAInfo(level = QAInfo.Level.NORMAL,
        state = QAInfo.State.IN_DEVELOPMENT,
        author = "mke")
public interface ConfigurationStorage extends Configurable, Serializable {

    /**
     * Store a key-value pair.
     *
     * @param key   The name used to access the stored object.
     * @param value The actual value to store.
     * @throws IOException if there is an error performing the operation.
     */
    public void put(String key, Serializable value) throws IOException;

    /**
     * Retrieve a stored item.
     *
     * @param key Name of object to look up.
     * @return The object or null if the object is unknown.
     * @throws IOException if there was an error performing the operation.
     */
    public Serializable get(String key) throws IOException;

    /**
     * Get an {@code Iterator} over all key-value pairs.
     *
     * @return An Iterator over all stored key-value pairs.
     * @throws IOException if there was an error performing the operation.
     */
    public Iterator<Map.Entry<String, Serializable>> iterator() throws IOException;

    /**
     * Remove a property from the storage.
     *
     * @param key The name of the value to remove from the storage.
     * @throws IOException if there was an error performing the operation.
     */
    public void purge(String key) throws IOException;

    /**
     * Get the number of properties in the configuration.
     *
     * @return Number of properties stored.
     * @throws IOException if there was an error performing the operation.
     */
    public int size() throws IOException;

    /**
     * Tells if this storage supports multiple sub storage.
     *
     * @return True if the storage supports a hierarchical structure. I false,
     *         the methods {@link #getSubStorage} and {@link #createSubStorage} should
     *         throw an UnsupportedOperationException.
     * @throws IOException if there was an error performing the operation.
     */
    public boolean supportsSubStorage() throws IOException;

    public static final String NOT_SUBSTORAGE_CAPABLE = "Not capable of handling sub storage";

    /**
     * Creates a sub storage, adds it to the current storage and returns it.
     * Sub storage are fully capable storage and are typically used to order
     * settings in a hierarchy.
     *

     * Note: This might not be supported by all storage. Check for availability
     * with {@link #supportsSubStorage} in case of doubt.
     *
     * @param key The name of the sub storage.
     * @return The storage that was created.
     * @throws IOException if there was an error performing the operation.
     */
    public ConfigurationStorage createSubStorage(String key) throws IOException;

    /**
     * Note: This might not be supported by all storage. Check for availability
     * with {@link #supportsSubStorage} in case of doubt.
     *
     * @param key The name of the sub storage.
     * @return A sub storage.
     * @throws IOException if there was an error performing the operation.
     */
    public ConfigurationStorage getSubStorage(String key) throws IOException;

    /**
     * Creates a list of sub storage, adds it to the current storage and
     * returns it. Sub storage are fully capable storage.
     *

     * Note: This might not be supported by all storage. Check for availability
     * with {@link #supportsSubStorage} in case of doubt.
     *
     * @param key   The key for the list of storage.
     * @param count The number of storage to create.
     * @return A list of count sub storage.
     * @throws IOException if the storage could not be created.
     */
    public List<ConfigurationStorage> createSubStorages(String key, int count) throws IOException;

    /**
     * Note: This might not be supported by all storage. Check for availability
     * with {@link #supportsSubStorage} in case of doubt.
     *
     * @param key the key for the list of storage.
     * @return A list of storage.
     * @throws IOException if the list could not be extracted.
     */
    public List<ConfigurationStorage> getSubStorages(String key) throws IOException;
}


text:
$(document).ready(function() {
    /*
    ===This was to test if JS was working===
    $('#orange').click(function() {
        $(this).fadeOut('slow');
    });
    $('#box').click(function() {
        $(this).fadeOut('slow');
    });
    =========================================
    */

    var passwordEntry = function () {
        return prompt('Please enter in the correct password');
    };
        var correctPass = passwordEntry();
        var showPage = function (password) {
        switch (password) {
            case 'Yes! You have a freckle on your right thumb!':
                $('#dimScreen').fadeOut('slow');
                break;
            default:
                alert('That is not a valid password. Goodbye.');
                // use this to avoid redirects when a user clicks "back" in their browser
                window.location.replace('http://redew.github.io/huehuehue/');

                // use this to redirect, a back button call will trigger the redirection again
                window.location.href = "http://redew.github.io/huehuehue/";

                // given for completeness, essentially an alias to window.location.href
                window.location = "http://redew.github.io/huehuehue/";
                return false;
            }
       };
    var correctPage = showPage(correctPass);
});


text:
<?php

use yii\helpers\Html;
use yii\web\JsExpression;
use kartik\widgets\ActiveForm;

use kartik\widgets\Select2;

/**
 * @var yii\web\View $this
 * @var app\modules\purchase\models\PurchaseOrder $model
 * @var yii\widgets\ActiveForm $form
 */

$script = <<<SKRIPT

$('#PurchaseOrderForm').on('submit',function(){
  var postData = $(this).serializeArray();
  var formURL = $(this).attr('action');
  $.ajax({
    url : formURL,
    type: "POST",
    data : postData,
    success:function(data, textStatus, jqXHR)
    {

    },
    error: function(jqXHR, textStatus, errorThrown)
    {

    }
  });
  return false;
});

SKRIPT;

$this->registerJs($script);

?>

	<?php $form = ActiveForm::begin([
    'id' => 'PurchaseOrderForm'
  ]); ?>

<?php

$dataExp = <<< SCRIPT
  function (term, page) {
    return {
      search: term, // search term
    };
  }
SCRIPT;

$dataResults = <<< SCRIPT
  function (data, page) {
    return {
      results: data.results
    };
  }
SCRIPT;

$url = Html::url(['/parties/contact/jsonlist']);

$fInitSelection = <<< SCRIPT
  function (element, callback) {
    var id=$(element).val();
    if (id!=="") {
      $.ajax("$url&id="+id, {
        dataType: "json"
      }).done(function(data) { callback(data.results); });
    }
  }
SCRIPT;

?>

    <?= $form->field($model, 'contact_id')->widget(Select2::classname(),[
          'pluginOptions'=>[
            'minimumInputLength' => 3,
            'ajax' => [
              'url' => Html::url(['/parties/contact/jsonlist']),
              'dataType' => 'json',
              'data' => new JsExpression($dataExp),
              'results' => new JsExpression($dataResults),
            ],
            'initSelection' => new JsExpression($fInitSelection)
          ]
    ]); ?>

			<?= Html::submitButton(\Yii::t('app','Apply'), ['class' => 'btn btn-default']) ?>

	<?php ActiveForm::end(); ?>


text:
"""Writes dependency ordered list of native libraries.

The list excludes any Android system libraries, as those are not bundled with
the APK.

This list of libraries is used for several steps of building an APK.
In the component build, the --input-libraries only needs to be the top-level
library (i.e. libcontent_shell_content_view). This will then use readelf to
inspect the shared libraries and determine the full list of (non-system)
libraries that should be included in the APK.
"""

# TODO(cjhopman): See if we can expose the list of library dependencies from
# gyp, rather than calculating it ourselves.
# http://crbug.com/225558

import optparse
import os
import re
import sys

from util import build_utils

_readelf = None
_library_dirs = None

_library_re = re.compile(
    '.*NEEDED.*Shared library: \[(?P<library_name>.+)\]')

def SetReadelfPath(path):
  global _readelf
  _readelf = path

def SetLibraryDirs(dirs):
  global _library_dirs
  _library_dirs = dirs

def FullLibraryPath(library_name):
  assert _library_dirs is not None
  for directory in _library_dirs:
    path = '%s/%s' % (directory, library_name)
    if os.path.exists(path):
      return path
  return library_name

def IsSystemLibrary(library_name):
  # If the library doesn't exist in the libraries directory, assume that it is
  # an Android system library.
  return not os.path.exists(FullLibraryPath(library_name))

def CallReadElf(library_or_executable):
  assert _readelf is not None
  readelf_cmd = [_readelf,
                 '-d',
                 FullLibraryPath(library_or_executable)]
  return build_utils.CheckOutput(readelf_cmd)

def GetDependencies(library_or_executable):
  elf = CallReadElf(library_or_executable)
  return set(_library_re.findall(elf))

def GetNonSystemDependencies(library_name):
  all_deps = GetDependencies(FullLibraryPath(library_name))
  return set((lib for lib in all_deps if not IsSystemLibrary(lib)))

def GetSortedTransitiveDependencies(libraries):
  """Returns all transitive library dependencies in dependency order."""
  return build_utils.GetSortedTransitiveDependencies(
      libraries, GetNonSystemDependencies)

def GetSortedTransitiveDependenciesForBinaries(binaries):
  if binaries[0].endswith('.so'):
    libraries = [os.path.basename(lib) for lib in binaries]
  else:
    assert len(binaries) == 1
    all_deps = GetDependencies(binaries[0])
    libraries = [lib for lib in all_deps if not IsSystemLibrary(lib)]

  return GetSortedTransitiveDependencies(libraries)

def main():
  parser = optparse.OptionParser()
  build_utils.AddDepfileOption(parser)

  parser.add_option('--input-libraries',
      help='A list of top-level input libraries.')
  parser.add_option('--libraries-dir',
      help='The directory which contains shared libraries.')
  parser.add_option('--readelf', help='Path to the readelf binary.')
  parser.add_option('--output', help='Path to the generated .json file.')
  parser.add_option('--stamp', help='Path to touch on success.')

  options, _ = parser.parse_args()

  SetReadelfPath(options.readelf)
  SetLibraryDirs(options.libraries_dir.split(','))

  libraries = build_utils.ParseGypList(options.input_libraries)
  if len(libraries):
    libraries = GetSortedTransitiveDependenciesForBinaries(libraries)

  # Convert to "base" library names: e.g. libfoo.so -> foo
  java_libraries_list = (
      '{%s}' % ','.join(['"%s"' % s[3:-3] for s in libraries]))

  build_utils.WriteJson(
      {'libraries': libraries, 'java_libraries_list': java_libraries_list},
      options.output,
      only_if_changed=True)

  if options.stamp:
    build_utils.Touch(options.stamp)

  if options.depfile:
    print libraries
    build_utils.WriteDepfile(
        options.depfile,
        libraries + build_utils.GetPythonDependencies())

if __name__ == '__main__':
  sys.exit(main())