text:
/*
Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic
Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic

Eonic changes to this script (By Rob) appear on lines

180 - Call to .net reflector script

629 - 639 Call to Show Hide Case Studies

Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic
Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic Eonic
*/

/*
Name:       ImageFlow
Version:    1.2.1 (August 10 2009)
Author:     Finn Rudolph
Support:    http://finnrudolph.de/ImageFlow

Licence:    ImageFlow is licensed under a Creative Commons
Attribution-Noncommercial 3.0 Unported License
(http://creativecommons.org/licenses/by-nc/3.0/).

You are free:
+ to Share - to copy, distribute and transmit the work
+ to Remix - to adapt the work

Under the following conditions:
+ Attribution. You must attribute the work in the manner specified by the author or licensor
(but not in any way that suggests that they endorse you or your use of the work).
+ Noncommercial. You may not use this work for commercial purposes.

+ For any reuse or distribution, you must make clear to others the license terms of this work.
+ Any of the above conditions can be waived if you get permission from the copyright holder.
+ Nothing in this license impairs or restricts the author's moral rights.

Credits:    This script is based on Michael L. Perrys Cover flow in Javascript [1].
The reflections are generated server-sided by a slightly hacked version
of Richard Daveys easyreflections [2] written in PHP. The mouse wheel
support is an implementation of Adomas Paltanavicius JavaScript mouse
wheel code [3]. It also uses the domReadyEvent from Tanny O'Haley [4].

[1] http://www.adventuresinsoftware.com/blog/?p=104#comment-1981
[2] http://reflection.corephp.co.uk/v2.php
[3] http://adomas.org/javascript-mouse-wheel/
[4] http://tanny.ica.com/ICA/TKO/tkoblog.nsf/dx/domcontentloaded-for-browsers-part-v
*/

