text:
/*
 * @author Riccardo Zaccarelli, PhD (<riccardo(at)gfz-potsdam.de>, <riccardo.zaccarelli(at)gmail.com>), Marc Wieland <mwieland(at)gfz-potsdam.de>
 * @date Mon October 10 2014, 21:09
 */
(function(crvn){
	var leaf = L;
    var $ = jQuery;
	/**
	 * Class (Function) for managing legend and geocells colors.
	 * It first builds a scale of increasing values each associated to a color,
	 * by taking as argument an html element E. It first scans E finding all elements
	 * with 'data-value' attribute (whose value represents a number, and whose css
	 * 'background-color' property must evaluate to a valid color) and builds the
	 * above mentioned scale.
	 * It then implements a function, color(val) which
	 * takes a value val and returns the corresponding color according to the
	 * built scale, stored internally. The color returned is the 'closest' to val,
	 * unless the argument interpolate is true: in that case, for non boundary values,
	 * it interpolates linearly between the two closest colors. This works for
	 * color scale which are consistent with the scale (i.e., whose color value
	 * increases or descreases according to the scale)
	 * Out-of bounds values return the closest boundary color.
	 */
	function ColorMap($div, interpolate){
    	//WARNING: IF YOU PUT THE G  FLAG YOU HAVE TO SET THE LASTINDEX REGEX PROPERTY TO 0 BEFORE ANY TEST OR EXEC!
    	var rgbRe = /rgba*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*(.+))*\s*\)/i;
    	var hexRe = /#(?:(?:([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f]))|(?:([0-9a-f])([0-9a-f])([0-9a-f])))$/i;
    	var pInt = parseInt;
    	var pFloat = parseFloat;
    	var _fl_ = Math.floor; //JavaScript auto-converts integer division to float.
    	//Sometimes we need integer division (see e.g., 'this.color' function below)
    	//NOTE: parseInt seems to be slower than math.floor
    	//(see http://jsperf.com/math-floor-vs-math-round-vs-parseint/2)
    	//it should be tested cross  browser, but it makes sense since parseInt
    	//does 'more'. We use _fl_ when we do not need to parse strings for example
    	var abs = Math.abs;
    	var round = Math.round

    	//I could set static methods for these three functions (so they are not instantiated every time):
    	function rgb(colorstr){
    		var a = hexRe.exec(colorstr);
    		if(a && a.length === 7){
    			return a[1] === undefined
    					? [pInt(a[4]+a[4],16), pInt(a[5]+a[5],16), pInt(a[6]+a[6],16)]
    					: [pInt(a[1],16), pInt(a[2],16), pInt(a[3],16)];
    		}
    		a = rgbRe.exec(colorstr);
    		if(a && a.length === 5){
    			return [pInt(a[1]), pInt(a[2]), pInt(a[3])];
    		}
    		return undefined;
    	}

    	function hexstr(r, g, b) {
            r = r.toString(16);
            g = g.toString(16);
            b = b.toString(16);
            return "#" + (r.length === 1 ? "0" + r : r) + (g.length === 1 ? "0" + g : g) + (b.length === 1 ? "0" + b : b);
    	}

    	function interpolationColor(val1, color1, val2, color2, val3){
    		//val1 is lower than val2
    		var a1 = rgb(color1);
    		if(!a1){return undefined;}
    		if(val3 <= val1){return hexstr(a1[0],a1[1],a1[2]);}
    		var a2 = rgb(color2);
    		if(!a2){return undefined;}
    		if(val3 >= val2){return hexstr(a2[0],a2[1],a2[2]);}
    		var den = (val3-val1)/(val2-val1);
    		//y = cmp1 + den*(cmp2-cmp1)
    		function cmp(cmp1, cmp2){
    			return cmp1===cmp2 ? cmp1 : round(cmp1 + den*(cmp2-cmp1));
    		};
    		for (var i=0; i<3 ; i++){ a2[i] = cmp(a1[i], a2[i]); }
    		//console.log('mean: ' + a2);
    		return hexstr(a2[0],a2[1],a2[2]);
    	}

    	var a=[];

    	$div.find('*[data-value]').each(function(i,elm){
    		var $elm = $(elm);
    		a.push([pFloat($elm.data('value')), $elm.css('background-color')]);
    	});

    	//sort array (modifying it):
    	a.sort(function(a,b){return a[0]-b[0];});

    	//we use it below in the binary search algorithm

    	var interp = interpolate || false;
    	this.color = function(val){ //binary search algorithm to find color value (array is sorted)
    		var lo = 0;
    		var last = a.length - 1;
            var hi = last;
            while (lo <= hi) {
                // Key is in a[lo..hi] or not present.
                var mid = lo + _fl_((hi - lo) / 2);
                var cmp = a[mid][0];
                if      (val < cmp) hi = mid - 1;
                else if (val > cmp) lo = mid + 1;
                else return a[mid][1];
            }
            //just a check for safety:
            if(lo<=0){
            	return a[lo][1];
            }
            if(lo>=a.length){
            	return a[lo-1][1];
            }

            if(interp){
            	return interpolationColor(a[lo-1][0], a[lo-1][1],a[lo][0], a[lo][1], val) || "";
            }
            //in any other case, return closest value
            //lo is now the insertion index, so check whether it is closer to lo or lo-1
            return abs(a[lo][1]-val)<abs(a[lo-1][1]-val) ? a[lo][1] : a[lo-1][1];
        };

        var _values=undefined;
        this.values = function(){
        	//lazily create it:
        	if(_values === undefined){
        		_values=[];
        		for(var i=0; i< a.length; i++){
        			_values.push(a[i][0]);
        		}
        	}
        	return _values;
        };

        var _labels=undefined;
        this.labels = function(){
        	//lazily create it:
        	if(_labels === undefined){
                _labels = [];
        		for(var i=0; i< a.length; i++){
        			_labels.push("");
        		}
                $div.find("*[data-label]").each(function(i, elm){
                    _labels[i] = $(elm).data('label')+"";
                });
        	}
        	return _labels;
        };
	}

    //In order to display the map on the website the leaflet library is used
    //for information and documentation see http://leafletjs.com/

	//var crvn = caravan; //globally defined
    function MapManager(mapElementId /*, layerNames*/) {
        var map;
        var baseLayer;

        var gmpeLayer; //instanceof
        var $ = jQuery;
        //instantiate once (faster lookup):
        var pInt = parseInt;

        //DEFINES EACH GEOJSON FEATURE 'PROPERTY' FIELDS
        //I.E., GIVEN A GEOJSON FEATURE F, WE CAN SAY F.properties[P_FIELD_BLABLA]
        var P_FIELD_FAT = 'fatalities_prob_dist'; // 'fatalities_perc';
        var P_FIELD_GMPE = 'gmpe_perc';

        try {
            //CREATING THE MAP. SEE http://leafletjs.com/reference.html#map-constructor
            map = leaf.map(mapElementId).setView([41.25, 74.75], 7);
            //add baselayer SEE http://leafletjs.com/reference.html#tilelayer
            baseLayer = leaf.tileLayer('https://{s}.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWF4cGl0dG9yZSIsImEiOiJlZGU3NTk0NzFlY2UyOGI2MTI5N2YwOWVlOTE0MTgyMiJ9.X5fepwoCb37pkwO9pUlBkA', {
                maxZoom: 18,
                attribution: 'Processing © GFZ Potsdam - Centre for Early Warning Systems' +
                        ' | Map data © OpenStreetMap, ' +
                        ' | Imagery © Mapbox |  ',
                id: 'mapbox.outdoors'
            }).addTo(map);
        } catch (e) {
            //console.log(e);
            return;
        }

        var _layers = {}; //a dict of keys : caravan-layer properties
        //a caravan-layer is simply a javascript plain object which holds the
        //leaflet layer, plus a colormap function and a style function

        //defining the style default and the style function
        //which will delegate the caravan-layer style function.

        //defining default style and empty style objects
        //(empty by default in leaflet IS NOT NO-STYLE, but assigns a
        //custom style where each geocell is rendered with blue borders and semi transparent fill colors)
        var DEFAULT_STYLE = function(){ return {
                radius: 10,
                //fillColor: val, //colors[val + 1], // '#0B0B3B',
                color: '#000000', //colors[val + 1], //'#0B0B3B',
                opacity: 1, //should be set the half of the value below cause they overlap?? fix me...
                weight: 0,
                fillOpacity: 0.5
        	};
        };
        var EMPTY_STYLE = function(){
        	return {
        		opacity: 0,
                fillOpacity: 0
        	};
        };

        //passing an empty dict tot the style function
        function getStyleFunction(layer_key_name){
        	return function(feature){
        		if(layer_key_name in feature.properties){
        			if('styleFcn' in _layers[layer_key_name]){
        				var props = feature.properties[layer_key_name];
                        var val = props.value;
                        if(val!==null && val!==undefined){
                            var defOpts = DEFAULT_STYLE();
                            _layers[layer_key_name].styleFcn(feature, val, _layers[layer_key_name].colorMap, defOpts);
                            return defOpts;
                        }
        			}
        		}
        		return EMPTY_STYLE();
        	};
        }

        var selLayerName = undefined;

        //this function manages the controlchart of the legend
        var control = (function(){
        	function Control(){
            	var _style_ = 'none';
            	var imgs = {'none': crvn.imgPath('arrow-down-01-32.png'), "":crvn.imgPath('arrow-up-01-32.png')};
            	var _div = $("\

\

\

\

\
            		\
                    	\
                	\

\

\

");
            	this.getDiv = function(){return _div;}
            	var velocity = 'fast';
            	_div.find('a').click(function(){
            		_style_ = !_style_ ? "none" : "";
            		$(this).find('img').attr('src',imgs[_style_]);
            		if(_style_){
            			_div.find('#leaflet-layer-switcher').hide(/*velocity*/);
            		}else{
            			_div.find('#leaflet-layer-switcher').slideDown(velocity);
            		}
            		return false;
            	});
            	var doRadioClick = function(name){
            		if(selLayerName){
            			map.removeLayer(_layers[selLayerName].layer);
            			_layers[selLayerName].legend.detach();
            		}
            		_layers[name].layer.addTo(map);
            		var $legendContainer = _div.find('#legend-container');
            		_layers[name].legend.detach().appendTo($legendContainer);
            		selLayerName = name;
            		//set div with arrow height equal to legend height.
            		//Note that we set box-sizing border-box to both in layout.css
            		//note: set the anchor height and line-height (for vertical align):
            		var $a = _div.find('#leaflet-layer-switcher-toggler').children('a');
            		var h = $legendContainer.css('height')
            		$a.css({'height':h,'line-height':h});
            	};
            	this.addLayer = function(name){
                	var $radio = $('<input>').attr('type','radio').attr('name','leaflet-layer-selector').change(function(){
                		doRadioClick(name);
                		_div.find('a').click(); //closes the popup
                	});
                	if(!selLayerName){
                		$radio.prop('checked',true);
                		doRadioClick(name);
                	}
                	var $l = $('').append($radio).append($('').attr('data-title',name).html(crvn.dict.title(name)));
                	_div.find('#leaflet-layer-switcher').append($l);
            	};
            }
            return new Control();
        })();

        //defining function to add a control:
        var _addControl =function(position, div){
            var ctrl = leaf.control({
                position : position
            });
            ctrl.onAdd = function(map) {
                this._div = $(div).get(0);
                return this._div;
            };
            ctrl.addTo(map);
            return ctrl;
       };

       //adding custom legend:
       _addControl('topright', control.getDiv());

       /**
        * Function addControl(position, div)
        * adds a control wrapping div (an html, a string or a jQuery element)
        * to the map, returning the leaflet control object. The object
        * can be removed via ctrl.removeFrom(map)
        * position is the position, e.g., 'topright'
        */
       this.addControl = _addControl;

        /**
         * Adds a new empty GeoJson Layer to the internal leaflet map,
         * returning it. The second arg is a function
         * function(feature, featureData, colorMap, defOpts)
         * used for styling the given feature.
         * featureData is an object with two fields: data and value
         *  data is the feature data (usually an array, e.g. the feature percentiles)
         *  value is the feature value, the one which is usually used for mapping
         *  a feature to a color (i.e., value might be data last index if data is an array of percentiles
         *  and value should return the last percentile, but it might be also the index of max(data))
         * colorMap is an object (JavaScript function) which maps the given legend to a set of colors.
         *  It has two methods: values(), which returns the sorted ascending tick values of the legend,
         *  and color(val) which takes a scalar and converts it to a color
         * defOpts is the leaflet dictionary (JavaScript object) which will be returned for styling the
         * feature. It is set by default as DEFAULT_STYLE (see above)
         * This function does not need to return any value, just fill defOpts with whatever you want
         * (see http://leafletjs.com/examples/geojson.html and
         * http://leafletjs.com/reference.html#geojson)
         */
		this.addLayer = function(name, $divLegend, interpolate, styleFcn){
        	//needs to add it to the _layers object BEFORE adding to the map:
        	var clay = {
        		legend: $divLegend,
    			colorMap : new ColorMap($divLegend, interpolate),
    			layer : leaf.geoJson([], {
    		        style: getStyleFunction(name)//,
    		        /*onEachFeature: onEachFeatureFcn*/ /*,
    		         pointToLayer: function (feature, latlng) {
    		         var mrk = leaflet.circleMarker(latlng);
    		         return mrk;
    		         }*/
    		    })
        	};
        	//add function later, because we add it only if it is a function
        	//(no guarantee it's well implemented, but getStyleFunction above
        	//will return the empty object if we don't enter this 'if'
        	if (typeof(styleFcn) === "function") {
        		clay.styleFcn = styleFcn;
        	}
        	_layers[name] = clay;
        	//var lay = clay.layer; //the leaflet layer
        	//lay.addTo(map);
        	control.addLayer(name);
        	return clay;
        };

        /**
         * @return the leaflet GeoJson layer identified by name
         * returning it
         * @param name the name associated to the given layer, as set in addLayer
         */
        this.getLayer = function(name){
        	return name in _layers ? _layers[name].layer : undefined;
        };
        /**
         *
         * @param {type} name
         * @returns {clay.colorMap} the colorMap object associated to the layer mapped to name
         * It is a class (function) which has two interesting methods: values() (returns all
         * the values set as ticks for the legend) and color(val), which returns a color
         * associated to a given value
         */
        this.getColorMap = function(name){
            return name in _layers ? _layers[name].colorMap : undefined;
        };

        //common function for add/set/empty Layers 0: delete, 1:set, 2: add
        var doLayer = function(operation, name, data){
        	var myLayer = _layers[name];
        	if(myLayer){
        		//Note: myLayer.layer is the leaflet layer
        		if(operation < 2){
            		myLayer.layer.clearLayers(); // inherited from LayerGroup
                }
            	if(operation > 0){
            		myLayer.layer.addData(data); // inherited from LayerGroup
                }
            	return myLayer;
        	}
        	return undefined;
        };

        /**
         * Removes the data from the layer identified by name
         * @return the layer identified by name, or undefined
         */
        this.removeData = function(name){
        	return doLayer(0, name);
        };

        /**
         * Sets data to the layer identified by name, removing previously set data
         * geoJsonFeatures is an array of GeoJson encoded features
         * @return the layer identified by name, or undefined
         */
        this.setData = function(name, geojsonFeatures){
        	return doLayer(1, name, geojsonFeatures);
        };

        /**
         * Adds data to the layer identified by name.
         * geoJsonFeatures is an array of GeoJson encoded features
         * @return the layer identified by name, or undefined
         */
        this.addData = function(name, geojsonFeatures){
        	return doLayer(2, name, geojsonFeatures);
        };

        //add scale:
        leaf.control.scale().addTo(map);

        //adding lat lon display when moving with the mouse on the map, and when clicking
        var latlon = $("#latlon");
        var setLatLon = function (e) {
            var lat = "--.---";
            var lng = "--.---";
            if (e && e.latlng) {
                var l = e.latlng;
                lat = l.lat.toFixed(3);
                lng = l.lng.toFixed(3);
            }
            latlon.html("lat: " + lat + " lng: " + lng);
        };

        //add event listener for mouse moving:
        map.on('mousemove', function (e) {
            setLatLon(e);
        });
        map.on('click', function (e) {
            setLatLon(e);
        });
        //set default:
        setLatLon();

        /**
         * @return the leaflet map
         */
        this.getMap = function () {
            return map;
        };

        //defining the epicenter and centerEpicenter functions
        var epicenter = undefined;

        /**
         * Fits the bounds of the map, zooming to include
         * the current layers bounds. includeEpicenter is a self-explanatory
         * boolean argument. If true and only the epicenter is shown, it does
         * not zoom, simply centers the map to it
         */
        this.fitBounds = function (includeEpicenter) {
        	var zoomLayers = [];
        	//zoomLayers are leaflet layers properly set via addLayers AND
        	//whose bounds are valid (which apparently is not the case
        	//the layer has no data, i.e. when uninitialized):
        	for(var n in _layers){
        		var lay = _layers[n].layer; //leaflet layer
    			if(lay.getBounds().isValid()){
    				zoomLayers.push(lay);
    			}
    		}

        	var noLayers = !(zoomLayers.length);
        	var noEpicenter = !includeEpicenter || !epicenter;

        	if(noLayers && noEpicenter){
        		return;
        	}else if(noLayers){ //center epicenter
        		map.panTo(epicenter.getLatLng()); //new leaf.LatLng(40.737, -73.923));
        	}else{
        		if(!noEpicenter){
        			zoomLayers.push(epicenter);
        		}
        		//fit bounds: to be sure we use a small delay
                var DELAY = 150;
                setTimeout(function () {
                    var group = new leaf.featureGroup(zoomLayers);
                    map.fitBounds(group.getBounds());
                }, DELAY);
        	}
        };

        /**
         * With no arguments, returns an Array of two elements
         * [latitude, longitude] of the epicenter, or undefined if the
         * epicenter has not been created (same function with arguments must
         * have been called)
         * With arguments, it creates (if not present) the epicenter
         * and will set its position according to the first two arguments (mandatory)
         * lat and lon.
         * The third argument (optional) will zoom to the epicenter.
         * Note that if only
         * the epicenter is present, zoom will actually center the epicenter (leaflet
         * panTo function)
         */
        this.epicenter = function (lat, lon, zoom) {
            if (!arguments || !arguments.length) {
                if (!epicenter) {
                    return undefined;
                }
                var latlng = epicenter.getLatLng();
                return [latlng.lat, latlng.lng];
            } else {
            	//defining zoom function, which does something
            	//only if param is set
            	var me = this;
            	function dozoom(){
            		if(zoom){me.fitBounds(true);} //defined above (or below, jsut see)
            	};
                if (!epicenter) {
                	//when creating an epicenter, we need to know its size
                	//because the iconAnchor leaflet property is necessary
                	//to properly center the epicenter icon. We use javascript,
                	//but in this case we need to defer all stuff after image is loaded
                	var _iconUrl = crvn.imgPath('epi.png');
                	var img = new Image();
                	img.onload = function() {
                		var w = this.width;var h = this.height; //remainder: 'this' is the image
                		var iconProperties={
                        	iconSize : [w, h],
                        	iconAnchor : [w/2, h/2],
                        	iconUrl: _iconUrl
                        };
                        epicenter = leaf.marker([lat, lon], {icon:  leaf.icon(iconProperties)}).addTo(map);
                        dozoom(); //does nothing if zoom evaluates to false
                	};
                	img.src = _iconUrl;
                } else {
                    var latlng = epicenter.getLatLng();
                    if (latlng.lat === lat && latlng.lng === lon) {
                        return;
                    }
                    epicenter.setLatLng([lat, lon]);
                    dozoom(); //does nothing if zoom evaluates to false
                }
            }
        };

        //setting ids of the <input> lat and lon elements.
        //Use caravan params keys, written from server python code
        var latId = '#'+crvn.params.LAT;
        var lonId = '#'+crvn.params.LON;
        //internal function which centers the map including the epicenter on
        //input changes
        var me = this; //see below why
        this.centerEpicenter = function() {
            //consider the case where we typed a two element value, such as: 75.5 0.6
            var reg = /(?:,\s;)/;

            var latarray = $(latId).val().split(reg);
            var lonarray = $(lonId).val().split(reg);

            if (latarray.length && lonarray.length) {
                var lat = parseFloat(latarray[0]);
                var lon = parseFloat(lonarray[0]);
                if (!isNaN(lat) && !isNaN(lon)) {
                    me.epicenter(lat, lon, true);
                }
            }
        };

        //From: http://stackoverflow.com/questions/7105997/javascript-change-event-on-input-element-fires-on-only-losing-focus
        //make text input change event (real change, not change + focus lost etcetera):
        //however, two events are sufficient (see http://stackoverflow.com/questions/5494648/catching-all-changes-to-the-contents-of-an-input-box-using-javascript-jquery/5494697#5494697)
        //Note in any case that it will NOT fire when we programmatically set the val() attribute
        $(latId).add($(lonId)).on('input propertychange', function () {
            me.centerEpicenter(); //this is the clicked component. centerEpicenter has a ref on this so we call this mapmanager centerEpicenter
        });
       //this is the window object. centerEpicenter has a ref on this so we call this mapmanager centerEpicenter
        me.centerEpicenter(); //programmatically starts centering

        //======================================================================================
        var _events={};
        /**
         * Adds an event listener to the specified eventName to ALL layers
         * of the map. Follows the same syntax described here:
         * http://leafletjs.com/reference.html#events
         *
         * To add an event to the map, use thisobject getMap() function
         * e.g.: map.getMap().on('click'...)
         * NOTE that function_ accepts MORE arguments than the default layer listeners functions:
         * It is of the form
         * f(name, layer, feature, featureData, e)
         * where:
         * name is the layer name, as added to this class object (map)
         * layer is the leaflet layer event target. It is the associated to name (the "parent" layer)
         * feature is the geoJson feature where actually the event occurs (might be undefined).
         * See geoJson format for infos. The associated layer (child of layer defined above)
         * can be retrieved via e.layer
         * featureData is an object with two fields: data and value
         *  data is the feature data (usually an array, e.g. the feature percentiles)
         *  value is the feature value, the one which is usually used for mapping
         *  a feature to a color (i.e., value might be data last index if data is an array of percentiles
         *  and value should return the last percentile, but it might be also the index of max(data)), and
         * e is the leaflet event as described here: http://leafletjs.com/reference.html#event-objects
         * (Most of the arguments are actually retrieved from e)
         * The this keyword refers to this map object, so that called name the
         * first argument, this.getLayer(name) returns the current layer
         * The function_ implemented as argument does not need to return any value
         *
         * @param {type} eventName
         * @param {type} function_
         * @returns {undefined}
         */
        this.on = function(eventName, function_){
            _events[eventName] = function_;
            var me = this;
            for(var n in _layers){
                var makeFunc = function(name){
                    return function(e){
                        var feature = e.layer && e.layer.feature ? e.layer.feature : undefined;
                        var data = (feature && feature.properties && feature.properties[name]) ? feature.properties[name] : undefined;
                        function_.apply(me, [name, e.target, feature, data, e]);
                    };
                };
                this.getLayer(n).on(eventName, makeFunc(n));
            }
        };

        this.off = function(eventName, function_){
            delete _events[eventName];
            for(var n in _layers){
                this.getLayer(n).off(eventName);
            }
        };

        /**
         * Function updating the leaflet map. It takes a session_id (whereby a server request is made)
         * and an optional callbakc to be executed at the end of the request regardless if the query was succesfull or not
         */
        this.update = function (session_id, optional_onalways) {

            if (!map) {
                return;
            }

            //building wait div
            //another option would be to hide the map and then show it again, and put the div
            //inside the map container
            var $waiting = $('
').addClass('mapWaiter').addClass("waiting");
            var $mapC = $(map._container); //see leaflet object in browser debugger
            $waiting.html("UPDATING MAP...");
            //FIXME: should be harmless. We need it cause mapWaiter has position:absolute
            $mapC.parent().css('position', 'relative');
            $waiting.appendTo($mapC.parent());

            var me = this;

            $.post('query_simulation_data', JSON.stringify({session_id: session_id}), function (data, textStatus, jqXHR) {

                var n;

                for(n in _layers){
                	me.removeData(n);
                }

                if(!data){return;}

                var feats = data.features;
                if (!feats || !feats.length) {
                    return;
                }

                //NOTE: locally (in ubuntu 14.04, python 2.7.6 at least) each feats element has the
                //key 'geometry' as valid geoJson OBJECT. In other circumstances (eg. lhotse, python 2.7.3 I guess)
                //it is in string format, as if it was stringified once more and therefore here it's back
                //to its original value (as set server side, see caravan_wsgi query_simulation_data function).
                //That's weird, the 'best' solution is to use the browser JSON parse function. Brutal maybe, but it works
                //(Json is implemented in all major browsers, including IE8+)
                var first = feats[0];
                if(typeof first.geometry === 'string'){
                    var flen = feats.length;
                    var parsefunc = JSON.parse; //declare once (should be faster)
                    for(var i=0; i < flen; i++){
                        feats[i].geometry = parsefunc(feats[i].geometry);
                    }
                }

                for(n in _layers){
                	if(n in data.captions){
                		me.addData(n, feats);
                	}
                }

                me.fitBounds(false);

            }, "json").fail(function () {
                //NOTE: we SHOULD NEVER BE here (SEE SERVER SIDE CODE). LEFT HERE FOR SAFETY
            }).always(function () {
                //remove wait div
                $waiting.remove();
                if (optional_onalways) {
                    optional_onalways();
                }
            });
        };
    }

    crvn.initMap = function(mapId){
    	if(!crvn.map){ crvn.map = new MapManager(mapId); }
    	return crvn.map;
    };

}
)(caravan);


