text:
/* *
 *
 *  (c) 2010-2020 Torstein Honsi
 *
 *  License: www.highcharts.com/license
 *
 *  !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
 *
 * */
'use strict';
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __spreadArrays = (this && this.__spreadArrays) || function () {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};
import defaultOptions from './MapViewOptionsDefault.js';
import defaultInsetsOptions from './MapViewInsetsOptionsDefault.js';
import GeoJSONModule from '../Extensions/GeoJSON.js';
var topo2geo = GeoJSONModule.topo2geo;
import MapChart from '../Core/Chart/MapChart.js';
var maps = MapChart.maps;
import MU from './MapUtilities.js';
var boundsFromPath = MU.boundsFromPath, pointInPolygon = MU.pointInPolygon;
import Projection from './Projection.js';
import U from '../Core/Utilities.js';
var addEvent = U.addEvent, clamp = U.clamp, fireEvent = U.fireEvent, isArray = U.isArray, isNumber = U.isNumber, isObject = U.isObject, isString = U.isString, merge = U.merge, pick = U.pick, relativeLength = U.relativeLength;
/**
 * The world size in terms of 10k meters in the Web Mercator projection, to
 * match a 256 square tile to zoom level 0
 */
var worldSize = 400.979322;
var tileSize = 256;
// Compute the zoom from given bounds and the size of the playing field. Used in
// two places, hence the local function.
var zoomFromBounds = function (b, playingField) {
    var width = playingField.width, height = playingField.height, scaleToField = Math.max((b.x2 - b.x1) / (width / tileSize), (b.y2 - b.y1) / (height / tileSize));
    return Math.log(worldSize / scaleToField) / Math.log(2);
};
/*
const mergeCollections = <
    T extends Array<AnyRecord|undefined>
>(a: T, b: T): T => {
    b.forEach((newer, i): void => {
        // Only merge by id supported for now. We may consider later to support
        // more complex rules like those of `Chart.update` with `oneToOne`, but
        // it is probably not needed. Existing insets can be disabled by
        // overwriting the `geoBounds` with empty data.
        if (newer && isString(newer.id)) {
            const older = U.find(
                a,
                (aItem): boolean => (aItem && aItem.id) === newer.id
            );
            if (older) {
                const aIndex = a.indexOf(older);
                a[aIndex] = merge(older, newer);
            }
        }
    });
    return a;
};
*/
/**
 * The map view handles zooming and centering on the map, and various
 * client-side projection capabilities.
 *
 * On a chart instance, the map view is available as `chart.mapView`.
 *
 * @class
 * @name Highcharts.MapView
 *
 * @param {Highcharts.Chart} chart
 *        The Chart instance
 * @param {Highcharts.MapViewOptions} options
 *        MapView options
 */