/* ImageFlow constructor */
function ImageFlow() {
    /* Setting option defaults */
    this.defaults =
	{
	    aspectRatio: 1.964,          /* Aspect ratio of the ImageFlow container (width divided by height) */
	    buttons: false,          /* Toggle navigation buttons */
	    captions: true,           /* Toggle captions */
	    imageCursor: 'default',      /* Cursor type for all images - default is 'default' */
	    ImageFlowID: 'imageflow',    /* Default id of the ImageFlow container */
	    imageFocusM: 1.0,            /* Multiplicator for the focussed image size in percent */
	    imageFocusMax: 4,              /* Max number of images on each side of the focussed one */
	    imageScaling: true,           /* Toggle image scaling */
	    imagesHeight: 0.67,           /* Height of the images div container in percent */
	    imagesM: 1.0,            /* Multiplicator for all images in percent */
	    onClick: function() { document.location = this.url; },   /* Onclick behaviour */
	    opacity: false,          /* Toggle image opacity */
	    opacityArray: [10, 8, 6, 4, 2],   /* Image opacity (range: 0 to 10) first value is for the focussed image */
	    percentLandscape: 118,            /* Scale landscape format */
	    percentOther: 100,            /* Scale portrait and square format */
	    preloadImages: true,           /* Toggles loading bar (false: requires img attributes height and width) */
	    reflections: true,           /* Toggle reflections */
	    reflectionGET: '',             /* Pass variables via the GET method to the reflect_.php script */
	    reflectionP: 0.5,            /* Height of the reflection in percent of the source image */
	    reflectionPNG: false,          /* Toggle reflect2.php or reflect3.php */
	    scrollbarP: 0.6,            /* Width of the scrollbar in percent */
	    slider: true,           /* Toggle slider */
	    sliderCursor: 'e-resize',     /* Slider cursor type - default is 'default' */
	    sliderWidth: 14,             /* Width of the slider in px */
	    startID: 1,              /* Glide to this image ID on startup */
	    startAnimation: false,          /* Animate images moving in from the right on startup */
	    xStep: 150             /* Step width on the x-axis in px */
	};

    /* Closure for this */
    var thisObject = this;

    /* Initiate ImageFlow */
    this.init = function(options) {
        /* Evaluate options */
        var optionsArray = ['aspectRatio', 'buttons', 'captions', 'imageCursor', 'imagesM', 'ImageFlowID', 'imageFocusM', 'imageFocusMax', 'imagesHeight', 'onClick', 'opacity', 'opacityArray', 'percentLandscape', 'percentOther', 'preloadImages', 'reflections', 'reflectionGET', 'reflectionP', 'reflectionPNG', 'imageScaling', 'scrollbarP', 'slider', 'sliderCursor', 'sliderWidth', 'startID', 'startAnimation', 'xStep'];
        var max = optionsArray.length;
        for (var i = 0; i < max; i++) {
            var name = optionsArray[i];
            this[name] = (options !== undefined && options[name] !== undefined) ? options[name] : thisObject.defaults[name];
        }

        /* Try to get ImageFlow div element */
        var ImageFlowDiv = document.getElementById(thisObject.ImageFlowID);
        if (ImageFlowDiv) {
            /* Set it global within the ImageFlow scope */
            ImageFlowDiv.style.visibility = 'visible';
            this.ImageFlowDiv = ImageFlowDiv;

            /* Try to create XHTML structure */
            if (this.createStructure()) {
                this.imagesDiv = document.getElementById(thisObject.ImageFlowID + '_images');
                this.captionDiv = document.getElementById(thisObject.ImageFlowID + '_caption');
                this.navigationDiv = document.getElementById(thisObject.ImageFlowID + '_navigation');
                this.scrollbarDiv = document.getElementById(thisObject.ImageFlowID + '_scrollbar');
                this.sliderDiv = document.getElementById(thisObject.ImageFlowID + '_slider');
                this.buttonNextDiv = document.getElementById(thisObject.ImageFlowID + '_next');
                this.buttonPreviousDiv = document.getElementById(thisObject.ImageFlowID + '_previous');

                this.indexArray = [];
                this.current = 0;
                this.imageID = 0;
                this.target = 0;
                this.memTarget = 0;
                this.firstRefresh = true;
                this.firstCheck = true;
                this.busy = false;

                /* Toggle Slider */
                if (this.slider === false) {
                    this.scrollbarDiv.style.display = 'none';
                }

                /* Set height of the ImageFlow container and center the loading bar */
                var width = this.ImageFlowDiv.offsetWidth;
                var height = Math.round(width / thisObject.aspectRatio);
                document.getElementById(thisObject.ImageFlowID + '_loading_txt').style.paddingTop = ((height * 0.5) - 22) + 'px';
                ImageFlowDiv.style.height = height + 'px';

                /* Init loading progress */
                this.loadingProgress();
            }
        }
    };

    /* Create HTML Structure */
    this.createStructure = function() {
        /* Create images div container */
        var imagesDiv = thisObject.Helper.createDocumentElement('div', 'images');

        /* Shift all images into the images div */
        var node = null;
        var max = this.ImageFlowDiv.childNodes.length;
        for (var index = 0; index < max; index++) {
            node = this.ImageFlowDiv.childNodes[index];
            if (node && node.nodeType == 1 && node.nodeName == 'IMG') {
                /* Add 'reflect.php?img=' */
                if (thisObject.reflections === true) {
                    var version = '2';
                    if (thisObject.reflectionPNG === true) {
                        version = '3';
                    }
                    var src = node.getAttribute('src', 2);
                    src = '/ewcommon/tools/reflectImage.ashx?img=' + src + thisObject.reflectionGET;
                    node.setAttribute('src', src);
                }

                var imageNode = node.cloneNode(true);
                imagesDiv.appendChild(imageNode);
            }
        }

        /* Create loading text container */
        var loadingP = thisObject.Helper.createDocumentElement('p', 'loading_txt');
        var loadingText = document.createTextNode(' ');
        loadingP.appendChild(loadingText);

        /* Create loading div container */
        var loadingDiv = thisObject.Helper.createDocumentElement('div', 'loading');

        /* Create loading bar div container inside the loading div */
        var loadingBarDiv = thisObject.Helper.createDocumentElement('div', 'loading_bar');
        loadingDiv.appendChild(loadingBarDiv);

        /* Create captions div container */
        var captionDiv = thisObject.Helper.createDocumentElement('div', 'caption');

        /* Create slider and button div container inside the scrollbar div */
        var scrollbarDiv = thisObject.Helper.createDocumentElement('div', 'scrollbar');
        var sliderDiv = thisObject.Helper.createDocumentElement('div', 'slider');
        scrollbarDiv.appendChild(sliderDiv);
        if (thisObject.buttons) {
            var buttonPreviousDiv = thisObject.Helper.createDocumentElement('div', 'previous', 'button');
            var buttonNextDiv = thisObject.Helper.createDocumentElement('div', 'next', 'button');
            scrollbarDiv.appendChild(buttonPreviousDiv);
            scrollbarDiv.appendChild(buttonNextDiv);
        }

        /* Create navigation div container beneath images div */
        var navigationDiv = thisObject.Helper.createDocumentElement('div', 'navigation');
        navigationDiv.appendChild(captionDiv);
        navigationDiv.appendChild(scrollbarDiv);

        /* Update document structure and return true on success */
        var success = false;
        if (thisObject.ImageFlowDiv.appendChild(imagesDiv) &&
			thisObject.ImageFlowDiv.appendChild(loadingP) &&
			thisObject.ImageFlowDiv.appendChild(loadingDiv) &&
			thisObject.ImageFlowDiv.appendChild(navigationDiv)) {
            /* Remove image nodes outside the images div */
            for (index = 0; index < max; index++) {
                node = this.ImageFlowDiv.childNodes[index];
                if (node && node.nodeType == 1 && node.nodeName == 'IMG') {
                    this.ImageFlowDiv.removeChild(node);
                }
            }
            success = true;
        }
        return success;
    };

    /* Manage loading progress and call the refresh function */
    this.loadingProgress = function() {
        var p = thisObject.loadingStatus();
        if (p < 100 || thisObject.firstCheck === true && thisObject.preloadImages === true) {
            /* Insert a short delay if the browser loads rapidly from its cache */
            if (thisObject.firstCheck === true && p == 100) {
                thisObject.firstCheck = false;
                window.setTimeout(thisObject.loadingProgress, 100);
            }
            else {
                window.setTimeout(thisObject.loadingProgress, 40);
            }
        }
        else {
            /* Hide loading elements */
            document.getElementById(thisObject.ImageFlowID + '_loading_txt').style.display = 'none';
            document.getElementById(thisObject.ImageFlowID + '_loading').style.display = 'none';

            /* Refresh ImageFlow on window resize - delay adding this event for the IE */
            window.setTimeout(thisObject.Helper.addResizeEvent, 1000);

            /* Initialize mouse, touch and key support */
            /*thisObject.MouseWheel.init();*/
            thisObject.MouseDrag.init();
            thisObject.Touch.init();
            thisObject.Key.init();

            /* Call refresh function */
            thisObject.refresh(true);

            /* Unhide scrollbar elements */
            document.getElementById(thisObject.ImageFlowID + '_scrollbar').style.visibility = 'visible';

            /* Glide to start image */
            var startID = thisObject.startID - 1;
            if (startID < 0) {
                startID = 0;
            }
            if (startID > thisObject.max) {
                startID = thisObject.max - 1;
            }
            thisObject.glideTo(startID);

            /* Animate images moving in from the right */
            if (thisObject.startAnimation === true) {
                thisObject.moveTo(5000);
            }
        }
    };

    /* Return loaded images in percent, set loading bar width and loading text */
    this.loadingStatus = function() {
        var max = thisObject.imagesDiv.childNodes.length;
        var i = 0, completed = 0;
        var image = null;
        for (var index = 0; index < max; index++) {
            image = thisObject.imagesDiv.childNodes[index];
            if (image && image.nodeType == 1 && image.nodeName == 'IMG') {
                if (image.complete === true) {
                    completed++;
                }
                i++;
            }
        }
        var finished = Math.round((completed / i) * 100);
        var loadingBar = document.getElementById(thisObject.ImageFlowID + '_loading_bar');
        loadingBar.style.width = finished + '%';

        var loadingP = document.getElementById(thisObject.ImageFlowID + '_loading_txt');
        var loadingTxt = document.createTextNode('loading images ' + completed + '/' + i);
        loadingP.replaceChild(loadingTxt, loadingP.firstChild);
        return finished;
    };

    /* Cache EVERYTHING that only changes on refresh or resize of the window */
    this.refresh = function() {
        /* Cache global variables */
        this.imagesDivWidth = thisObject.imagesDiv.offsetWidth + thisObject.imagesDiv.offsetLeft;
        this.maxHeight = Math.round(thisObject.imagesDivWidth / thisObject.aspectRatio);
        this.maxFocus = thisObject.imageFocusMax * thisObject.xStep;
        this.size = thisObject.imagesDivWidth * 0.5;
        this.sliderWidth = thisObject.sliderWidth * 0.5;
        this.scrollbarWidth = (thisObject.imagesDivWidth - (Math.round(thisObject.sliderWidth) * 2)) * thisObject.scrollbarP;
        this.imagesDivHeight = Math.round(thisObject.maxHeight * thisObject.imagesHeight);

        /* Change imageflow div properties */
        thisObject.ImageFlowDiv.style.height = thisObject.maxHeight + 'px';

        /* Change images div properties */
        thisObject.imagesDiv.style.height = thisObject.imagesDivHeight + 'px';

        /* Change images div properties */
        thisObject.navigationDiv.style.height = (thisObject.maxHeight - thisObject.imagesDivHeight) + 'px';

        /* Change captions div properties */
        thisObject.captionDiv.style.width = thisObject.imagesDivWidth + 'px';
        thisObject.captionDiv.style.paddingTop = Math.round(thisObject.imagesDivWidth * 0.02) + 'px';

        /* Change scrollbar div properties
        thisObject.scrollbarDiv.style.width = thisObject.scrollbarWidth + 'px';
        thisObject.scrollbarDiv.style.marginTop = Math.round(thisObject.imagesDivWidth * 0.02) + 'px';
        thisObject.scrollbarDiv.style.marginLeft = Math.round(thisObject.sliderWidth + ((thisObject.imagesDivWidth - thisObject.scrollbarWidth) / 2)) + 'px';*/

        /* Change scrollbar div properties */
        thisObject.scrollbarDiv.style.width = '377px';
        thisObject.scrollbarDiv.style.marginTop = '5px';
        thisObject.scrollbarDiv.style.marginLeft = '36px';

        /* Set slider attributes */
        thisObject.sliderDiv.style.cursor = thisObject.sliderCursor;
        thisObject.sliderDiv.onmousedown = function() { thisObject.MouseDrag.start(this); return false; };

        if (thisObject.buttons) {
            thisObject.buttonPreviousDiv.onclick = function() { thisObject.MouseWheel.handle(1); };
            thisObject.buttonNextDiv.onclick = function() { thisObject.MouseWheel.handle(-1); };
        }

        /* Set the reflection multiplicator */
        var multi = (thisObject.reflections === true) ? thisObject.reflectionP + 1 : 1;

        /* Set image attributes */
        var max = thisObject.imagesDiv.childNodes.length;
        var i = 0;
        var image = null;
        for (var index = 0; index < max; index++) {
            image = thisObject.imagesDiv.childNodes[index];
            if (image !== null && image.nodeType == 1 && image.nodeName == 'IMG') {
                this.indexArray[i] = index;

                /* Set image attributes to store values */
                image.url = image.getAttribute('longdesc');
                image.xPosition = (-i * thisObject.xStep);
                image.i = i;

                /* Add width and height as attributes only once */
                if (thisObject.firstRefresh) {
                    if (image.getAttribute('width') !== null && image.getAttribute('height') !== null) {
                        image.w = image.getAttribute('width');
                        image.h = image.getAttribute('height') * multi;
                    }
                    else {
                        image.w = image.width;
                        image.h = image.height;
                    }
                }

                /* Check source image format. Get image height minus reflection height! */
                if ((image.w) > (image.h / (thisObject.reflectionP + 1))) {
                    /* Landscape format */
                    image.pc = thisObject.percentLandscape;
                    image.pcMem = thisObject.percentLandscape;
                }
                else {
                    /* Portrait and square format */
                    image.pc = thisObject.percentOther;
                    image.pcMem = thisObject.percentOther;
                }

                /* Change image positioning */
                if (thisObject.imageScaling === false) {
                    image.style.position = 'relative';
                    image.style.display = 'inline';
                }

                /* Set image cursor type */
                image.style.cursor = thisObject.imageCursor;
                i++;
            }
        }
        this.max = thisObject.indexArray.length;

        /* Override dynamic sizes based on the first image */
        if (thisObject.imageScaling === false) {
            image = thisObject.imagesDiv.childNodes[thisObject.indexArray[0]];

            /* Set left padding for the first image */
            this.totalImagesWidth = image.w * thisObject.max;
            image.style.paddingLeft = (thisObject.imagesDivWidth / 2) + (image.w / 2) + 'px';

            /* Override images and navigation div height */
            thisObject.imagesDiv.style.height = image.h + 'px';
            thisObject.navigationDiv.style.height = (thisObject.maxHeight - image.h) + 'px';
        }

        /* Reset variable */
        if (thisObject.firstRefresh) {
            thisObject.firstRefresh = false;
        }

        /* Display images in current order */
        thisObject.glideTo(thisObject.imageID);
        thisObject.moveTo(thisObject.current);
    };

    /* Main animation function */
    this.moveTo = function(x) {
        this.current = x;
        this.zIndex = thisObject.max;

        /* Main loop */
        for (var index = 0; index < thisObject.max; index++) {
            var image = thisObject.imagesDiv.childNodes[thisObject.indexArray[index]];
            var currentImage = index * -thisObject.xStep;

            /* Enabled image scaling */
            if (thisObject.imageScaling) {
                /* Don't display images that are not conf_focussed */
                if ((currentImage + thisObject.maxFocus) < thisObject.memTarget || (currentImage - thisObject.maxFocus) > thisObject.memTarget) {
                    image.style.visibility = 'hidden';
                    image.style.display = 'none';
                }
                else {
                    var z = (Math.sqrt(10000 + x * x) + 100) * thisObject.imagesM;
                    var xs = x / z * thisObject.size + thisObject.size;

                    /* Still hide images until they are processed, but set display style to block */
                    image.style.display = 'block';

                    /* Process new image height and image width */
                    var newImageH = (image.h / image.w * image.pc) / z * thisObject.size;
                    var newImageW = 0;
                    switch (newImageH > thisObject.maxHeight) {
                        case false:
                            newImageW = image.pc / z * thisObject.size;
                            break;

                        default:
                            newImageH = thisObject.maxHeight;
                            newImageW = image.w * newImageH / image.h;
                            break;
                    }

                    var newImageTop = (thisObject.imagesDivHeight - newImageH) + ((newImageH / (thisObject.reflectionP + 1)) * thisObject.reflectionP);

                    /* Set new image properties */
                    image.style.left = xs - (image.pc / 2) / z * thisObject.size + 'px';
                    if (newImageW && newImageH) {
                        image.style.height = newImageH + 'px';
                        image.style.width = newImageW + 'px';
                        image.style.top = newImageTop + 'px';
                    }
                    image.style.visibility = 'visible';

                    /* Set image layer through zIndex */
                    switch (x < 0) {
                        case true:
                            this.zIndex++;
                            break;

                        default:
                            this.zIndex = thisObject.zIndex - 1;
                            break;
                    }

                    /* Change zIndex and onclick function of the focussed image */
                    switch (image.i == thisObject.imageID) {
                        case false:
                            image.onclick = function() { thisObject.glideTo(this.i); };
                            break;

                        default:
                            this.zIndex = thisObject.zIndex + 1;
                            if (image.url !== '') {
                                image.onclick = thisObject.onClick;
                            }
                            break;
                    }
                    image.style.zIndex = thisObject.zIndex;
                }
            }

            /* Disabled image scaling */
            else {
                if ((currentImage + thisObject.maxFocus) < thisObject.memTarget || (currentImage - thisObject.maxFocus) > thisObject.memTarget) {
                    image.style.visibility = 'hidden';
                }
                else {
                    image.style.visibility = 'visible';

                    /* Change onclick function of the focussed image */
                    switch (image.i == thisObject.imageID) {
                        case false:
                            image.onclick = function() { thisObject.glideTo(this.i); };
                            break;

                        default:
                            if (image.url !== '') {
                                image.onclick = thisObject.onClick;
                            }
                            break;
                    }
                }
                thisObject.imagesDiv.style.marginLeft = (x - thisObject.totalImagesWidth) + 'px';
            }

            x += thisObject.xStep;
        }
    };

    /* Initializes image gliding animation */
    this.glideTo = function(imageID) {
        /* Calculate new image position target */
        var x = -imageID * thisObject.xStep;
        this.target = x;
        this.memTarget = x;
        this.imageID = imageID;

        /* Display new caption */
        var caption = thisObject.imagesDiv.childNodes[imageID].getAttribute('alt');
        if (caption === '' || thisObject.captions === false) {
            caption = ' ';
        }
        thisObject.captionDiv.innerHTML = caption;

        /* Set scrollbar slider to new position */
        if (thisObject.MouseDrag.busy === false) {
            this.newSliderX = (imageID * thisObject.scrollbarWidth) / (thisObject.max - 1) - thisObject.MouseDrag.newX;
            thisObject.sliderDiv.style.marginLeft = (thisObject.newSliderX - thisObject.sliderWidth) + 'px';
        }

        /* Only process if opacity or a multiplicator for the focussed image has been set */
        if (thisObject.opacity === true || thisObject.imageFocusM !== thisObject.defaults.imageFocusM) {
            /* Set opacity for centered image */
            thisObject.Helper.setOpacity(thisObject.imagesDiv.childNodes[imageID], thisObject.opacityArray[0]);
            thisObject.imagesDiv.childNodes[imageID].pc = thisObject.imagesDiv.childNodes[imageID].pc * thisObject.imageFocusM;

            /* Set opacity for the other images that are displayed */
            var opacityValue = 0;
            var rightID = 0;
            var leftID = 0;
            var last = thisObject.opacityArray.length;

            for (var i = 1; i < (thisObject.imageFocusMax + 1); i++) {
                if ((i + 1) > last) {
                    opacityValue = thisObject.opacityArray[last - 1];
                }
                else {
                    opacityValue = thisObject.opacityArray[i];
                }

                rightID = imageID + i;
                leftID = imageID - i;

                if (rightID < thisObject.max) {
                    thisObject.Helper.setOpacity(thisObject.imagesDiv.childNodes[rightID], opacityValue);
                    thisObject.imagesDiv.childNodes[rightID].pc = thisObject.imagesDiv.childNodes[rightID].pcMem;
                }
                if (leftID >= 0) {
                    thisObject.Helper.setOpacity(thisObject.imagesDiv.childNodes[leftID], opacityValue);
                    thisObject.imagesDiv.childNodes[leftID].pc = thisObject.imagesDiv.childNodes[leftID].pcMem;
                }
            }
        }

        /* Animate gliding to new x position */
        if (thisObject.busy === false) {
            window.setTimeout(thisObject.animate, 50);
            thisObject.busy = true;
        }

        /*Amended */

        //Identify id of current image
        var image = new String;
        image = thisObject.imagesDiv.childNodes[thisObject.indexArray[imageID]].id;
        var myImage = '#caseStudy_' + image.split('_')[1];
        //Hide all case study briefs
        $('.casestudyBrief').addClass('hidden').attr('style', 'position: static;');
        //Show current case study
        $(myImage).attr('style', 'position: static;').removeClass('hidden').fadeIn('slow');
    };

    /* Animates image gliding */
    this.animate = function() {
        switch (thisObject.target < thisObject.current - 1 || thisObject.target > thisObject.current + 1) {
            case true:
                thisObject.moveTo(thisObject.current + (thisObject.target - thisObject.current) / 3);
                window.setTimeout(thisObject.animate, 50);
                thisObject.busy = true;
                break;
            default:
                thisObject.busy = false;
                break;
        }
    };

    /* Mouse Wheel support */
    this.MouseWheel =
	{
	    init: function() {
	        /* Init mouse wheel listener */
	        if (window.addEventListener) {
	            thisObject.ImageFlowDiv.addEventListener('DOMMouseScroll', thisObject.MouseWheel.get, false);
	        }
	        thisObject.Helper.addEvent(thisObject.ImageFlowDiv, 'mousewheel', thisObject.MouseWheel.get);
	    },

	    get: function(event) {
	        var delta = 0;
	        if (!event) {
	            event = window.event;
	        }
	        if (event.wheelDelta) {
	            delta = event.wheelDelta / 120;
	        }
	        else if (event.detail) {
	            delta = -event.detail / 3;
	        }
	        if (delta) {
	            thisObject.MouseWheel.handle(delta);
	        }
	        thisObject.Helper.suppressBrowserDefault(event);
	    },

	    handle: function(delta) {
	        var change = false;
	        var newImageID = 0;
	        if (delta > 0) {
	            if (thisObject.imageID >= 1) {
	                newImageID = thisObject.imageID - 1;
	                change = true;
	            }
	        }
	        else {
	            if (thisObject.imageID < (thisObject.max - 1)) {
	                newImageID = thisObject.imageID + 1;
	                change = true;
	            }
	        }

	        /* Glide to next (mouse wheel down) / previous (mouse wheel up) image  */
	        if (change === true) {
	            thisObject.glideTo(newImageID);
	        }
	    }
	};

    /* Mouse Dragging*/
    this.MouseDrag =
	{
	    object: null,
	    objectX: 0,
	    mouseX: 0,
	    newX: 0,
	    busy: false,

	    /* Init mouse event listener */
	    init: function() {
	        thisObject.Helper.addEvent(thisObject.ImageFlowDiv, 'mousemove', thisObject.MouseDrag.drag);
	        thisObject.Helper.addEvent(thisObject.ImageFlowDiv, 'mouseup', thisObject.MouseDrag.stop);
	        thisObject.Helper.addEvent(document, 'mouseup', thisObject.MouseDrag.stop);

	        /* Avoid text and image selection while dragging  */
	        thisObject.ImageFlowDiv.onselectstart = function() {
	            var selection = true;
	            if (thisObject.MouseDrag.busy === true) {
	                selection = false;
	            }
	            return selection;
	        };
	    },

	    start: function(o) {
	        thisObject.MouseDrag.object = o;
	        thisObject.MouseDrag.objectX = thisObject.MouseDrag.mouseX - o.offsetLeft + thisObject.newSliderX;

	    },

	    stop: function() {
	        thisObject.MouseDrag.object = null;
	        thisObject.MouseDrag.busy = false;
	    },

	    drag: function(e) {
	        var posx = 0;
	        if (!e) {
	            e = window.event;
	        }
	        if (e.pageX) {
	            posx = e.pageX;
	        }
	        else if (e.clientX) {
	            posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
	        }
	        thisObject.MouseDrag.mouseX = posx;

	        if (thisObject.MouseDrag.object !== null) {
	            var newX = (thisObject.MouseDrag.mouseX - thisObject.MouseDrag.objectX) + thisObject.sliderWidth;

	            /* Make sure, that the slider is moved in proper relation to previous movements by the glideTo function */
	            if (newX < (-thisObject.newSliderX)) {
	                newX = -thisObject.newSliderX;
	            }
	            if (newX > (thisObject.scrollbarWidth - thisObject.newSliderX)) {
	                newX = thisObject.scrollbarWidth - thisObject.newSliderX;
	            }

	            /* Set new slider position */
	            var step = (newX + thisObject.newSliderX) / (thisObject.scrollbarWidth / (thisObject.max - 1));
	            var imageID = Math.round(step);
	            thisObject.MouseDrag.newX = newX;
	            thisObject.MouseDrag.object.style.left = newX + 'px';
	            if (thisObject.imageID !== imageID) {
	                thisObject.glideTo(imageID);
	            }
	            thisObject.MouseDrag.busy = true;
	        }
	    }
	};

    /* Safari touch events on the iPhone and iPod Touch */
    this.Touch =
	{
	    x: 0,
	    startX: 0,
	    stopX: 0,
	    busy: false,
	    first: true,

	    /* Init touch event listener */
	    init: function() {
	        thisObject.Helper.addEvent(thisObject.navigationDiv, 'touchstart', thisObject.Touch.start);
	        thisObject.Helper.addEvent(document, 'touchmove', thisObject.Touch.handle);
	        thisObject.Helper.addEvent(document, 'touchend', thisObject.Touch.stop);
	    },

	    isOnNavigationDiv: function(e) {
	        var state = false;
	        if (e.touches) {
	            var target = e.touches[0].target;
	            if (target === thisObject.navigationDiv || target === thisObject.sliderDiv || target === thisObject.scrollbarDiv) {
	                state = true;
	            }
	        }
	        return state;
	    },

	    getX: function(e) {
	        var x = 0;
	        if (e.touches) {
	            x = e.touches[0].pageX;
	        }
	        return x;
	    },

	    start: function(e) {
	        thisObject.Touch.startX = thisObject.Touch.getX(e);
	        thisObject.Touch.busy = true;
	        thisObject.Helper.suppressBrowserDefault(e);
	    },

	    isBusy: function() {
	        var busy = false;
	        if (thisObject.Touch.busy === true) {
	            busy = true;
	        }
	        return busy;
	    },

	    /* Handle touch event position within the navigation div */
	    handle: function(e) {
	        if (thisObject.Touch.isBusy && thisObject.Touch.isOnNavigationDiv(e)) {
	            if (thisObject.Touch.first) {
	                thisObject.Touch.stopX = ((thisObject.max - 1) - thisObject.imageID) * (thisObject.imagesDivWidth / (thisObject.max - 1));
	                thisObject.Touch.first = false;
	            }
	            var newX = -(thisObject.Touch.getX(e) - thisObject.Touch.startX - thisObject.Touch.stopX);

	            /* Map x-axis touch coordinates in range of the ImageFlow width */
	            if (newX < 0) {
	                newX = 0;
	            }
	            if (newX > thisObject.imagesDivWidth) {
	                newX = thisObject.imagesDivWidth;
	            }

	            thisObject.Touch.x = newX;

	            var imageID = Math.round(newX / (thisObject.imagesDivWidth / (thisObject.max - 1)));
	            imageID = (thisObject.max - 1) - imageID;
	            if (thisObject.imageID !== imageID) {
	                thisObject.glideTo(imageID);
	            }
	            thisObject.Helper.suppressBrowserDefault(e);
	        }
	    },

	    stop: function() {
	        thisObject.Touch.stopX = thisObject.Touch.x;
	        //thisObject.Touch.stopX = -(thisObject.Touch.x - thisObject.imagesDivWidth);

	        thisObject.Touch.busy = false;
	    }
	};

    /* Key support */
    this.Key =
	{
	    /* Init key event listener */
	    init: function() {
	        document.onkeydown = function(event) { thisObject.Key.handle(event); };
	    },

	    /* Handle the arrow keys */
	    handle: function(event) {
	        var charCode = thisObject.Key.get(event);
	        switch (charCode) {
	            /* Right arrow key */
	            case 39:
	                thisObject.MouseWheel.handle(-1);
	                break;

	            /* Left arrow key */
	            case 37:
	                thisObject.MouseWheel.handle(1);
	                break;
	        }
	    },

	    /* Get the current keycode */
	    get: function(event) {
	        event = event || window.event;
	        return event.keyCode;
	    }
	};

    /* Helper functions */
    this.Helper =
	{
	    /* Add events */
	    addEvent: function(obj, type, fn) {
	        if (obj.addEventListener) {
	            obj.addEventListener(type, fn, false);
	        }
	        else if (obj.attachEvent) {
	            obj["e" + type + fn] = fn;
	            obj[type + fn] = function() { obj["e" + type + fn](window.event); };
	            obj.attachEvent("on" + type, obj[type + fn]);
	        }
	    },

	    /* Set image opacity */
	    setOpacity: function(object, value) {
	        if (thisObject.opacity === true) {
	            object.style.opacity = value / 10;
	            object.style.filter = 'alpha(opacity=' + value * 10 + ')';
	        }
	    },

	    /* Creates HTML elements */
	    createDocumentElement: function(type, id, optionalClass) {
	        var element = document.createElement(type);
	        element.setAttribute('id', thisObject.ImageFlowID + '_' + id);
	        if (optionalClass !== undefined) {
	            id += ' ' + optionalClass;
	        }
	        element.setAttribute('class', id);
	        element.setAttribute('className', id);
	        return element;
	    },

	    /* Suppress default browser behaviour to avoid image/text selection while dragging */
	    suppressBrowserDefault: function(e) {
	        if (e.preventDefault) {
	            e.preventDefault();
	        }
	        else {
	            e.returnValue = false;
	        }
	        return false;
	    },

	    /* Adds functions to the window.onresize event - can not be done by addEvent */
	    addResizeEvent: function() {
	        var otherFunctions = window.onresize;
	        if (typeof window.onresize != 'function') {
	            window.onresize = function() {
	                thisObject.refresh();
	            };
	        }
	        else {
	            window.onresize = function() {
	                if (otherFunctions) {
	                    otherFunctions();
	                }
	                thisObject.refresh();
	            };
	        }
	    }
	};
}