text:
title: "PuppetDB 4.3: Load testing"
layout: default
---

[export]: ./anonymization.html

A basic tool for simulating PuppetDB loads is included with the standard
PuppetDB distribution. **This tool is currently experimental and is likely to
change in future releases**.

The load testing tool can submit catalogs, facts, and/or reports at a defined
interval, for a specified number of nodes. It is also able to vary the submitted
catalogs over time to simulate catalog changes (which can cause a higher
PuppetDB load). The intent of the tool is to get a rough idea about how the
system (and software) will handle load under realistic conditions. The tool will
use catalogs/reports/facts specified by the user, including those exported from
a production/running system, to simulate real-world conditions. While originally
designed as a PuppetDB developer tool, we expect that many users may find it
useful.

Getting data for the tool
-----

The load testing tool does not yet have the ability to generate its own data. To
run simulations, you will need a collection of catalogs, facts and/or reports.
The easiest source of this information is the export tool included with PuppetDB
(more information [here][export]). The export will produce a tar.gz file
containing facts, catalogs, and reports.

Unzip the exported data. When unzipped/untared, find the
`puppetdb-bak/catalogs`, `puppetdb-bak/facts` and a `puppetdb-back/reports`
directories. One or all of these directories can be used as input to the load
testing tool.

Running the load testing tool
-----