var MapView = /** @class */ (function () {
    function MapView(chart, options) {
        var _this = this;
        this.insets = [];
        this.padding = [0, 0, 0, 0];
        this.eventsToUnbind = [];
        var recommendedMapView;
        var recommendedProjection;
        if (!(this instanceof MapViewInset)) {
            // Handle the global map and series-level mapData
            var geoMaps = __spreadArrays([
                chart.options.chart.map
            ], (chart.options.series || []).map(function (s) { return s.mapData; })).map(function (mapData) { return _this.getGeoMap(mapData); });
            var allGeoBounds_1 = [];
            geoMaps.forEach(function (geoMap) {
                if (geoMap) {
                    // Use the first geo map as main
                    if (!recommendedMapView) {
                        recommendedMapView = geoMap['hc-recommended-mapview'];
                    }
                    // Combine the bounding boxes of all loaded maps
                    if (geoMap.bbox) {
                        var _a = geoMap.bbox, x1 = _a[0], y1 = _a[1], x2 = _a[2], y2 = _a[3];
                        allGeoBounds_1.push({ x1: x1, y1: y1, x2: x2, y2: y2 });
                    }
                }
            });
            // Get the composite bounds
            var geoBounds = (allGeoBounds_1.length &&
                MapView.compositeBounds(allGeoBounds_1));
            // Provide a best-guess recommended projection if not set in the map
            // or in user options
            if (geoBounds) {
                var x1 = geoBounds.x1, y1 = geoBounds.y1, x2 = geoBounds.x2, y2 = geoBounds.y2;
                recommendedProjection = (x2 - x1 > 180 && y2 - y1 > 90) ?
                    // Wide angle, go for the world view
                    {
                        name: 'EqualEarth'
                    } :
                    // Narrower angle, use a projection better suited for local
                    // view
                    {
                        name: 'LambertConformalConic',
                        parallels: [y1, y2],
                        rotation: [-(x1 + x2) / 2]
                    };
            }
            // Register the main geo map (from options.chart.map) if set
            this.geoMap = geoMaps[0];
        }
        this.userOptions = options || {};
        var o = merge(defaultOptions, { projection: recommendedProjection }, recommendedMapView, options);
        // Merge the inset collections by id, or index if id missing
        var recInsets = recommendedMapView && recommendedMapView.insets, optInsets = options && options.insets;
        if (recInsets && optInsets) {
            o.insets = MapView.mergeInsets(recInsets, optInsets);
        }
        this.chart = chart;
        /**
         * The current center of the view in terms of `[longitude, latitude]`.
         * @name Highcharts.MapView#center
         * @readonly
         * @type {LonLatArray}
         */
        this.center = o.center;
        this.options = o;
        this.projection = new Projection(o.projection);
        // Initialize with full plot box so we don't have to check for undefined
        // every time we use it
        this.playingField = chart.plotBox;
        /**
         * The current zoom level of the view.
         * @name Highcharts.MapView#zoom
         * @readonly
         * @type {number}
         */
        this.zoom = o.zoom || 0;
        // Create the insets
        this.createInsets();
        // Initialize and respond to chart size changes
        this.eventsToUnbind.push(addEvent(chart, 'afterSetChartSize', function () {
            _this.playingField = _this.getField();
            if (_this.minZoom === void 0 || // When initializing the chart
                _this.minZoom === _this.zoom // When resizing the chart
            ) {
                _this.fitToBounds(void 0, void 0, false);
                if (
                // Set zoom only when initializing the chart
                // (do not overwrite when zooming in/out, #17082)
                !_this.chart.hasRendered &&
                    isNumber(_this.userOptions.zoom)) {
                    _this.zoom = _this.userOptions.zoom;
                }
                if (_this.userOptions.center) {
                    merge(true, _this.center, _this.userOptions.center);
                }
            }
        }));
        this.setUpEvents();
    }
    // Merge two collections of insets by the id
    MapView.mergeInsets = function (a, b) {
        var toObject = function (insets) {
            var ob = {};
            insets.forEach(function (inset, i) {
                ob[inset && inset.id || "i" + i] = inset;
            });
            return ob;
        };
        var insetsObj = merge(toObject(a), toObject(b)), insets = Object
            .keys(insetsObj)
            .map(function (key) { return insetsObj[key]; });
        return insets;
    };
    // Create MapViewInset instances from insets options
    MapView.prototype.createInsets = function () {
        var _this = this;
        var options = this.options, insets = options.insets;
        if (insets) {
            insets.forEach(function (item) {
                var inset = new MapViewInset(_this, merge(options.insetOptions, item));
                _this.insets.push(inset);
            });
        }
    };
    /**
     * Fit the view to given bounds
     *
     * @function Highcharts.MapView#fitToBounds
     * @param {Object} bounds
     *        Bounds in terms of projected units given as  `{ x1, y1, x2, y2 }`.
     *        If not set, fit to the bounds of the current data set
     * @param {number|string} [padding=0]
     *        Padding inside the bounds. A number signifies pixels, while a
     *        percentage string (like `5%`) can be used as a fraction of the
     *        plot area size.
     * @param {boolean} [redraw=true]
     *        Whether to redraw the chart immediately
     * @param {boolean|Partial<Highcharts.AnimationOptionsObject>} [animation]
     *        What animation to use for redraw
     */
    MapView.prototype.fitToBounds = function (bounds, padding, redraw, animation) {
        if (redraw === void 0) { redraw = true; }
        var b = bounds || this.getProjectedBounds();
        if (b) {
            var pad = pick(padding, bounds ? 0 : this.options.padding), fullField = this.getField(false), padArr = isArray(pad) ? pad : [pad, pad, pad, pad];
            this.padding = [
                relativeLength(padArr[0], fullField.height),
                relativeLength(padArr[1], fullField.width),
                relativeLength(padArr[2], fullField.height),
                relativeLength(padArr[3], fullField.width)
            ];
            // Apply the playing field, corrected with padding
            this.playingField = this.getField();
            var zoom = zoomFromBounds(b, this.playingField);
            // Reset minZoom when fitting to natural bounds
            if (!bounds) {
                this.minZoom = zoom;
            }
            var center = this.projection.inverse([
                (b.x2 + b.x1) / 2,
                (b.y2 + b.y1) / 2
            ]);
            this.setView(center, zoom, redraw, animation);
        }
    };
    MapView.prototype.getField = function (padded) {
        if (padded === void 0) { padded = true; }
        var padding = padded ? this.padding : [0, 0, 0, 0];
        return {
            x: padding[3],
            y: padding[0],
            width: this.chart.plotWidth - padding[1] - padding[3],
            height: this.chart.plotHeight - padding[0] - padding[2]
        };
    };
    MapView.prototype.getGeoMap = function (map) {
        if (isString(map)) {
            return maps[map];
        }
        if (isObject(map, true)) {
            if (map.type === 'FeatureCollection') {
                return map;
            }
            if (map.type === 'Topology') {
                return topo2geo(map);
            }
        }
    };
    MapView.prototype.getMapBBox = function () {
        var bounds = this.getProjectedBounds(), scale = this.getScale();
        if (bounds) {
            var padding = this.padding, p1 = this.projectedUnitsToPixels({
                x: bounds.x1,
                y: bounds.y2
            }), width = ((bounds.x2 - bounds.x1) * scale +
                padding[1] + padding[3]), height = ((bounds.y2 - bounds.y1) * scale +
                padding[0] + padding[2]);
            return {
                width: width,
                height: height,
                x: p1.x - padding[3],
                y: p1.y - padding[0]
            };
        }
    };
    MapView.prototype.getProjectedBounds = function () {
        var allBounds = this.chart.series.reduce(function (acc, s) {
            var bounds = s.getProjectedBounds && s.getProjectedBounds();
            if (bounds &&
                s.options.affectsMapView !== false) {
                acc.push(bounds);
            }
            return acc;
        }, []);
        return this.projection.bounds || MapView.compositeBounds(allBounds);
    };
    MapView.prototype.getScale = function () {
        // A zoom of 0 means the world (360x360 degrees) fits in a 256x256 px
        // tile
        return (tileSize / worldSize) * Math.pow(2, this.zoom);
    };
    // Calculate the SVG transform to be applied to series groups
    MapView.prototype.getSVGTransform = function () {
        var _a = this.playingField, x = _a.x, y = _a.y, width = _a.width, height = _a.height, projectedCenter = this.projection.forward(this.center), flipFactor = this.projection.hasCoordinates ? -1 : 1, scaleX = this.getScale(), scaleY = scaleX * flipFactor, translateX = x + width / 2 - projectedCenter[0] * scaleX, translateY = y + height / 2 - projectedCenter[1] * scaleY;
        return { scaleX: scaleX, scaleY: scaleY, translateX: translateX, translateY: translateY };
    };
    /**
     * Convert map coordinates in longitude/latitude to pixels
     *
     * @function Highcharts.MapView#lonLatToPixels
     * @since 10.0.0
     * @param  {Highcharts.MapLonLatObject} lonLat
     *         The map coordinates
     * @return {Highcharts.PositionObject|undefined}
     *         The pixel position
     */
    MapView.prototype.lonLatToPixels = function (lonLat) {
        var pos = this.lonLatToProjectedUnits(lonLat);
        if (pos) {
            return this.projectedUnitsToPixels(pos);
        }
    };
    /**
     * Get projected units from longitude/latitude. Insets are accounted for.
     * Returns an object with x and y values corresponding to positions on the
     * projected plane.
     *
     * @requires modules/map
     *
     * @function Highcharts.MapView#lonLatToProjectedUnits
     *
     * @since 10.0.0
     * @sample maps/series/latlon-to-point/ Find a point from lon/lat
     *
     * @param {Highcharts.MapLonLatObject} lonLat Coordinates.
     *
     * @return {Highcharts.ProjectedXY} X and Y coordinates in terms of
     *      projected values
     */
    MapView.prototype.lonLatToProjectedUnits = function (lonLat) {
        var chart = this.chart, mapTransforms = chart.mapTransforms;
        // Legacy, built-in transforms
        if (mapTransforms) {
            for (var transform in mapTransforms) {
                if (Object.hasOwnProperty.call(mapTransforms, transform) &&
                    mapTransforms[transform].hitZone) {
                    var coords = chart.transformFromLatLon(lonLat, mapTransforms[transform]);
                    if (coords && pointInPolygon(coords, mapTransforms[transform].hitZone.coordinates[0])) {
                        return coords;
                    }
                }
            }
            return chart.transformFromLatLon(lonLat, mapTransforms['default'] // eslint-disable-line dot-notation
            );
        }
        // Handle insets
        for (var _i = 0, _a = this.insets; _i < _a.length; _i++) {
            var inset = _a[_i];
            if (inset.options.geoBounds &&
                pointInPolygon({ x: lonLat.lon, y: lonLat.lat }, inset.options.geoBounds.coordinates[0])) {
                var insetProjectedPoint = inset.projection.forward([lonLat.lon, lonLat.lat]), pxPoint = inset.projectedUnitsToPixels({ x: insetProjectedPoint[0], y: insetProjectedPoint[1] });
                return this.pixelsToProjectedUnits(pxPoint);
            }
        }
        var point = this.projection.forward([lonLat.lon, lonLat.lat]);
        if (!point.outside) {
            return { x: point[0], y: point[1] };
        }
    };
    /**
     * Calculate longitude/latitude values for a point or position. Returns an
     * object with the numeric properties `lon` and `lat`.
     *
     * @requires modules/map
     *
     * @function Highcharts.MapView#projectedUnitsToLonLat
     *
     * @since 10.0.0
     *
     * @sample maps/demo/latlon-advanced/ Advanced lat/lon demo
     *
     * @param {Highcharts.Point|Highcharts.ProjectedXY} point
     *        A `Point` instance or anything containing `x` and `y` properties
     *        with numeric values.
     *
     * @return {Highcharts.MapLonLatObject|undefined} An object with `lat` and
     *         `lon` properties.
     */
    MapView.prototype.projectedUnitsToLonLat = function (point) {
        var chart = this.chart, mapTransforms = chart.mapTransforms;
        // Legacy, built-in transforms
        if (mapTransforms) {
            for (var transform in mapTransforms) {
                if (Object.hasOwnProperty.call(mapTransforms, transform) &&
                    mapTransforms[transform].hitZone &&
                    pointInPolygon(point, mapTransforms[transform].hitZone.coordinates[0])) {
                    return chart.transformToLatLon(point, mapTransforms[transform]);
                }
            }
            return chart.transformToLatLon(point, mapTransforms['default'] // eslint-disable-line dot-notation
            );
        }
        var pxPoint = this.projectedUnitsToPixels(point);
        for (var _i = 0, _a = this.insets; _i < _a.length; _i++) {
            var inset = _a[_i];
            if (inset.hitZone &&
                pointInPolygon(pxPoint, inset.hitZone.coordinates[0])) {
                var insetProjectedPoint = inset
                    .pixelsToProjectedUnits(pxPoint), coordinates_1 = inset.projection.inverse([insetProjectedPoint.x, insetProjectedPoint.y]);
                return { lon: coordinates_1[0], lat: coordinates_1[1] };
            }
        }
        var coordinates = this.projection.inverse([point.x, point.y]);
        return { lon: coordinates[0], lat: coordinates[1] };
    };
    MapView.prototype.redraw = function (animation) {
        this.chart.series.forEach(function (s) {
            if (s.useMapGeometry) {
                s.isDirty = true;
            }
        });
        this.chart.redraw(animation);
    };
    /**
     * Set the view to given center and zoom values.
     * @function Highcharts.MapView#setView
     * @param {Highcharts.LonLatArray|undefined} center
     *        The center point
     * @param {number} zoom
     *        The zoom level
     * @param {boolean} [redraw=true]
     *        Whether to redraw immediately
     * @param {boolean|Partial<Highcharts.AnimationOptionsObject>} [animation]
     *        Animation options for the redraw
     *
     * @sample maps/mapview/setview
     *        Set the view programmatically
     */
    MapView.prototype.setView = function (center, zoom, redraw, animation) {
        if (redraw === void 0) { redraw = true; }
        if (center) {
            this.center = center;
        }
        if (typeof zoom === 'number') {
            if (typeof this.minZoom === 'number') {
                zoom = Math.max(zoom, this.minZoom);
            }
            if (typeof this.options.maxZoom === 'number') {
                zoom = Math.min(zoom, this.options.maxZoom);
            }
            this.zoom = zoom;
        }
        var bounds = this.getProjectedBounds();
        if (bounds) {
            var projectedCenter = this.projection.forward(this.center), _a = this.playingField, x = _a.x, y = _a.y, width = _a.width, height = _a.height, scale = this.getScale(), bottomLeft = this.projectedUnitsToPixels({
                x: bounds.x1,
                y: bounds.y1
            }), topRight = this.projectedUnitsToPixels({
                x: bounds.x2,
                y: bounds.y2
            }), boundsCenterProjected = [
                (bounds.x1 + bounds.x2) / 2,
                (bounds.y1 + bounds.y2) / 2
            ];
            // Constrain to data bounds
            // Pixel coordinate system is reversed vs projected
            var x1 = bottomLeft.x, y1 = topRight.y, x2 = topRight.x, y2 = bottomLeft.y;
            // Map smaller than plot area, center it
            if (x2 - x1 < width) {
                projectedCenter[0] = boundsCenterProjected[0];
                // Off west
            }
            else if (x1 < x && x2 < x + width) {
                // Adjust eastwards
                projectedCenter[0] += Math.max(x1 - x, x2 - width - x) / scale;
                // Off east
            }
            else if (x2 > x + width && x1 > x) {
                // Adjust westwards
                projectedCenter[0] += Math.min(x2 - width - x, x1 - x) / scale;
            }
            // Map smaller than plot area, center it
            if (y2 - y1 < height) {
                projectedCenter[1] = boundsCenterProjected[1];
                // Off north
            }
            else if (y1 < y && y2 < y + height) {
                // Adjust southwards
                projectedCenter[1] -= Math.max(y1 - y, y2 - height - y) / scale;
                // Off south
            }
            else if (y2 > y + height && y1 > y) {
                // Adjust northwards
                projectedCenter[1] -= Math.min(y2 - height - y, y1 - y) / scale;
            }
            this.center = this.projection.inverse(projectedCenter);
            this.insets.forEach(function (inset) {
                if (inset.options.field) {
                    inset.hitZone = inset.getHitZone();
                    inset.playingField = inset.getField();
                }
            });
            this.render();
        }
        fireEvent(this, 'afterSetView');
        if (redraw) {
            this.redraw(animation);
        }
    };
    /**
     * Convert projected units to pixel position
     *
     * @function Highcharts.MapView#projectedUnitsToPixels
     * @param {Highcharts.PositionObject} pos
     *        The position in projected units
     * @return {Highcharts.PositionObject} The position in pixels
     */
    MapView.prototype.projectedUnitsToPixels = function (pos) {
        var scale = this.getScale(), projectedCenter = this.projection.forward(this.center), field = this.playingField, centerPxX = field.x + field.width / 2, centerPxY = field.y + field.height / 2;
        var x = centerPxX - scale * (projectedCenter[0] - pos.x);
        var y = centerPxY + scale * (projectedCenter[1] - pos.y);
        return { x: x, y: y };
    };
    /**
     * Convert pixel position to longitude and latitude.
     *
     * @function Highcharts.MapView#pixelsToLonLat
     * @since 10.0.0
     * @param  {Highcharts.PositionObject} pos
     *         The position in pixels
     * @return {Highcharts.MapLonLatObject|undefined}
     *         The map coordinates
     */
    MapView.prototype.pixelsToLonLat = function (pos) {
        return this.projectedUnitsToLonLat(this.pixelsToProjectedUnits(pos));
    };
    /**
     * Convert pixel position to projected units
     *
     * @function Highcharts.MapView#pixelsToProjectedUnits
     * @param {Highcharts.PositionObject} pos
     *        The position in pixels
     * @return {Highcharts.PositionObject} The position in projected units
     */
    MapView.prototype.pixelsToProjectedUnits = function (pos) {
        var x = pos.x, y = pos.y, scale = this.getScale(), projectedCenter = this.projection.forward(this.center), field = this.playingField, centerPxX = field.x + field.width / 2, centerPxY = field.y + field.height / 2;
        var projectedX = projectedCenter[0] + (x - centerPxX) / scale;
        var projectedY = projectedCenter[1] - (y - centerPxY) / scale;
        return { x: projectedX, y: projectedY };
    };
    MapView.prototype.setUpEvents = function () {
        var _this = this;
        var chart = this.chart;
        // Set up panning for maps. In orthographic projections the globe will
        // rotate, otherwise adjust the map center.
        var mouseDownCenterProjected;
        var mouseDownKey;
        var mouseDownRotation;
        var onPan = function (e) {
            var pinchDown = chart.pointer.pinchDown, projection = _this.projection;
            var mouseDownX = chart.mouseDownX, mouseDownY = chart.mouseDownY;
            if (pinchDown.length === 1) {
                mouseDownX = pinchDown[0].chartX;
                mouseDownY = pinchDown[0].chartY;
            }
            if (typeof mouseDownX === 'number' &&
                typeof mouseDownY === 'number') {
                var key = mouseDownX + "," + mouseDownY, _a = e.originalEvent, chartX = _a.chartX, chartY = _a.chartY;
                // Reset starting position
                if (key !== mouseDownKey) {
                    mouseDownKey = key;
                    mouseDownCenterProjected = _this.projection
                        .forward(_this.center);
                    mouseDownRotation = (_this.projection.options.rotation || [0, 0]).slice();
                }
                // Get the natural zoom level of the projection itself when
                // zoomed to view the full world
                var worldBounds = projection.def && projection.def.bounds, worldZoom = (worldBounds &&
                    zoomFromBounds(worldBounds, _this.playingField)) || -Infinity;
                // Panning rotates the globe
                if (projection.options.name === 'Orthographic' &&
                    // ... but don't rotate if we're loading only a part of the
                    // world
                    (_this.minZoom || Infinity) < worldZoom * 1.1) {
                    // Empirical ratio where the globe rotates roughly the same
                    // speed as moving the pointer across the center of the
                    // projection
                    var ratio = 440 / (_this.getScale() * Math.min(chart.plotWidth, chart.plotHeight));
                    if (mouseDownRotation) {
                        var lon = (mouseDownX - chartX) * ratio -
                            mouseDownRotation[0], lat = clamp(-mouseDownRotation[1] -
                            (mouseDownY - chartY) * ratio, -80, 80), zoom = _this.zoom;
                        _this.update({
                            projection: {
                                rotation: [-lon, -lat]
                            }
                        }, false);
                        _this.zoom = zoom;
                        chart.redraw(false);
                    }
                }
                else {
                    var scale = _this.getScale();
                    var newCenter = _this.projection.inverse([
                        mouseDownCenterProjected[0] +
                            (mouseDownX - chartX) / scale,
                        mouseDownCenterProjected[1] -
                            (mouseDownY - chartY) / scale
                    ]);
                    _this.setView(newCenter, void 0, true, false);
                }
                e.preventDefault();
            }
        };
        addEvent(chart, 'pan', onPan);
        addEvent(chart, 'touchpan', onPan);
        // Perform the map zoom by selection
        addEvent(chart, 'selection', function (evt) {
            // Zoom in
            if (!evt.resetSelection) {
                var x = evt.x - chart.plotLeft;
                var y = evt.y - chart.plotTop;
                var _a = _this.pixelsToProjectedUnits({ x: x, y: y }), y1 = _a.y, x1 = _a.x;
                var _b = _this.pixelsToProjectedUnits({ x: x + evt.width, y: y + evt.height }), y2 = _b.y, x2 = _b.x;
                _this.fitToBounds({ x1: x1, y1: y1, x2: x2, y2: y2 }, void 0, true, evt.originalEvent.touches ?
                    // On touch zoom, don't animate, since we're already in
                    // transformed zoom preview
                    false :
                    // On mouse zoom, obey the chart-level animation
                    void 0);
                // Only for mouse. Touch users can pinch out.
                if (!/^touch/.test((evt.originalEvent.type))) {
                    chart.showResetZoom();
                }
                evt.preventDefault();
                // Reset zoom
            }
            else {
                _this.zoomBy();
            }
        });
    };
    MapView.prototype.render = function () {
        // We need a group for the insets
        if (!this.group) {
            this.group = this.chart.renderer.g('map-view')
                .attr({ zIndex: 4 })
                .add();
        }
    };
    /**
     * Update the view with given options
     *
     * @function Highcharts.MapView#update
     *
     * @param {Partial<Highcharts.MapViewOptions>} options
     *        The new map view options to apply
     * @param {boolean} [redraw=true]
     *        Whether to redraw immediately
     * @param {boolean|Partial<Highcharts.AnimationOptionsObject>} [animation]
     *        The animation to apply to a the redraw
     */
    MapView.prototype.update = function (options, redraw, animation) {
        if (redraw === void 0) { redraw = true; }
        var newProjection = options.projection;
        var isDirtyProjection = newProjection && ((Projection.toString(newProjection) !==
            Projection.toString(this.options.projection))), isDirtyInsets = false;
        merge(true, this.userOptions, options);
        merge(true, this.options, options);
        // If anything changed with the insets, destroy them all and create
        // again below
        if ('insets' in options) {
            this.insets.forEach(function (inset) { return inset.destroy(); });
            this.insets.length = 0;
            isDirtyInsets = true;
        }
        if (isDirtyProjection || isDirtyInsets) {
            this.chart.series.forEach(function (series) {
                var groups = series.transformGroups;
                if (series.clearBounds) {
                    series.clearBounds();
                }
                series.isDirty = true;
                series.isDirtyData = true;
                // Destroy inset transform groups
                if (isDirtyInsets && groups) {
                    while (groups.length > 1) {
                        var group = groups.pop();
                        if (group) {
                            group.destroy();
                        }
                    }
                }
            });
            if (isDirtyProjection) {
                this.projection = new Projection(this.options.projection);
            }
            // Create new insets
            if (isDirtyInsets) {
                this.createInsets();
            }
            // Fit to natural bounds if center/zoom are not explicitly given
            if (!options.center && !isNumber(options.zoom)) {
                this.fitToBounds(void 0, void 0, false);
            }
        }
        if (options.center || isNumber(options.zoom)) {
            this.setView(this.options.center, options.zoom, false);
        }
        if (redraw) {
            this.chart.redraw(animation);
        }
    };
    /**
     * Zoom the map view by a given number
     *
     * @function Highcharts.MapView#zoomBy
     *
     * @param {number|undefined} [howMuch]
     *        The amount of zoom to apply. 1 zooms in on half the current view,
     *        -1 zooms out. Pass `undefined` to zoom to the full bounds of the
     *        map.
     * @param {Highcharts.LonLatArray} [coords]
     *        Optional map coordinates to keep fixed
     * @param {Array<number>} [chartCoords]
     *        Optional chart coordinates to keep fixed, in pixels
     * @param {boolean|Partial<Highcharts.AnimationOptionsObject>} [animation]
     *        The animation to apply to a the redraw
     */
    MapView.prototype.zoomBy = function (howMuch, coords, chartCoords, animation) {
        var chart = this.chart;
        var projectedCenter = this.projection.forward(this.center);
        // let { x, y } = coords || {};
        var _a = coords ? this.projection.forward(coords) : [], x = _a[0], y = _a[1];
        if (typeof howMuch === 'number') {
            var zoom = this.zoom + howMuch;
            var center = void 0;
            // Keep chartX and chartY stationary - convert to lat and lng
            if (chartCoords) {
                var chartX = chartCoords[0], chartY = chartCoords[1];
                var scale = this.getScale();
                var offsetX = chartX - chart.plotLeft - chart.plotWidth / 2;
                var offsetY = chartY - chart.plotTop - chart.plotHeight / 2;
                x = projectedCenter[0] + offsetX / scale;
                y = projectedCenter[1] + offsetY / scale;
            }
            // Keep lon and lat stationary by adjusting the center
            if (typeof x === 'number' && typeof y === 'number') {
                var scale = 1 - Math.pow(2, this.zoom) / Math.pow(2, zoom);
                // const projectedCenter = this.projection.forward(this.center);
                var offsetX = projectedCenter[0] - x;
                var offsetY = projectedCenter[1] - y;
                projectedCenter[0] -= offsetX * scale;
                projectedCenter[1] += offsetY * scale;
                center = this.projection.inverse(projectedCenter);
            }
            this.setView(center, zoom, void 0, animation);
            // Undefined howMuch => reset zoom
        }
        else {
            this.fitToBounds(void 0, void 0, void 0, animation);
        }
    };
    /* *
     * Return the composite bounding box of a collection of bounding boxes
     */
    MapView.compositeBounds = function (arrayOfBounds) {
        if (arrayOfBounds.length) {
            return arrayOfBounds
                .slice(1)
                .reduce(function (acc, cur) {
                acc.x1 = Math.min(acc.x1, cur.x1);
                acc.y1 = Math.min(acc.y1, cur.y1);
                acc.x2 = Math.max(acc.x2, cur.x2);
                acc.y2 = Math.max(acc.y2, cur.y2);
                return acc;
            }, merge(arrayOfBounds[0]));
        }
        return;
    };
    return MapView;
}());
// Putting this in the same file due to circular dependency with MapView
var MapViewInset = /** @class */ (function (_super) {
    __extends(MapViewInset, _super);
    function MapViewInset(mapView, options) {
        var _this = _super.call(this, mapView.chart, options) || this;
        _this.id = options.id;
        _this.mapView = mapView;
        _this.options = merge(defaultInsetsOptions, options);
        _this.allBounds = [];
        if (_this.options.geoBounds) {
            // The path in projected units in the map view's main projection.
            // This is used for hit testing where the points should render.
            var path = mapView.projection.path(_this.options.geoBounds);
            _this.geoBoundsProjectedBox = boundsFromPath(path);
            _this.geoBoundsProjectedPolygon = path.map(function (segment) { return [
                segment[1] || 0,
                segment[2] || 0
            ]; });
        }
        return _this;
    }
    // Get the playing field in pixels
    MapViewInset.prototype.getField = function (padded) {
        if (padded === void 0) { padded = true; }
        var hitZone = this.hitZone;
        if (hitZone) {
            var padding = padded ? this.padding : [0, 0, 0, 0], polygon = hitZone.coordinates[0], xs = polygon.map(function (xy) { return xy[0]; }), ys = polygon.map(function (xy) { return xy[1]; }), x = Math.min.apply(0, xs) + padding[3], x2 = Math.max.apply(0, xs) - padding[1], y = Math.min.apply(0, ys) + padding[0], y2 = Math.max.apply(0, ys) - padding[2];
            if (isNumber(x) && isNumber(y)) {
                return {
                    x: x,
                    y: y,
                    width: x2 - x,
                    height: y2 - y
                };
            }
        }
        // Fall back to plot area
        return _super.prototype.getField.call(this, padded);
    };
    // Get the hit zone in pixels
    MapViewInset.prototype.getHitZone = function () {
        var _a = this, chart = _a.chart, mapView = _a.mapView, options = _a.options, coordinates = (options.field || {}).coordinates;
        if (coordinates) {
            var polygon = coordinates[0];
            if (options.units === 'percent') {
                var relativeTo_1 = options.relativeTo === 'mapBoundingBox' &&
                    mapView.getMapBBox() ||
                    merge(chart.plotBox, { x: 0, y: 0 });
                polygon = polygon.map(function (xy) { return [
                    relativeLength(xy[0] + "%", relativeTo_1.width, relativeTo_1.x),
                    relativeLength(xy[1] + "%", relativeTo_1.height, relativeTo_1.y)
                ]; });
            }
            return {
                type: 'Polygon',
                coordinates: [polygon]
            };
        }
    };
    MapViewInset.prototype.getProjectedBounds = function () {
        return MapView.compositeBounds(this.allBounds);
    };
    // Determine whether a point on the main projected plane is inside the
    // geoBounds of the inset.
    MapViewInset.prototype.isInside = function (point) {
        var _a = this, geoBoundsProjectedBox = _a.geoBoundsProjectedBox, geoBoundsProjectedPolygon = _a.geoBoundsProjectedPolygon;
        return Boolean(
        // First we do a pre-pass to check whether the test point is inside
        // the rectangular bounding box of the polygon. This is less
        // expensive and will rule out most cases.
        geoBoundsProjectedBox &&
            point.x >= geoBoundsProjectedBox.x1 &&
            point.x <= geoBoundsProjectedBox.x2 &&
            point.y >= geoBoundsProjectedBox.y1 &&
            point.y <= geoBoundsProjectedBox.y2 &&
            // Next, do the more expensive check whether the point is inside the
            // polygon itself.
            geoBoundsProjectedPolygon &&
            pointInPolygon(point, geoBoundsProjectedPolygon));
    };
    // Render the map view inset with the border path
    MapViewInset.prototype.render = function () {
        var _a = this, chart = _a.chart, mapView = _a.mapView, options = _a.options, borderPath = options.borderPath || options.field;
        if (borderPath && mapView.group) {
            var animate = true;
            if (!this.border) {
                this.border = chart.renderer
                    .path()
                    .addClass('highcharts-mapview-inset-border')
                    .add(mapView.group);
                animate = false;
            }
            if (!chart.styledMode) {
                this.border.attr({
                    stroke: options.borderColor,
                    'stroke-width': options.borderWidth
                });
            }
            var crisp_1 = Math.round(this.border.strokeWidth()) % 2 / 2, field_1 = (options.relativeTo === 'mapBoundingBox' &&
                mapView.getMapBBox()) || mapView.playingField;
            var d = (borderPath.coordinates || []).reduce(function (d, lineString) {
                return lineString.reduce(function (d, point, i) {
                    var x = point[0], y = point[1];
                    if (options.units === 'percent') {
                        x = chart.plotLeft + relativeLength(x + "%", field_1.width, field_1.x);
                        y = chart.plotTop + relativeLength(y + "%", field_1.height, field_1.y);
                    }
                    x = Math.floor(x) + crisp_1;
                    y = Math.floor(y) + crisp_1;
                    d.push(i === 0 ? ['M', x, y] : ['L', x, y]);
                    return d;
                }, d);
            }, []);
            // Apply the border path
            this.border[animate ? 'animate' : 'attr']({ d: d });
        }
    };
    MapViewInset.prototype.destroy = function () {
        if (this.border) {
            this.border = this.border.destroy();
        }
        this.eventsToUnbind.forEach(function (f) { return f(); });
    };
    // No chart-level events for insets
    MapViewInset.prototype.setUpEvents = function () { };
    return MapViewInset;
}(MapView));
// Initialize the MapView after initialization, but before firstRender
addEvent(MapChart, 'afterInit', function () {
    this.mapView = new MapView(this, this.options.mapView);
});
export default MapView;