/* DOMContentLoaded event handler - by Tanny O'Haley [4] */
var domReadyEvent =
{
    name: "domReadyEvent",
    /* Array of DOMContentLoaded event handlers.*/
    events: {},
    domReadyID: 1,
    bDone: false,
    DOMContentLoadedCustom: null,

    /* Function that adds DOMContentLoaded listeners to the array.*/
    add: function(handler) {
        /* Assign each event handler a unique ID. If the handler has an ID, it has already been added to the events object or been run.*/
        if (!handler.$$domReadyID) {
            handler.$$domReadyID = this.domReadyID++;

            /* If the DOMContentLoaded event has happened, run the function. */
            if (this.bDone) {
                handler();
            }

            /* store the event handler in the hash table */
            this.events[handler.$$domReadyID] = handler;
        }
    },

    remove: function(handler) {
        /* Delete the event handler from the hash table */
        if (handler.$$domReadyID) {
            delete this.events[handler.$$domReadyID];
        }
    },

    /* Function to process the DOMContentLoaded events array. */
    run: function() {
        /* quit if this function has already been called */
        if (this.bDone) {
            return;
        }

        /* Flag this function so we don't do the same thing twice */
        this.bDone = true;

        /* iterates through array of registered functions */
        for (var i in this.events) {
            this.events[i]();
        }
    },

    schedule: function() {
        /* Quit if the init function has already been called*/
        if (this.bDone) {
            return;
        }

        /* First, check for Safari or KHTML.*/
        if (/KHTML|WebKit/i.test(navigator.userAgent)) {
            if (/loaded|complete/.test(document.readyState)) {
                this.run();
            }
            else {
                /* Not ready yet, wait a little more.*/
                setTimeout(this.name + ".schedule()", 100);
            }
        }
        else if (document.getElementById("__ie_onload")) {
            /* Second, check for IE.*/
            return true;
        }

        /* Check for custom developer provided function.*/
        if (typeof this.DOMContentLoadedCustom === "function") {
            /* if DOM methods are supported, and the body element exists (using a double-check
            including document.body, for the benefit of older moz builds [eg ns7.1] in which
            getElementsByTagName('body')[0] is undefined, unless this script is in the body section) */
            if (typeof document.getElementsByTagName !== 'undefined' && (document.getElementsByTagName('body')[0] !== null || document.body !== null)) {
                /* Call custom function. */
                if (this.DOMContentLoadedCustom()) {
                    this.run();
                }
                else {
                    /* Not ready yet, wait a little more. */
                    setTimeout(this.name + ".schedule()", 250);
                }
            }
        }
        return true;
    },

    init: function() {
        /* If addEventListener supports the DOMContentLoaded event.*/
        if (document.addEventListener) {
            document.addEventListener("DOMContentLoaded", function() { domReadyEvent.run(); }, false);
        }

        /* Schedule to run the init function.*/
        setTimeout("domReadyEvent.schedule()", 100);

        function run() {
            domReadyEvent.run();
        }

        /* Just in case window.onload happens first, add it to onload using an available method.*/
        if (typeof addEvent !== "undefined") {
            addEvent(window, "load", run);
        }
        else if (document.addEventListener) {
            document.addEventListener("load", run, false);
        }
        else if (typeof window.onload === "function") {
            var oldonload = window.onload;
            window.onload = function() {
                domReadyEvent.run();
                oldonload();
            };
        }
        else {
            window.onload = run;
        }

        /* for Internet Explorer */
        /*@cc_on
        @if (@_win32 || @_win64)
        document.write("<script id=__ie_onload defer src=\"//:\"><\/script>");
        var script = document.getElementById("__ie_onload");
        script.onreadystatechange = function() {
            if (this.readyState == "complete") {
                domReadyEvent.run(); // call the onload handler
            }
        };
        @end
        @*/
    }
};