Before running the load testing tool, make sure you have the full path to your
example data. You'll also need a config file (such as `config.ini`) with the
host and port information for the PuppetDB instance you wish to load test. The
config file format is the same as the one PuppetDB uses, but you only need two
entries:

      [jetty]
      host=<host name here>
      port=<port here>

There is currently no script for running the tool, so you'll need a command like
the one below:

    $ /usr/bin/java -cp /opt/puppetlabs/server/apps/puppetdb/puppetdb.jar clojure.main -m puppetlabs.puppetdb.cli.benchmark --config myconfig.ini --catalogs /tmp/puppetdb-bak/catalogs --runinterval 30 --numhosts 1000 --rand-perc 10

### Arguments accepted by the benchmark command

- **`--config / -c`**: path to the INI file that has the host/port configuration
  for the PuppetDB instance to be tested.
- **`--catalogs / -C`**: directory containing catalogs to use for testing
  (probably from a previous PuppetDB export).
- **`--reports / -R`**: directory containing reports to use for testing
  (probably from a previous PuppetDB export).
- **`--facts / -F`**: directory containing facts to use for testing (probably
  from a previous PuppetDB export).
- **`--archive / -A`**: tarball archive obtained via a PuppetDB export. This
  option is incompatible with the preceding four.
- **`--runinterval / -i`**: integer indicating the amount of time in minutes
  between puppet runs for each simulated node. Typical values are 30 or 60.
