text:
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery.turbolinks
//= require turbolinks
//= require highcharts/highcharts
//= require highcharts/highcharts-more
//= require_tree .

// necessary for javascript to work with turbolinks
// it is cllosed at the end of this document
$(document).on('turbolinks:load', function() {

// <<<<<< custom.js
/*jshint -W117*/

$(function () {

    'use strict';

    // Trigeer NiceScroll

    $('html').niceScroll({
        cursorcolor: '#dc0008',
        cursorwidth: '8px',
        cursorborderradius: '3px',
        cursorborder: '0',
    });

    $("html").mouseover(function() {
        $("html").getNiceScroll().resize();
    });

    //Change Header Height

    var myHeader = $(".header");

    myHeader.height($(window).height());

    if (myHeader.height() < 640) {
        myHeader.height($(window).height()+300);
    }

    myHeader.width($(window).width());

    $(window).resize(function () {
        myHeader.height($(window).height());
        if (myHeader.height() < 640) {
            myHeader.height($(window).height()+300);
        }

        myHeader.width($(window).width());
    });

    //Change Contact Page Height

    var myContact = $(".contact");

    myContact.height($(window).height());

    if (myContact.height() < 640) {
        myContact.height($(window).height()+500);
    }

    // Menu Bar In Small Screen
    var click = 0;

    $('.fa-bars').click(function () {

        if (click == 0) {
            $('.links').addClass('active-menu');
            $('.links').hide();
            $('.links').slideDown(400);
            click ++;
        }
        else {

            $('.links').slideUp(400);
            $('.links').addClass('active-menu');
            click --;
        }

    });

    // arrow of scroll up

    $(window).on("scroll", function () {
        var scr = $(window).scrollTop();

        if( scr >450) {
            $('.fa-chevron-up').fadeIn();
        }
        else {
            $('.fa-chevron-up').fadeOut();
        }

    });

    //Make Smooth Scroll

    $('.fa-chevron-up').click (function () {
        $('html, body').animate({

            scrollTop: 0
        } ,900);
    });

    $('.links a').click (function () {
        $('html, body').animate({
            scrollTop: $('#' + $(this).data('value') ).offset().top - 20,
        }, 900 );

        console.log($(this).data('value'));
    });

    //Scroll To Features

    $('.links a').click (function () {
        $('html, body').animate({
            scrollTop: $('#' + $(this).data('value') ).offset().top - 20,
        }, 900 );

        console.log($(this).data('value'));
    });

    $('.header .arrow i').click(function () {
        $('html, body').animate({
            scrollTop: $('.features').offset().top -110
        }, 700);
    });

    $('.hire').click(function () {

        $('html, body').animate({
            scrollTop: $('.contact').offset().top
        }, 700);

    });

    $('.work-button').click(function () {

        $('html, body').animate({
            scrollTop: $('.our-work').offset().top
        }, 700);

    });

    /*--------- Down Counter ----------*/

    // Set the date we're counting down to
    var DateInNumbers = Number($('#time_in_ms').val())
    var countDownDate = new Date(DateInNumbers)

    // Update the count down every 1 second
    var x = setInterval(function() {

        // Get todays date and time
        var now = new Date().getTime();

        // Find the distance between now an the count down date
        var distance = countDownDate - now;

        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        // Output the result in an element with id="demo"
        document.getElementById("demo-days").innerHTML =days;
        document.getElementById("demo-hours").innerHTML =hours;
        document.getElementById("demo-minutes").innerHTML =minutes;
        document.getElementById("demo-seconds").innerHTML =seconds;

        // If the count down is over, write some text
        if (distance < 0) {
            clearInterval(x);
            document.getElementById("demo").innerHTML = "EXPIRED";
        }
    }, 1000);

    // Adjust MixItUp

    $('#Container').mixItUp();

    // Project Selector

    $('.project li').click(function () {
        $(this).addClass('active').siblings().removeClass('active');
    });

    // Check Our-client

    var leftArrow = $('.our-client .fa-angle-left'),
        rightArrow = $('.our-client .fa-angle-right');

    function checkClients() {
        $('.client:first').hasClass('active') ? leftArrow.fadeOut() : leftArrow.fadeIn();

        $('.client:last').hasClass('active') ? rightArrow.fadeOut() : rightArrow.fadeIn();
    }

    checkClients();

    $('.our-client i').click(function () {
        if ($(this).hasClass('fa-angle-right')) {
            $('.our-client .active').fadeOut(100, function () {
                $(this).removeClass('active').next('.client').addClass('active').fadeIn();
                checkClients();
            });
        } else {

            $('.our-client .active').fadeOut(100, function () {
                $(this).removeClass('active').prev('.client').addClass('active').fadeIn();
                checkClients();
            });
        }
    });

});
// <<<<<< custom-photo.js

/*
Gallerie - A JQuery Gallery Plugin
Copyright (c) 2013 Patrick Brown
web: http://browniethoughts.com/

Released under MIT LICENSE
*/

;(function($) {

    var _body = document.body || document.documentElement,
        _style = _body.style,
        _transition,
        _transform;

    // detect support for transition
    if (_style.transition !== undefined) {
        _transition = 'transition';
    } else if (_style.WebkitTransition !== undefined) {
        _transition = '-webkit-transition';
    } else if (_style.MozTransition !== undefined) {
        _transition = '-moz-transition';
    } else if (_style.MsTransition !== undefined) {
        _transition = '-ms-transition';
    } else if (_style.OTransition !== undefined) {
        _transition = '-o-transition';
    }

    // detect support for transform
    if (_style.transform !== undefined) {
        _transform = 'transform';
    } else if (_style.WebkitTransform !== undefined) {
        _transform = '-webkit-transform';
    } else if (_style.MozTransform !== undefined) {
        _transform = '-moz-transform';
    } else if (_style.MsTransform !== undefined) {
        _transform = '-ms-transform';
    } else if (_style.OTransform !== undefined) {
        _transform = '-o-transform';
    }

    $.fn.gallerie = function (method) {

        function rebuildOverlay(target, imageLinks){
            var $this = $(target),
                options = $this.data('gallerie')['options'],
                $overlay = $('
'),
                $imageBox = $('
'),
                $image = $(''),
                $imageLoading = $('
'),
                $captionBox = $('

«

»

'),
                $thumbList = $('

'),
                $thumbBox = $('
'),
                $thumbItem,
                $imageLink;

            $.each(imageLinks, function(index, imageLink) {

                $imageLink = $(imageLink);
                $thumbItem = $(imageLink).find('img');

                // listbox thumbs
                $thumbItem = $('

')
                            .append(
                                $('').prop({
                                    href: $imageLink.prop('href')
                                }).append(
                                    $('').prop({
                                        src: $thumbItem.prop('src'),
                                        title: $thumbItem.prop('title')
                                    })
                                )
                            );
                $thumbList.append($thumbItem);
            });

            $overlay.append($imageBox.append($image).append($imageLoading))
                    .append($captionBox)
                    .append($thumbBox.append($thumbList));

            $overlay.on('click.gallerie', function(event){
                $this.gallerie('close');
            });

            $overlay.on('click.gallerie', '.gallerie-control-previous', function(event){
                $this.gallerie('previous');
                return false;
            });

            $overlay.on('click.gallerie', '.gallerie-control-next', function(event){
                $this.gallerie('next');
                return false;
            });

            var scrollHover = 0;

            $thumbBox.mousemove(function(event){

                var triggerWidth = options['thumbboxTriggerWidth'],
                    thumbboxWidth = $thumbList.outerWidth(),
                    windowWidth = $(window).width();

                // adjust triggerWidth to pixels if it is a percentage
                if (triggerWidth < 1)
                        triggerWidth = windowWidth * triggerWidth;

                var oldHover = scrollHover;
                if (event.pageX < triggerWidth) {
                    scrollHover = 0;
                } else if (windowWidth - event.pageX < triggerWidth) {
                    scrollHover = 1;
                } else {
                    scrollHover = -1;
                }

                if (oldHover != scrollHover) {

                    scrollStop($thumbList);

                    if (scrollHover < 0)
                        return;

                    var oldLeft=0,
                        newLeft,
                        travelAmount;

                    if (_transform !== undefined && _transition !== undefined) {
                        // get current transform
                        var matrix = $thumbList.css(_transform),
                        marray = matrixToArray(matrix);
                        if (marray.length > 4) {
                            oldLeft = parseInt(marray[4]);
                        }

                    } else {
                        oldLeft = parseInt($thumbList.css('left'),10);
                    }

                    newLeft = -(scrollHover * thumbboxWidth) + (windowWidth * scrollHover);
                    travelAmount = Math.abs(newLeft - oldLeft);

                    scrollAnimate($thumbList, newLeft, {
                        duration: travelAmount * 1/options['thumbboxSpeed'],
                        easing: 'linear'
                    });
                }

            }).mouseleave(function(event){
                scrollStop($thumbList);
                scrollHover = -1;
            });

            $overlay.find('.gallerie-thumbbox li').on('click.gallerie', function(event){
                var imageLink = $(this).find('a:first')[0];
                $this.gallerie('open', imageLink);
                event.preventDefault();
                event.stopPropagation();

            }).hover(function(){
                $(this).addClass('gallerie-thumbbox-hover');
            }, function(){
                $(this).removeClass('gallerie-thumbbox-hover');
            });

            // remove any old overlays
            $this.find('.gallerie-overlay').remove();
            $this.append($overlay.hide());

            return $overlay;

        }

        function matrixToArray(matrix) {
            var marray = matrix.substr(7, matrix.length - 8).split(',');
            return marray;
        }

        function scrollStop($element) {
            // transition support
            if (_transition !== undefined) {
                var css = {};

                // transform support
                if (_transform !== undefined) {
                    // get current transform
                    var matrix = $element.css(_transform),
                        marray = matrixToArray(matrix);
                    css[_transform] = 'translate('+marray[4]+'px)';
                    css[_transition] = _transform +' 0ms';
                } else {
                    css['left'] = $element.css('left');
                    css[_transition] = 'left 0ms';
                }

                $element.css(css);

            }else { // jquery animations
                $element.clearQueue().stop();
            }
        }

        function scrollAnimate($element, leftPos, options) {

            // transition support
            if (_transition !== undefined) {

                if (options['easing'] == undefined) {
                    options['easing'] = 'ease';
                }

                var css  = {};

                // transform support
                if (_transform !== undefined) {
                    css[_transform] = 'translate('+leftPos+'px)';
                    css[_transition] = _transform +' '+ options.duration + 'ms ' + options['easing'];
                } else {
                    css['left'] = leftPos;
                    css[_transition] = 'left '+ options.duration + 'ms ' + options['easing'];
                }

                $element.css(css);

            } else { // default to using jQuery's animate
                $element.animate({
                    left: leftPos,
                }, options);
            }
        }

        function displayLoadedImage(targets) {

            // unwrap if target is event
            if (targets instanceof $.Event) {
                targets = targets['data'];
            }

            var preloadImage = targets['preloadImage'],
                $image = targets['$image'],
                $imageBox = $image.closest('.gallerie-imagebox');
                $imageLoading = targets['$imageLoading'],
                maxWidth = $imageBox.width() - $image.outerWidth() + $image.width(),
                maxHeight = $imageBox.height() - $image.outerHeight() + $image.height(),
                height=0,
                width=0;

            if (preloadImage != $image.data('preloadImage'))
                return;

            // adjust width and height according to determined maxWidth
            width = preloadImage.width > maxWidth ? maxWidth : preloadImage.width;
            height = preloadImage.height * width / preloadImage.width;

            // if height still too big, use maxHeight scale width & height
            if (height > maxHeight) {
                height = maxHeight;
                width = preloadImage.width * height / preloadImage.height;
            }

            // load the target image
            $image.prop({
                src: preloadImage.src,
                title: preloadImage.title
            }).css({
                width: width,
                height: height
            }).removeClass('loading');

            $imageLoading.hide();
        }

        // public methods
        var methods = {

            init : function (options) {

                var defaults = {
                    thumbboxTriggerWidth: 0.10,
                    thumbboxSpeed: 0.5,
                    imageEvent: 'click',
                    elem: 'a.photo-link',
                    wrapAround: true
                };

                var options =  $.extend(defaults, options);

                return this.each(function(){

                    var $this = $(this),
                        plugindata = $this.data('gallerie');

                    // if plugin has not been initialized on element
                    if (!plugindata) {

                        $this.data('gallerie', {
                            options: options,
                            target: $this,
                        });

                        // load image data
                        $this.gallerie('load', options['elem']);

                        // set to the first image
                        $this.gallerie('setImage', 1);
                    }

                });

            },

            setImage: function(imageLink){
                return this.each(function(){

                    var $this = $(this),
                        options = $this.data('gallerie')['options'],
                        $overlay = $this.find('.gallerie-overlay'),
                        $thumbBox = $this.find('.gallerie-thumbbox'),
                        $captionBox = $this.find('.gallerie-captionbox'),
                        $thumbList = $thumbBox.find('ul:first'),
                        linkType = $.type(imageLink),
                        $imageLink,
                        $image,
                        preloadImage,
                        $imageLoading;

                    // if image is a number, we consider it the index of the target thumb
                    if (linkType == 'number') {
                        imageLink = $thumbList.find('li a')[imageLink-1];
                    }
                    else if (linkType == 'string') {
                        imageLink = $('').prop('href', imageLink)[0];
                    }

                    // we assume it is a link otherwise
                    $imageLink = $(imageLink);
                    $image = $overlay.find('.gallerie-image');
                    $imageLoading = $overlay.find('.gallerie-loading');

                    $image.addClass('loading');

                    // construct new image element to work-around onLoad issues with various browsers
                    preloadImage = new Image();
                    var targetData = {
                        'preloadImage': preloadImage,
                        '$image': $image,
                        '$imageLoading': $imageLoading
                    };

                    // when image has loaded, call displayLoadedImage to update real image to preloadImage
                    $(preloadImage).on('load.gallerie', targetData, displayLoadedImage);
                    $image.data('preloadImage', preloadImage);
                    preloadImage.src = $imageLink.prop('href');

                    // give the image 250ms to load before showing imageLoading (lowers flicker chance of imageLoading)
                    setTimeout(function(){
                        // image still has not loaded, so we show imageLoading
                        if (!preloadImage.complete) {
                            $imageLoading.show();

                            // hide image loading if target already loaded while showing imageLoading
                            if (preloadImage.complete) {
                                displayLoadedImage(targetData);
                            }
                        }
                    }, 250);

                    // attempt to find link in thumbnails
                    var $thumbLink = $thumbBox.find(imageLink),
                        $targetThumb;

                    // could not find same link element, so we search by href
                    if ($thumbLink.length == 0) {
                        var imageLinkHref = $imageLink.prop('href');
                        $thumbBox.find('a').each(function(index, elem) {
                            if ($(elem).prop('href') == imageLinkHref) {
                                $thumbLink = $(elem);
                                return false;
                            }
                        });
                    }

                    $targetThumb = $thumbLink.closest('li');

                    // remove selected from old thumb
                    $thumbBox.find('.gallerie-thumbbox-selected').removeClass('gallerie-thumbbox-selected');

                    // add selected to new thumb
                    $targetThumb.addClass('gallerie-thumbbox-selected');

                    var $thumbs = $thumbBox.find('li'),
                        thumbPosition = $thumbs.index($targetThumb)+1,
                        thumbTotal = $thumbs.length;

                    // set caption
                    $captionBox.find(".gallerie-title").text($targetThumb.find('img').prop('title'));
                    $captionBox.find(".gallerie-index").text(thumbPosition + ' of ' + thumbTotal);

                    var thumbpos = $targetThumb.position().left + $targetThumb.outerWidth(true)/2,
                        winwidth = $(window).width();

                    if ($targetThumb.offset().left < 0 || thumbpos > winwidth) {
                        // calculate new left edge of thumblist
                        var newLeft = -(winwidth/2 - thumbpos);

                        // if edge is beyond normal scrolling bounds, bring it to within bounds
                        newLeft = Math.max(0, newLeft);
                        newLeft = Math.min($thumbList.outerWidth() - winwidth, newLeft);

                        // clear queue of effects (otherwise backlog happens when user advances quickly)
                        $thumbList.clearQueue();

                        // animate scroll to the position
                        scrollAnimate($thumbList, -newLeft, {'duration': 1000});
                    }

                });
            },

            isOpen : function() {
                var $this = $(this[0]),
                    $overlay = $this.find('.gallerie-overlay');

                return $overlay.is(':visible');
            },

            open : function(imageLink){
                return this.each(function(){
                    var $this = $(this),
                        options = $this.data('gallerie')['options'],
                        $overlay = $this.find('.gallerie-overlay'),
                        $imageBox = $this.find('.gallerie-imagebox'),
                        $captionBox = $this.find('.gallerie-captionbox'),
                        $thumbBox = $this.find('.gallerie-thumbbox');

                    if ($overlay.is(':hidden')) {
                        $(document).on('keyup.gallerie', function(e) {
                            if (e.keyCode == 13 || e.keyCode == 27) {
                                $this.gallerie('close');
                            } else if (e.keyCode == 37) {
                                $this.gallerie('previous');
                            } else if (e.keyCode == 39) {
                                $this.gallerie('next');
                            }
                        });

                        // remove scrollbar from window
                        $('body').css({ overflow: 'hidden' });

                        // resize imagebox to fill void not filled by captionBox and thumbBox
                        $imageBox.css({height: $overlay.height() - $captionBox.outerHeight() - $thumbBox.outerHeight() - parseInt($imageBox.css('margin-bottom'), 10) - parseInt($imageBox.css('margin-top'), 10)});

                    }

                    $overlay.fadeIn(500, function(){
                        if (imageLink) {
                            $this.gallerie('setImage', imageLink);
                        }
                    });
                });
            },

            close : function(){
                return this.each(function(){
                    $(this).find('.gallerie-overlay').hide();
                    $(document).off('keyup.gallerie');

                    // restore window scrollbar, etc
                    $("body").css({ overflow: 'inherit' });
                });
            },

            next : function(){
                return this.each(function(){
                    var $this = $(this),
                        options = $this.data('gallerie')['options'],
                        $thumbBox = $this.find('.gallerie-thumbbox');

                    var $selectedItem = $thumbBox.find('.gallerie-thumbbox-selected'),
                        $nextItem = $selectedItem.next();

                    if ($nextItem.length == 0) {
                        if (!options['wrapAround']) {
                            return;
                        }

                        $nextItem = $thumbBox.find('li:first');
                    }

                    $this.gallerie('setImage', $nextItem.find('a'));
                });
            },

            previous : function(){
                return this.each(function(){
                    var $this = $(this),
                        options = $this.data('gallerie')['options'],
                        $thumbBox = $this.find('.gallerie-thumbbox');

                    var $selectedItem = $thumbBox.find('.gallerie-thumbbox-selected'),
                        $prevItem = $selectedItem.prev();

                    if ($prevItem.length == 0) {
                        if (!options['wrapAround']) {
                            return;
                        }

                        $prevItem = $thumbBox.find('li:last');
                    }

                    $this.gallerie('setImage', $prevItem.find('a'));
                });
            },

            load: function(elem){
                return this.each(function(){
                    var $this = $(this),
                        options = $this.data('gallerie')['options'];

                    if (elem === undefined) {
                        elem = options['elem'];
                    }

                    rebuildOverlay(this, $this.find(elem).toArray());

                    $(document).on(options['imageEvent'] + '.gallerie', elem, function(e){
                        $this.gallerie('open', this);
                        e.stopPropagation();
                        e.preventDefault();
                    });
                });
            },

            option: function(key, value) {

                var newOptions = {};

                if (value === undefined && $.type(key) != 'string') {
                    newOptions = key;
                } else if (value === undefined) {
                    return $(this[0]).data('gallerie')['options'][key];
                } else {
                    newOptions = {}
                    newOptions[key] = value;
                }

                return this.each(function(){
                    var $this = $(this),
                        data = $this.data('gallerie'),
                        options = data['options'];

                    $.each(newOptions, function(key, value){
                        if (key == 'elem' || key == 'imageEvent') {
                            // unbind old events
                            $(document).off(options['imageEvent'] + '.gallerie', options['elem']);

                            // update option
                            options[key] = value;

                            // rebind with new option
                            $(document).on(options['imageEvent'] + '.gallerie', options['elem'], function(e){
                                $this.gallerie('open', this);
                                e.stopPropagation();
                                e.preventDefault();
                            });

                        } else if (key in options) {
                            options[key] = value;
                        }
                    });

                    data['options'] = options;
                    $this.data('gallerie', data);

                });
            }
        };

        // handle accessing of public methods
        // this is essentially bootstrapping this plugin
        if ( methods[method] ) {
          return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
          return methods.init.apply( this, arguments );
        } else {
          $.error( 'Method ' +  method + ' does not exist on jQuery.gallerie' );
        }
    }
})(jQuery);

    var initPhotoSwipeFromDOM = function(gallerySelector) {

    // parse slide data (url, title, size ...) from DOM elements
    // (children of gallerySelector)
    var parseThumbnailElements = function(el) {
        var thumbElements = el.childNodes,
        numNodes = thumbElements.length,
        items = [],
        figureEl,
        linkEl,
        size,
        item;

        for(var i = 0; i < numNodes; i++) {

            figureEl = thumbElements[i]; //
 element

            // include only element nodes
            if(figureEl.nodeType !== 1) {
                continue;
            }

            linkEl = figureEl.children[0]; //  element

            size = linkEl.getAttribute('data-size').split('x');

            // create slide object
            item = {
                src: linkEl.getAttribute('href'),
                w: parseInt(size[0], 10),
                h: parseInt(size[1], 10)
            };

            if(figureEl.children.length > 1) {
                //
 content
                item.title = figureEl.children[1].innerHTML;
            }

            if(linkEl.children.length > 0) {
                //  thumbnail element, retrieving thumbnail url
                item.msrc = linkEl.children[0].getAttribute('src');
            }

            item.el = figureEl; // save link to element for getThumbBoundsFn
            items.push(item);
        }

        return items;
    };

    // find nearest parent element
    var closest = function closest(el, fn) {
        return el && ( fn(el) ? el : closest(el.parentNode, fn) );
    };

    // triggers when user clicks on thumbnail
    var onThumbnailsClick = function(e) {
        e = e || window.event;
        e.preventDefault ? e.preventDefault() : e.returnValue = false;

        var eTarget = e.target || e.srcElement;

        // find root element of slide
        var clickedListItem = closest(eTarget, function(el) {
            return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
        });

        if(!clickedListItem) {
            return;
        }

        // find index of clicked item by looping through all child nodes
        // alternatively, you may define index via data- attribute
        var clickedGallery = clickedListItem.parentNode,
        childNodes = clickedListItem.parentNode.childNodes,
        numChildNodes = childNodes.length,
        nodeIndex = 0,
        index;

        for (var i = 0; i < numChildNodes; i++) {
            if(childNodes[i].nodeType !== 1) {
                continue;
            }

            if(childNodes[i] === clickedListItem) {
                index = nodeIndex;
                break;
            }
            nodeIndex++;
        }

        if(index >= 0) {
            // open PhotoSwipe if valid index found
            openPhotoSwipe( index, clickedGallery );
        }
        return false;
    };

    // parse picture index and gallery index from URL (#&pid=1&gid=2)
    var photoswipeParseHash = function() {
        var hash = window.location.hash.substring(1),
        params = {};

        if(hash.length < 5) {
            return params;
        }

        var vars = hash.split('&');
        for (var i = 0; i < vars.length; i++) {
            if(!vars[i]) {
                continue;
            }
            var pair = vars[i].split('=');
            if(pair.length < 2) {
                continue;
            }
            params[pair[0]] = pair[1];
        }

        if(params.gid) {
            params.gid = parseInt(params.gid, 10);
        }

        return params;
    };

    var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
        var pswpElement = document.querySelectorAll('.pswp')[0],
        gallery,
        options,
        items;

        items = parseThumbnailElements(galleryElement);

        // define options (if needed)
        options = {

            // define gallery index (for URL)
            galleryUID: galleryElement.getAttribute('data-pswp-uid'),

            getThumbBoundsFn: function(index) {
                // See Options -> getThumbBoundsFn section of documentation for more info
                var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
                pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                rect = thumbnail.getBoundingClientRect();

                return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
            }

        };

        // PhotoSwipe opened from URL
        if(fromURL) {
            if(options.galleryPIDs) {
                // parse real index when custom PIDs are used
                // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
                for(var j = 0; j < items.length; j++) {
                    if(items[j].pid == index) {
                        options.index = j;
                        break;
                    }
                }
            } else {
                // in URL indexes start from 1
                options.index = parseInt(index, 10) - 1;
            }
        } else {
            options.index = parseInt(index, 10);
        }

        // exit if index not found
        if( isNaN(options.index) ) {
            return;
        }

        if(disableAnimation) {
            options.showAnimationDuration = 0;
        }

        // Pass data to PhotoSwipe and initialize it
        gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
        gallery.init();
    };

    // loop through all gallery elements and bind events
    var galleryElements = document.querySelectorAll( gallerySelector );

    for(var i = 0, l = galleryElements.length; i < l; i++) {
        galleryElements[i].setAttribute('data-pswp-uid', i+1);
        galleryElements[i].onclick = onThumbnailsClick;
    }

    // Parse URL and open gallery if it contains #&pid=3&gid=1
    var hashData = photoswipeParseHash();
    if(hashData.pid && hashData.gid) {
        openPhotoSwipe( hashData.pid ,  galleryElements[ hashData.gid - 1 ], true, true );
    }
    };

    // execute above function
    initPhotoSwipeFromDOM('.photo-gallery');

    $(document).ready(function(){
        if ($("#gallery").length > 0){
            $("#gallery").gallerie();
        }
        if ($("#photo_work_id").length > 0){
            $("#photo_work_id").select2();
        }
        if ($("select#type").length > 0){
            $("select#type").select2();
        }
        if ($("select#shortened_url_campaign_id").length > 0){
            $("select#shortened_url_campaign_id").select2();
        }
        if ($("select#shortened_url_work_id").length > 0){
            $("select#shortened_url_work_id").select2();
        }
        if ($("select#video_work_id").length > 0){
            $("select#video_work_id").select2();
        }
        if ($("table#works").length > 0){
            $("table#works").DataTable();
        }
        if ($("table#campaigns").length > 0){
            $("table#campaigns").DataTable();
        }
        if ($("table#shortened_urls").length > 0){
            $("table#shortened_urls").DataTable();
        }

    });

});


text:
package com.nowgroup.scsee.cat.part;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.nowgroup.scsee.repository.HibernateRepository;

/**
 * @author https://github.com/diego-torres
 *
 */
@Repository
public class HibernatePartRepository extends HibernateRepository<Part, Integer>implements IPartRepository {
	/**
	 *
	 * @param sessionFactory
	 */
	@Autowired
	public HibernatePartRepository(SessionFactory sessionFactory) {
		super(Part.class, sessionFactory);
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.drools.camel.example;

import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.drools.core.runtime.impl.ExecutionResultImpl;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Collection;

public class CamelDecisionTableTest extends CamelSpringTestSupport {

    // templates to send to input endpoints
    @Produce(uri = "direct://ruleOnBodyDT")
    protected ProducerTemplate ruleOnBodyEndpoint;
    @Produce(uri = "direct://ruleOnCommandDT")
    protected ProducerTemplate ruleOnCommandEndpoint;

    @Test
    public void testRuleOnBody() throws Exception {
        Person person = new Person();
        person.setName("Young Scott");
        person.setAge(18);

        Cheese cheese = new Cheese();
        cheese.setPrice(10);
        cheese.setType("Stilton");

        // Add cheese
        ruleOnBodyEndpoint.requestBody(cheese, Cheese.class);

        // Check If Person can Drink
        Person response = ruleOnBodyEndpoint.requestBody(person, Person.class);

        assertNotNull(response);
        assertFalse(person.isCanDrink());

        // Test for alternative result
        person.setName("Scott");
        person.setAge(21);

        response = ruleOnBodyEndpoint.requestBody(person, Person.class);

        assertNotNull(response);
        assertTrue(person.isCanDrink());
    }

    @Test
    // TODO drools-camel component should be improved to allow to set Global value on the session
    public void testRuleOnCommand() throws Exception {
        Person person = new Person();
        person.setName("Young Scott");
        person.setAge(18);

        Cheese cheese = new Cheese();
        cheese.setPrice(10);
        cheese.setType("Stilton");

        // Add a Person
        ruleOnBodyEndpoint.requestBody(cheese, Cheese.class);

        // Add cheese
        ruleOnBodyEndpoint.requestBody(cheese, Cheese.class);

        // Remark : passing person here is not required
        ExecutionResultImpl response = ruleOnCommandEndpoint.requestBody(person, ExecutionResultImpl.class);

        assertNotNull(response);

        // Expecting single result value of type Person
        Collection<String> identifiers = response.getIdentifiers();
        assertNotNull(identifiers);
        assertTrue(identifiers.size() >= 1);

        for (String identifier : identifiers) {
            final Object value = response.getValue(identifier);
            assertNotNull(value);
            assertIsInstanceOf(Person.class, value);
            assertFalse(((Person) value).isCanDrink());
            System.out.println(identifier + " = " + value);
        }

        // Test for alternative result

        person.setName("Scott");
        person.setAge(21);

        response = ruleOnCommandEndpoint.requestBody(person, ExecutionResultImpl.class);

        assertNotNull(response);

        // Expecting single result value of type Person
        identifiers = response.getIdentifiers();
        assertNotNull(identifiers);
        assertTrue(identifiers.size() >= 1);

        for (String identifier : identifiers) {
            final Object value = response.getValue(identifier);
            assertNotNull(value);
            assertIsInstanceOf(Person.class, value);
            assertTrue(((Person) value).isCanDrink());
            System.out.println(identifier + " = " + value);
        }
    }

    @Override
    protected ClassPathXmlApplicationContext createApplicationContext() {
        return new ClassPathXmlApplicationContext("META-INF/spring/camel-context-decision-table.xml");
    }
}


text:
/**
 * POST /api/v1/logout
 * Logs out.
 */
module.exports = (req, res) => {
  req.session.destroy(function (err) {
    res.clearCookie('connect.sid');
    req.logout();
    res.json({ msg: 'Successfully logged out.' });
  });
};


text:
// Aleth: Ethereum C++ client, tools and libraries.
// Copyright 2013-2019 Aleth Authors.
// Licensed under the GNU General Public License, Version 3.

#pragma once

#include "Account.h"
#include "SecureTrieDB.h"
#include "Transaction.h"
#include "TransactionReceipt.h"
#include <libdevcore/Common.h>
#include <libdevcore/OverlayDB.h>
#include <libdevcore/RLP.h>
#include <libethcore/BlockHeader.h>
#include <libethcore/Exceptions.h>
#include <libethereum/CodeSizeCache.h>
#include <libevm/ExtVMFace.h>
#include <array>
#include <unordered_map>

namespace dev
{

namespace test { class ImportTest; class StateLoader; }

namespace eth
{

// Import-specific errinfos
using errinfo_uncleIndex = boost::error_info<struct tag_uncleIndex, unsigned>;
using errinfo_currentNumber = boost::error_info<struct tag_currentNumber, u256>;
using errinfo_uncleNumber = boost::error_info<struct tag_uncleNumber, u256>;
using errinfo_unclesExcluded = boost::error_info<struct tag_unclesExcluded, h256Hash>;
using errinfo_block = boost::error_info<struct tag_block, bytes>;
using errinfo_now = boost::error_info<struct tag_now, unsigned>;

using errinfo_transactionIndex = boost::error_info<struct tag_transactionIndex, unsigned>;

using errinfo_vmtrace = boost::error_info<struct tag_vmtrace, std::string>;
using errinfo_receipts = boost::error_info<struct tag_receipts, std::vector<bytes>>;
using errinfo_transaction = boost::error_info<struct tag_transaction, bytes>;
using errinfo_phase = boost::error_info<struct tag_phase, unsigned>;
using errinfo_required_LogBloom = boost::error_info<struct tag_required_LogBloom, LogBloom>;
using errinfo_got_LogBloom = boost::error_info<struct tag_get_LogBloom, LogBloom>;
using LogBloomRequirementError = boost::tuple<errinfo_required_LogBloom, errinfo_got_LogBloom>;

class State;
class TransactionQueue;
struct VerifiedBlockRef;

enum class BaseState
{
    PreExisting,
    Empty
};

enum class Permanence
{
    Reverted,
    Committed,
    Uncommitted  ///< Uncommitted state for change log readings in tests.
};

DEV_SIMPLE_EXCEPTION(InvalidAccountStartNonceInState);
DEV_SIMPLE_EXCEPTION(IncorrectAccountStartNonceInState);

class SealEngineFace;
class Executive;

/// An atomic state changelog entry.
struct Change
{
    enum Kind: int
    {
        /// Account balance changed. Change::value contains the amount the
        /// balance was increased by.
        Balance,

        /// Account storage was modified. Change::key contains the storage key,
        /// Change::value the storage value.
        Storage,

        /// Account storage root was modified.  Change::value contains the old
        /// account storage root.
        StorageRoot,

        /// Account nonce was changed.
        Nonce,

        /// Account was created (it was not existing before).
        Create,

        /// New code was added to an account (by "create" message execution).
        Code,

        /// Account was touched for the first time.
        Touch
    };

    Kind kind;        ///< The kind of the change.
    Address address;  ///< Changed account address.
    u256 value;       ///< Change value, e.g. balance, storage and nonce.
    u256 key;         ///< Storage key. Last because used only in one case.

    /// Helper constructor to make change log update more readable.
    Change(Kind _kind, Address const& _addr, u256 const& _value = 0):
            kind(_kind), address(_addr), value(_value)
    {
    }

    /// Helper constructor especially for storage change log.
    Change(Address const& _addr, u256 const& _key, u256 const& _value):
            kind(Storage), address(_addr), value(_value), key(_key)
    {}

    /// Helper constructor for nonce change log.
    Change(Address const& _addr, u256 const& _value):
            kind(Nonce), address(_addr), value(_value)
    {}
};

using ChangeLog = std::vector<Change>;

/**
 * Model of an Ethereum state, essentially a facade for the trie.
 *
 * Allows you to query the state of accounts as well as creating and modifying
 * accounts. It has built-in caching for various aspects of the state.
 *
 * # State Changelog
 *
 * Any atomic change to any account is registered and appended in the changelog.
 * In case some changes must be reverted, the changes are popped from the
 * changelog and undone. For possible atomic changes list @see Change::Kind.
 * The changelog is managed by savepoint(), rollback() and commit() methods.
 */
class State
{
    friend class ExtVM;
    friend class dev::test::ImportTest;
    friend class dev::test::StateLoader;

public:
    enum class CommitBehaviour
    {
        KeepEmptyAccounts,
        RemoveEmptyAccounts
    };

    using AddressMap = std::map<h256, Address>;

    /// Default constructor; creates with a blank database prepopulated with the genesis block.
    explicit State(u256 const& _accountStartNonce): State(_accountStartNonce, OverlayDB(), BaseState::Empty) {}

    /// Basic state object from database.
    /// Use the default when you already have a database and you just want to make a State object
    /// which uses it. If you have no preexisting database then set BaseState to something other
    /// than BaseState::PreExisting in order to prepopulate the Trie.
    explicit State(u256 const& _accountStartNonce, OverlayDB const& _db, BaseState _bs = BaseState::PreExisting);

    enum NullType { Null };
    State(NullType): State(Invalid256, OverlayDB(), BaseState::Empty) {}

    /// Copy state object.
    State(State const& _s);

    /// Copy state object.
    State& operator=(State const& _s);

    /// Open a DB - useful for passing into the constructor & keeping for other states that are necessary.
    static OverlayDB openDB(boost::filesystem::path const& _path, h256 const& _genesisHash, WithExisting _we = WithExisting::Trust);
    OverlayDB const& db() const { return m_db; }
    OverlayDB& db() { return m_db; }

    /// Populate the state from the given AccountMap. Just uses dev::eth::commit().
    void populateFrom(AccountMap const& _map);

    /// @returns the set containing all addresses currently in use in Ethereum.
    /// @warning This is slowslowslow. Don't use it unless you want to lock the object for seconds or minutes at a time.
    /// @throws InterfaceNotSupported if compiled without ETH_FATDB.
    std::unordered_map<Address, u256> addresses() const;

    /// @returns the map with maximum _maxResults elements containing hash->addresses and the next
    /// address hash. This method faster then addresses() const;
    std::pair<AddressMap, h256> addresses(h256 const& _begin, size_t _maxResults) const;

    /// Execute a given transaction.
    /// This will change the state accordingly.
    std::pair<ExecutionResult, TransactionReceipt> execute(EnvInfo const& _envInfo, SealEngineFace const& _sealEngine, Transaction const& _t, Permanence _p = Permanence::Committed, OnOpFunc const& _onOp = OnOpFunc());

    /// Check if the address is in use.
    bool addressInUse(Address const& _address) const;

    /// Check if the account exists in the state and is non empty (nonce > 0 || balance > 0 || code nonempty).
    /// These two notions are equivalent after EIP158.
    bool accountNonemptyAndExisting(Address const& _address) const;

    /// Check if the address contains executable code.
    bool addressHasCode(Address const& _address) const;

    /// Get an account's balance.
    /// @returns 0 if the address has never been used.
    u256 balance(Address const& _id) const;

    /// Add some amount to balance.
    /// Will initialise the address if it has never been used.
    virtual void addBalance(Address const& _id, u256 const& _amount); // qtum

    /// Subtract the @p _value amount from the balance of @p _addr account.
    /// @throws NotEnoughCash if the balance of the account is less than the
    /// amount to be subtrackted (also in case the account does not exist).
    void subBalance(Address const& _addr, u256 const& _value);

    /// Set the balance of @p _addr to @p _value.
    /// Will instantiate the address if it has never been used.
    void setBalance(Address const& _addr, u256 const& _value);

    /**
     * @brief Transfers "the balance @a _value between two accounts.
     * @param _from Account from which @a _value will be deducted.
     * @param _to Account to which @a _value will be added.
     * @param _value Amount to be transferred.
     */
    virtual void transferBalance(Address const& _from, Address const& _to, u256 const& _value) { subBalance(_from, _value); addBalance(_to, _value); }

    /// Get the root of the storage of an account.
    h256 storageRoot(Address const& _contract) const;

    /// Get the value of a storage position of an account.
    /// @returns 0 if no account exists at that address.
    u256 storage(Address const& _contract, u256 const& _memory) const;

    /// Set the value of a storage position of an account.
    void setStorage(Address const& _contract, u256 const& _location, u256 const& _value);

    /// Get the original value of a storage position of an account (before modifications saved in
    /// account cache).
    /// @returns 0 if no account exists at that address.
    u256 originalStorageValue(Address const& _contract, u256 const& _key) const;

    /// Clear the storage root hash of an account to the hash of the empty trie.
    void clearStorage(Address const& _contract);

    /// Create a contract at the given address (with unset code and unchanged balance).
    void createContract(Address const& _address);

    /// Sets the code of the account. Must only be called during / after contract creation.
    void setCode(Address const& _address, bytes&& _code, u256 const& _version);

    /// Delete an account (used for processing selfdestructs).
    virtual void kill(Address _a);

    /// Get the storage of an account.
    /// @note This is expensive. Don't use it unless you need to.
    /// @returns map of hashed keys to key-value pairs or empty map if no account exists at that address.
    std::map<h256, std::pair<u256, u256>> storage(Address const& _contract) const;

    /// Get the code of an account.
    /// @returns bytes() if no account exists at that address.
    /// @warning The reference to the code is only valid until the access to
    ///          other account. Do not keep it.
    bytes const& code(Address const& _addr) const;

    /// Get the code hash of an account.
    /// @returns EmptySHA3 if no account exists at that address or if there is no code associated with the address.
    h256 codeHash(Address const& _contract) const;

    /// Get the byte-size of the code of an account.
    /// @returns code(_contract).size(), but utilizes CodeSizeHash.
    size_t codeSize(Address const& _contract) const;

    /// Get contract account's version.
    /// @returns 0 if no account exists at that address.
    u256 version(Address const& _contract) const;

    /// Increament the account nonce.
    void incNonce(Address const& _id);

    /// Set the account nonce.
    void setNonce(Address const& _addr, u256 const& _newNonce);

    /// Get the account nonce -- the number of transactions it has sent.
    /// @returns 0 if the address has never been used.
    u256 getNonce(Address const& _addr) const;

    /// The hash of the root of our state tree.
    h256 rootHash() const { return m_state.root(); }

    /// Commit all changes waiting in the address cache to the DB.
    /// @param _commitBehaviour whether or not to remove empty accounts during commit.
    void commit(CommitBehaviour _commitBehaviour);

    /// Resets any uncommitted changes to the cache.
    void setRoot(h256 const& _root);

    /// Get the account start nonce. May be required.
    u256 const& accountStartNonce() const { return m_accountStartNonce; }
    u256 const& requireAccountStartNonce() const;
    void noteAccountStartNonce(u256 const& _actual);

    /// Mark account as touched and keep it touched even in case of rollback
    void unrevertableTouch(Address const& _addr);

    /// Create a savepoint in the state changelog.
    /// @return The savepoint index that can be used in rollback() function.
    size_t savepoint() const;

    /// Revert all recent changes up to the given @p _savepoint savepoint.
    void rollback(size_t _savepoint);

    ChangeLog const& changeLog() const { return m_changeLog; }

    virtual ~State(){}

protected:
    /// Turns all "touched" empty accounts into non-alive accounts.
    void removeEmptyAccounts();

    /// @returns the account at the given address or a null pointer if it does not exist.
    /// The pointer is valid until the next access to the state or account.
    Account const* account(Address const& _addr) const;

    /// @returns the account at the given address or a null pointer if it does not exist.
    /// The pointer is valid until the next access to the state or account.
    Account* account(Address const& _addr);

    /// Purges non-modified entries in m_cache if it grows too large.
    void clearCacheIfTooLarge() const;

    void createAccount(Address const& _address, Account const&& _account);

    /// @returns true when normally halted; false when exceptionally halted; throws when internal VM
    /// exception occurred.
    bool executeTransaction(Executive& _e, Transaction const& _t, OnOpFunc const& _onOp);

    /// Our overlay for the state tree.
    OverlayDB m_db;
    /// Our state tree, as an OverlayDB DB.
    SecureTrieDB<Address, OverlayDB> m_state;
    /// Our address cache. This stores the states of each address that has (or at least might have)
    /// been changed.
    mutable std::unordered_map<Address, Account> m_cache;
    /// Tracks entries in m_cache that can potentially be purged if it grows too large.
    mutable std::vector<Address> m_unchangedCacheEntries;
    /// Tracks addresses that are known to not exist.
    mutable std::set<Address> m_nonExistingAccountsCache;
    /// Tracks all addresses touched so far.
    AddressHash m_touched;
    /// Tracks addresses that were touched and should stay touched in case of rollback
    AddressHash m_unrevertablyTouched;

    u256 m_accountStartNonce;

    friend std::ostream& operator<<(std::ostream& _out, State const& _s);
    ChangeLog m_changeLog;
};

std::ostream& operator<<(std::ostream& _out, State const& _s);

template <class DB>
AddressHash commit(AccountMap const& _cache, SecureTrieDB<Address, DB>& _state);

}
}


text:
<?php

class Kendesign_Lowerpriceform_Adminhtml_LowerpriceformController extends Mage_Adminhtml_Controller_action
{

	protected function _initAction() {
		$this->loadLayout()
			->_setActiveMenu('lowerpriceform/items')
			->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager'));

		return $this;
	}

	public function indexAction() {
		$this->_initAction()
			->renderLayout();
	}

	public function editAction() {
		$id     = $this->getRequest()->getParam('id');
		$model  = Mage::getModel('lowerpriceform/lowerpriceform')->load($id);

		if ($model->getId() || $id == 0) {
			$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
			if (!empty($data)) {
				$model->setData($data);
			}

			Mage::register('lowerpriceform_data', $model);

			$this->loadLayout();
			$this->_setActiveMenu('lowerpriceform/items');

			$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
			$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));

			$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

			$this->_addContent($this->getLayout()->createBlock('lowerpriceform/adminhtml_lowerpriceform_edit'))
				->_addLeft($this->getLayout()->createBlock('lowerpriceform/adminhtml_lowerpriceform_edit_tabs'));

			$this->renderLayout();
		} else {
			Mage::getSingleton('adminhtml/session')->addError(Mage::helper('lowerpriceform')->__('Item does not exist'));
			$this->_redirect('*/*/');
		}
	}

	public function newAction() {
		$this->_forward('edit');
	}

	public function saveAction() {
		if ($data = $this->getRequest()->getPost()) {

			if(isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '') {
				try {
					/* Starting upload */
					$uploader = new Varien_File_Uploader('filename');

					// Any extention would work
	           		$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
					$uploader->setAllowRenameFiles(false);

					// Set the file upload mode
					// false -> get the file directly in the specified folder
					// true -> get the file in the product like folders
					//	(file.jpg will go in something like /media/f/i/file.jpg)
					$uploader->setFilesDispersion(false);

					// We set media as the upload dir
					$path = Mage::getBaseDir('media') . DS ;
					$uploader->save($path, $_FILES['filename']['name'] );

				} catch (Exception $e) {

		        }

		        //this way the name is saved in DB
	  			$data['filename'] = $_FILES['filename']['name'];
			}

			$model = Mage::getModel('lowerpriceform/lowerpriceform');
			$model->setData($data)
				->setId($this->getRequest()->getParam('id'));

			try {
				if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
					$model->setCreatedTime(now())
						->setUpdateTime(now());
				} else {
					$model->setUpdateTime(now());
				}

				$model->save();
				Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('lowerpriceform')->__('Item was successfully saved'));
				Mage::getSingleton('adminhtml/session')->setFormData(false);

				if ($this->getRequest()->getParam('back')) {
					$this->_redirect('*/*/edit', array('id' => $model->getId()));
					return;
				}
				$this->_redirect('*/*/');
				return;
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                Mage::getSingleton('adminhtml/session')->setFormData($data);
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                return;
            }
        }
        Mage::getSingleton('adminhtml/session')->addError(Mage::helper('lowerpriceform')->__('Unable to find item to save'));
        $this->_redirect('*/*/');
	}

	public function deleteAction() {
		if( $this->getRequest()->getParam('id') > 0 ) {
			try {
				$model = Mage::getModel('lowerpriceform/lowerpriceform');

				$model->setId($this->getRequest()->getParam('id'))
					->delete();

				Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
				$this->_redirect('*/*/');
			} catch (Exception $e) {
				Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
				$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
			}
		}
		$this->_redirect('*/*/');
	}

    public function massDeleteAction() {
        $lowerpriceformIds = $this->getRequest()->getParam('lowerpriceform');
        if(!is_array($lowerpriceformIds)) {
			Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));
        } else {
            try {
                foreach ($lowerpriceformIds as $lowerpriceformId) {
                    $lowerpriceform = Mage::getModel('lowerpriceform/lowerpriceform')->load($lowerpriceformId);
                    $lowerpriceform->delete();
                }
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('adminhtml')->__(
                        'Total of %d record(s) were successfully deleted', count($lowerpriceformIds)
                    )
                );
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            }
        }
        $this->_redirect('*/*/index');
    }

    public function massStatusAction()
    {
        $lowerpriceformIds = $this->getRequest()->getParam('lowerpriceform');
        if(!is_array($lowerpriceformIds)) {
            Mage::getSingleton('adminhtml/session')->addError($this->__('Please select item(s)'));
        } else {
            try {
                foreach ($lowerpriceformIds as $lowerpriceformId) {
                    $lowerpriceform = Mage::getSingleton('lowerpriceform/lowerpriceform')
                        ->load($lowerpriceformId)
                        ->setStatus($this->getRequest()->getParam('status'))
                        ->setIsMassupdate(true)
                        ->save();
                }
                $this->_getSession()->addSuccess(
                    $this->__('Total of %d record(s) were successfully updated', count($lowerpriceformIds))
                );
            } catch (Exception $e) {
                $this->_getSession()->addError($e->getMessage());
            }
        }
        $this->_redirect('*/*/index');
    }

    public function exportCsvAction()
    {
        $fileName   = 'lowerpriceform.csv';
        $content    = $this->getLayout()->createBlock('lowerpriceform/adminhtml_lowerpriceform_grid')
            ->getCsv();

        $this->_sendUploadResponse($fileName, $content);
    }

    public function exportXmlAction()
    {
        $fileName   = 'lowerpriceform.xml';
        $content    = $this->getLayout()->createBlock('lowerpriceform/adminhtml_lowerpriceform_grid')
            ->getXml();

        $this->_sendUploadResponse($fileName, $content);
    }

    protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream')
    {
        $response = $this->getResponse();
        $response->setHeader('HTTP/1.1 200 OK','');
        $response->setHeader('Pragma', 'public', true);
        $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
        $response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
        $response->setHeader('Last-Modified', date('r'));
        $response->setHeader('Accept-Ranges', 'bytes');
        $response->setHeader('Content-Length', strlen($content));
        $response->setHeader('Content-type', $contentType);
        $response->setBody($content);
        $response->sendResponse();
        die;
    }
}


text:
typedef void (^MSALTestHttpCompletionBlock)(NSData *data, NSURLResponse *response, NSError *error);

@interface MSIDTestURLSession (MSAL)

@end


text:
#include "config.h"

#if ENABLE(WEB_AUDIO)

#include "HRTFPanner.h"

#include "AudioBus.h"
#include "FFTConvolver.h"
#include "HRTFDatabase.h"
#include "HRTFDatabaseLoader.h"
#include <algorithm>
#include <wtf/MathExtras.h>
#include <wtf/RefPtr.h>

namespace WebCore {

// The value of 2 milliseconds is larger than the largest delay which exists in any HRTFKernel from the default HRTFDatabase (0.0136 seconds).
// We ASSERT the delay values used in process() with this value.
const double MaxDelayTimeSeconds = 0.002;

const int UninitializedAzimuth = -1;
const unsigned RenderingQuantum = 128;

HRTFPanner::HRTFPanner(float sampleRate, HRTFDatabaseLoader* databaseLoader)
    : Panner(PanningModelHRTF)
    , m_databaseLoader(databaseLoader)
    , m_sampleRate(sampleRate)
    , m_crossfadeSelection(CrossfadeSelection1)
    , m_azimuthIndex1(UninitializedAzimuth)
    , m_elevation1(0)
    , m_azimuthIndex2(UninitializedAzimuth)
    , m_elevation2(0)
    , m_crossfadeX(0)
    , m_crossfadeIncr(0)
    , m_convolverL1(fftSizeForSampleRate(sampleRate))
    , m_convolverR1(fftSizeForSampleRate(sampleRate))
    , m_convolverL2(fftSizeForSampleRate(sampleRate))
    , m_convolverR2(fftSizeForSampleRate(sampleRate))
    , m_delayLineL(MaxDelayTimeSeconds, sampleRate)
    , m_delayLineR(MaxDelayTimeSeconds, sampleRate)
    , m_tempL1(RenderingQuantum)
    , m_tempR1(RenderingQuantum)
    , m_tempL2(RenderingQuantum)
    , m_tempR2(RenderingQuantum)
{
    ASSERT(databaseLoader);
}

HRTFPanner::~HRTFPanner()
{
}

size_t HRTFPanner::fftSizeForSampleRate(float sampleRate)
{
    // The HRTF impulse responses (loaded as audio resources) are 512 sample-frames @44.1KHz.
    // Currently, we truncate the impulse responses to half this size, but an FFT-size of twice impulse response size is needed (for convolution).
    // So for sample rates around 44.1KHz an FFT size of 512 is good. We double the FFT-size only for sample rates at least double this.
    ASSERT(sampleRate >= 44100 && sampleRate <= 96000.0);
    return (sampleRate < 88200.0) ? 512 : 1024;
}

void HRTFPanner::reset()
{
    m_convolverL1.reset();
    m_convolverR1.reset();
    m_convolverL2.reset();
    m_convolverR2.reset();
    m_delayLineL.reset();
    m_delayLineR.reset();
}

int HRTFPanner::calculateDesiredAzimuthIndexAndBlend(double azimuth, double& azimuthBlend)
{
    // Convert the azimuth angle from the range -180 -> +180 into the range 0 -> 360.
    // The azimuth index may then be calculated from this positive value.
    if (azimuth < 0)
        azimuth += 360.0;

    HRTFDatabase* database = m_databaseLoader->database();
    ASSERT(database);

    int numberOfAzimuths = database->numberOfAzimuths();
    const double angleBetweenAzimuths = 360.0 / numberOfAzimuths;

    // Calculate the azimuth index and the blend (0 -> 1) for interpolation.
    double desiredAzimuthIndexFloat = azimuth / angleBetweenAzimuths;
    int desiredAzimuthIndex = static_cast<int>(desiredAzimuthIndexFloat);
    azimuthBlend = desiredAzimuthIndexFloat - static_cast<double>(desiredAzimuthIndex);

    // We don't immediately start using this azimuth index, but instead approach this index from the last index we rendered at.
    // This minimizes the clicks and graininess for moving sources which occur otherwise.
    desiredAzimuthIndex = std::max(0, desiredAzimuthIndex);
    desiredAzimuthIndex = std::min(numberOfAzimuths - 1, desiredAzimuthIndex);
    return desiredAzimuthIndex;
}

void HRTFPanner::pan(double desiredAzimuth, double elevation, const AudioBus* inputBus, AudioBus* outputBus, size_t framesToProcess)
{
    unsigned numInputChannels = inputBus ? inputBus->numberOfChannels() : 0;

    bool isInputGood = inputBus &&  numInputChannels >= 1 && numInputChannels <= 2;
    ASSERT(isInputGood);

    bool isOutputGood = outputBus && outputBus->numberOfChannels() == 2 && framesToProcess <= outputBus->length();
    ASSERT(isOutputGood);

    if (!isInputGood || !isOutputGood) {
        if (outputBus)
            outputBus->zero();
        return;
    }

    // This code only runs as long as the context is alive and after database has been loaded.
    HRTFDatabase* database = m_databaseLoader->database();
    ASSERT(database);
    if (!database) {
        outputBus->zero();
        return;
    }

    // IRCAM HRTF azimuths values from the loaded database is reversed from the panner's notion of azimuth.
    double azimuth = -desiredAzimuth;

    bool isAzimuthGood = azimuth >= -180.0 && azimuth <= 180.0;
    ASSERT(isAzimuthGood);
    if (!isAzimuthGood) {
        outputBus->zero();
        return;
    }

    // Normally, we'll just be dealing with mono sources.
    // If we have a stereo input, implement stereo panning with left source processed by left HRTF, and right source by right HRTF.
    const AudioChannel* inputChannelL = inputBus->channelByType(AudioBus::ChannelLeft);
    const AudioChannel* inputChannelR = numInputChannels > 1 ? inputBus->channelByType(AudioBus::ChannelRight) : 0;

    // Get source and destination pointers.
    const float* sourceL = inputChannelL->data();
    const float* sourceR = numInputChannels > 1 ? inputChannelR->data() : sourceL;
    float* destinationL = outputBus->channelByType(AudioBus::ChannelLeft)->mutableData();
    float* destinationR = outputBus->channelByType(AudioBus::ChannelRight)->mutableData();

    double azimuthBlend;
    int desiredAzimuthIndex = calculateDesiredAzimuthIndexAndBlend(azimuth, azimuthBlend);

    // Initially snap azimuth and elevation values to first values encountered.
    if (m_azimuthIndex1 == UninitializedAzimuth) {
        m_azimuthIndex1 = desiredAzimuthIndex;
        m_elevation1 = elevation;
    }
    if (m_azimuthIndex2 == UninitializedAzimuth) {
        m_azimuthIndex2 = desiredAzimuthIndex;
        m_elevation2 = elevation;
    }

    // Cross-fade / transition over a period of around 45 milliseconds.
    // This is an empirical value tuned to be a reasonable trade-off between
    // smoothness and speed.
    const double fadeFrames = sampleRate() <= 48000 ? 2048 : 4096;

    // Check for azimuth and elevation changes, initiating a cross-fade if needed.
    if (!m_crossfadeX && m_crossfadeSelection == CrossfadeSelection1) {
        if (desiredAzimuthIndex != m_azimuthIndex1 || elevation != m_elevation1) {
            // Cross-fade from 1 -> 2
            m_crossfadeIncr = 1 / fadeFrames;
            m_azimuthIndex2 = desiredAzimuthIndex;
            m_elevation2 = elevation;
        }
    }
    if (m_crossfadeX == 1 && m_crossfadeSelection == CrossfadeSelection2) {
        if (desiredAzimuthIndex != m_azimuthIndex2 || elevation != m_elevation2) {
            // Cross-fade from 2 -> 1
            m_crossfadeIncr = -1 / fadeFrames;
            m_azimuthIndex1 = desiredAzimuthIndex;
            m_elevation1 = elevation;
        }
    }

    // This algorithm currently requires that we process in power-of-two size chunks at least RenderingQuantum.
    ASSERT(1UL << static_cast<int>(log2(framesToProcess)) == framesToProcess);
    ASSERT(framesToProcess >= RenderingQuantum);

    const unsigned framesPerSegment = RenderingQuantum;
    const unsigned numberOfSegments = framesToProcess / framesPerSegment;

    for (unsigned segment = 0; segment < numberOfSegments; ++segment) {
        // Get the HRTFKernels and interpolated delays.
        HRTFKernel* kernelL1;
        HRTFKernel* kernelR1;
        HRTFKernel* kernelL2;
        HRTFKernel* kernelR2;
        double frameDelayL1;
        double frameDelayR1;
        double frameDelayL2;
        double frameDelayR2;
        database->getKernelsFromAzimuthElevation(azimuthBlend, m_azimuthIndex1, m_elevation1, kernelL1, kernelR1, frameDelayL1, frameDelayR1);
        database->getKernelsFromAzimuthElevation(azimuthBlend, m_azimuthIndex2, m_elevation2, kernelL2, kernelR2, frameDelayL2, frameDelayR2);

        bool areKernelsGood = kernelL1 && kernelR1 && kernelL2 && kernelR2;
        ASSERT(areKernelsGood);
        if (!areKernelsGood) {
            outputBus->zero();
            return;
        }

        ASSERT(frameDelayL1 / sampleRate() < MaxDelayTimeSeconds && frameDelayR1 / sampleRate() < MaxDelayTimeSeconds);
        ASSERT(frameDelayL2 / sampleRate() < MaxDelayTimeSeconds && frameDelayR2 / sampleRate() < MaxDelayTimeSeconds);

        // Crossfade inter-aural delays based on transitions.
        double frameDelayL = (1 - m_crossfadeX) * frameDelayL1 + m_crossfadeX * frameDelayL2;
        double frameDelayR = (1 - m_crossfadeX) * frameDelayR1 + m_crossfadeX * frameDelayR2;

        // Calculate the source and destination pointers for the current segment.
        unsigned offset = segment * framesPerSegment;
        const float* segmentSourceL = sourceL + offset;
        const float* segmentSourceR = sourceR + offset;
        float* segmentDestinationL = destinationL + offset;
        float* segmentDestinationR = destinationR + offset;

        // First run through delay lines for inter-aural time difference.
        m_delayLineL.setDelayFrames(frameDelayL);
        m_delayLineR.setDelayFrames(frameDelayR);
        m_delayLineL.process(segmentSourceL, segmentDestinationL, framesPerSegment);
        m_delayLineR.process(segmentSourceR, segmentDestinationR, framesPerSegment);

        bool needsCrossfading = m_crossfadeIncr;

        // Have the convolvers render directly to the final destination if we're not cross-fading.
        float* convolutionDestinationL1 = needsCrossfading ? m_tempL1.data() : segmentDestinationL;
        float* convolutionDestinationR1 = needsCrossfading ? m_tempR1.data() : segmentDestinationR;
        float* convolutionDestinationL2 = needsCrossfading ? m_tempL2.data() : segmentDestinationL;
        float* convolutionDestinationR2 = needsCrossfading ? m_tempR2.data() : segmentDestinationR;

        // Now do the convolutions.
        // Note that we avoid doing convolutions on both sets of convolvers if we're not currently cross-fading.

        if (m_crossfadeSelection == CrossfadeSelection1 || needsCrossfading) {
            m_convolverL1.process(kernelL1->fftFrame(), segmentDestinationL, convolutionDestinationL1, framesPerSegment);
            m_convolverR1.process(kernelR1->fftFrame(), segmentDestinationR, convolutionDestinationR1, framesPerSegment);
        }

        if (m_crossfadeSelection == CrossfadeSelection2 || needsCrossfading) {
            m_convolverL2.process(kernelL2->fftFrame(), segmentDestinationL, convolutionDestinationL2, framesPerSegment);
            m_convolverR2.process(kernelR2->fftFrame(), segmentDestinationR, convolutionDestinationR2, framesPerSegment);
        }

        if (needsCrossfading) {
            // Apply linear cross-fade.
            float x = m_crossfadeX;
            float incr = m_crossfadeIncr;
            for (unsigned i = 0; i < framesPerSegment; ++i) {
                segmentDestinationL[i] = (1 - x) * convolutionDestinationL1[i] + x * convolutionDestinationL2[i];
                segmentDestinationR[i] = (1 - x) * convolutionDestinationR1[i] + x * convolutionDestinationR2[i];
                x += incr;
            }
            // Update cross-fade value from local.
            m_crossfadeX = x;

            if (m_crossfadeIncr > 0 && fabs(m_crossfadeX - 1) < m_crossfadeIncr) {
                // We've fully made the crossfade transition from 1 -> 2.
                m_crossfadeSelection = CrossfadeSelection2;
                m_crossfadeX = 1;
                m_crossfadeIncr = 0;
            } else if (m_crossfadeIncr < 0 && fabs(m_crossfadeX) < -m_crossfadeIncr) {
                // We've fully made the crossfade transition from 2 -> 1.
                m_crossfadeSelection = CrossfadeSelection1;
                m_crossfadeX = 0;
                m_crossfadeIncr = 0;
            }
        }
    }
}

double HRTFPanner::tailTime() const
{
    // Because HRTFPanner is implemented with a DelayKernel and a FFTConvolver, the tailTime of the HRTFPanner
    // is the sum of the tailTime of the DelayKernel and the tailTime of the FFTConvolver, which is MaxDelayTimeSeconds
    // and fftSize() / 2, respectively.
    return MaxDelayTimeSeconds + (fftSize() / 2) / static_cast<double>(sampleRate());
}

double HRTFPanner::latencyTime() const
{
    // The latency of a FFTConvolver is also fftSize() / 2, and is in addition to its tailTime of the
    // same value.
    return (fftSize() / 2) / static_cast<double>(sampleRate());
}

} // namespace WebCore

#endif // ENABLE(WEB_AUDIO)


text:
import json
import ops_parts
# import typing

# ValidFieldTypes = typing.TypeVar('ValidFieldTypes', int, float, bool, str)

class Package(object):

    def __init__(self, package_json):
        self.version = package_json['version']
        self.summary = package_json['summary']
        self.has_native_code = package_json['native-modules']
        self.license = package_json["license"]
        self.exposed_modules =  package_json["exposed-modules"]
        self.elm_version = package_json["elm-version"]
        self.source_directories = package_json["source-directories"]
        self.dependencies = package_json['dependencies']
        self.repository = package_json['repository']
        self.elm_path = package_json['elm-path']

    def install(self, **kwargs):
        self.write_elm_package_file()
        ops_parts.run_elm_make('.', elm_path=self.elm_path)
        self.clean()

    def clean(self):
        ops_parts.clean_elm_package_file()

    def compile(self):
        self.install()

    def to_dict(self): # -> typing.Dict[str, ValidFieldTypes]:
        return {
            'version' : self.version,
            'summary' : self.summary,
            'native-modules' : self.has_native_code,
            'license' : self.license,
            'exposed-modules' : self.exposed_modules,
            'elm-version' : self.elm_version,
            'source-directories' : self.source_directories,
            'dependencies' : self.dependencies,
            'repository' : self.repository
        }

    def write_elm_package_file(self):
        self_as_dict = self.to_dict()

        with open('elm-package.json', 'w') as f:
            json.dump(self_as_dict, f, indent=4)

class ProductionAppPackage(Package):

    def __init__(self, package_json):
        Package.__init__(self, package_json)
        self.output_dir = package_json["output-dir"]
        self.entry_points = package_json['entry-points']

    def compile(self):
        Package.compile(self)
        Package.write_elm_package_file(self)

        if self.output_dir == '':
            raise "You really don't want to have an empty output dir"

        for entry_point in self.entry_points:
            out_file = self.output_dir + '/' + self.entry_points[entry_point]
            ops_parts.run_elm_make('.', self.elm_path, entry_point, '--output', out_file)

        Package.clean(self)

class ProductionTestPackage(Package):

    def __init__(self, package_json):
        Package.__init__(self, package_json)
        self.source_directories.append(package_json['test-directory'])
        self.dependencies.update(package_json['test-deps'])
        self.entry_point = package_json['test-file']

    def compile(self):
        Package.compile(self)
        Package.write_elm_package_file(self)

        ops_parts.run_elm_make('.', self.elm_path, self.entry_point, '--output', '_elm_tests.js')

        Package.clean(self)

class ProductionPackage(object):

    def __init__(self, package_json):
        self.app_package = ProductionAppPackage(package_json)
        self.test_package = ProductionTestPackage(package_json)


text:
<?php

namespace Xajax\Config;

class Yaml
{
    /**
     * Read and set Xajax options from a YAML formatted config file
     *
     * @param array         $sConfigFile        The full path to the config file
     * @param string        $sKeys                The keys of the options in the file
     *
     * @return void
     */
    public static function read($sConfigFile, $sKey = '')
    {
        $sConfigFile = realpath($sConfigFile);
        if(!extension_loaded('yaml'))
        {
            throw new \Xajax\Exception\Config\Yaml('install');
        }
        if(!is_readable($sConfigFile))
        {
            throw new \Xajax\Exception\Config\File('access', $sConfigFile);
        }
        $aConfigOptions = yaml_parse_file($sConfigFile);
        if(!is_array($aConfigOptions))
        {
            throw new \Xajax\Exception\Config\File('content', $sConfigFile);
        }

        // Content read from config file. Try to parse.
        Config::setOptions($aConfigOptions, $sKey);
    }
}


text:
Tests how table names are escaped in database table view.

Bug 74422


text:
/*jshint node:true, es3:false*/

'use strict';

module.exports = function (task) {
    task
    .id('install')
    .name('Project installation')
    .author('Indigo United')
    .description('Install project dependencies')
    .option('force', 'Force fetching of remote sources', false)

    .setup(function (opts, ctx, next) {
        opts.trailCmd = opts.force ? ' -f' : '';
        next();
    })

    .do('run', {
        description: 'Install client environment dependencies',
        options: {
            // TODO: bower should be called programatically?
            //       this would avoid having a global dependency on bower
            //       on the other hand.. its a good idea to force the user to install
            //       bower because it will be used as package manager for every project
            cmd: 'bower install{{trailCmd}}'
        }
    })
    .do('run', {
        description: 'Install node environment dependencies',
        options: {
            // TODO: should npm be called programatically?
            cmd: 'npm install{{trailCmd}}'
        }
    })
    .do('rm', {
        description: 'Cleanup files',
        options: {
            files: '.dejavurc'
        }
    });
};


text:
using System;
using System.Threading;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Peachpie.AspNetCore.Web;

namespace MyWebsite.Server
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadPool.GetMinThreads(out int workerThread, out int completionThread);
            // Double ThreadPool for non-async calls
            ThreadPool.SetMinThreads(workerThread * 2, completionThread);

            var host = new WebHostBuilder()
                .UseKestrel()
                .UseUrls("http://*:8080/")
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }

	class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            // app.UseResponseBuffering();
            app.UsePhp(new PhpRequestOptions(scriptAssemblyName: "Website"));
            // app.UseDefaultFiles();
            // app.UseStaticFiles();
        }
    }
}