var domReady = function(handler) { domReadyEvent.add(handler); };
domReadyEvent.init();

/* Create ImageFlow instances when the DOM structure has been loaded */
domReady(function() {
    var instanceOne = new ImageFlow();
    instanceOne.init({
        aspectRatio: 1.964,          /* Aspect ratio of the ImageFlow container (width divided by height) */
        buttons: true,          /* Toggle navigation buttons */
        captions: true,           /* Toggle captions */
        imageCursor: 'default',      /* Cursor type for all images - default is 'default' */
        ImageFlowID: 'coverflow',    /* Default id of the ImageFlow container */
        imageFocusM: 1.0,            /* Multiplicator for the focussed image size in percent */
        imageFocusMax: 4,              /* Max number of images on each side of the focussed one */
        imageScaling: true,           /* Toggle image scaling */
        imagesHeight: 0.47,           /* Height of the images div container in percent */
        imagesM: 1.0,            /* Multiplicator for all images in percent */
        onClick: function() { document.location = this.url; },   /* Onclick behaviour */
        opacity: false,          /* Toggle image opacity */
        opacityArray: [10, 8, 6, 4, 2],   /* Image opacity (range: 0 to 10) first value is for the focussed image */
        percentLandscape: 118,            /* Scale landscape format */
        percentOther: 100,            /* Scale portrait and square format */
        preloadImages: true,           /* Toggles loading bar (false: requires img attributes height and width) */
        reflections: true,           /* Toggle reflections */
        reflectionGET: '',             /* Pass variables via the GET method to the reflect_.php script */
        reflectionP: 0.5,            /* Height of the reflection in percent of the source image */
        reflectionPNG: true,          /* Toggle reflect2.php or reflect3.php */
        scrollbarP: 0.85,            /* Width of the scrollbar in percent */
        slider: true,           /* Toggle slider */
        sliderCursor: 'e-resize',     /* Slider cursor type - default is 'default' */
        sliderWidth: 14,             /* Width of the slider in px */
        startID: 4,              /* Glide to this image ID on startup */
        startAnimation: true,          /* Animate images moving in from the right on startup */
        xStep: 150             /* Step width on the x-axis in px */
    });
});


text:
require_relative '../faster_test_helper'

require './app/serializers/name_serializer'

describe NameSerializer do
  it 'should load a name as a Name' do
    assert_instance_of Name, NameSerializer.load("Little John")
  end

  it 'should dump as a string' do
    raw_name = "Little John"
    assert_equal raw_name, NameSerializer.dump(Name.new(raw_name))
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php
session_start();
require_once('config/connect.php');
require_once('functions/testdata.php');
$Err	=	NULL;
if($_POST)
{
	$username	=	checkNassign('post', 'email');
	$password	=	checkNassign('post', 'password');
	if($username != '' && $password != '')
	{
		$query	=	"SELECT * FROM users WHERE user_name = '$username' && password = SHA1('$password')";
		$result =	mysqli_query($db_connection, $query);
		//print_r(mysqli_num_rows($result));
		if(mysqli_num_rows($result))
		{
			$_SESSION['user']	=	$username;
			header('location: http://localhost/YoBluntRMS/');
		}
	}else{
		$Err = 'Invalid Username or Password';
	}
}
?>


text:
#include "TileMapUtil.h"
#include "SmoothMapManipulator.h"
#include "TileMapToolkit.h"
#include "MapOperationInterface.h"
#include "MapDrawingInterface.h"
#include "MapManipulator.h"
#include <math.h>
#ifdef __SYMBIAN__
#include <e32math.h>
#endif

#include "MC2Point.h"
#include "Utility.h"

// millisecond thresholds for keypresses
#define THRESHOLD_ONE 250
#define THRESHOLD_TWO 500
#define THRESHOLD_THREE 1000

// Default delta for movement.
#define  MOVEDELTA_DEFAULT  2

// Threshold and default/max values for rotation
#define  ROTDELTA_DEFAULT  15
#define  ROTDELTA_THRESHOLD_ONE  60
#define  ROTDELTA_THRESHOLD_TWO  60
#define  ROTDELTA_THRESHOLD_THREE  60
#define  ROTDELTA_THRESHOLD_FOUR  60
#define  ROTDELTA_MAX  90

// Threshold values for the zoom
#define  ZOOMDELTA_THRESHOLD_ONE  0.40546f  // ln(1.5) = 0.40546
#define  ZOOMDELTA_THRESHOLD_TWO  0.55961f  // ln(1.75) = 0.55961f
#define  ZOOMDELTA_THRESHOLD_THREE 0.69314f // ln(2.0) = 0.69314f
#define  ZOOMDELTA_THRESHOLD_FOUR 0.91629f  // ln(2.5) = 0.91629f
#define  ZOOMDELTA_MAX           0.40546f

#define TIMER_PERIOD 10

SmoothMapManipulator::SmoothMapManipulator(
   MapManipulator& mapManipulator,
   WFAPI::MapDrawingInterface* drawingInterface,
   TileMapToolkit* toolkit) :
   m_mapManipulator(mapManipulator),
   m_operationState(STATIC),
   m_operationInterface(NULL),
   m_drawingInterface(drawingInterface)
{
   resetTimes();
   m_lastDrawTime = 0;
   m_zoomingState.inFactor = 1.0f;
   m_zoomingState.outFactor = 1.0f;
   m_movingState.delta = 0;
   m_rotationState.delta = 0;

   m_timerListener  =
      new TileMapTimerListenerTemplate<SmoothMapManipulator>(this);

   m_timer =
      toolkit->createPeriodicTimer( m_timerListener,
                                    TileMapToolkit::PRIO_STANDARD);

}

void SmoothMapManipulator::resetTimes()
{
   for(int i = 0; i < NUM_SMOOTH_OPERATIONS; i++) {
      m_active[i] = 0;
   }
}

bool SmoothMapManipulator::attemptOperation(OperationType operation)
{
   bool alreadyActive = m_active[operation];

   if(!m_mapManipulator.okayToStart(MapManipulator::SMOOTH)) {
      return false;
   } else {
      if(!alreadyActive) {
         m_mapManipulator.setIsStarting(MapManipulator::DRAGGING);
      }
   }

   if(!m_active[operation]) {
      resetTimes();
      m_active[operation] = TileMapUtil::currentTimeMillis();
      m_lastDrawTime = TileMapUtil::currentTimeMillis();
      m_timer->start(TIMER_PERIOD);
   }

   operationState state = classify(operation);

   if( state != m_operationState ) {
      setMapState(state);
   }

   return true;
}

SmoothMapManipulator::operationState
SmoothMapManipulator::classify(OperationType type)
{
   switch(type) {
   case MOVE_UP:
   case MOVE_DOWN:
   case MOVE_LEFT:
   case MOVE_RIGHT:
   case MOVE_UP_AND_RIGHT:
   case MOVE_DOWN_AND_RIGHT:
   case MOVE_UP_AND_LEFT:
   case MOVE_DOWN_AND_LEFT:
      return MOVING;
   case ZOOM_IN_POINT:
   case ZOOM_IN:
   case ZOOM_OUT:
      return ZOOMING;
   case ROTATE_LEFT:
   case ROTATE_RIGHT:
      return ROTATING;
   default:
      return STATIC;
   }
}

void SmoothMapManipulator::endOperation(OperationType operation)
{
   // Currently, ending one operation will stop all operations.
   // Just as beginning one will stop all.

   m_active[operation] = 0;
   resetTimes();
   m_timer->stop();

   setMapState(STATIC);
}

void SmoothMapManipulator::setMapState(operationState group)
{
   if(group != STATIC) {
      m_operationInterface->setMovementMode(true);
   } else {
      m_operationInterface->setMovementMode(false);
   }

   m_operationState = group;
}

void SmoothMapManipulator::updateState() {
   switch(m_operationState) {
   case MOVING:
      updateMovingState();
      break;
   case ROTATING:
      updateRotatingState();
      break;
   case STATIC:
      updateStaticState();
      break;
   case ZOOMING:
      updateZoomingState();
      break;
   }
}

void SmoothMapManipulator::updateMovingState()
{
   MC2Point moveDelta;

    if( m_active[ MOVE_DOWN ]) {
       updateMovingState(m_active[ MOVE_DOWN ]);
       moveDelta = MC2Point(0, m_movingState.delta);
    }
    else if( m_active[ MOVE_UP ] ) {
       updateMovingState( m_active[ MOVE_UP ] );
       moveDelta = MC2Point(0, -m_movingState.delta);
    }
    else if( m_active[ MOVE_LEFT ] ) {
       updateMovingState( m_active[ MOVE_LEFT ] );
       moveDelta = MC2Point(-m_movingState.delta, 0);
    }
    else if( m_active[ MOVE_RIGHT ] ) {
       updateMovingState( m_active[ MOVE_RIGHT ] );
       moveDelta = MC2Point(m_movingState.delta, 0);
    }
    else if( m_active[ MOVE_DOWN_AND_RIGHT ]) {
       updateMovingState(m_active[ MOVE_DOWN_AND_RIGHT ]);
       moveDelta = MC2Point(m_movingState.delta, m_movingState.delta);
    }
    else if( m_active[ MOVE_UP_AND_RIGHT ] ) {
       updateMovingState( m_active[ MOVE_UP_AND_RIGHT ] );
       moveDelta = MC2Point(m_movingState.delta, -m_movingState.delta);
    }
    else if( m_active[ MOVE_DOWN_AND_LEFT ]) {
       updateMovingState(m_active[ MOVE_DOWN_AND_LEFT ]);
       moveDelta = MC2Point(-m_movingState.delta, m_movingState.delta);
    }
    else if( m_active[ MOVE_UP_AND_LEFT ] ) {
       updateMovingState( m_active[ MOVE_UP_AND_LEFT ] );
       moveDelta = MC2Point(-m_movingState.delta, -m_movingState.delta);
    }

    if(moveDelta.getX() || moveDelta.getY()) {
       m_operationInterface->move(moveDelta.getX(), moveDelta.getY());
       m_drawingInterface->requestRepaint();
    }
}

void SmoothMapManipulator::updateMovingState(uint32 keyTime)
{
   // create threshold and delta arrays
   static const float32
      thresholds[] = { 125,
                       THRESHOLD_ONE,   // 250
                       THRESHOLD_TWO,   // 500
                       THRESHOLD_THREE, // 1000
                       2000,
                       2500,
                       float(MAX_UINT32) };

   static const float32 deltas[] = { 0, 50, 100, 150, 150, 150, 150 };

#ifndef ENABLE_MAPPERFORMANCE_DEBUGGING
   // Production values.
   static const float32 maxVals[] = { 0, 7, 7, 10, 15, 50, 50 };
#else
   // Test values.
   static const float32 maxVals[] = { 0, 1, 1, 1, 1, 1, 1 };
#endif
   // get delta based on time
   float32 delta = getDelta(thresholds,
                            deltas,
                            maxVals,
                            sizeof(thresholds) / sizeof( thresholds[0] ),
                            keyTime);

   /* adjust the value, since it will be truncated to zero
      on conversion to integer */
   if(delta < 1.0f) {
      delta = 1.0f;
   }

   // set movement delta to calculated value
   m_movingState.delta = (uint32) delta;
}