- **`--numhosts / -n`**: number of separate hosts that the tool should simulate.
- **`--rand-perc / -r`**: what percentage of catalogs submissions should be
  changed (this simulates typical catalog changes, such as adding a resource,
  edge, or something similar). More changes to catalogs will cause a higher load
  on PuppetDB. A typical change percentage is 10.

>**Note:** If --facts, --catalogs, --reports, and --archive are unspecified, the
>PuppetDB sample data will be used. This data includes catalogs, facts, and
>reports.

redpajama_set_name: RedPajamaGithub


text:
package org.apache.lucene.gdata.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;

import junit.framework.TestCase;

import org.apache.lucene.gdata.server.GDataRequest.OutputFormat;
import org.apache.lucene.gdata.utils.ProvidedServiceStub;
import org.easymock.MockControl;

import com.google.gdata.data.Entry;
import com.google.gdata.data.ExtensionProfile;
import com.google.gdata.data.Feed;
import com.google.gdata.data.PlainTextConstruct;
/**
 *
 * @author Simon Willnauer
 *
 */
public class TestGDataResponse extends TestCase {
    private GDataResponse response;
    private HttpServletResponse httpResponse;
    private MockControl control;
    private static String generatedFeedAtom = "<?xml version='1.0'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'><entry><title type='text'>Test</title></entry></feed>";
    private static String generatedEntryAtom = "<?xml version='1.0'?><entry xmlns='http://www.w3.org/2005/Atom'><title type='text'>Test</title></entry>";
    private static String generatedFeedRSS = "<?xml version='1.0'?><rss xmlns:atom='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' version='2.0'><channel><description></description><item><title>Test</title></item></channel></rss>";
    private static String generatedEntryRSS = "<?xml version='1.0'?><item xmlns:atom='http://www.w3.org/2005/Atom'><title>Test</title></item>";
    protected void setUp() throws Exception {
        this.control = MockControl.createControl(HttpServletResponse.class);
        this.httpResponse = (HttpServletResponse)this.control.getMock();
        this.response = new GDataResponse(this.httpResponse);

    }

    protected void tearDown() throws Exception {
        super.tearDown();
    }

    public void testConstructor(){
        try{
        new GDataResponse(null);
        fail("IllegalArgumentExceptin expected");
        }catch (IllegalArgumentException e) {
            // TODO: handle exception
        }
    }
    /*
     * Test method for 'org.apache.lucene.gdata.server.GDataResponse.sendResponse(BaseFeed, ExtensionProfile)'
     */
    public void testSendResponseBaseFeedExtensionProfile() throws IOException {
        try{
            Feed f = null;
            this.response.sendResponse(f, new ProvidedServiceStub());
            fail("Exception expected");
        }catch (IllegalArgumentException e) {
            //
        }

        try{
            Feed f = createFeed();
            this.response.sendResponse(f,null);
            fail("Exception expected");
        }catch (IllegalArgumentException e) {
            //
        }
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);

        this.control.expectAndReturn(this.httpResponse.getWriter(),writer);
        this.httpResponse.setContentType(GDataResponse.XMLMIME_ATOM);
        this.response.setOutputFormat(OutputFormat.ATOM);
        this.control.replay();

        this.response.sendResponse(createFeed(), new ProvidedServiceStub());
        assertEquals("Simple XML representation",stringWriter.toString(),generatedFeedAtom);
        this.control.reset();

        stringWriter = new StringWriter();
        writer = new PrintWriter(stringWriter);

        this.control.expectAndReturn(this.httpResponse.getWriter(),writer);
        this.response.setOutputFormat(OutputFormat.RSS);
        this.httpResponse.setContentType(GDataResponse.XMLMIME_RSS);
        this.control.replay();

        this.response.sendResponse(createFeed(), new ProvidedServiceStub());
        assertEquals("Simple XML representation",stringWriter.toString(),generatedFeedRSS);

    }

    /*
     * Test method for 'org.apache.lucene.gdata.server.GDataResponse.sendResponse(BaseEntry, ExtensionProfile)'
     */
    public void testSendResponseBaseEntryExtensionProfile() throws IOException {
        try{
            Entry e = null;
            this.response.sendResponse(e, new ProvidedServiceStub());
            fail("Exception expected");
        }catch (IllegalArgumentException e) {
            //
        }
        try{
            Entry e = createEntry();
            this.response.sendResponse(e,null);
            fail("Exception expected");
        }catch (IllegalArgumentException e) {
            //
        }
//        // test Atom output
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);

        this.control.expectAndReturn(this.httpResponse.getWriter(),writer);
        this.httpResponse.setContentType(GDataResponse.XMLMIME_ATOM);
        this.response.setOutputFormat(OutputFormat.ATOM);
        this.control.replay();

        this.response.sendResponse(createEntry(), new ProvidedServiceStub());
        assertEquals("Simple XML representation ATOM",stringWriter.toString(),generatedEntryAtom);

        // test rss output
        this.control.reset();
        stringWriter = new StringWriter();
        writer = new PrintWriter(stringWriter);

        this.control.expectAndReturn(this.httpResponse.getWriter(),writer);
        this.httpResponse.setContentType(GDataResponse.XMLMIME_RSS);
        this.response.setOutputFormat(OutputFormat.RSS);
        this.control.replay();

        this.response.sendResponse(createEntry(), new ProvidedServiceStub());

        assertEquals("Simple XML representation RSS",stringWriter.toString(),generatedEntryRSS);

    }

    /* create a simple feed */
    private Feed createFeed(){
        Feed feed = new Feed();

        feed.getEntries().add(createEntry());

        return feed;
    }
    /* create a simple entry */
    private Entry createEntry(){
        Entry e = new Entry();
        e.setTitle(new PlainTextConstruct("Test"));
        return e;
    }

}