text:
bool D3D::CompileShader(
	const std::string& path,
	const std::string& entryPoint,
	const std::string& target,
	const char* source,
	size_t sourceLen,
	uint8_t** outBytecode,
	size_t* outBytecodeLen,
	std::string& errorMsg)
{
	ID3DBlob* shader = nullptr;
	ID3DBlob* errors = nullptr;

	const HRESULT hRes = D3DCompile(
		source,
		sourceLen,
		path.c_str(),
		nullptr,                           // No defines.
		D3D_COMPILE_STANDARD_FILE_INCLUDE, // Use default include handler (FIXME: create "smart" one).
		entryPoint.c_str(),
		target.c_str(),
#if defined(_DEBUG) || defined(_DESIGN)
		D3DCOMPILE_OPTIMIZATION_LEVEL3,
#else
		D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE_SKIP_VALIDATION,
#endif
		0,
		&shader,
		&errors);

	if (S_OK != hRes)
	{
		if (nullptr != errors)
		{
			errorMsg = std::string(reinterpret_cast<char*>(errors->GetBufferPointer()));

			// Not using D3D_ASSERT_MSG as this may be called from a job thread so I don't want a throw.
			ASSERT_MSG(0, errorMsg.c_str());
		}

		SAFE_RELEASE(errors);
		return false;
	}

	ASSERT(nullptr != shader && shader->GetBufferSize() > 0);
	*outBytecode = new uint8_t[shader->GetBufferSize()];
	memcpy(*outBytecode, reinterpret_cast<uint8_t*>(shader->GetBufferPointer()), (size_t) shader->GetBufferSize());
	*outBytecodeLen = (size_t) shader->GetBufferSize();
	shader->Release();

	return true;
}