void SmoothMapManipulator::updateRotatingState() {

   int rotateDeg = 0;

   if(m_active[ROTATE_LEFT]) {
      updateRotatingState(m_active[ROTATE_LEFT]);
      rotateDeg = m_rotationState.delta;
   }
   else if(m_active[ROTATE_RIGHT]) {
      updateRotatingState(m_active[ROTATE_RIGHT]);
      rotateDeg = -m_rotationState.delta;
   }

   if(rotateDeg) {
      m_operationInterface->rotateLeftDeg(rotateDeg);
      m_drawingInterface->requestRepaint();
   }
}

void SmoothMapManipulator::updateRotatingState(uint32 keyTime)
{

   // create threshold and delta arrays
   static const float32
      thresholds[4] = { THRESHOLD_ONE, THRESHOLD_TWO, THRESHOLD_THREE,
                        float(MAX_UINT32) };

   static const float32 deltas[4] = { ROTDELTA_THRESHOLD_ONE,
                                      ROTDELTA_THRESHOLD_TWO,
                                      ROTDELTA_THRESHOLD_THREE,
                                      ROTDELTA_THRESHOLD_FOUR };

   static const float32 maxVals[] = { ROTDELTA_MAX, ROTDELTA_MAX,
                                      ROTDELTA_MAX, ROTDELTA_MAX };

   // get delta based on time
   float32 delta = getDelta(thresholds, deltas, maxVals,
                            sizeof(thresholds) / sizeof( thresholds[0] ),
                            keyTime);

   /* adjust the value, since it will be truncated to zero
      on conversion to integer */
   if(delta < 1.0f) {
      delta = 1.0f;
   }

   // set rotation delta to calculated value
   m_rotationState.delta = (uint32) delta;

   return;
}

void SmoothMapManipulator::updateStaticState()
{

}

void SmoothMapManipulator::updateZoomingToPointState(uint32 keyTime)
{

}

void SmoothMapManipulator::updateZoomingState()
{

   float zoomFactor = 1.0f;

   if(m_active[ZOOM_IN]) {
      updateZoomingState(m_active[ZOOM_IN]);
      zoomFactor = m_zoomingState.inFactor;
   } else if(m_active[ZOOM_OUT]) {
      updateZoomingState(m_active[ZOOM_OUT]);
      zoomFactor = m_zoomingState.outFactor;
   } else if(m_active[ZOOM_IN_POINT]) {
      updateZoomingState(m_active[ZOOM_IN_POINT]);
      zoomFactor = m_zoomingState.inFactor;
   }

   if(zoomFactor != 1.0f) {
      if(m_zoomingState.zoomingToPoint) {
         m_operationInterface->zoom(zoomFactor,
                                       m_zoomingState.coord,
                                       m_zoomingState.point);
      } else {
         m_operationInterface->zoom(zoomFactor);
      }

      m_drawingInterface->requestRepaint();
   }
}

void SmoothMapManipulator::updateZoomingState(uint32 keyTime) {

   // create threshold and delta arrays for zooming
   static const float32
      thresholds[4] = { THRESHOLD_ONE, THRESHOLD_TWO, THRESHOLD_THREE,
                        float(MAX_UINT32) };
   static const float32
      deltas[4] = { ZOOMDELTA_THRESHOLD_ONE,
                    ZOOMDELTA_THRESHOLD_TWO,
                    ZOOMDELTA_THRESHOLD_THREE,
                    ZOOMDELTA_THRESHOLD_FOUR };

   static const float32 maxVals[] = { ZOOMDELTA_MAX,
                                      ZOOMDELTA_MAX,
                                      ZOOMDELTA_MAX,
                                      ZOOMDELTA_MAX };

   // get zoom-in delta based on time
   const float32 delta = getDelta(thresholds,
                                  deltas,
                                  maxVals,
                                  sizeof(thresholds) / sizeof( thresholds[0] ),
                                  keyTime);

   // set zoom-in delta to calculated value
#ifdef __SYMBIAN32__
   TReal expDelta = 1.0;
   Math::Exp( expDelta, delta );
#else
   double expDelta = exp( delta );
#endif

   m_zoomingState.inFactor = 1 / expDelta;

   // set zoom-out delta to calculated value
   m_zoomingState.outFactor = expDelta;

   return;
}

float32 SmoothMapManipulator::getDelta(const float32* thresholds,
                                    const float32* deltas,
                                    const float32* maxValues,
                                    int nbrThresholds,
                                    uint32 firstKeyPress)
{
   float32 curDelta = 0;

   uint32 curKeyPress = TileMapUtil::currentTimeMillis();

   // calculate the time between keypresses
   uint32 curTime = curKeyPress - firstKeyPress;

   // time since last drawn.
   uint32 timeSinceLastDrawn = curKeyPress - m_lastDrawTime;

   float32 maxValue = 0.0;

   // check the curTime against the thresholds
   // (currently, hardcoded for nbr values)
   for ( int i = 0; i < nbrThresholds; ++i ) {
      if ( curTime < thresholds[i] ) {
         curDelta = deltas[i] * ((float32) timeSinceLastDrawn / 1000.0f);
#ifdef ARCH_OS_WINDOWS
         // Until the deltas can be sent into TMKH,
         // hardcode that windows needs 5 times larger deltas.
         curDelta *= 5;
#endif
         maxValue = maxValues[ i ];
         break;
      }
   }

   // check against maxValue
   if(curDelta > maxValue) {
      curDelta = maxValue;
   }

   if ( curDelta > 0 ) {
      m_lastDrawTime = curKeyPress;
   }

   return(curDelta);
}

bool SmoothMapManipulator::attemptMoveUp()
{
   return attemptOperation(MOVE_UP);
}

void SmoothMapManipulator::endMoveUp()
{
   endOperation(MOVE_UP);
}

bool SmoothMapManipulator::attemptMoveDown()
{
   return attemptOperation(MOVE_DOWN);
}

void SmoothMapManipulator::endMoveDown()
{
   endOperation(MOVE_DOWN);
}

bool SmoothMapManipulator::attemptMoveLeft()
{
   return attemptOperation(MOVE_LEFT);
}

void SmoothMapManipulator::endMoveLeft()
{
   endOperation(MOVE_LEFT);
}

bool SmoothMapManipulator::attemptMoveRight()
{
   return attemptOperation(MOVE_RIGHT);
}

void SmoothMapManipulator::endMoveRight()
{
   endOperation(MOVE_RIGHT);
}

bool SmoothMapManipulator::attemptMoveUpAndRight()
{
   return attemptOperation(MOVE_UP_AND_RIGHT);
}

void SmoothMapManipulator::endMoveUpAndRight()
{
   endOperation(MOVE_UP_AND_RIGHT);
}

bool SmoothMapManipulator::attemptMoveUpAndLeft()
{
   return attemptOperation(MOVE_UP_AND_LEFT);
}

void SmoothMapManipulator::endMoveUpAndLeft()
{
   endOperation(MOVE_UP_AND_LEFT);
}

bool SmoothMapManipulator::attemptMoveDownAndRight()
{
   return attemptOperation(MOVE_DOWN_AND_RIGHT);
}

void SmoothMapManipulator::endMoveDownAndRight()
{
   endOperation(MOVE_DOWN_AND_RIGHT);
}

bool SmoothMapManipulator::attemptMoveDownAndLeft()
{
   return attemptOperation(MOVE_DOWN_AND_LEFT);
}

void SmoothMapManipulator::endMoveDownAndLeft()
{
   endOperation(MOVE_DOWN_AND_LEFT);
}

bool SmoothMapManipulator::attemptRotateLeft()
{
   return attemptOperation(ROTATE_LEFT);
}

void SmoothMapManipulator::endRotateLeft()
{
   endOperation(ROTATE_LEFT);
}

bool SmoothMapManipulator::attemptRotateRight()
{
   return attemptOperation(ROTATE_RIGHT);
}

void SmoothMapManipulator::endRotateRight()
{
   endOperation(ROTATE_RIGHT);
}

bool SmoothMapManipulator::attemptZoomIn()
{
   m_zoomingState.zoomingToPoint = false;
   return attemptOperation(ZOOM_IN);
}

void SmoothMapManipulator::endZoomIn()
{
   endOperation(ZOOM_IN);
}

bool SmoothMapManipulator::isWorking()
{
   return m_operationState != STATIC;
}

void SmoothMapManipulator::stopWorking()
{
   resetTimes();
}

bool SmoothMapManipulator::attemptZoomOut()
{
   m_zoomingState.zoomingToPoint = false;
   return attemptOperation(ZOOM_OUT);
}

void SmoothMapManipulator::endZoomOut()
{
   endOperation(ZOOM_OUT);
}

void SmoothMapManipulator::timerExpired(uint32)
{
   updateState();

}

bool SmoothMapManipulator::attemptZoomInPoint(const MC2Point& point,
                                              const MC2Coordinate& coord)
{
   m_zoomingState.coord = coord;
   m_zoomingState.point = point;
   m_zoomingState.zoomingToPoint = true;
   return attemptOperation(ZOOM_IN_POINT);
}

void SmoothMapManipulator::endZoomInPoint(const MC2Point& point,
                                       const MC2Coordinate& coord)
{
   endOperation(ZOOM_IN_POINT);
}

bool SmoothMapManipulator::currentlyZoomingInPoint() const
{
   return m_active[ZOOM_IN_POINT] != 0;
}

bool SmoothMapManipulator::attemptResetRotation(){
   if(!m_mapManipulator.okayToStart(MapManipulator::SMOOTH)) {
      return false;
   } else {
      m_mapManipulator.setIsStarting(MapManipulator::DRAGGING);
   }

   m_operationInterface->setAngle(0);
   m_drawingInterface->requestRepaint();

   return true;
}

SmoothMapManipulator::~SmoothMapManipulator()
{
   delete m_timerListener;
   delete m_timer;
}

void
SmoothMapManipulator::setMapOperationInterface(
   WFAPI::MapOperationInterface* operationInterface)
{
   m_operationInterface = operationInterface;
}


text:
require 'yaml'

module LockJar
  # Global configuration for LockJar
  class Config
    CONFIG_ENV = 'LOCKJAR_CONFIG'.freeze
    DEFAULT_FILENAME = '.lockjar'.freeze

    attr_reader :repositories

    class << self
      # Load .lockjar YAML config file from ENV['LOCKJAR_CONFIG'], current_dir, or
      # home dir.
      def load_config_file
        local_config_paths =
          [Dir.pwd, Dir.home]
          .map { |path| File.join(path, DEFAULT_FILENAME) }

        config_path =
          ([ENV[CONFIG_ENV]] + local_config_paths)
          .compact
          .find { |path| File.exist? path }

        new(YAML.load_file(config_path)) if config_path
      end
    end

    #
    # {
    #   'repositories' => {
    #     ':url' => {
    #       'username' => ''
    #       'password' => ''
    #     }
    #   }
    # }
    def initialize(config)
      @repositories = config['repositories'] || {}
    end
  end
end


text:
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//

package com.cloud.utils.exception;

import java.util.HashMap;

import org.apache.log4j.Logger;

/**
 * CSExceptionErrorCode lists the CloudStack error codes that correspond
 * to a each exception thrown by the CloudStack API.
 */

public class CSExceptionErrorCode {

    public static final Logger s_logger = Logger.getLogger(CSExceptionErrorCode.class.getName());

    // Declare a hashmap of CloudStack Error Codes for Exceptions.
    protected static final HashMap<String, Integer> ExceptionErrorCodeMap;