text:
package com.wavesplatform.network

import java.io.IOException

import com.wavesplatform.utils.{ScorexLogging, forceStopApplication}
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter}

import scala.util.control.NonFatal
@Sharable
class FatalErrorHandler extends ChannelInboundHandlerAdapter with ScorexLogging {
  override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable): Unit = cause match {
    case ioe: IOException if ioe.getMessage == "Connection reset by peer" =>
      // https://stackoverflow.com/q/9829531
      // https://stackoverflow.com/q/1434451
      log.trace(s"${id(ctx)} Connection reset by peer")
    case NonFatal(_) =>
      log.debug(s"${id(ctx)} Exception caught", cause)
    case _ =>
      new Thread(() => {
        log.error(s"${id(ctx)} Fatal error in channel, terminating application", cause)
        forceStopApplication()
      }, "waves-platform-shutdown-thread").start()
  }
}


text:
package abstract_factory

import (
	"errors"
	"fmt"
)

type VehicleFactory interface {
	GetVehicle(v int) (Vehicle, error)
}

const (
	CarFactoryType       = 1
	MotorbikeFactoryType = 2
)

func GetVehicleFactory(f int) (VehicleFactory, error) {
	switch f {
	case CarFactoryType:
		return new(CarFactory), nil
	case MotorbikeFactoryType:
		return new(MotorbikeFactory), nil
	default:
		return nil, errors.New(fmt.Sprintf("Factory with id %d not recongnized\n", f))
	}
}