redpajama_set_name: RedPajamaGithub


text:
namespace net {

namespace {

// When we initialize the SocketPool, we allocate kInitialPoolSize sockets.
// When we allocate a socket, we ensure we have at least kAllocateMinSize
// sockets to choose from.  Freed sockets are not retained.

// On Windows, we can't request specific (random) ports, since that will
// trigger firewall prompts, so request default ones, but keep a pile of
// them.  Everywhere else, request fresh, random ports each time.
#if defined(OS_WIN)
const DatagramSocket::BindType kBindType = DatagramSocket::DEFAULT_BIND;
const unsigned kInitialPoolSize = 256;
const unsigned kAllocateMinSize = 256;
#else
const DatagramSocket::BindType kBindType = DatagramSocket::RANDOM_BIND;
const unsigned kInitialPoolSize = 0;
const unsigned kAllocateMinSize = 1;
#endif

} // namespace

DnsSocketPool::DnsSocketPool(ClientSocketFactory* socket_factory,
                             const RandIntCallback& rand_int_callback)
    : socket_factory_(socket_factory),
      rand_int_callback_(rand_int_callback),
      net_log_(NULL),
      nameservers_(NULL),
      initialized_(false) {}

void DnsSocketPool::InitializeInternal(
    const std::vector<IPEndPoint>* nameservers,
    NetLog* net_log) {
  DCHECK(nameservers);
  DCHECK(!initialized_);

  net_log_ = net_log;
  nameservers_ = nameservers;
  initialized_ = true;
}

std::unique_ptr<StreamSocket> DnsSocketPool::CreateTCPSocket(
    unsigned server_index,
    const NetLogSource& source) {
  DCHECK_LT(server_index, nameservers_->size());

  return std::unique_ptr<StreamSocket>(
      socket_factory_->CreateTransportClientSocket(
          AddressList((*nameservers_)[server_index]), NULL, net_log_, source));
}

std::unique_ptr<DatagramClientSocket> DnsSocketPool::CreateConnectedSocket(
    unsigned server_index) {
  DCHECK_LT(server_index, nameservers_->size());

  std::unique_ptr<DatagramClientSocket> socket;

  NetLogSource no_source;
  socket = socket_factory_->CreateDatagramClientSocket(kBindType, net_log_,
                                                       no_source);

  if (socket.get()) {
    int rv = socket->Connect((*nameservers_)[server_index]);
    if (rv != OK) {
      DVLOG(1) << "Failed to connect socket: " << rv;
      socket.reset();
    }
  } else {
    DVLOG(1) << "Failed to create socket.";
  }

  return socket;
}

int DnsSocketPool::GetRandomInt(int min, int max) {
  return rand_int_callback_.Run(min, max);
}

class NullDnsSocketPool : public DnsSocketPool {
 public:
  NullDnsSocketPool(ClientSocketFactory* factory,
                    const RandIntCallback& rand_int_callback)
      : DnsSocketPool(factory, rand_int_callback) {}

  void Initialize(const std::vector<IPEndPoint>* nameservers,
                  NetLog* net_log) override {
    InitializeInternal(nameservers, net_log);
  }

  std::unique_ptr<DatagramClientSocket> AllocateSocket(
      unsigned server_index) override {
    return CreateConnectedSocket(server_index);
  }

  void FreeSocket(unsigned server_index,
                  std::unique_ptr<DatagramClientSocket> socket) override {}

 private:
  DISALLOW_COPY_AND_ASSIGN(NullDnsSocketPool);
};

// static
std::unique_ptr<DnsSocketPool> DnsSocketPool::CreateNull(
    ClientSocketFactory* factory,
    const RandIntCallback& rand_int_callback) {
  return std::unique_ptr<DnsSocketPool>(
      new NullDnsSocketPool(factory, rand_int_callback));
}

class DefaultDnsSocketPool : public DnsSocketPool {
 public:
  DefaultDnsSocketPool(ClientSocketFactory* factory,
                       const RandIntCallback& rand_int_callback)
      : DnsSocketPool(factory, rand_int_callback){};

  ~DefaultDnsSocketPool() override;

  void Initialize(const std::vector<IPEndPoint>* nameservers,
                  NetLog* net_log) override;

  std::unique_ptr<DatagramClientSocket> AllocateSocket(
      unsigned server_index) override;

  void FreeSocket(unsigned server_index,
                  std::unique_ptr<DatagramClientSocket> socket) override;

 private:
  void FillPool(unsigned server_index, unsigned size);

  typedef std::vector<std::unique_ptr<DatagramClientSocket>> SocketVector;

  std::vector<SocketVector> pools_;

  DISALLOW_COPY_AND_ASSIGN(DefaultDnsSocketPool);
};

DnsSocketPool::~DnsSocketPool() = default;

// static
std::unique_ptr<DnsSocketPool> DnsSocketPool::CreateDefault(
    ClientSocketFactory* factory,
    const RandIntCallback& rand_int_callback) {
  return std::unique_ptr<DnsSocketPool>(
      new DefaultDnsSocketPool(factory, rand_int_callback));
}

void DefaultDnsSocketPool::Initialize(
    const std::vector<IPEndPoint>* nameservers,
    NetLog* net_log) {
  InitializeInternal(nameservers, net_log);

  DCHECK(pools_.empty());
  const unsigned num_servers = nameservers->size();
  pools_.resize(num_servers);
  for (unsigned server_index = 0; server_index < num_servers; ++server_index)
    FillPool(server_index, kInitialPoolSize);
}

DefaultDnsSocketPool::~DefaultDnsSocketPool() = default;

std::unique_ptr<DatagramClientSocket> DefaultDnsSocketPool::AllocateSocket(
    unsigned server_index) {
  DCHECK_LT(server_index, pools_.size());
  SocketVector& pool = pools_[server_index];

  FillPool(server_index, kAllocateMinSize);
  if (pool.size() == 0) {
    DVLOG(1) << "No DNS sockets available in pool " << server_index << "!";
    return std::unique_ptr<DatagramClientSocket>();
  }

  if (pool.size() < kAllocateMinSize) {
    DVLOG(1) << "Low DNS port entropy: wanted " << kAllocateMinSize
             << " sockets to choose from, but only have " << pool.size()
             << " in pool " << server_index << ".";
  }

  unsigned socket_index = GetRandomInt(0, pool.size() - 1);
  std::unique_ptr<DatagramClientSocket> socket = std::move(pool[socket_index]);
  pool[socket_index] = std::move(pool.back());
  pool.pop_back();

  return socket;
}

void DefaultDnsSocketPool::FreeSocket(
    unsigned server_index,
    std::unique_ptr<DatagramClientSocket> socket) {
  DCHECK_LT(server_index, pools_.size());
}

void DefaultDnsSocketPool::FillPool(unsigned server_index, unsigned size) {
  SocketVector& pool = pools_[server_index];

  for (unsigned pool_index = pool.size(); pool_index < size; ++pool_index) {
    std::unique_ptr<DatagramClientSocket> socket =
        CreateConnectedSocket(server_index);
    if (!socket)
      break;
    pool.push_back(std::move(socket));
  }
}

} // namespace net


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Revis. gen. pl. (Leipzig) 3: 441 (1898)