    static {
        try {
            ExceptionErrorCodeMap = new HashMap<String, Integer>();
            ExceptionErrorCodeMap.put("com.cloud.utils.exception.CloudRuntimeException", 4250);
            ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExecutionException", 4260);
            ExceptionErrorCodeMap.put("com.cloud.utils.exception.HypervisorVersionChangedException", 4265);
            ExceptionErrorCodeMap.put("com.cloud.utils.exception.NioConnectionException", 4270);
            ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4275);
            ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4280);
            ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4285);
            ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4290);
            ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4300);
            ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4305);
            ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4310);
            ExceptionErrorCodeMap.put("com.cloud.exception.HAStateException", 4315);
            ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientAddressCapacityException", 4320);
            ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientCapacityException", 4325);
            ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientNetworkCapacityException", 4330);
            ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientVirtualNetworkCapacityException", 4331);
            ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientServerCapacityException", 4335);
            ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientStorageCapacityException", 4340);
            ExceptionErrorCodeMap.put("com.cloud.exception.InternalErrorException", 4345);
            ExceptionErrorCodeMap.put("com.cloud.exception.InvalidParameterValueException", 4350);
            ExceptionErrorCodeMap.put("com.cloud.exception.ManagementServerException", 4355);
            ExceptionErrorCodeMap.put("com.cloud.exception.NetworkRuleConflictException", 4360);
            ExceptionErrorCodeMap.put("com.cloud.exception.PermissionDeniedException", 4365);
            ExceptionErrorCodeMap.put("com.cloud.exception.ResourceAllocationException", 4370);
            ExceptionErrorCodeMap.put("com.cloud.exception.ResourceInUseException", 4375);
            ExceptionErrorCodeMap.put("com.cloud.exception.ResourceUnavailableException", 4380);
            ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4385);
            ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4390);
            ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4395);
            ExceptionErrorCodeMap.put("com.cloud.async.AsyncCommandQueued", 4540);
            ExceptionErrorCodeMap.put("com.cloud.exception.RequestLimitException", 4545);
            ExceptionErrorCodeMap.put("com.cloud.exception.StorageConflictException", 4550);

            // Have a special error code for ServerApiException when it is
            // thrown in a standalone manner when failing to detect any of the above
            // standard exceptions.
            ExceptionErrorCodeMap.put("org.apache.cloudstack.api.ServerApiException", 9999);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError(e);
        }
    }

    public static HashMap<String, Integer> getErrCodeList() {
        return ExceptionErrorCodeMap;
    }

    public static int getCSErrCode(String exceptionName) {
        if (ExceptionErrorCodeMap.containsKey(exceptionName)) {
            return ExceptionErrorCodeMap.get(exceptionName);
        } else {
            s_logger.info("Could not find exception: " + exceptionName + " in error code list for exceptions");
            return -1;
        }
    }

    public static String getCurMethodName() {
        StackTraceElement stackTraceCalls[] = (new Throwable()).getStackTrace();
        return stackTraceCalls[1].toString();
    }
}


text:
```xml
<add key="Auth0Domain" value="https://<%= account.namespace %>/"/>
<add key="Auth0ClientID" value="<%= account.clientId %>"/>
<add key="Auth0ClientSecret" value="<%= account.clientSecret %>"/>
```


text:
NS_SWIFT_NAME(LikeButtonPopWAV)
@interface FBSDKLikeButtonPopWAV : FBSDKAudioResourceLoader
@end


text:
package org.osgi.impl.service.upnp.cd.control;

import java.util.Hashtable;

// This class contains the error codes, their errorDescription and Description
// which are relevent to control layer. The error codes are mapped to errorDescription
// and Description which can be retreived through the provided methods.
public class SOAPErrorCodes {
	// This table maps the error codes to their description.
	private static Hashtable<String,String[]> errorMap;

	// This is the constructor which initializes the error table and populates
	// it.
	public SOAPErrorCodes() {
		errorMap = new Hashtable<>();
		errorMap.put("401", new String[] {"Invalid Action",
				"No action by that name at this service."});
		errorMap
				.put(
						"402",
						new String[] {
								"Invalid Args",
								"Could be any of the following: not "
										+ "enough in args, too many in args, no in args, no in args by that name, "
										+ "one or more in args are of the wrong data type."});
		errorMap.put("403", new String[] {"Out of Sync",
				"Out of synchronization."});
		errorMap.put("501", new String[] {
				"Action Failed",
				"May be returned in current state of "
						+ "service prevents invoking that action."});
		errorMap.put("404", new String[] {"Invalid Var",
				"No state variable by that name at this service."});
	}

	// This method takes the error code and returns the description.
	static String getDesc(String code) {
		String[] str = errorMap.get(code);
		if (str == null) {
			return null;
		}
		return str[1];
	}

	// This method takes the error code and returns the error description.
	static String getErrorDesc(String code) {
		String[] str = errorMap.get(code);
		if (str == null) {
			return null;
		}
		return str[0];
	}
}


text:
layout: residence
title: Résidence La Belle Colline | Promotion Immobilière à Djenane Sfari
permalink: /projets-en-cours/la-belle-colline.html
delivery: Juin 2018
location: Birkhadem
redirect_from: [/fr/projets-en-cours/la-belle-colline,/en/ongoing-project/la-belle-colline,/es/proyectos-en-curso/la-belle-colline]
description: Implantée à Djenane Sfari dans la commune de Birkhadem, la Résidence La Belle Colline de Bessa Promotion Immobilière est un projet ambitieux d'éco quartier
slug: La Belle Colline
---

Présentation

  Située à Djenane Sfari dans la commune de Birkhadem, la résidence La Belle Colline représente un de nos projets les plus ambitieux : Construire un important ensemble résidentiel géré à la pointe de la technologie.

 Conçue en partenariat avec un bureau d'étude sud-coréen, la résidence  propose une très grande variété d'appartements et de surfaces du F2 au F5 en simplex et duplex, répartis sur plusieurs bâtiments de sorte à former un éco-quartier.

    En plus de proposer des vues imprenables sur la Mitidja dans certains appartements et un
    accès très facile sur l'autoroute, la résidence disposera également de locaux commerciaux, d'une salle de fitness,
    d'un spa et d'espace verts aménagés de sorte à garantir un environnement convivial et un cadre de vie où le fonctionnel
    et l'esthétique ont été étroitement associés pour le bien-être de tous les résidents.

Nos offres sur la résidence {{page.slug}}

Type d'appartement

Surface

              {% for residence in site.data.offres.bellecolline %}

{{residence.type}}

{{residence.surface}}

              {% endfor %}

       {% for item in site.data.images.residences.bellecolline.slider %}

       {% endfor %}


text:
In this directory is a collection of documents that cover a number of the
technical and architectural decisions that have been made while building
front-end applications at Cloudflare.

The goal of this handbook is to both document internal best practices and share
our opinions externally by publishing these documents in the open.

If any of this interests you, maybe you should consider
[joining our team](https://www.cloudflare.com/join-our-team/).

### Documents

- [Functional Testing Containers](functional-testing-containers.md)
- [Broken Promises](broken-promises.md)
- [cf-ui monorepo](cf-ui-monorepo.md)
- [Wrapping External APIs](wrapping-external-apis.md)
- [Plan for Abstraction](plan-for-abstraction.md)
- [Selectors Lite™](selectors-lite.md)
- [ALL THE NPM PACKAGES!!!](all-the-npm-packages.md)
- [Backbone to React](backbone-to-react.md)
- [Solving problems in layers](solving-problems-in-layers.md)
- [Die inheritance die](die-inheritance-die.md)


text:
recurrent-title: "Consumer advice and fire safety drop-in"
recurrent-day: first Tuesday of the month
recurrent-times: 1000-1200
recurrent-location: beccles-library
recurrent-location-display-name: Beccles Library
recurrent-location-display-url: /branches/beccles-library/
recurrent-category: surgeries-advice
---


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

package cmd

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"io/ioutil"
	"math"
	"math/rand"
	"strconv"
	"testing"
	"time"
)

// Prepare benchmark backend
func prepareBenchmarkBackend(instanceType string) (ObjectLayer, []string, error) {
	nDisks := 16
	disks, err := getRandomDisks(nDisks)
	if err != nil {
		return nil, nil, err
	}
	obj, _, err := initObjectLayer(disks, nil)
	if err != nil {
		return nil, nil, err
	}
	return obj, disks, nil
}

// Benchmark utility functions for ObjectLayer.PutObject().
// Creates Object layer setup ( MakeBucket ) and then runs the PutObject benchmark.
func runPutObjectBenchmark(b *testing.B, obj ObjectLayer, objSize int) {
	var err error
	// obtains random bucket name.
	bucket := getRandomBucketName()
	// create bucket.
	err = obj.MakeBucket(bucket)
	if err != nil {
		b.Fatal(err)
	}

	// get text data generated for number of bytes equal to object size.
	textData := generateBytesData(objSize)
	// generate md5sum for the generated data.
	// md5sum of the data to written is required as input for PutObject.
	hasher := md5.New()
	hasher.Write([]byte(textData))
	metadata := make(map[string]string)
	metadata["md5Sum"] = hex.EncodeToString(hasher.Sum(nil))
	sha256sum := ""
	// benchmark utility which helps obtain number of allocations and bytes allocated per ops.
	b.ReportAllocs()
	// the actual benchmark for PutObject starts here. Reset the benchmark timer.
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		// insert the object.
		objInfo, err := obj.PutObject(bucket, "object"+strconv.Itoa(i), int64(len(textData)), bytes.NewBuffer(textData), metadata, sha256sum)
		if err != nil {
			b.Fatal(err)
		}
		if objInfo.MD5Sum != metadata["md5Sum"] {
			b.Fatalf("Write no: %d: Md5Sum mismatch during object write into the bucket: Expected %s, got %s", i+1, objInfo.MD5Sum, metadata["md5Sum"])
		}
	}
	// Benchmark ends here. Stop timer.
	b.StopTimer()
}

// Benchmark utility functions for ObjectLayer.PutObjectPart().
// Creates Object layer setup ( MakeBucket ) and then runs the PutObjectPart benchmark.
func runPutObjectPartBenchmark(b *testing.B, obj ObjectLayer, partSize int) {
	var err error
	// obtains random bucket name.
	bucket := getRandomBucketName()
	object := getRandomObjectName()

	// create bucket.
	err = obj.MakeBucket(bucket)
	if err != nil {
		b.Fatal(err)
	}

	objSize := 128 * 1024 * 1024

	// PutObjectPart returns md5Sum of the object inserted.
	// md5Sum variable is assigned with that value.
	var md5Sum, uploadID string
	// get text data generated for number of bytes equal to object size.
	textData := generateBytesData(objSize)
	// generate md5sum for the generated data.
	// md5sum of the data to written is required as input for NewMultipartUpload.
	hasher := md5.New()
	hasher.Write([]byte(textData))
	metadata := make(map[string]string)
	metadata["md5Sum"] = hex.EncodeToString(hasher.Sum(nil))
	sha256sum := ""
	uploadID, err = obj.NewMultipartUpload(bucket, object, metadata)
	if err != nil {
		b.Fatal(err)
	}

	var textPartData []byte
	// benchmark utility which helps obtain number of allocations and bytes allocated per ops.
	b.ReportAllocs()
	// the actual benchmark for PutObjectPart starts here. Reset the benchmark timer.
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		// insert the object.
		totalPartsNR := int(math.Ceil(float64(objSize) / float64(partSize)))
		for j := 0; j < totalPartsNR; j++ {
			hasher.Reset()
			if j < totalPartsNR-1 {
				textPartData = textData[j*partSize : (j+1)*partSize-1]
			} else {
				textPartData = textData[j*partSize:]
			}
			hasher.Write([]byte(textPartData))
			metadata := make(map[string]string)
			metadata["md5Sum"] = hex.EncodeToString(hasher.Sum(nil))
			md5Sum, err = obj.PutObjectPart(bucket, object, uploadID, j, int64(len(textPartData)), bytes.NewBuffer(textPartData), metadata["md5Sum"], sha256sum)
			if err != nil {
				b.Fatal(err)
			}
			if md5Sum != metadata["md5Sum"] {
				b.Fatalf("Write no: %d: Md5Sum mismatch during object write into the bucket: Expected %s, got %s", i+1, md5Sum, metadata["md5Sum"])
			}
		}
	}
	// Benchmark ends here. Stop timer.
	b.StopTimer()
}