text:
NowAndNext
==========

Now and Next, a simple App that uses BBC Programme APIs to show the upcoming programmes for BBC channels


text: Efficient and Useful jQuery Business Finance Calculators


text:
<demo-component [demoId]="'functions-demo-basic'">
  <functions-demo-basic></functions-demo-basic>
</demo-component>


text:
use std::fmt::Display;
/// Create stats for contigs.
pub trait Stats<T: Display> {
    /// Gets stats.
    fn stats(&self) -> T;
    /// Prints stats.
    fn print_stats(&self) {
        print!("{}", self.stats());
    }
    /// Logs stats.
    fn log_stats(&self) {
        debug!("{}", self.stats());
    }
}

mod contigs;
mod collections;
pub use self::collections::{Opt, CollectionStats, Counts};
pub use self::contigs::ContigsStats;


text:
package org.apache.flink.connector.kafka.source;

import org.apache.flink.api.common.accumulators.ListAccumulator;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.connector.kafka.source.reader.deserializer.KafkaRecordDeserializer;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.util.Collector;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.IntegerDeserializer;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;

/** Unite test class for {@link KafkaSource}. */
public class KafkaSourceITCase {
    private static final String TOPIC1 = "topic1";
    private static final String TOPIC2 = "topic2";

    @BeforeClass
    public static void setup() throws Throwable {
        KafkaSourceTestEnv.setup();
        KafkaSourceTestEnv.setupTopic(TOPIC1, true, true);
        KafkaSourceTestEnv.setupTopic(TOPIC2, true, true);
    }