text:
/**
 * Created by xc- on 2.4.2016.
 */
var expressopot = require('../index');
var chai = require('chai');
var _ = require('lodash');

var expect = chai.expect;
var assert = chai.assert;

function error404(req, res, next) {
  next(new Error('Not Found'));
}

function error500dev(err, req, res, next) {
  var foo = 'bar';
}

function error500pro(err, req, res, next) {
  var bar = 'foo'
}

var names = function(collection) {
  return _.map(collection, function(val) {
    return val.name;
  });
};

const environments = {
  production: null,
  development: null
};

describe('HTTP Errors', function () {
  var express = require('express');

  it('Should include error handlers', function() {
    var config = {
      middleware: {
        http_errors: {
          404: error404,
          500: error500dev
        }
      }
    };
    var error_mw_names = [error404.name, error500dev.name];
    var app = expressopot(express(), config);
    expect(names(app._router.stack)).to.include.members(error_mw_names);
  });

  it('Should include error handlers according to environment', function() {
    var config = {
      middleware: {
        http_errors: {
          404: error404,
          500: {
            development: error500dev,
            production: error500pro
          }
        }
      }
    };
    var test_environments = _.cloneDeep(environments);
    test_environments.development = [error404.name, error500dev.name];
    test_environments.production = [error404.name, error500pro.name];
    _.forEach(test_environments, function(e_names, env) {
      var app = express();
      app.set('env', env);
      app = expressopot(app, config);
      expect(names(app._router.stack)).to.include.members(e_names);
    });
  });
});


text:
<?php

namespace Theme\AssetManager;

use \Zend\View\Helper\Placeholder\Container\AbstractStandalone;

/**
 *
 * @author PedromDev
 */
interface DependencyInterface
{
    /**
     *
     * @param string $name
     */
    public function setName($name);

    /**
     *
     * @return string
     */
    public function getName();

    /**
     * Add a new dependency
     *
     * @param DependencyInterface $dependency
     * @throws DependencyException
     */
    public function add(DependencyInterface $dependency);

    /**
     *
     * @param string $name
     * @return DependencyInterface
     * @throws DependencyException
     */
    public function get($name);

    /**
     *
     * @param string $name
     * @return boolean
     */
    public function has($name);

    /**
     *
     * @param string $name
     * @throws DependencyException
     * @return boolean
     */
    public function remove($name);

    /**
     *
     * @return DependencyInterface[]
     */
    public function getAll();

    /**
     *
     * @return boolean
     */
    public function hasDependencies();

    /**
     *
     * @return boolean
     */
    public function removeAll();

    /**
     *
     */
    public function enqueue();
}


text:
// -*- c++ -*-
// Generated by gmmproc 2.46.2 -- DO NOT MODIFY!
#ifndef _GIOMM_BUFFEREDINPUTSTREAM_H
#define _GIOMM_BUFFEREDINPUTSTREAM_H

#include <glibmm/ustring.h>
#include <sigc++/sigc++.h>

// -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 2 -*-

#include <giomm/filterinputstream.h>
#include <glibmm/object.h>

#ifndef DOXYGEN_SHOULD_SKIP_THIS
typedef struct _GBufferedInputStream GBufferedInputStream;
typedef struct _GBufferedInputStreamClass GBufferedInputStreamClass;
#endif /* DOXYGEN_SHOULD_SKIP_THIS */

#ifndef DOXYGEN_SHOULD_SKIP_THIS
namespace Gio
{ class BufferedInputStream_Class; } // namespace Gio
#endif //DOXYGEN_SHOULD_SKIP_THIS

namespace Gio
{

/** @defgroup Streams Stream Classes
 *
 */

/** The buffered input stream implements FilterInputStream and provides for buffered reads.
 * By default, BufferedInputStream's buffer size is set at 4 kilobytes, but you can specify
 * this to the constructor.
 *
 * To get the size of a buffer within a buffered input stream, use get_buffer_size().
 * To change the size of a buffered input stream's buffer, use set_buffer_size().
 * Note that the buffer's size cannot be reduced below the size of the data within the buffer.
 *
 * @ingroup Streams
 *
 * @newin{2,16}
 */

class BufferedInputStream : public Gio::FilterInputStream
{

#ifndef DOXYGEN_SHOULD_SKIP_THIS

public:
  typedef BufferedInputStream CppObjectType;
  typedef BufferedInputStream_Class CppClassType;
  typedef GBufferedInputStream BaseObjectType;
  typedef GBufferedInputStreamClass BaseClassType;

  // noncopyable
  BufferedInputStream(const BufferedInputStream&) = delete;
  BufferedInputStream& operator=(const BufferedInputStream&) = delete;

private:  friend class BufferedInputStream_Class;
  static CppClassType bufferedinputstream_class_;

protected:
  explicit BufferedInputStream(const Glib::ConstructParams& construct_params);
  explicit BufferedInputStream(GBufferedInputStream* castitem);

#endif /* DOXYGEN_SHOULD_SKIP_THIS */

public:

  BufferedInputStream(BufferedInputStream&& src) noexcept;
  BufferedInputStream& operator=(BufferedInputStream&& src) noexcept;

  virtual ~BufferedInputStream() noexcept;

  /** Get the GType for this class, for use with the underlying GObject type system.
   */
  static GType get_type()      G_GNUC_CONST;

#ifndef DOXYGEN_SHOULD_SKIP_THIS

  static GType get_base_type() G_GNUC_CONST;
#endif

  ///Provides access to the underlying C GObject.
  GBufferedInputStream*       gobj()       { return reinterpret_cast<GBufferedInputStream*>(gobject_); }

  ///Provides access to the underlying C GObject.
  const GBufferedInputStream* gobj() const { return reinterpret_cast<GBufferedInputStream*>(gobject_); }

  ///Provides access to the underlying C instance. The caller is responsible for unrefing it. Use when directly setting fields in structs.
  GBufferedInputStream* gobj_copy();

private:

protected:
    explicit BufferedInputStream(const Glib::RefPtr<InputStream>& base_stream);

  //Note that we rename the size parameter to buffer_size because that is the actual name of the property.
    explicit BufferedInputStream(const Glib::RefPtr<InputStream>& base_stream, gsize buffer_size);

public:
  /** Creates a new InputStream from the given base_stream, with a buffer set to the default size (4 kilobytes).
   *
   * @param base_stream An InputStream.
   * @result an InputStream for the given base_stream.
	 */

  static Glib::RefPtr<BufferedInputStream> create(const Glib::RefPtr<InputStream>& base_stream);

  /** Creates a new InputStream from the given base_stream, with a buffer set to size.
   *
   * @param base_stream An InputStream.
   * @param buffer_size A size.
   * @result an InputStream for the given base_stream.
	 */
  static Glib::RefPtr<BufferedInputStream> create_sized(const Glib::RefPtr<InputStream>& base_stream, gsize buffer_size);

  /** Gets the size of the input buffer.
   *
   * @return The current buffer size.
   */
  gsize get_buffer_size() const;

  /** Sets the size of the internal buffer of @a stream to @a size, or to the
   * size of the contents of the buffer. The buffer can never be resized
   * smaller than its current contents.
   *
   * @param size A #gsize.
   */
  void set_buffer_size(gsize size);

  /** Gets the size of the available data within the stream.
   *
   * @return Size of the available stream.
   */
  gsize get_available() const;

  /** Peeks in the buffer, copying data of size @a count into @a buffer,
   * offset @a offset bytes.
   *
   * @param buffer A pointer to
   * an allocated chunk of memory.
   * @param offset A #gsize.
   * @param count A #gsize.
   * @return A #gsize of the number of bytes peeked, or -1 on error.
   */
  gsize peek(void* buffer, gsize offset, gsize count) const;