// creates XL/FS backend setup, obtains the object layer and calls the runPutObjectPartBenchmark function.
func benchmarkPutObjectPart(b *testing.B, instanceType string, objSize int) {
	// create a temp XL/FS backend.
	objLayer, disks, err := prepareBenchmarkBackend(instanceType)
	if err != nil {
		b.Fatalf("Failed obtaining Temp Backend: <ERROR> %s", err)
	}
	// cleaning up the backend by removing all the directories and files created on function return.
	defer removeRoots(disks)
	// uses *testing.B and the object Layer to run the benchmark.
	runPutObjectPartBenchmark(b, objLayer, objSize)
}

// creates XL/FS backend setup, obtains the object layer and calls the runPutObjectBenchmark function.
func benchmarkPutObject(b *testing.B, instanceType string, objSize int) {
	// create a temp XL/FS backend.
	objLayer, disks, err := prepareBenchmarkBackend(instanceType)
	if err != nil {
		b.Fatalf("Failed obtaining Temp Backend: <ERROR> %s", err)
	}
	// cleaning up the backend by removing all the directories and files created on function return.
	defer removeRoots(disks)
	// uses *testing.B and the object Layer to run the benchmark.
	runPutObjectBenchmark(b, objLayer, objSize)
}

// creates XL/FS backend setup, obtains the object layer and runs parallel benchmark for put object.
func benchmarkPutObjectParallel(b *testing.B, instanceType string, objSize int) {
	// create a temp XL/FS backend.
	objLayer, disks, err := prepareBenchmarkBackend(instanceType)
	if err != nil {
		b.Fatalf("Failed obtaining Temp Backend: <ERROR> %s", err)
	}
	// cleaning up the backend by removing all the directories and files created on function return.
	defer removeRoots(disks)
	// uses *testing.B and the object Layer to run the benchmark.
	runPutObjectBenchmarkParallel(b, objLayer, objSize)
}

// Benchmark utility functions for ObjectLayer.GetObject().
// Creates Object layer setup ( MakeBucket, PutObject) and then runs the benchmark.
func runGetObjectBenchmark(b *testing.B, obj ObjectLayer, objSize int) {
	var err error
	// obtains random bucket name.
	bucket := getRandomBucketName()
	// create bucket.
	err = obj.MakeBucket(bucket)
	if err != nil {
		b.Fatal(err)
	}

	sha256sum := ""
	for i := 0; i < 10; i++ {
		// get text data generated for number of bytes equal to object size.
		textData := generateBytesData(objSize)
		// generate md5sum for the generated data.
		// md5sum of the data to written is required as input for PutObject.
		// PutObject is the functions which writes the data onto the FS/XL backend.
		hasher := md5.New()
		hasher.Write([]byte(textData))
		metadata := make(map[string]string)
		metadata["md5Sum"] = hex.EncodeToString(hasher.Sum(nil))
		// insert the object.
		var objInfo ObjectInfo
		objInfo, err = obj.PutObject(bucket, "object"+strconv.Itoa(i), int64(len(textData)), bytes.NewBuffer(textData), metadata, sha256sum)
		if err != nil {
			b.Fatal(err)
		}
		if objInfo.MD5Sum != metadata["md5Sum"] {
			b.Fatalf("Write no: %d: Md5Sum mismatch during object write into the bucket: Expected %s, got %s", i+1, objInfo.MD5Sum, metadata["md5Sum"])
		}
	}

	// benchmark utility which helps obtain number of allocations and bytes allocated per ops.
	b.ReportAllocs()
	// the actual benchmark for GetObject starts here. Reset the benchmark timer.
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		var buffer = new(bytes.Buffer)
		err = obj.GetObject(bucket, "object"+strconv.Itoa(i%10), 0, int64(objSize), buffer)
		if err != nil {
			b.Error(err)
		}
	}
	// Benchmark ends here. Stop timer.
	b.StopTimer()

}

// randomly picks a character and returns its equivalent byte array.
func getRandomByte() []byte {
	const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	// seeding the random number generator.
	rand.Seed(time.Now().UTC().UnixNano())
	var b byte
	// pick a character randomly.
	b = letterBytes[rand.Intn(len(letterBytes))]
	return []byte{b}
}

// picks a random byte and repeats it to size bytes.
func generateBytesData(size int) []byte {
	// repeat the random character chosen size
	return bytes.Repeat(getRandomByte(), size)
}

// creates XL/FS backend setup, obtains the object layer and calls the runGetObjectBenchmark function.
func benchmarkGetObject(b *testing.B, instanceType string, objSize int) {
	// create a temp XL/FS backend.
	objLayer, disks, err := prepareBenchmarkBackend(instanceType)
	if err != nil {
		b.Fatalf("Failed obtaining Temp Backend: <ERROR> %s", err)
	}
	// cleaning up the backend by removing all the directories and files created.
	defer removeRoots(disks)
	//  uses *testing.B and the object Layer to run the benchmark.
	runGetObjectBenchmark(b, objLayer, objSize)
}

// creates XL/FS backend setup, obtains the object layer and runs parallel benchmark for ObjectLayer.GetObject() .
func benchmarkGetObjectParallel(b *testing.B, instanceType string, objSize int) {
	// create a temp XL/FS backend.
	objLayer, disks, err := prepareBenchmarkBackend(instanceType)
	if err != nil {
		b.Fatalf("Failed obtaining Temp Backend: <ERROR> %s", err)
	}
	// cleaning up the backend by removing all the directories and files created.
	defer removeRoots(disks)
	//  uses *testing.B and the object Layer to run the benchmark.
	runGetObjectBenchmarkParallel(b, objLayer, objSize)
}

// Parallel benchmark utility functions for ObjectLayer.PutObject().
// Creates Object layer setup ( MakeBucket ) and then runs the PutObject benchmark.
func runPutObjectBenchmarkParallel(b *testing.B, obj ObjectLayer, objSize int) {
	var err error
	// obtains random bucket name.
	bucket := getRandomBucketName()
	// create bucket.
	err = obj.MakeBucket(bucket)
	if err != nil {
		b.Fatal(err)
	}

	// get text data generated for number of bytes equal to object size.
	textData := generateBytesData(objSize)
	// generate md5sum for the generated data.
	// md5sum of the data to written is required as input for PutObject.
	hasher := md5.New()
	hasher.Write([]byte(textData))
	metadata := make(map[string]string)
	metadata["md5Sum"] = hex.EncodeToString(hasher.Sum(nil))
	sha256sum := ""
	// benchmark utility which helps obtain number of allocations and bytes allocated per ops.
	b.ReportAllocs()
	// the actual benchmark for PutObject starts here. Reset the benchmark timer.
	b.ResetTimer()

	b.RunParallel(func(pb *testing.PB) {
		i := 0
		for pb.Next() {
			// insert the object.
			objInfo, err := obj.PutObject(bucket, "object"+strconv.Itoa(i), int64(len(textData)), bytes.NewBuffer(textData), metadata, sha256sum)
			if err != nil {
				b.Fatal(err)
			}
			if objInfo.MD5Sum != metadata["md5Sum"] {
				b.Fatalf("Write no: Md5Sum mismatch during object write into the bucket: Expected %s, got %s", objInfo.MD5Sum, metadata["md5Sum"])
			}
			i++
		}
	})

	// Benchmark ends here. Stop timer.
	b.StopTimer()
}

// Parallel benchmark utility functions for ObjectLayer.GetObject().
// Creates Object layer setup ( MakeBucket, PutObject) and then runs the benchmark.
func runGetObjectBenchmarkParallel(b *testing.B, obj ObjectLayer, objSize int) {
	var err error
	// obtains random bucket name.
	bucket := getRandomBucketName()
	// create bucket.
	err = obj.MakeBucket(bucket)
	if err != nil {
		b.Fatal(err)
	}

	for i := 0; i < 10; i++ {
		// get text data generated for number of bytes equal to object size.
		textData := generateBytesData(objSize)
		// generate md5sum for the generated data.
		// md5sum of the data to written is required as input for PutObject.
		// PutObject is the functions which writes the data onto the FS/XL backend.
		hasher := md5.New()
		hasher.Write([]byte(textData))
		metadata := make(map[string]string)
		metadata["md5Sum"] = hex.EncodeToString(hasher.Sum(nil))
		sha256sum := ""
		// insert the object.
		var objInfo ObjectInfo
		objInfo, err = obj.PutObject(bucket, "object"+strconv.Itoa(i), int64(len(textData)), bytes.NewBuffer(textData), metadata, sha256sum)
		if err != nil {
			b.Fatal(err)
		}
		if objInfo.MD5Sum != metadata["md5Sum"] {
			b.Fatalf("Write no: %d: Md5Sum mismatch during object write into the bucket: Expected %s, got %s", i+1, objInfo.MD5Sum, metadata["md5Sum"])
		}
	}

	// benchmark utility which helps obtain number of allocations and bytes allocated per ops.
	b.ReportAllocs()
	// the actual benchmark for GetObject starts here. Reset the benchmark timer.
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		i := 0
		for pb.Next() {
			err = obj.GetObject(bucket, "object"+strconv.Itoa(i), 0, int64(objSize), ioutil.Discard)
			if err != nil {
				b.Error(err)
			}
			i++
			if i == 10 {
				i = 0
			}
		}
	})
	// Benchmark ends here. Stop timer.
	b.StopTimer()

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Title</title>

Category Sentiment Analysis

Total Comments

        382

Top Positive Promoter Theme

        <confirmit:wysiwygcomponent type="AggregatedTable" id="3f31b95b-7661-4ca4-aaa3-cfac6499e366" />

Top Negative Promoter Theme

        <confirmit:wysiwygcomponent type="AggregatedTable" id="9ff3344e-4101-4a2b-943f-fe8e6d66884a" />

Top Negative Detractor Theme

        <confirmit:wysiwygcomponent type="AggregatedTable" id="489a090c-28fe-4887-af19-d66f6ca5da61" />

          Category:
          <confirmit:wysiwygcomponent type="ReportalDropDown" id="9595fc25-60ed-4a6e-a780-a9145521864d" />

          View By:
          <confirmit:wysiwygcomponent type="ParameterNavigator" id="77176463-0225-432e-a6d3-3594aae8c00a" />

        <confirmit:wysiwygcomponent type="AggregatedTable" id="9f434bd8-cf0c-466f-b67a-0a0b79b71705" />

<confirmit:wysiwygcomponent type="AggregatedTable" id="0193c920-fd26-433f-944e-6ffb96484a25" />


text:
module Copyleaks
  class CommandException < StandardError
    attr_reader :reason

    def initialize(reason)
      @reason = reason
    end
  end
end


text:
package source

import (
	"bytes"
	"fmt"
	"strings"
	"text/template"

	log "github.com/Sirupsen/logrus"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/pkg/apis/extensions/v1beta1"

	"github.com/kubernetes-incubator/external-dns/endpoint"
)

// ingressSource is an implementation of Source for Kubernetes ingress objects.
// Ingress implementation will use the spec.rules.host value for the hostname
// Ingress annotations are ignored
type ingressSource struct {
	client       kubernetes.Interface
	namespace    string
	fqdntemplate *template.Template
}

// NewIngressSource creates a new ingressSource with the given client and namespace scope.
func NewIngressSource(client kubernetes.Interface, namespace string, fqdntemplate string) (Source, error) {
	var tmpl *template.Template
	var err error
	if fqdntemplate != "" {
		tmpl, err = template.New("endpoint").Funcs(template.FuncMap{
			"trimPrefix": strings.TrimPrefix,
		}).Parse(fqdntemplate)
		if err != nil {
			return nil, err
		}
	}

	return &ingressSource{
		client:       client,
		namespace:    namespace,
		fqdntemplate: tmpl,
	}, nil
}