#### Original name
Phallus caninus Huds., 1778

### Remarks
null


text:
package projects.numbers;

import org.junit.Assert;
import org.junit.Test;

public class TestPiToNthDigit {

	@Test
	public void test() {
		Assert.assertEquals("3.1", PiToNthDigit.calculatePi(1));
		Assert.assertEquals("3.14", PiToNthDigit.calculatePi(2));
		Assert.assertEquals("3.141", PiToNthDigit.calculatePi(3));
		Assert.assertEquals("3.1415", PiToNthDigit.calculatePi(4));
		Assert.assertEquals("3.14159", PiToNthDigit.calculatePi(5));
		Assert.assertEquals("3.141592", PiToNthDigit.calculatePi(6));
		Assert.assertEquals("3.1415926", PiToNthDigit.calculatePi(7));
		Assert.assertEquals("3.14159265", PiToNthDigit.calculatePi(8));
		Assert.assertEquals("3.141592653", PiToNthDigit.calculatePi(9));
		Assert.assertEquals("3.14159265359", PiToNthDigit.calculatePi(10));
	}

}


text:
package org.apache.sqoop.model;

import org.apache.sqoop.classification.InterfaceAudience;
import org.apache.sqoop.classification.InterfaceStability;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Field annotation. Each field that user might change in configuration object
 * need to have this annotation.
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Input {
  /**
   * Sqoop will ensure that sensitive information will not be easily
   * accessible.
   *
   * @return True if field is sensitive
   */
  boolean sensitive() default false;

  /**
   * Indicates the entity that can edit the input's values, all inputs are
   * created/deleted only by the connector code, other entities do not have
   * access to either create/delete an input
   *
   * @return editable
   */
  InputEditable editable() default InputEditable.ANY;

  /**
   * Maximal length of field if applicable.
   *
   * @return Maximal length
   */
  short size() default -1;

  /**
   * In-order to express dependency on other inputs, the value supports a comma
   * separated list of other inputs in the config class. It validates the
   * attribute value obeys the expected conditions
   */
  String overrides() default "";

  /**
   * List of validators associated with this input.
   *
   * @return
   */
  Validator[] validators() default {};

}


text:
<!doctype html>

    <meta charset="utf-8">

    <title>Guitar Chords</title>
    <meta name="description" content="Guitar Chords">
    <meta name="author" content="Nadun">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.0/gh-fork-ribbon.min.css" />

    <link rel="stylesheet" href="https://oss.maxcdn.com/libs/normalize-css/3.0.0/normalize.min.css">
    <link rel="stylesheet" href="./styles.css">

    Fork
        me on GitHub

Chords Transposer

            Chords Transposer can manipulate guitar chords in many ways such as Guitar Chords parsing and Transposing.

Usage

Click parse to filter raw song into chords and song lines.

Click Transpose G# to transpose song from this scale to given scale (in this scenario G to G#)

Click Transpose +1 to increase scale by 1 semitone

Click Transpose -1 to decrease scale by 1 semitone

        <textarea id="src_id" cols="67" rows="20" placeholder="Raw song(s) to parse"></textarea>

        <input type="button" value="Parse" onclick="parse('src_id','dst_id')" />
        <input type="button" value="Transpose to G#" onclick="shift('src_id','dst_id','G','G#')" />
        <input type="button" value="Transpose +1" onclick="shiftPlus('src_id','dst_id')" />
        <input type="button" value="Transpose -1" onclick="shiftMinus('src_id','dst_id')" />

example #1:

| Gm | F | Gm | Eb |
| B  | F | B | Gm |
Gm  F    Gm Eb     B   F     B  Gm
Mandaramen eha, dew duwak athi bala
B    Cm    B    F
Mata yanna denna siyumeliye
Suwanda soya soya
B  Cm       B   F
Me raththriyama nisansalai
Gm
Eth oba nisa

example #2:

[Intro]
----------------------------------------
|	Eb | - | Ab | - |
| Eb | - | Cm | Dm |
| Fm | - | Cm | Bb |
| Eb |

[Chorus]
----------------------------------------
    Eb
Anganavo
Bb        Eb
Geethe Leewa
Bb         Eb
Thaale Damuwa
Eb           Bb        Ab        Bb
Sihinen mata keewa oba maage kiyala
    Eb
Anganavo
Rupikawo
Bb            Eb
Ranguman Ranguwa
     Bb         Eb
Mata Ama mee peuwa
         Bb       Ab       Bb      Eb
Inne obe loke dan inne man obage loke

About

            Chords Transposer was written by
            Nadun indunil.


text:
package com.github.ykrasik.jaci.commands;

import com.github.ykrasik.jaci.api.*;

/**
 * These are all the ways of declaring commands with optional params.
 * Optional params may either have a const default value (set in the annotation) or a default value that is supplied
 * at runtime via a supplier.
 * Primitives and their boxed version are interchangeable.
 *
 * @author Yevgeny Krasik
 */
@CommandPath("optionalParams")
public class OptionalParamsCommands {
    private CommandOutput output;

    @Command(description = "All params are optional, with const default values.")
    public void defaultConstValues(@BoolParam(value = "b", optional = true, defaultValue = true) boolean b,
                                   @IntParam(value = "i", optional = true, defaultValue = 5) int i,
                                   @DoubleParam(value = "d", optional = true, defaultValue = 4.5) double d,
                                   @StringParam(value = "str", optional = true, defaultValue = "default") String str) {
        output.message("defaultConstValues: b="+b+", i="+i+", d="+d+", str="+str);
    }

    @Command(description = "All params are optional, with default value suppliers.")
    public void defaultValueSuppliers(@BoolParam(value = "b", optional = true, defaultValueSupplier = "booleanSupplier") boolean b,
                                      @IntParam(value = "i", optional = true, defaultValueSupplier = "intSupplier") int i,
                                      @DoubleParam(value = "d", optional = true, defaultValueSupplier = "doubleSupplier") double d,
                                      @StringParam(value = "str", optional = true, defaultValueSupplier = "stringSupplier") String str) {
        output.message("defaultValueSuppliers: b="+b+", i="+i+", d="+d+", str="+str);
    }

    private Boolean booleanSupplier() {
        return true;
    }

    private int intSupplier() {
        return 2;
    }

    private double doubleSupplier() {
        return 3.5;
    }

    private String stringSupplier() {
        return "suppliedDefault";
    }
}


text:
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const experimental_utils_1 = require("@typescript-eslint/experimental-utils");
const util = __importStar(require("../util"));
exports.default = util.createRule({
    name: 'consistent-type-definitions',
    meta: {
        type: 'suggestion',
        docs: {
            description: 'Consistent with type definition either `interface` or `type`',
            category: 'Stylistic Issues',
            // too opinionated to be recommended
            recommended: false,
        },
        messages: {
            interfaceOverType: 'Use an `interface` instead of a `type`',
            typeOverInterface: 'Use a `type` instead of an `interface`',
        },
        schema: [
            {
                enum: ['interface', 'type'],
            },
        ],
        fixable: 'code',
    },
    defaultOptions: ['interface'],
    create(context, [option]) {
        const sourceCode = context.getSourceCode();
        return {
            "TSTypeAliasDeclaration[typeAnnotation.type='TSTypeLiteral']"(node) {
                if (option === 'interface') {
                    context.report({
                        node: node.id,
                        messageId: 'interfaceOverType',
                        fix(fixer) {
                            var _a;
                            const typeNode = (_a = node.typeParameters, (_a !== null && _a !== void 0 ? _a : node.id));
                            const fixes = [];
                            const firstToken = sourceCode.getFirstToken(node);
                            if (firstToken) {
                                fixes.push(fixer.replaceText(firstToken, 'interface'));
                                fixes.push(fixer.replaceTextRange([typeNode.range[1], node.typeAnnotation.range[0]], ' '));
                            }
                            const afterToken = sourceCode.getTokenAfter(node.typeAnnotation);
                            if (afterToken &&
                                afterToken.type === experimental_utils_1.AST_TOKEN_TYPES.Punctuator &&
                                afterToken.value === ';') {
                                fixes.push(fixer.remove(afterToken));
                            }
                            return fixes;
                        },
                    });
                }
            },
            TSInterfaceDeclaration(node) {
                if (option === 'type') {
                    context.report({
                        node: node.id,
                        messageId: 'typeOverInterface',
                        fix(fixer) {
                            var _a;
                            const typeNode = (_a = node.typeParameters, (_a !== null && _a !== void 0 ? _a : node.id));
                            const fixes = [];
                            const firstToken = sourceCode.getFirstToken(node);
                            if (firstToken) {
                                fixes.push(fixer.replaceText(firstToken, 'type'));
                                fixes.push(fixer.replaceTextRange([typeNode.range[1], node.body.range[0]], ' = '));
                            }
                            if (node.extends) {
                                node.extends.forEach(heritage => {
                                    const typeIdentifier = sourceCode.getText(heritage);
                                    fixes.push(fixer.insertTextAfter(node.body, ` & ${typeIdentifier}`));
                                });
                            }
                            return fixes;
                        },
                    });
                }
            },
        };
    },
});
//# sourceMappingURL=consistent-type-definitions.js.map


text:
package org.opencb.biodata.models.variant;

import java.util.List;

/**
 * @author Alejandro Aleman Ramos <aaleman@cipf.es>
 * @author Cristina Yenyxe Gonzalez Garcia <cyenyxe@ebi.ac.uk>
 */
public interface VariantFactory {