  /** Returns the buffer with the currently available bytes. The returned
   * buffer must not be modified and will become invalid when reading from
   * the stream or filling the buffer.
   *
   * @param count A #gsize to get the number of bytes available in the buffer.
   * @return Read-only buffer.
   */
  const void* peek_buffer(gsize& count) const;

  /** Tries to read @a count bytes from the stream into the buffer.
   * Will block during this read.
   *
   * If @a count is zero, returns zero and does nothing. A value of @a count
   * larger than MAXSSIZE will cause a Gio::Error to be thrown, with INVALID_ARGUMENT.
   *
   * On success, the number of bytes read into the buffer is returned.
   * It is not an error if this is not the same as the requested size, as it
   * can happen e.g. near the end of a file. Zero is returned on end of file
   * (or if @a count is zero),  but never otherwise.
   *
   * The operation can be cancelled by
   * triggering the cancellable object from another thread. If the operation
   * was cancelled, a Gio::Error will be thrown with CANCELLED. If an
   * operation was partially finished when the operation was cancelled the
   * partial result will be returned, without an error.
   *
   *
   *
   * For the asynchronous, non-blocking, version of this function, see
   * g_buffered_input_stream_fill_async().
   *
   * @param count The number of bytes that will be read from the stream.
   * @param cancellable Cancellable object.
   * @return The number of bytes read into @a stream's buffer, up to @a count,
   * or -1 on error.
   */
  gssize fill(gssize count, const Glib::RefPtr<Cancellable>& cancellable);

  /// A fill() convenience overload.
  gssize fill(gssize count);

  /** Reads data into the stream's buffer asynchronously, up to @a count size.
   * @a io_priority can be used to prioritize reads. For the synchronous version of
   * this function, see fill().
   *
   * @param slot A AsyncReadyCallback.
   * @param count The number of bytes to read.
   * @param cancellable Cancellable object.
   * @param io_priority the I/O priority of the request.
   */
  void fill_async(const SlotAsyncReady& slot,
                  gssize count,
                  const Glib::RefPtr<Cancellable>& cancellable,
                  int io_priority = Glib::PRIORITY_DEFAULT);

  /** Reads data into the stream's buffer asynchronously, up to @a count size.
   * @a io_priority can be used to prioritize reads. For the synchronous version of
   * this function, see fill().
   *
   * @param slot A AsyncReadyCallback.
   * @param count The number of bytes to read.
   * @param io_priority the I/O priority of the request.
   */
  void fill_async(const SlotAsyncReady& slot,
                  gssize count,
                  int io_priority = Glib::PRIORITY_DEFAULT);

  /** Finishes an asynchronous read.
   *
   * @param result A AsyncResult.
   * @return A #gssize of the read stream, or %-1 on an error.
   */
  gssize fill_finish(const Glib::RefPtr<AsyncResult>& result);

  /** Tries to read a single byte from the stream or the buffer. Will block
   * during this read.
   *
   * On success, the byte read from the stream is returned. On end of stream
   * -1 is returned but it's not an exceptional error and @a error is not set.
   *
   * The operation can be cancelled by
   * triggering the cancellable object from another thread. If the operation
   * was cancelled, a Gio::Error will be thrown with CANCELLED. If an
   * operation was partially finished when the operation was cancelled the
   * partial result will be returned, without an error.
   *
   * @param cancellable Cancellable object.
   * @return The byte read from the @a stream, or -1 on end of stream or error.
   */
  int read_byte(const Glib::RefPtr<Cancellable>& cancellable);

  /// A read_byte() convenience overload.
  int read_byte();

  /** The size of the backend buffer.
   *
   * @return A PropertyProxy that allows you to get or set the value of the property,
   * or receive notification when the value of the property changes.
   */
  Glib::PropertyProxy< guint > property_buffer_size() ;

/** The size of the backend buffer.
   *
   * @return A PropertyProxy_ReadOnly that allows you to get the value of the property,
   * or receive notification when the value of the property changes.
   */
  Glib::PropertyProxy_ReadOnly< guint > property_buffer_size() const;

protected:

  //_WRAP_VFUNC(gssize fill(gssize count, const Glib::RefPtr<Cancellable>& cancellable, GError** error), "fill")

public:

public:
  //C++ methods used to invoke GTK+ virtual functions:

protected:
  //GTK+ Virtual Functions (override these to change behaviour):

  //Default Signal Handlers::

};

} // namespace Gio

namespace Glib
{
  /** A Glib::wrap() method for this object.
   *
   * @param object The C instance.
   * @param take_copy False if the result should take ownership of the C instance. True if it should take a new copy or ref.
   * @result A C++ instance that wraps this C instance.
   *
   * @relates Gio::BufferedInputStream
   */
  Glib::RefPtr<Gio::BufferedInputStream> wrap(GBufferedInputStream* object, bool take_copy = false);
}

#endif /* _GIOMM_BUFFEREDINPUTSTREAM_H */


text:
'use strict';

/**
 * @class
 * Initializes a new instance of the MAMPolicyProperties class.
 * @constructor
 * @member {string} friendlyName
 *
 * @member {string} [description]
 *
 * @member {string} [appSharingFromLevel] Possible values include: 'none',
 * 'policyManagedApps', 'allApps'. Default value: 'none' .
 *
 * @member {string} [appSharingToLevel] Possible values include: 'none',
 * 'policyManagedApps', 'allApps'. Default value: 'none' .
 *
 * @member {string} [authentication] Possible values include: 'required',
 * 'notRequired'. Default value: 'required' .
 *
 * @member {string} [clipboardSharingLevel] Possible values include: 'blocked',
 * 'policyManagedApps', 'policyManagedAppsWithPasteIn', 'allApps'. Default
 * value: 'blocked' .
 *
 * @member {string} [dataBackup] Possible values include: 'allow', 'block'.
 * Default value: 'allow' .
 *
 * @member {string} [fileSharingSaveAs] Possible values include: 'allow',
 * 'block'. Default value: 'allow' .
 *
 * @member {string} [pin] Possible values include: 'required', 'notRequired'.
 * Default value: 'required' .
 *
 * @member {number} [pinNumRetry]
 *
 * @member {string} [deviceCompliance] Possible values include: 'enable',
 * 'disable'. Default value: 'enable' .
 *
 * @member {string} [managedBrowser] Possible values include: 'required',
 * 'notRequired'. Default value: 'required' .
 *
 * @member {moment.duration} [accessRecheckOfflineTimeout]
 *
 * @member {moment.duration} [accessRecheckOnlineTimeout]
 *
 * @member {moment.duration} [offlineWipeTimeout]
 *
 * @member {number} [numOfApps]
 *
 * @member {string} [groupStatus] Possible values include: 'notTargeted',
 * 'targeted'. Default value: 'notTargeted' .
 *
 * @member {date} [lastModifiedTime]
 *
 */
class MAMPolicyProperties {
  constructor() {
  }