// Endpoints returns endpoint objects for each host-target combination that should be processed.
// Retrieves all ingress resources on all namespaces
func (sc *ingressSource) Endpoints() ([]*endpoint.Endpoint, error) {
	ingresses, err := sc.client.Extensions().Ingresses(sc.namespace).List(metav1.ListOptions{})
	if err != nil {
		return nil, err
	}

	endpoints := []*endpoint.Endpoint{}

	for _, ing := range ingresses.Items {
		// Check controller annotation to see if we are responsible.
		controller, ok := ing.Annotations[controllerAnnotationKey]
		if ok && controller != controllerAnnotationValue {
			log.Debugf("Skipping ingress %s/%s because controller value does not match, found: %s, required: %s",
				ing.Namespace, ing.Name, controller, controllerAnnotationValue)
			continue
		}

		ingEndpoints := endpointsFromIngress(&ing)

		// apply template if host is missing on ingress
		if len(ingEndpoints) == 0 && sc.fqdntemplate != nil {
			ingEndpoints, err = sc.endpointsFromTemplate(&ing)
			if err != nil {
				return nil, err
			}
		}

		if len(ingEndpoints) == 0 {
			log.Debugf("No endpoints could be generated from ingress %s/%s", ing.Namespace, ing.Name)
			continue
		}

		log.Debugf("Endpoints generated from ingress: %s/%s: %v", ing.Namespace, ing.Name, ingEndpoints)
		endpoints = append(endpoints, ingEndpoints...)
	}

	return endpoints, nil
}

func (sc *ingressSource) endpointsFromTemplate(ing *v1beta1.Ingress) ([]*endpoint.Endpoint, error) {
	var endpoints []*endpoint.Endpoint

	var buf bytes.Buffer
	err := sc.fqdntemplate.Execute(&buf, ing)
	if err != nil {
		return nil, fmt.Errorf("failed to apply template on ingress %s: %v", ing.String(), err)
	}

	hostname := buf.String()
	for _, lb := range ing.Status.LoadBalancer.Ingress {
		if lb.IP != "" {
			endpoints = append(endpoints, endpoint.NewEndpoint(hostname, lb.IP, ""))
		}
		if lb.Hostname != "" {
			endpoints = append(endpoints, endpoint.NewEndpoint(hostname, lb.Hostname, ""))
		}
	}

	return endpoints, nil
}

// endpointsFromIngress extracts the endpoints from ingress object
func endpointsFromIngress(ing *v1beta1.Ingress) []*endpoint.Endpoint {
	var endpoints []*endpoint.Endpoint

	for _, rule := range ing.Spec.Rules {
		if rule.Host == "" {
			continue
		}
		for _, lb := range ing.Status.LoadBalancer.Ingress {
			if lb.IP != "" {
				endpoints = append(endpoints, endpoint.NewEndpoint(rule.Host, lb.IP, ""))
			}
			if lb.Hostname != "" {
				endpoints = append(endpoints, endpoint.NewEndpoint(rule.Host, lb.Hostname, ""))
			}
		}
	}

	return endpoints
}


text:
@class JavaSecurityPermission;

#include "J2ObjC_header.h"
#include "java/io/Serializable.h"
#include "java/security/BasicPermission.h"
#include "java/security/Guard.h"

@interface JavaUtilLoggingLoggingPermission : JavaSecurityBasicPermission < JavaSecurityGuard, JavaIoSerializable > {
}

- (instancetype)initWithNSString:(NSString *)name
                    withNSString:(NSString *)actions;

- (NSString *)getActions;

- (jboolean)impliesWithJavaSecurityPermission:(JavaSecurityPermission *)permission;

@end

J2OBJC_EMPTY_STATIC_INIT(JavaUtilLoggingLoggingPermission)

CF_EXTERN_C_BEGIN
CF_EXTERN_C_END

J2OBJC_TYPE_LITERAL_HEADER(JavaUtilLoggingLoggingPermission)

#endif // _JavaUtilLoggingLoggingPermission_H_


text:
package com.amazonaws.services.redshift.model;

import com.amazonaws.AmazonServiceException;

/**
 * <p>
 * The operation would exceed the number of nodes allowed for a cluster.
 * </p>
 */
public class NumberOfNodesPerClusterLimitExceededException extends
        AmazonServiceException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new NumberOfNodesPerClusterLimitExceededException with the
     * specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public NumberOfNodesPerClusterLimitExceededException(String message) {
        super(message);
    }

}


text:
package core.formatter.marketplace.order

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.{ JsonSerializer, ObjectMapper, SerializerProvider }
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.lvxingpai.model.account.{ RealNameInfo, UserInfo }
import com.lvxingpai.model.geo.Locality
import com.lvxingpai.model.marketplace.order.Bounty
import com.lvxingpai.model.marketplace.product.Schedule
import com.lvxingpai.model.marketplace.seller.Seller
import com.lvxingpai.model.misc.{ ImageItem, PhoneNumber, RichText }
import core.formatter.BaseFormatter
import core.formatter.geo.SimpleLocalitySerializer
import core.formatter.marketplace.seller.MiniSellerSerializer
import core.formatter.misc.{ ImageItemSerializer, PhoneNumberSerializer, RealNameInfoSerializer, RichTextSerializer }
import core.formatter.user.UserSerializer
import core.misc.Utils
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.{ DateTime, DateTimeZone }

import scala.collection.JavaConversions._

/**
 * Created by topy on 2016/3/31.
 */
class SimpleBountyFormatter extends BaseFormatter {

  override protected val objectMapper = {
    val mapper = new ObjectMapper()
    val module = new SimpleModule()
    mapper.registerModule(DefaultScalaModule)
    module.addSerializer(classOf[Bounty], new SimpleBountySerializer)
    module.addSerializer(classOf[Seller], new MiniSellerSerializer)
    module.addSerializer(classOf[RichText], new RichTextSerializer)
    module.addSerializer(classOf[PhoneNumber], new PhoneNumberSerializer)
    module.addSerializer(classOf[UserInfo], new UserSerializer)
    module.addSerializer(classOf[ImageItem], new ImageItemSerializer)
    module.addSerializer(classOf[RealNameInfo], new RealNameInfoSerializer)
    module.addSerializer(classOf[Locality], new SimpleLocalitySerializer)
    mapper.registerModule(module)
    mapper
  }
}

object SimpleBountyFormatter {
  lazy val instance = new SimpleBountyFormatter
}

class SimpleBountySerializer extends JsonSerializer[Bounty] {

  override def serialize(bounty: Bounty, gen: JsonGenerator, serializers: SerializerProvider): Unit = {
    gen.writeStartObject()

    gen.writeNumberField("itemId", bounty.itemId)
    gen.writeNumberField("consumerId", bounty.consumerId)
    gen.writeFieldName("consumer")
    val userInfo = bounty.consumer
    val retUserInfo = if (userInfo != null) serializers.findValueSerializer(classOf[UserInfo], null)
    else serializers.findNullValueSerializer(null)
    retUserInfo.serialize(userInfo, gen, serializers)

    gen.writeNumberField("takersCnt", (Option(bounty.takers) map (_.toSeq) getOrElse Seq()).size)

    gen.writeFieldName("destination")
    gen.writeStartArray()
    val plans = bounty.destination
    if (plans != null) {
      val ret = serializers.findValueSerializer(classOf[Locality], null)
      for (pl <- plans)
        ret.serialize(pl, gen, serializers)
    }
    gen.writeEndArray()

    gen.writeNumberField("timeCost", bounty.timeCost)
    gen.writeNumberField("budget", bounty.budget)

    val departureDate = Option(bounty.departureDate) map (date => {
      val tzDate = new DateTime(date) toDateTime DateTimeZone.forID("Asia/Shanghai")
      val fmt = ISODateTimeFormat.date()
      tzDate.toString(fmt)
    }) getOrElse ""
    gen.writeStringField("departureDate", departureDate)

    gen.writeStringField("service", bounty.service)
    gen.writeStringField("topic", bounty.topic)

    //gen.writeBooleanField("paid", bounty.paid)
    // 是否已支付商家的行程安排
    gen.writeBooleanField("schedulePaid", bounty.schedulePaid)
    gen.writeNumberField("totalPrice", Utils.getActualPrice(bounty.totalPrice))
    // 是否已支付赏金
    gen.writeBooleanField("bountyPaid", bounty.bountyPaid)
    gen.writeNumberField("bountyPrice", Utils.getActualPrice(bounty.bountyPrice))

    gen.writeFieldName("scheduled")
    val scheduled = bounty.scheduled
    if (Option(scheduled).nonEmpty)
      serializers.findValueSerializer(classOf[Schedule], null).serialize(scheduled, gen, serializers)
    else {
      gen.writeStartObject()
      gen.writeEndObject()
    }

    gen.writeNumberField("createTime", if (bounty.createTime != null) bounty.createTime.getTime else 0)
    gen.writeNumberField("updateTime", if (bounty.updateTime != null) bounty.updateTime.getTime else 0)
    gen.writeEndObject()
  }
}


text:
@class SCNNode;

@interface SKEDocumentAddChildAtIndexEdition : SKEDocumentEdition
{
    SCNNode *_parentNode;
    SCNNode *_childNode;
    unsigned long long _index;
}

- (void).cxx_destruct;
- (BOOL)revert;
- (BOOL)apply;
- (id)initWithDocument:(id)arg1 parentNode:(id)arg2 childNode:(id)arg3 index:(unsigned long long)arg4;

@end


text:
<?php

namespace MicrosoftAzure\Storage\Tests\Unit\Blob\Models;

use MicrosoftAzure\Storage\Common\Internal\Utilities;
use MicrosoftAzure\Storage\Tests\Framework\TestResources;
use MicrosoftAzure\Storage\Blob\Models\PutBlockResult;

/**
 * Unit tests for class PutBlockResult
 *
 * @category  Microsoft
 * @package   MicrosoftAzure\Storage\Tests\Unit\Blob\Models
 * @author    Azure Storage PHP SDK <dmsh@microsoft.com>
 * @copyright 2016 Microsoft Corporation
 * @license   https://github.com/azure/azure-storage-php/LICENSE
 * @link      https://github.com/azure/azure-storage-php
 */
class PutBlockResultTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers MicrosoftAzure\Storage\Blob\Models\PutBlockResult::create
     * @covers MicrosoftAzure\Storage\Blob\Models\PutBlockResult::setContentMD5
     * @covers MicrosoftAzure\Storage\Blob\Models\PutBlockResult::getContentMD5
     * @covers MicrosoftAzure\Storage\Blob\Models\PutBlockResult::setRequestServerEncrypted
     * @covers MicrosoftAzure\Storage\Blob\Models\PutBlockResult::getRequestServerEncrypted
     */
    public function testCreate()
    {
        // Setup
        $sample = TestResources::listBlobsOneEntry();
        $expected = $sample['Blobs']['Blob']['Properties'];

        // Test
        $actual = PutBlockResult::create($expected);

        // Assert
        $this->assertEquals($expected['Content-MD5'], $actual->getContentMD5());
        $this->assertEquals(Utilities::toBoolean($expected['x-ms-request-server-encrypted']), $actual->getRequestServerEncrypted());
    }
}


text:
using System.Runtime.Serialization;

namespace Trakt.Api.DataContracts.BaseModel
{
    [DataContract]
    public abstract class TraktRated
    {
        [DataMember(Name = "rating")]
        public int? Rating { get; set; }

        [DataMember(Name = "rated_at")]
        public string RatedAt { get; set; }
    }
}


text:
from distutils.core import setup, Extension
import numpy as np

setup(
    name= 'watermark',
    version= '1.0',
    author= 'youki sada',
    author_email= 'youki@kaede-tokyo.net',
    description= 'This is a package involves my functions',
    package_dir = {'watermark':''},
    packages = ['watermark'],
    py_modules = ['watermark.src.myfunction'],
    ext_modules= [
        Extension('watermark.sequence',['src/sequence.c'],extra_objects = [],include_dirs = [np.get_include()])
    ]
)