    @AfterClass
    public static void tearDown() throws Exception {
        KafkaSourceTestEnv.tearDown();
    }

    @Test
    public void testBasicRead() throws Exception {
        KafkaSource<PartitionAndValue> source =
                KafkaSource.<PartitionAndValue>builder()
                        .setBootstrapServers(KafkaSourceTestEnv.brokerConnectionStrings)
                        .setGroupId("testBasicRead")
                        .setTopics(Arrays.asList(TOPIC1, TOPIC2))
                        .setDeserializer(new TestingKafkaRecordDeserializer())
                        .setStartingOffsets(OffsetsInitializer.earliest())
                        .setBounded(OffsetsInitializer.latest())
                        .build();

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStream<PartitionAndValue> stream =
                env.fromSource(source, WatermarkStrategy.noWatermarks(), "testBasicRead");
        executeAndVerify(env, stream);
    }

    // -----------------

    private static class PartitionAndValue implements Serializable {
        private static final long serialVersionUID = 4813439951036021779L;
        private final String tp;
        private final int value;

        private PartitionAndValue(TopicPartition tp, int value) {
            this.tp = tp.toString();
            this.value = value;
        }
    }

    private static class TestingKafkaRecordDeserializer
            implements KafkaRecordDeserializer<PartitionAndValue> {
        private static final long serialVersionUID = -3765473065594331694L;
        private transient Deserializer<Integer> deserializer;

        @Override
        public void deserialize(
                ConsumerRecord<byte[], byte[]> record, Collector<PartitionAndValue> collector)
                throws Exception {
            if (deserializer == null) {
                deserializer = new IntegerDeserializer();
            }
            collector.collect(
                    new PartitionAndValue(
                            new TopicPartition(record.topic(), record.partition()),
                            deserializer.deserialize(record.topic(), record.value())));
        }

        @Override
        public TypeInformation<PartitionAndValue> getProducedType() {
            return TypeInformation.of(PartitionAndValue.class);
        }
    }