  /**
   * Defines the metadata of MAMPolicyProperties
   *
   * @returns {object} metadata of MAMPolicyProperties
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'MAMPolicyProperties',
      type: {
        name: 'Composite',
        className: 'MAMPolicyProperties',
        modelProperties: {
          friendlyName: {
            required: true,
            serializedName: 'friendlyName',
            type: {
              name: 'String'
            }
          },
          description: {
            required: false,
            serializedName: 'description',
            type: {
              name: 'String'
            }
          },
          appSharingFromLevel: {
            required: false,
            serializedName: 'appSharingFromLevel',
            defaultValue: 'none',
            type: {
              name: 'String'
            }
          },
          appSharingToLevel: {
            required: false,
            serializedName: 'appSharingToLevel',
            defaultValue: 'none',
            type: {
              name: 'String'
            }
          },
          authentication: {
            required: false,
            serializedName: 'authentication',
            defaultValue: 'required',
            type: {
              name: 'String'
            }
          },
          clipboardSharingLevel: {
            required: false,
            serializedName: 'clipboardSharingLevel',
            defaultValue: 'blocked',
            type: {
              name: 'String'
            }
          },
          dataBackup: {
            required: false,
            serializedName: 'dataBackup',
            defaultValue: 'allow',
            type: {
              name: 'String'
            }
          },
          fileSharingSaveAs: {
            required: false,
            serializedName: 'fileSharingSaveAs',
            defaultValue: 'allow',
            type: {
              name: 'String'
            }
          },
          pin: {
            required: false,
            serializedName: 'pin',
            defaultValue: 'required',
            type: {
              name: 'String'
            }
          },
          pinNumRetry: {
            required: false,
            serializedName: 'pinNumRetry',
            type: {
              name: 'Number'
            }
          },
          deviceCompliance: {
            required: false,
            serializedName: 'deviceCompliance',
            defaultValue: 'enable',
            type: {
              name: 'String'
            }
          },
          managedBrowser: {
            required: false,
            serializedName: 'managedBrowser',
            defaultValue: 'required',
            type: {
              name: 'String'
            }
          },
          accessRecheckOfflineTimeout: {
            required: false,
            serializedName: 'accessRecheckOfflineTimeout',
            type: {
              name: 'TimeSpan'
            }
          },
          accessRecheckOnlineTimeout: {
            required: false,
            serializedName: 'accessRecheckOnlineTimeout',
            type: {
              name: 'TimeSpan'
            }
          },
          offlineWipeTimeout: {
            required: false,
            serializedName: 'offlineWipeTimeout',
            type: {
              name: 'TimeSpan'
            }
          },
          numOfApps: {
            required: false,
            readOnly: true,
            serializedName: 'numOfApps',
            type: {
              name: 'Number'
            }
          },
          groupStatus: {
            required: false,
            readOnly: true,
            serializedName: 'groupStatus',
            defaultValue: 'notTargeted',
            type: {
              name: 'String'
            }
          },
          lastModifiedTime: {
            required: false,
            readOnly: true,
            serializedName: 'lastModifiedTime',
            type: {
              name: 'DateTime'
            }
          }
        }
      }
    };
  }
}

module.exports = MAMPolicyProperties;


text:
import theano

from .base import Layer
from ..random import get_rng

from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams

__all__ = [
    "DropoutLayer",
    "dropout",
    "GaussianNoiseLayer",
]

class DropoutLayer(Layer):
    """Dropout layer

    Sets values to zero with probability p. See notes for disabling dropout
    during testing.

    Parameters
    ----------
    incoming : a :class:`Layer` instance or a tuple
        the layer feeding into this layer, or the expected input shape
    p : float or scalar tensor
        The probability of setting a value to zero
    rescale : bool
        If true the input is rescaled with input / (1-p) when deterministic
        is False.

    Notes
    -----
    The dropout layer is a regularizer that randomly sets input values to
    zero; see [1]_, [2]_ for why this might improve generalization.
    During training you should set deterministic to false and during
    testing you should set deterministic to true.

    If rescale is true the input is scaled with input / (1-p) when
    deterministic is false, see references for further discussion. Note that
    this implementation scales the input at training time.

    References
    ----------
    .. [1] Hinton, G., Srivastava, N., Krizhevsky, A., Sutskever, I.,
           Salakhutdinov, R. R. (2012):
           Improving neural networks by preventing co-adaptation of feature
           detectors. arXiv preprint arXiv:1207.0580.

    .. [2] Srivastava Nitish, Hinton, G., Krizhevsky, A., Sutskever,
           I., & Salakhutdinov, R. R. (2014):
           Dropout: A Simple Way to Prevent Neural Networks from Overfitting.
           Journal of Machine Learning Research, 5(Jun)(2), 1929-1958.
    """
    def __init__(self, incoming, p=0.5, rescale=True, **kwargs):
        super(DropoutLayer, self).__init__(incoming, **kwargs)
        self._srng = RandomStreams(get_rng().randint(1, 2147462579))
        self.p = p
        self.rescale = rescale

    def get_output_for(self, input, deterministic=False, **kwargs):
        """
        Parameters
        ----------
        input : tensor
            output from the previous layer
        deterministic : bool
            If true dropout and scaling is disabled, see notes
        """
        if deterministic or self.p == 0:
            return input
        else:
            retain_prob = 1 - self.p
            if self.rescale:
                input /= retain_prob

            # use nonsymbolic shape for dropout mask if possible
            input_shape = self.input_shape
            if any(s is None for s in input_shape):
                input_shape = input.shape

            return input * self._srng.binomial(input_shape, p=retain_prob,
                                               dtype=theano.config.floatX)

dropout = DropoutLayer  # shortcut

class GaussianNoiseLayer(Layer):
    """Gaussian noise layer.

    Add zero-mean Gaussian noise of given standard deviation to the input [1]_.

    Parameters
    ----------
    incoming : a :class:`Layer` instance or a tuple
            the layer feeding into this layer, or the expected input shape
    sigma : float or tensor scalar
            Standard deviation of added Gaussian noise

    Notes
    -----
    The Gaussian noise layer is a regularizer. During training you should set
    deterministic to false and during testing you should set deterministic to
    true.

    References
    ----------
    .. [1] K.-C. Jim, C. Giles, and B. Horne (1996):
           An analysis of noise in recurrent neural networks: convergence and
           generalization.
           IEEE Transactions on Neural Networks, 7(6):1424-1438.
    """
    def __init__(self, incoming, sigma=0.1, **kwargs):
        super(GaussianNoiseLayer, self).__init__(incoming, **kwargs)
        self._srng = RandomStreams(get_rng().randint(1, 2147462579))
        self.sigma = sigma

    def get_output_for(self, input, deterministic=False, **kwargs):
        """
        Parameters
        ----------
        input : tensor
            output from the previous layer
        deterministic : bool
            If true noise is disabled, see notes
        """
        if deterministic or self.sigma == 0:
            return input
        else:
            return input + self._srng.normal(input.shape,
                                             avg=0.0,
                                             std=self.sigma)


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="edu.cs4730.mapdemov2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <permission
        android:name="edu.cs4730.mapdemov2.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="edu.cs4730.mapdemov2.permission.MAPS_RECEIVE" />
        <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="edu.cs4730.mapdemov2.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".BasicMapActivity"
           android:label="Basic Map Demo"
            android:parentActivityName=".MainActivity"
            android:uiOptions="splitActionBarWhenNarrow">
            <meta-data android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
       </activity>
        <activity android:name=".CompassActivity"
           android:label="Compass Demo"
            android:parentActivityName=".MainActivity"
            android:uiOptions="splitActionBarWhenNarrow"
            android:screenOrientation="portrait">
            <meta-data android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
       </activity>
        <activity android:name=".DrawMapActivity"
           android:label="Drawing Map Demo"
            android:parentActivityName=".MainActivity"
            android:uiOptions="splitActionBarWhenNarrow">
            <meta-data android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
       </activity>
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyDTsgPdmTG3q_LxCnVQ5Dr431ohOaQnzdw" />

    </application>

</manifest>


text:
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <scale
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:fromXScale="1.0"
        android:toXScale="1.4"
        android:fromYScale="1.0"
        android:toYScale="0.6"
        android:pivotX="50%"
        android:pivotY="50%"
        android:fillAfter="false"
        android:duration="700" />

    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:duration="400" />

    <set
        android:interpolator="@android:anim/accelerate_interpolator"
        android:startOffset="700">

        <rotate
            android:fromDegrees="0"
            android:toDegrees="360"

            android:interpolator="@android:anim/linear_interpolator"
            android:duration="400"
            android:pivotX="50%"
            android:pivotY="0%"
            />

        <scale
            android:fromXScale="1.4"
            android:toXScale="0.0"
            android:fromYScale="0.6"
            android:toYScale="0.0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:duration="400" />
    </set>

</set>


text:
package syntax

// Simplify returns a regexp equivalent to re but without counted repetitions
// and with various other simplifications, such as rewriting /(?:a+)+/ to /a+/.
// The resulting regexp will execute correctly but its string representation
// will not produce the same parse tree, because capturing parentheses
// may have been duplicated or removed.  For example, the simplified form
// for /(x){1,2}/ is /(x)(x)?/ but both parentheses capture as $1.
// The returned regexp may share structure with or be the original.
func (re *Regexp) Simplify() *Regexp {
	if re == nil {
		return nil
	}
	switch re.Op {
	case OpCapture, OpConcat, OpAlternate:
		// Simplify children, building new Regexp if children change.
		nre := re
		for i, sub := range re.Sub {
			nsub := sub.Simplify()
			if nre == re && nsub != sub {
				// Start a copy.
				nre = new(Regexp)
				*nre = *re
				nre.Rune = nil
				nre.Sub = append(nre.Sub0[:0], re.Sub[:i]...)
			}
			if nre != re {
				nre.Sub = append(nre.Sub, nsub)
			}
		}
		return nre

	case OpStar, OpPlus, OpQuest:
		sub := re.Sub[0].Simplify()
		return simplify1(re.Op, re.Flags, sub, re)

	case OpRepeat:
		// Special special case: x{0} matches the empty string
		// and doesn't even need to consider x.
		if re.Min == 0 && re.Max == 0 {
			return &Regexp{Op: OpEmptyMatch}
		}

		// The fun begins.
		sub := re.Sub[0].Simplify()

		// x{n,} means at least n matches of x.
		if re.Max == -1 {
			// Special case: x{0,} is x*.
			if re.Min == 0 {
				return simplify1(OpStar, re.Flags, sub, nil)
			}

			// Special case: x{1,} is x+.
			if re.Min == 1 {
				return simplify1(OpPlus, re.Flags, sub, nil)
			}

			// General case: x{4,} is xxxx+.
			nre := &Regexp{Op: OpConcat}
			nre.Sub = nre.Sub0[:0]
			for i := 0; i < re.Min-1; i++ {
				nre.Sub = append(nre.Sub, sub)
			}
			nre.Sub = append(nre.Sub, simplify1(OpPlus, re.Flags, sub, nil))
			return nre
		}

		// Special case x{0} handled above.

		// Special case: x{1} is just x.
		if re.Min == 1 && re.Max == 1 {
			return sub
		}

		// General case: x{n,m} means n copies of x and m copies of x?
		// The machine will do less work if we nest the final m copies,
		// so that x{2,5} = xx(x(x(x)?)?)?

		// Build leading prefix: xx.
		var prefix *Regexp
		if re.Min > 0 {
			prefix = &Regexp{Op: OpConcat}
			prefix.Sub = prefix.Sub0[:0]
			for i := 0; i < re.Min; i++ {
				prefix.Sub = append(prefix.Sub, sub)
			}
		}

		// Build and attach suffix: (x(x(x)?)?)?
		if re.Max > re.Min {
			suffix := simplify1(OpQuest, re.Flags, sub, nil)
			for i := re.Min + 1; i < re.Max; i++ {
				nre2 := &Regexp{Op: OpConcat}
				nre2.Sub = append(nre2.Sub0[:0], sub, suffix)
				suffix = simplify1(OpQuest, re.Flags, nre2, nil)
			}
			if prefix == nil {
				return suffix
			}
			prefix.Sub = append(prefix.Sub, suffix)
		}
		if prefix != nil {
			return prefix
		}

		// Some degenerate case like min > max or min < max < 0.
		// Handle as impossible match.
		return &Regexp{Op: OpNoMatch}
	}

	return re
}

// simplify1 implements Simplify for the unary OpStar,
// OpPlus, and OpQuest operators.  It returns the simple regexp
// equivalent to
//
//	Regexp{Op: op, Flags: flags, Sub: {sub}}
//
// under the assumption that sub is already simple, and
// without first allocating that structure.  If the regexp
// to be returned turns out to be equivalent to re, simplify1
// returns re instead.
//
// simplify1 is factored out of Simplify because the implementation
// for other operators generates these unary expressions.
// Letting them call simplify1 makes sure the expressions they
// generate are simple.
func simplify1(op Op, flags Flags, sub, re *Regexp) *Regexp {
	// Special case: repeat the empty string as much as
	// you want, but it's still the empty string.
	if sub.Op == OpEmptyMatch {
		return sub
	}
	// The operators are idempotent if the flags match.
	if op == sub.Op && flags&NonGreedy == sub.Flags&NonGreedy {
		return sub
	}
	if re != nil && re.Op == op && re.Flags&NonGreedy == flags&NonGreedy && sub == re.Sub[0] {
		return re
	}

	re = &Regexp{Op: op, Flags: flags}
	re.Sub = append(re.Sub0[:0], sub)
	return re
}


text:
package vpc

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// DescribeVSwitchAttributes invokes the vpc.DescribeVSwitchAttributes API synchronously
// api document: https://help.aliyun.com/api/vpc/describevswitchattributes.html
func (client *Client) DescribeVSwitchAttributes(request *DescribeVSwitchAttributesRequest) (response *DescribeVSwitchAttributesResponse, err error) {
	response = CreateDescribeVSwitchAttributesResponse()
	err = client.DoAction(request, response)
	return
}

// DescribeVSwitchAttributesWithChan invokes the vpc.DescribeVSwitchAttributes API asynchronously
// api document: https://help.aliyun.com/api/vpc/describevswitchattributes.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeVSwitchAttributesWithChan(request *DescribeVSwitchAttributesRequest) (<-chan *DescribeVSwitchAttributesResponse, <-chan error) {
	responseChan := make(chan *DescribeVSwitchAttributesResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.DescribeVSwitchAttributes(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// DescribeVSwitchAttributesWithCallback invokes the vpc.DescribeVSwitchAttributes API asynchronously
// api document: https://help.aliyun.com/api/vpc/describevswitchattributes.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) DescribeVSwitchAttributesWithCallback(request *DescribeVSwitchAttributesRequest, callback func(response *DescribeVSwitchAttributesResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *DescribeVSwitchAttributesResponse
		var err error
		defer close(result)
		response, err = client.DescribeVSwitchAttributes(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// DescribeVSwitchAttributesRequest is the request struct for api DescribeVSwitchAttributes
type DescribeVSwitchAttributesRequest struct {
	*requests.RpcRequest
	VSwitchId            string           `position:"Query" name:"VSwitchId"`
	ResourceOwnerId      requests.Integer `position:"Query" name:"ResourceOwnerId"`
	ResourceOwnerAccount string           `position:"Query" name:"ResourceOwnerAccount"`
	OwnerAccount         string           `position:"Query" name:"OwnerAccount"`
	OwnerId              requests.Integer `position:"Query" name:"OwnerId"`
}

// DescribeVSwitchAttributesResponse is the response struct for api DescribeVSwitchAttributes
type DescribeVSwitchAttributesResponse struct {
	*responses.BaseResponse
	RequestId               string                                    `json:"RequestId" xml:"RequestId"`
	VSwitchId               string                                    `json:"VSwitchId" xml:"VSwitchId"`
	VpcId                   string                                    `json:"VpcId" xml:"VpcId"`
	Status                  string                                    `json:"Status" xml:"Status"`
	CidrBlock               string                                    `json:"CidrBlock" xml:"CidrBlock"`
	ZoneId                  string                                    `json:"ZoneId" xml:"ZoneId"`
	AvailableIpAddressCount int                                       `json:"AvailableIpAddressCount" xml:"AvailableIpAddressCount"`
	Description             string                                    `json:"Description" xml:"Description"`
	VSwitchName             string                                    `json:"VSwitchName" xml:"VSwitchName"`
	CreationTime            string                                    `json:"CreationTime" xml:"CreationTime"`
	IsDefault               bool                                      `json:"IsDefault" xml:"IsDefault"`
	RouteTable              RouteTable                                `json:"RouteTable" xml:"RouteTable"`
	CloudResources          CloudResourcesInDescribeVSwitchAttributes `json:"CloudResources" xml:"CloudResources"`
}

// CreateDescribeVSwitchAttributesRequest creates a request to invoke DescribeVSwitchAttributes API
func CreateDescribeVSwitchAttributesRequest() (request *DescribeVSwitchAttributesRequest) {
	request = &DescribeVSwitchAttributesRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Vpc", "2016-04-28", "DescribeVSwitchAttributes", "vpc", "openAPI")
	return
}

// CreateDescribeVSwitchAttributesResponse creates a response to parse from DescribeVSwitchAttributes response
func CreateDescribeVSwitchAttributesResponse() (response *DescribeVSwitchAttributesResponse) {
	response = &DescribeVSwitchAttributesResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
package org.w3c.dom.svg;

import org.w3c.dom5.DOMException;

public interface SVGTransformList {
  public int getNumberOfItems( );

  public void   clear (  )
                  throws DOMException;
  public SVGTransform initialize ( SVGTransform newItem )
                  throws DOMException, SVGException;
  public SVGTransform getItem ( int index )
                  throws DOMException;
  public SVGTransform insertItemBefore ( SVGTransform newItem, int index )
                  throws DOMException, SVGException;
  public SVGTransform replaceItem ( SVGTransform newItem, int index )
                  throws DOMException, SVGException;
  public SVGTransform removeItem ( int index )
                  throws DOMException;
  public SVGTransform appendItem ( SVGTransform newItem )
                  throws DOMException, SVGException;
  public SVGTransform createSVGTransformFromMatrix ( SVGMatrix matrix );
  public SVGTransform consolidate (  );
}