    public List<Variant> create(VariantSource source, String line);

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PriInfo>
	<ResourceMap name="Coding4Fun.Toolkit.Controls" version="1.0" primary="true">
		<Qualifiers/>
		<ResourceMapSubtree name="Files">
			<ResourceMapSubtree name="Coding4Fun.Toolkit.Controls">
				<NamedResource name="Coding4Fun.Toolkit.Controls.xr.xml" uri="ms-resource://Coding4Fun.Toolkit.Controls/Files/Coding4Fun.Toolkit.Controls/Coding4Fun.Toolkit.Controls.xr.xml">
					<Candidate type="Path">
						<Value>Coding4Fun.Toolkit.Controls\Coding4Fun.Toolkit.Controls.xr.xml</Value>
					</Candidate>
				</NamedResource>
				<ResourceMapSubtree name="Themes">
					<NamedResource name="Generic.xbf" uri="ms-resource://Coding4Fun.Toolkit.Controls/Files/Coding4Fun.Toolkit.Controls/Themes/Generic.xbf">
						<Candidate type="Path">
							<Value>Coding4Fun.Toolkit.Controls\Themes\Generic.xbf</Value>
						</Candidate>
					</NamedResource>
				</ResourceMapSubtree>
			</ResourceMapSubtree>
		</ResourceMapSubtree>
	</ResourceMap>
</PriInfo>


text:
package org.apache.drill.exec.physical.impl;

import java.util.List;

import org.apache.drill.common.DeferredException;
import org.apache.drill.exec.exception.OutOfMemoryException;
import org.apache.drill.exec.ops.OpProfileDef;
import org.apache.drill.exec.ops.OperatorContext;
import org.apache.drill.exec.ops.OperatorStats;
import org.apache.drill.exec.ops.OperatorUtilities;
import org.apache.drill.exec.ops.RootFragmentContext;
import org.apache.drill.exec.physical.base.PhysicalOperator;
import org.apache.drill.exec.proto.ExecProtos.FragmentHandle;
import org.apache.drill.exec.record.CloseableRecordBatch;
import org.apache.drill.exec.record.RecordBatch;
import org.apache.drill.exec.record.RecordBatch.IterOutcome;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class BaseRootExec implements RootExec {
  private static final Logger logger = LoggerFactory.getLogger(BaseRootExec.class);

  public static final String ENABLE_BATCH_DUMP_CONFIG = "drill.exec.debug.dump_batches";
  protected OperatorStats stats;
  protected OperatorContext oContext;
  protected RootFragmentContext fragmentContext;
  private List<CloseableRecordBatch> operators;

  public BaseRootExec(final RootFragmentContext fragmentContext, final PhysicalOperator config) throws OutOfMemoryException {
    this(fragmentContext, null, config);
  }

  public BaseRootExec(final RootFragmentContext fragmentContext, final OperatorContext oContext,
                      final PhysicalOperator config) throws OutOfMemoryException {
    if (oContext == null) {
      this.oContext = fragmentContext.newOperatorContext(config, stats);
    } else {
      this.oContext = oContext;
    }
    //Creating new stat for appending to list
    stats = new OperatorStats(new OpProfileDef(config.getOperatorId(),
        config.getOperatorType(), OperatorUtilities.getChildCount(config)),
      this.oContext.getAllocator());
    fragmentContext.getStats().addOperatorStats(this.stats);
    this.fragmentContext = fragmentContext;
  }

  void setOperators(List<CloseableRecordBatch> operators) {
    this.operators = operators;

    if (logger.isDebugEnabled()) {
      final StringBuilder sb = new StringBuilder();
      sb.append("BaseRootExec(");
      sb.append(Integer.toString(System.identityHashCode(this)));
      sb.append(") operators: ");
      for(final CloseableRecordBatch crb : operators) {
        sb.append(crb.getClass().getName());
        sb.append(' ');
        sb.append(Integer.toString(System.identityHashCode(crb)));
        sb.append(", ");
      }

      // Cut off the last trailing comma and space
      sb.setLength(sb.length() - 2);

      logger.debug(sb.toString());
    }
  }

  @Override
  public final boolean next() {
    assert stats != null;
    fragmentContext.getExecutorState().checkContinue();
    try {
      stats.startProcessing();
      return innerNext();
    } finally {
      stats.stopProcessing();
    }
  }

  public final IterOutcome next(final RecordBatch b){
    stats.stopProcessing();
    IterOutcome next;
    try {
      next = b.next();
    } finally {
      stats.startProcessing();
    }

    switch(next){
      case OK_NEW_SCHEMA:
        stats.batchReceived(0, b.getRecordCount(), true);
        break;
      case OK:
        stats.batchReceived(0, b.getRecordCount(), false);
        break;
      default:
    }
    return next;
  }

  public abstract boolean innerNext();

  @Override
  public void receivingFragmentFinished(final FragmentHandle handle) {
    logger.warn("Currently not handling FinishedFragment message");
  }

  @Override
  public void dumpBatches(Throwable t) {
    if (operators == null) {
      return;
    }
    if (!fragmentContext.getConfig().getBoolean(ENABLE_BATCH_DUMP_CONFIG)) {
      return;
    }

    CloseableRecordBatch leafMost = findLeaf(operators, t);
    if (leafMost == null) {
      // Don't know which batch failed.
      return;
    }
    int batchPosn = operators.indexOf(leafMost);
    final int numberOfBatchesToDump = Math.min(batchPosn + 1, 2);
    logger.error("Batch dump started: dumping last {} failed batches", numberOfBatchesToDump);
    // As batches are stored in a 'flat' List there is a need to filter out the failed batch
    // and a few of its parent (actual number of batches is set by a constant defined above)
    for (int i = 0; i < numberOfBatchesToDump; i++) {
      operators.get(batchPosn--).dump();
    }
    logger.error("Batch dump completed.");
  }

  @Override
  public void close() throws Exception {
    // We want to account for the time spent waiting here as Wait time in the operator profile
    try {
      stats.startProcessing();
      stats.startWait();
      fragmentContext.waitForSendComplete();
    } finally {
      stats.stopWait();
      stats.stopProcessing();
    }

    // close all operators.
    if (operators != null) {
      final DeferredException df = new DeferredException();

      for (final CloseableRecordBatch crb : operators) {
        df.suppressingClose(crb);
        if (logger.isDebugEnabled()) {
          logger.debug(String.format("closed operator %d", System.identityHashCode(crb)));
        }
      }

      try {
        df.close();
      } catch (Exception e) {
        fragmentContext.getExecutorState().fail(e);
      }
    }
  }

  /**
   * Given a list of operators and a stack trace, walks the stack trace and
   * the operator list to find the leaf-most operator, which is the one
   * that was active when the exception was thrown. Handle the cases in
   * which no operator was active, each operator had multiple methods on
   * the stack, or the exception was thrown in some class called by
   * the operator.
   * <p>
   * Not all operators leave a mark in the trace. In particular if a the
   * call stack is only through base-class methods, then we have no way to
   * know the actual class during the call. This is OK because the leaf
   * methods are just pass-through operations, they are unlikely to fail.
   *
   * @param <T> the type of the operator. Parameterized to allow easier
   * testing
   * @param dag the list of operators from root-most to leaf-most
   * @param e the exception thrown somewhere in the operator tree
   * @return the leaf-most operator, if any
   */
  public static <T> T findLeaf(List<T> dag, Throwable e) {
    StackTraceElement[] trace = e.getStackTrace();
    for (int i = dag.size() - 1; i >= 0; i--) {
      T leaf = dag.get(i);
      String opName = leaf.getClass().getName();
      for (StackTraceElement element : trace) {
        String frameName = element.getClassName();
        if (frameName.contentEquals(opName)) {
          return leaf;
        }
      }
    }
    return null;
  }
}


text:
layout: page
title: "About"
description: "This is what I do."
header-img: "img/about-bg.jpg"
---

Fourth-year undergrad student at UC Berkeley, majoring in Computer Science. I love designing, developing, and creating awesome experiences for users. Most of my experience is with desktop and mobile web applications, but right now I'm learning iOS development.

Besides tech, I am really into teaching, mentoring, entrepreneurship, and learning and practicing leadership and public speaking skills. I'm quite a curious person. I want to understand how things work — my friends know me as the person who always asks "why?"

After graduation, I will be joining Google as a software engineering in August. Summer, I'll be traveling the world. Switzerland, Italy, Germany, Taiwan, Thailand, Malaysia, Myanmar, Vietnam, and the Amazon Rainforest are on my list. Come join me!


text:
#ifndef TRIO_TRIOSTR_H
#define TRIO_TRIOSTR_H

#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "triodef.h"
#include "triop.h"

enum {
  TRIO_HASH_NONE = 0,
  TRIO_HASH_PLAIN,
  TRIO_HASH_TWOSIGNED
};

#if !defined(TRIO_STRING_PUBLIC)
# if !defined(TRIO_PUBLIC)
#  define TRIO_PUBLIC
# endif
# define TRIO_STRING_PUBLIC TRIO_PUBLIC
#endif

/*************************************************************************
 * String functions
 */

TRIO_STRING_PUBLIC int trio_copy_max TRIO_PROTO((char *target, size_t max, const char *source));
TRIO_STRING_PUBLIC char *trio_create TRIO_PROTO((size_t size));
TRIO_STRING_PUBLIC void trio_destroy TRIO_PROTO((char *string));
TRIO_STRING_PUBLIC char *trio_duplicate TRIO_PROTO((const char *source));
TRIO_STRING_PUBLIC int trio_equal TRIO_PROTO((const char *first, const char *second));
TRIO_STRING_PUBLIC int trio_equal_case TRIO_PROTO((const char *first, const char *second));
TRIO_STRING_PUBLIC int trio_equal_locale TRIO_PROTO((const char *first, const char *second));
TRIO_STRING_PUBLIC int trio_equal_max TRIO_PROTO((const char *first, size_t max, const char *second));
TRIO_STRING_PUBLIC TRIO_CONST char *trio_error TRIO_PROTO((int));
TRIO_STRING_PUBLIC size_t trio_length TRIO_PROTO((const char *string));
TRIO_STRING_PUBLIC double trio_to_double TRIO_PROTO((const char *source, char **endp));
TRIO_STRING_PUBLIC long trio_to_long TRIO_PROTO((const char *source, char **endp, int base));
TRIO_STRING_PUBLIC trio_long_double_t trio_to_long_double TRIO_PROTO((const char *source, char **endp));
TRIO_STRING_PUBLIC int trio_to_upper TRIO_PROTO((int source));

#if !defined(TRIO_MINIMAL)

TRIO_STRING_PUBLIC int trio_append TRIO_PROTO((char *target, const char *source));
TRIO_STRING_PUBLIC int trio_append_max TRIO_PROTO((char *target, size_t max, const char *source));
TRIO_STRING_PUBLIC int trio_contains TRIO_PROTO((const char *string, const char *substring));
TRIO_STRING_PUBLIC int trio_copy TRIO_PROTO((char *target, const char *source));
TRIO_STRING_PUBLIC char *trio_duplicate_max TRIO_PROTO((const char *source, size_t max));
TRIO_STRING_PUBLIC int trio_equal_case_max TRIO_PROTO((const char *first, size_t max, const char *second));
TRIO_STRING_PUBLIC size_t trio_format_date_max TRIO_PROTO((char *target, size_t max, const char *format, const struct tm *datetime));
TRIO_STRING_PUBLIC unsigned long trio_hash TRIO_PROTO((const char *string, int type));
TRIO_STRING_PUBLIC char *trio_index TRIO_PROTO((const char *string, int character));
TRIO_STRING_PUBLIC char *trio_index_last TRIO_PROTO((const char *string, int character));
TRIO_STRING_PUBLIC int trio_lower TRIO_PROTO((char *target));
TRIO_STRING_PUBLIC int trio_match TRIO_PROTO((const char *string, const char *pattern));
TRIO_STRING_PUBLIC int trio_match_case TRIO_PROTO((const char *string, const char *pattern));
TRIO_STRING_PUBLIC size_t trio_span_function TRIO_PROTO((char *target, const char *source, int (*Function) TRIO_PROTO((int))));
TRIO_STRING_PUBLIC char *trio_substring TRIO_PROTO((const char *string, const char *substring));
TRIO_STRING_PUBLIC char *trio_substring_max TRIO_PROTO((const char *string, size_t max, const char *substring));
TRIO_STRING_PUBLIC float trio_to_float TRIO_PROTO((const char *source, char **endp));
TRIO_STRING_PUBLIC int trio_to_lower TRIO_PROTO((int source));
TRIO_STRING_PUBLIC unsigned long trio_to_unsigned_long TRIO_PROTO((const char *source, char **endp, int base));
TRIO_STRING_PUBLIC char *trio_tokenize TRIO_PROTO((char *string, const char *delimiters));
TRIO_STRING_PUBLIC int trio_upper TRIO_PROTO((char *target));

#endif /* !defined(TRIO_MINIMAL) */

/*************************************************************************
 * Dynamic string functions
 */

/*
 * Opaque type for dynamic strings
 */

typedef struct _trio_string_t trio_string_t;

TRIO_STRING_PUBLIC void trio_string_destroy TRIO_PROTO((trio_string_t *self));
TRIO_STRING_PUBLIC char *trio_string_extract TRIO_PROTO((trio_string_t *self));
TRIO_STRING_PUBLIC int trio_string_size TRIO_PROTO((trio_string_t *self));
TRIO_STRING_PUBLIC void trio_string_terminate TRIO_PROTO((trio_string_t *self));
TRIO_STRING_PUBLIC int trio_xstring_append_char TRIO_PROTO((trio_string_t *self, char character));
TRIO_STRING_PUBLIC trio_string_t *trio_xstring_duplicate TRIO_PROTO((const char *other));

#if !defined(TRIO_MINIMAL)

TRIO_STRING_PUBLIC trio_string_t *trio_string_create TRIO_PROTO((int initial_size));
TRIO_STRING_PUBLIC char *trio_string_get TRIO_PROTO((trio_string_t *self, int offset));
TRIO_STRING_PUBLIC void trio_xstring_set TRIO_PROTO((trio_string_t *self, char *buffer));

TRIO_STRING_PUBLIC int trio_string_append TRIO_PROTO((trio_string_t *self, trio_string_t *other));
TRIO_STRING_PUBLIC int trio_string_contains TRIO_PROTO((trio_string_t *self, trio_string_t *other));
TRIO_STRING_PUBLIC int trio_string_copy TRIO_PROTO((trio_string_t *self, trio_string_t *other));
TRIO_STRING_PUBLIC trio_string_t *trio_string_duplicate TRIO_PROTO((trio_string_t *other));
TRIO_STRING_PUBLIC int trio_string_equal TRIO_PROTO((trio_string_t *self, trio_string_t *other));
TRIO_STRING_PUBLIC int trio_string_equal_max TRIO_PROTO((trio_string_t *self, size_t max, trio_string_t *second));
TRIO_STRING_PUBLIC int trio_string_equal_case TRIO_PROTO((trio_string_t *self, trio_string_t *other));
TRIO_STRING_PUBLIC int trio_string_equal_case_max TRIO_PROTO((trio_string_t *self, size_t max, trio_string_t *other));
TRIO_STRING_PUBLIC size_t trio_string_format_date_max TRIO_PROTO((trio_string_t *self, size_t max, const char *format, const struct tm *datetime));
TRIO_STRING_PUBLIC char *trio_string_index TRIO_PROTO((trio_string_t *self, int character));
TRIO_STRING_PUBLIC char *trio_string_index_last TRIO_PROTO((trio_string_t *self, int character));
TRIO_STRING_PUBLIC int trio_string_length TRIO_PROTO((trio_string_t *self));
TRIO_STRING_PUBLIC int trio_string_lower TRIO_PROTO((trio_string_t *self));
TRIO_STRING_PUBLIC int trio_string_match TRIO_PROTO((trio_string_t *self, trio_string_t *other));
TRIO_STRING_PUBLIC int trio_string_match_case TRIO_PROTO((trio_string_t *self, trio_string_t *other));
TRIO_STRING_PUBLIC char *trio_string_substring TRIO_PROTO((trio_string_t *self, trio_string_t *other));
TRIO_STRING_PUBLIC int trio_string_upper TRIO_PROTO((trio_string_t *self));

TRIO_STRING_PUBLIC int trio_xstring_append TRIO_PROTO((trio_string_t *self, const char *other));
TRIO_STRING_PUBLIC int trio_xstring_contains TRIO_PROTO((trio_string_t *self, const char *other));
TRIO_STRING_PUBLIC int trio_xstring_copy TRIO_PROTO((trio_string_t *self, const char *other));
TRIO_STRING_PUBLIC int trio_xstring_equal TRIO_PROTO((trio_string_t *self, const char *other));
TRIO_STRING_PUBLIC int trio_xstring_equal_max TRIO_PROTO((trio_string_t *self, size_t max, const char *other));
TRIO_STRING_PUBLIC int trio_xstring_equal_case TRIO_PROTO((trio_string_t *self, const char *other));
TRIO_STRING_PUBLIC int trio_xstring_equal_case_max TRIO_PROTO((trio_string_t *self, size_t max, const char *other));
TRIO_STRING_PUBLIC int trio_xstring_match TRIO_PROTO((trio_string_t *self, const char *other));
TRIO_STRING_PUBLIC int trio_xstring_match_case TRIO_PROTO((trio_string_t *self, const char *other));
TRIO_STRING_PUBLIC char *trio_xstring_substring TRIO_PROTO((trio_string_t *self, const char *other));

#endif /* !defined(TRIO_MINIMAL) */

#endif /* TRIO_TRIOSTR_H */


text:
namespace eWAY.Rapid.Models
{
    /// <summary>
    /// Verification object returned from RefundResponse.
    /// </summary>
    public class Verification
    {
        /// <summary>
        /// Result of CVN Verification by card processor
        /// </summary>
        public string CVN { get; set; }
        /// <summary>
        /// Result of Address Verification by card processor
        /// </summary>
        public string Address { get; set; }
        /// <summary>
        /// Result of email verification by card processor
        /// </summary>
        public string Email { get; set; }
        /// <summary>
        /// Result of Mobile verification by card processor
        /// </summary>
        public string Mobile { get; set; }
        /// <summary>
        /// Result of phone verification by card processor
        /// </summary>
        public string Phone { get; set; }
    }
}


text:
using System.Linq;
using System.Reflection;

namespace Helpers.Core.Extensions
{
    /// <exclude/>
    internal static partial class ExtensionMethods
    {
        /// <exclude/>
        public static T MapPropertiesByName<T>(this object source, T target)
        {
            foreach (PropertyInfo sourceProp in source.GetType().GetProperties())
            {
                PropertyInfo targetProp = target.GetType().GetProperties().Where(p => p.Name.Equals(sourceProp.Name)).FirstOrDefault();
                if (targetProp != null && targetProp.GetType().Name.Equals(sourceProp.GetType().Name) && targetProp.CanWrite)
                {
                    targetProp.SetValue(target, sourceProp.GetValue(source));
                }
            }
            return target;
        }