    @SuppressWarnings("serial")
    private void executeAndVerify(
            StreamExecutionEnvironment env, DataStream<PartitionAndValue> stream) throws Exception {
        stream.addSink(
                new RichSinkFunction<PartitionAndValue>() {
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        getRuntimeContext()
                                .addAccumulator("result", new ListAccumulator<PartitionAndValue>());
                    }

                    @Override
                    public void invoke(PartitionAndValue value, Context context) throws Exception {
                        getRuntimeContext().getAccumulator("result").add(value);
                    }
                });
        List<PartitionAndValue> result = env.execute().getAccumulatorResult("result");
        Map<String, List<Integer>> resultPerPartition = new HashMap<>();
        result.forEach(
                partitionAndValue ->
                        resultPerPartition
                                .computeIfAbsent(partitionAndValue.tp, ignored -> new ArrayList<>())
                                .add(partitionAndValue.value));
        resultPerPartition.forEach(
                (tp, values) -> {
                    int firstExpectedValue = Integer.parseInt(tp.substring(tp.indexOf('-') + 1));
                    for (int i = 0; i < values.size(); i++) {
                        assertEquals(
                                String.format(
                                        "The %d-th value for partition %s should be %d", i, tp, i),
                                firstExpectedValue + i,
                                (int) values.get(i));
                    }
                });
    }
}


text:
import unittest
from vint.ast.plugin.scope_plugin.scope import Scope, ScopeVisibility, ExplicityOfScopeVisibility
from vint.ast.plugin.scope_plugin.scope_detector import (
    ScopeVisibilityHint,
    detect_possible_scope_visibility,
)
from test.unit.vint.ast.plugin.scope_plugin.stub_node import (
    create_id,
    create_curlyname,
    create_subscript_member,
)

# Shorthand
Vis = ScopeVisibility
Explicity = ExplicityOfScopeVisibility

def create_scope(visibility):  # type: (ScopeVisibility) -> Scope
    return Scope(scope_visibility=visibility)

def create_scope_visibility_hint(visibility, explicity=ExplicityOfScopeVisibility.EXPLICIT):
    return ScopeVisibilityHint(
        scope_visibility=visibility,
        explicity=explicity,
    )

class TestScopeDetector(unittest.TestCase):
    def test_parameterized(self):
        test_cases = [
            # Declarative variable test
            (Vis.SCRIPT_LOCAL, create_id('g:explicit_global'), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
            (Vis.SCRIPT_LOCAL, create_id('implicit_global'), Vis.GLOBAL_LIKE, Explicity.IMPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('g:explicit_global'), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),

            (Vis.SCRIPT_LOCAL, create_id('b:buffer_local'), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('b:buffer_local'), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),

            (Vis.SCRIPT_LOCAL, create_id('w:window_local'), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('w:window_local'), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),

            (Vis.SCRIPT_LOCAL, create_id('s:script_local'), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('s:script_local'), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),

            (Vis.FUNCTION_LOCAL, create_id('l:explicit_function_local'), Vis.FUNCTION_LOCAL, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('implicit_function_local'), Vis.FUNCTION_LOCAL, Explicity.IMPLICIT),

            (Vis.FUNCTION_LOCAL, create_id('param', is_declarative=True, is_declarative_parameter=True), Vis.FUNCTION_LOCAL, Explicity.IMPLICIT_BUT_CONSTRAINED),

            (Vis.SCRIPT_LOCAL, create_id('v:count'), Vis.BUILTIN, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('v:count'), Vis.BUILTIN, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('count'), Vis.BUILTIN, Explicity.IMPLICIT),

            (Vis.SCRIPT_LOCAL, create_curlyname(), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),
            (Vis.FUNCTION_LOCAL, create_curlyname(), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),

            (Vis.SCRIPT_LOCAL, create_subscript_member(), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),
            (Vis.FUNCTION_LOCAL, create_subscript_member(), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),

            (Vis.SCRIPT_LOCAL, create_id('g:ExplicitGlobalFunc', is_function=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
            (Vis.SCRIPT_LOCAL, create_id('ImplicitGlobalFunc', is_function=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),

            (Vis.SCRIPT_LOCAL, create_id('g:file#explicit_global_func', is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
            (Vis.SCRIPT_LOCAL, create_id('file#implicit_global_func', is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),

            (Vis.FUNCTION_LOCAL, create_id('g:ExplicitGlobalFunc', is_function=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('ImplicitGlobalFunc', is_function=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),

            (Vis.FUNCTION_LOCAL, create_id('g:file#explicit_global_func', is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('file#implicit_global_func', is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),

            (Vis.SCRIPT_LOCAL, create_id('s:ScriptLocalFunc', is_function=True), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('s:ScriptLocalFunc', is_function=True), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),

            (Vis.SCRIPT_LOCAL, create_id('t:InvalidScopeFunc', is_function=True), Vis.INVALID, Explicity.EXPLICIT),

            # Referencing variable test
            (Vis.SCRIPT_LOCAL, create_id('g:explicit_global', is_declarative=False), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
            (Vis.SCRIPT_LOCAL, create_id('implicit_global', is_declarative=False), Vis.GLOBAL_LIKE, Explicity.IMPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('g:explicit_global', is_declarative=False), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),

            (Vis.SCRIPT_LOCAL, create_id('b:buffer_local', is_declarative=False), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('b:buffer_local', is_declarative=False), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),

            (Vis.SCRIPT_LOCAL, create_id('w:window_local', is_declarative=False), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('w:window_local', is_declarative=False), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),

            (Vis.SCRIPT_LOCAL, create_id('s:script_local', is_declarative=False), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('s:script_local', is_declarative=False), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),

            (Vis.FUNCTION_LOCAL, create_id('l:explicit_function_local', is_declarative=False), Vis.FUNCTION_LOCAL, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('implicit_function_local', is_declarative=False), Vis.FUNCTION_LOCAL, Explicity.IMPLICIT),

            (Vis.FUNCTION_LOCAL, create_id('a:param', is_declarative=False), Vis.FUNCTION_LOCAL, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('a:000', is_declarative=False), Vis.FUNCTION_LOCAL, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('a:1', is_declarative=False), Vis.FUNCTION_LOCAL, Explicity.EXPLICIT),

            (Vis.SCRIPT_LOCAL, create_id('v:count', is_declarative=False), Vis.BUILTIN, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('v:count', is_declarative=False), Vis.BUILTIN, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('count', is_declarative=False), Vis.BUILTIN, Explicity.IMPLICIT),
            (Vis.SCRIPT_LOCAL, create_id('localtime', is_declarative=False, is_function=True), Vis.BUILTIN, Explicity.IMPLICIT_BUT_CONSTRAINED),

            (Vis.SCRIPT_LOCAL, create_curlyname(is_declarative=False), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),
            (Vis.FUNCTION_LOCAL, create_curlyname(is_declarative=False), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),

            (Vis.SCRIPT_LOCAL, create_subscript_member(is_declarative=False), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),
            (Vis.FUNCTION_LOCAL, create_subscript_member(is_declarative=False), Vis.UNANALYZABLE, Explicity.UNANALYZABLE),

            (Vis.SCRIPT_LOCAL, create_id('g:ExplicitGlobalFunc', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
            (Vis.SCRIPT_LOCAL, create_id('ImplicitGlobalFunc', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),

            (Vis.SCRIPT_LOCAL, create_id('g:file#explicit_global_func', is_declarative=False, is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
            (Vis.SCRIPT_LOCAL, create_id('file#implicit_global_func', is_declarative=False, is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),

            (Vis.FUNCTION_LOCAL, create_id('g:ExplicitGlobalFunc', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('ImplicitGlobalFunc', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),

            (Vis.FUNCTION_LOCAL, create_id('g:file#explicit_global_func', is_declarative=False, is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.UNRECOMMENDED_EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('file#implicit_global_func', is_declarative=False, is_function=True, is_autoload=True), Vis.GLOBAL_LIKE, Explicity.IMPLICIT_BUT_CONSTRAINED),

            (Vis.SCRIPT_LOCAL, create_id('s:ScriptLocalFunc', is_declarative=False, is_function=True), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),
            (Vis.FUNCTION_LOCAL, create_id('s:ScriptLocalFunc', is_declarative=False, is_function=True), Vis.SCRIPT_LOCAL, Explicity.EXPLICIT),

            (Vis.SCRIPT_LOCAL, create_id('t:TabLocalFuncRef', is_declarative=False, is_function=True), Vis.GLOBAL_LIKE, Explicity.EXPLICIT),
        ]

        for context_scope_visibility, id_node, expected_scope_visibility, expected_explicity in test_cases:
            scope = create_scope(context_scope_visibility)
            scope_visibility_hint = detect_possible_scope_visibility(id_node, scope)

            self.assertEqual(expected_scope_visibility, scope_visibility_hint.scope_visibility, id_node)
            self.assertEqual(expected_explicity, scope_visibility_hint.explicity, id_node)

if __name__ == '__main__':
    unittest.main()