        /// <exclude/>
        public static T MapPropertiesByName<T>(this object source) where T : new()
        {
            T target = new T();
            foreach (PropertyInfo sourceProp in source.GetType().GetProperties())
            {
                PropertyInfo targetProp = target.GetType().GetProperties().Where(p => p.Name == sourceProp.Name).FirstOrDefault();
                if (targetProp != null && targetProp.GetType().Name.Equals(sourceProp.GetType().Name) && targetProp.CanWrite)
                {
                    targetProp.SetValue(target, sourceProp.GetValue(source));
                }
            }
            return target;
        }
    }
}


text:
import smtpd
import asyncore
import asynchat
import logging
import sys
import os
import socket
import time
from email.parser import Parser
import json
import smtplib
import argparse

# === Configuration ========================================================================
argparser = argparse.ArgumentParser()
argparser.add_argument("--host", help="Hostname of listening address. (Default: localhost)", default='localhost')
argparser.add_argument("--port", type=int,  help="Portnumber of listening address. (Default: 25)", default=25)
argparser.add_argument("--mgmthost", help="Hostname of management interface. (Default: localhost)", default='localhost')
argparser.add_argument("--mgmtport", type=int,  help="Portnumber of management interface. (Default: 5252)", default=5252)

argparser.add_argument("--proxyhost", help="Hostname of smtp host address for relaying messages. (Default: localhost)", default='localhost')
argparser.add_argument("--proxyport", type=int,  help="Portnumber of smtp host address for relaying messages. (Default: 2525)", default=2525)
argparser.add_argument("-p", "--proxy", action="store_true", help="Enable proxy mode. This will relay messages to smtp server defined by proxyhost and proxyport.")
argparser.add_argument("-c", "--check", action="store_true", help="Check the arguments used")
args = argparser.parse_args()

print args

use_proxy=False
if args.proxy:
    use_proxy=True

# === Program info =============================================================
program = sys.argv[0]
__version__ = 'SMTP Stub version 0.2'

# === Log settings =============================================================
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)

base_dir = os.path.dirname(os.path.abspath(__file__))

# === Configuration summary ====================================================
logger.info("version: %s" % __version__)
logger.info("basedir: %s" % base_dir)
logger.info("host: %s" % args.host)
logger.info("port: %s" % args.port)
logger.info("mgmt host: %s" % args.mgmthost)
logger.info("mgmt port: %s" % args.mgmtport)

if use_proxy:
    logger.info('proxy mode on.')
    logger.info("proxy host: %s" % args.proxyhost)
    logger.info("proxy port: %s" % args.proxyport)
else:
    logger.info('proxy mode off.')

if args.check:
    # Just a config check. Exiting here...
    sys.exit()

# === Private constants=========================================================
NEWLINE = '\n'
EMPTYSTRING = ''
COMMASPACE = ', '

# Internal mail store
__mailstore = {}

class SMTPMgmtChannel(asynchat.async_chat):
    COMMAND = 0
    DATA = 1

    def __init__(self, server, conn, addr, mailstore):
        asynchat.async_chat.__init__(self, conn)
        self.__server = server
        self.__conn = conn
        self.__addr = addr
        self.__line = []
        self.__state = self.COMMAND
        self.__greeting = 0
        self.__data = ''
        self.__fqdn = socket.getfqdn()
        self.__mailstore = mailstore

        try:
            self.__peer = conn.getpeername()

        except socket.error, err:
            # a race condition  may occur if the other end is closing
            # before we can get the peername
            self.close()
            if err[0] != errno.ENOTCONN:
                raise
            return

        logger.debug('Peer: %s' % repr(self.__peer) )
        self.push('100 %s %s' % (self.__fqdn, __version__))
        self.set_terminator('\r\n')

    # Overrides base class for convenience
    def push(self, msg):
        asynchat.async_chat.push(self, msg + '\r\n')

    def pushdata(self, data):
        asynchat.async_chat.push(self, data)

    # Implementation of base class abstract method
    def collect_incoming_data(self, data):
        self.__line.append(data)

    # Implementation of base class abstract method
    def found_terminator(self):
        line = EMPTYSTRING.join(self.__line)
        logger.debug( 'Data: %s' % repr(line) )

        self.__line = []
        if self.__state == self.COMMAND:
            if not line:
                self.push('500 Error: bad syntax')
                return
            method = None
            i = line.find(' ')
            if i < 0:
                command = line.upper()
                arg = None
            else:
                command = line[:i].upper()
                arg = line[i+1:].strip()
            method = getattr(self, 'smtpmgmt_' + command, None)
            if not method:
                self.push('500 Error: command "%s" not implemented' % command)
                return
            method(arg)
            return
        else:
            if self.__state != self.DATA:
                self.push('500 Internal confusion')
                return
            # Remove extraneous carriage returns and de-transparency according
            # to RFC 821, Section 4.5.2.
            data = []
            for text in line.split('\r\n'):
                if text and text[0] == '.':
                    data.append(text[1:])
                else:
                    data.append(text)
            self.__data = NEWLINE.join(data)
            status = self.__server.process_data(self.__peer, self.__data)
            self.__state = self.COMMAND
            self.set_terminator('\r\n')
            if not status:
                self.push('250 Ok')
            else:
                self.push(status)

    # SMTP and ESMTP commands
    def smtpmgmt_HELO(self, arg):
        if not arg:
            self.push('500 Syntax: HELO hostname')
            return
        if self.__greeting:
            self.push('500 Duplicate HELO/EHLO')
        else:
            self.__greeting = arg
            self.push('250 %s' % self.__fqdn)

    def smtpmgmt_NOOP(self, arg):
        if arg:
            self.push('500 Syntax: NOOP')
        else:
            self.push('250 Ok')

    def smtpmgmt_ECHO(self, arg):
        if arg:
            self.push('250 %s' % arg)
        else:
            self.push('500 Syntax: ECHO <message>')

    def smtpmgmt_RESET(self, arg):
      if arg:
        self.push('500 Syntax: RESET')
      else:
        logger.info('Cleared internal mailstore')
        self.__mailstore.clear()
        self.push('250 Mailstore cleared')

    def smtpmgmt_MSGCNT(self, arg):
      if arg:
        logger.info('Count messages for recipient: %s' % arg)

        if arg in self.__mailstore:
          cnt = len(self.__mailstore[arg])
        else:
          cnt = 0

        logger.debug('# messages: %d' % cnt)
        self.push('250 %d' % cnt)

      else:
        self.push('500 Syntax: MSGCNT <recipient>')

    def smtpmgmt_MSGLST(self, arg):
      if arg:
        args = arg.split()
        rcpt = args[0]
        mode = 'plain'
        if len(args)>1:
          mode = args[1]

        if rcpt in self.__mailstore:
          cnt = len(self.__mailstore[rcpt])
        else:
          cnt = 0

        logger.debug('# messages: %d' % cnt)

        if mode == 'json':
          if cnt == 0:
            self.push('210 %d' % cnt)

          else:
            txt = json.dumps(self.__mailstore[rcpt], sort_keys=True,
                    indent=1, separators=(',', ': '))

            self.push('200 %d' % len(txt))
            self.pushdata(txt)

        else:
          self.push('210 %d' % cnt)
          idx = 1
          if cnt > 0:
            for msg in self.__mailstore[rcpt]:
              self.push("%03d:%s" % (idx, msg['subject']))
              idx += 1

      else:
        self.push('500 Syntax: MSGLST <recipient> [<mode>]')

    def smtpmgmt_MSGGET(self, arg):
      if arg:

        args = arg.split()
        rcpt, idx = args[0:2]
        if len(args)==3:
          mode = args[2]
        else:
          mode = 'plain'

        if rcpt in self.__mailstore:
        msgs = self.__mailstore[rcpt]
            if len(msgs)==0:
                self.push('500 No messages')
            elif int(idx) > len(msgs):
                self.push('500 Index: maximum exceeded')
            else:
                if idx>0:
        msg = msgs[int(idx)-1]
                elif idx<0:
                    msg = msgs[idx]
                else:
                    msg = msgs[0]

        if mode == 'json':
          txt = json.dumps(msg, sort_keys=True,
                  indent=1, separators=(',', ': '))
          self.push('200 %d' % len(txt))
          self.pushdata(txt)

        elif mode == 'mime':
          msglen = len(msg['data'])
          self.push('200 %d' % msglen)
          self.pushdata(msg['data'])

        else:
          msglen = len(msg['payload'])
          self.push('200 %d' % msglen)
          self.pushdata(msg['payload'])
        else:
            self.push('500 Unknown recipient')

      else:
        self.push('500 Syntax: MSGGET <recipient> <msgnr>')

    def smtpmgmt_DUMP(self, arg):

      if len(self.__mailstore):

        if arg == 'json':
          txt = json.dumps(self.__mailstore, sort_keys=True,
                  indent=1, separators=(',', ': '))

          self.push('200 %d' % len(txt))
          self.pushdata(txt)

        else:
          lines = 0
          for rcpt in self.__mailstore:
            lines += 1
            msgs = self.__mailstore[rcpt]
            lines += len(msgs)

          self.push('210 %d' % lines)

          for rcpt in self.__mailstore:
            self.push('%s:' % rcpt)
            msgs = self.__mailstore[rcpt]
            idx = 1

            for msg in msgs:
              self.push("\t%03d:%s" % (idx, msg['subject']) )
              idx += 1

      else:
        self.push('250 No entries')

    def smtpmgmt_HELP(self, arg):

      cmds = [ 'Avaiable commands:'
        , 'HELO    : Handshake'
        , 'NOOP    : Does nothing'
        , 'RESET   : Clears the mail store'
        , 'MSGCNT  : Message count for a recipient'
        , 'MSGLST  : List all id,subjects of a recipient'
        , 'MSGGET  : Get payload of a numbered message from recipient'
        , 'DUMP    : Dumps the current mail store'
        , 'HELP    : Help'
        , 'ECHO    : Echos message'
        , 'QUIT    : Quits the session'
      ]
      self.push('210 %d' % len(cmds))
      for c in cmds:
        self.push(c)

    def smtpmgmt_QUIT(self, arg):
      # args is ignored
      self.push('100 Bye')
      self.close_when_done()

class SMTPMgmtServer(asyncore.dispatcher):
    def __init__(self, localaddr, mailstore):
        self._localaddr = localaddr
        self.__mailstore = mailstore
        asyncore.dispatcher.__init__(self)
        try:
            self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
            # try to re-use a server port if possible
            self.set_reuse_addr()
            self.bind(localaddr)
            self.listen(5)
        except:
            # cleanup asyncore.socket_map before raising
            self.close()
            raise
        else:
            logger.debug('%s started at %s\n\tLocal addr: %s\n'
                        % (self.__class__.__name__, time.ctime(time.time()),  localaddr)
                        )

    def handle_accept(self):
        pair = self.accept()
        if pair is not None:
            conn, addr = pair
            logger.debug( 'Incoming connection from %s' % repr(addr) )
            channel = SMTPMgmtChannel(self, conn, addr, self.__mailstore)

class SMTPStubServer(smtpd.SMTPServer):
    proxyenabled = False
    proxyhost = None
    proxyport = None

    def __init__(self, localaddr, remoteaddr, mailstore):
      smtpd.SMTPServer.__init__(self, localaddr, remoteaddr)
      self.__mailstore = mailstore

    def process_message(self, peer, mailfrom, rcpttos, data):

      if self.proxyenabled:
          refused = self._deliver(mailfrom, rcpttos, data)
          if refused:
              logger.error(refused)

      msg = Parser().parsestr( data )
      print repr(msg)

      for rcpt in rcpttos:
        d = dict(peer=mailfrom,
          mailfrom=msg['From'],
          subject=msg['Subject'],
          payload=msg.get_payload(),
          data=data)

        if not rcpt in self.__mailstore:
          self.__mailstore[rcpt] = []

        self.__mailstore[rcpt].append(d)

      # print 'Receiving message from:', peer
      # print 'Message addressed from:', mailfrom
      # print 'Message addressed to  :', rcpttos
      # print 'Message length        :', len(data)

    def _deliver(self, mailfrom, rcpttos, data):
        if not self.proxyenabled:
            return {}

        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self.proxyhost, self.proxyport)
            try:
                refused = s.sendmail(mailfrom, rcpttos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused, e:
            logger.debug('got SMTPRecipientsRefused')
            refused = e.recipients
        except (socket.error, smtplib.SMTPException), e:
            logger.debug('got', e.__class__)
            # All recipients were refused.  If the exception had an associated
            # error code, use it.  Otherwise,fake it with a non-triggering
            # exception code.
            errcode = getattr(e, 'smtp_code', -1)
            errmsg = getattr(e, 'smtp_error', 'ignore')
            for r in rcpttos:
                refused[r] = (errcode, errmsg)
        return refused

    def enable_proxy(self, proxyhost='localhost', proxyport=25):
        self.proxyhost = proxyhost
        self.proxyport = proxyport
        self.proxyenabled=True

# === Main======================================================================
server = SMTPStubServer((args.host, args.port), None, __mailstore)
if use_proxy:
    server.enable_proxy(args.proxyhost, args.proxyport)

server_mgmt = SMTPMgmtServer((args.mgmthost, args.mgmtport), __mailstore)

try:
  asyncore.loop()

except KeyboardInterrupt:
  print '^C received, shutting down the web server'


text:
import { Mixin } from 'hops-mixin';
import { createElement } from 'react';
import { Provider } from './context';

class ImportComponentMixin extends Mixin {
  bootstrap(_req, res) {
    if (res) {
      res.locals.chunks = this.chunks = [];
    }
  }

  enhanceElement(element) {
    return createElement(Provider, { value: this.chunks }, element);
  }
}

export default ImportComponentMixin;