text:
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 __());
    };
})();
/**
 * @module ol/renderer/canvas/VectorTileLayer
 */
import { getUid } from '../../util.js';
import { createCanvasContext2D } from '../../dom.js';
import TileState from '../../TileState.js';
import ViewHint from '../../ViewHint.js';
import { listen, unlisten, unlistenByKey } from '../../events.js';
import EventType from '../../events/EventType.js';
import rbush from 'rbush';
import { buffer, containsCoordinate, equals, getIntersection, getTopLeft, intersects } from '../../extent.js';
import VectorTileRenderType from '../../layer/VectorTileRenderType.js';
import ReplayType from '../../render/canvas/BuilderType.js';
import { labelCache } from '../../render/canvas.js';
import CanvasBuilderGroup from '../../render/canvas/BuilderGroup.js';
import CanvasTileLayerRenderer from './TileLayer.js';
import { getSquaredTolerance as getSquaredRenderTolerance, renderFeature } from '../vector.js';
import { apply as applyTransform, create as createTransform, compose as composeTransform, reset as resetTransform, scale as scaleTransform, translate as translateTransform, toString as transformToString, makeScale, makeInverse } from '../../transform.js';
import CanvasExecutorGroup, { replayDeclutter } from '../../render/canvas/ExecutorGroup.js';
import { clear } from '../../obj.js';
/**
 * @type {!Object<string, Array<import("../../render/canvas/BuilderType.js").default>>}
 */
var IMAGE_REPLAYS = {
    'image': [ReplayType.POLYGON, ReplayType.CIRCLE,
        ReplayType.LINE_STRING, ReplayType.IMAGE, ReplayType.TEXT],
    'hybrid': [ReplayType.POLYGON, ReplayType.LINE_STRING]
};
/**
 * @type {!Object<string, Array<import("../../render/canvas/BuilderType.js").default>>}
 */
var VECTOR_REPLAYS = {
    'image': [ReplayType.DEFAULT],
    'hybrid': [ReplayType.IMAGE, ReplayType.TEXT, ReplayType.DEFAULT]
};
/**
 * @classdesc
 * Canvas renderer for vector tile layers.
 * @api
 */
var CanvasVectorTileLayerRenderer = /** @class */ (function (_super) {
    __extends(CanvasVectorTileLayerRenderer, _super);
    /**
     * @param {import("../../layer/VectorTile.js").default} layer VectorTile layer.
     */
    function CanvasVectorTileLayerRenderer(layer) {
        var _this = _super.call(this, layer) || this;
        var baseCanvas = _this.context.canvas;
        /**
         * @private
         * @type {CanvasRenderingContext2D}
         */
        _this.overlayContext_ = createCanvasContext2D();
        var overlayCanvas = _this.overlayContext_.canvas;
        overlayCanvas.style.position = 'absolute';
        overlayCanvas.style.transformOrigin = 'top left';
        var container = document.createElement('div');
        var style = container.style;
        style.position = 'absolute';
        style.width = '100%';
        style.height = '100%';
        container.appendChild(baseCanvas);
        container.appendChild(overlayCanvas);
        /**
         * @private
         * @type {HTMLElement}
         */
        _this.container_ = container;
        /**
         * The transform for rendered pixels to viewport CSS pixels for the overlay canvas.
         * @private
         * @type {import("../../transform.js").Transform}
         */
        _this.overlayPixelTransform_ = createTransform();
        /**
         * The transform for viewport CSS pixels to rendered pixels for the overlay canvas.
         * @private
         * @type {import("../../transform.js").Transform}
         */
        _this.inverseOverlayPixelTransform_ = createTransform();
        /**
         * Declutter tree.
         * @private
         */
        _this.declutterTree_ = layer.getDeclutter() ? rbush(9, undefined) : null;
        /**
         * @private
         * @type {boolean}
         */
        _this.dirty_ = false;
        /**
         * @private
         * @type {number}
         */
        _this.renderedLayerRevision_;
        /**
         * @private
         * @type {!Object<string, import("../../VectorRenderTile.js").default>}
         */
        _this.renderTileImageQueue_ = {};
        /**
         * @type {Object<string, import("../../events.js").EventsKey>}
         */
        _this.tileListenerKeys_ = {};
        /**
         * @private
         * @type {import("../../transform.js").Transform}
         */
        _this.tmpTransform_ = createTransform();
        // Use closest resolution.
        _this.zDirection = 0;
        listen(labelCache, EventType.CLEAR, _this.handleFontsChanged_, _this);
        return _this;
    }
    /**
     * @inheritDoc
     */
    CanvasVectorTileLayerRenderer.prototype.disposeInternal = function () {
        unlisten(labelCache, EventType.CLEAR, this.handleFontsChanged_, this);
        this.overlayContext_.canvas.width = this.overlayContext_.canvas.height = 0;
        _super.prototype.disposeInternal.call(this);
    };
    /**
     * @param {import("../../VectorRenderTile.js").default} tile Tile.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../../proj/Projection").default} projection Projection.
     */
    CanvasVectorTileLayerRenderer.prototype.prepareTile = function (tile, pixelRatio, projection) {
        var tileUid = getUid(tile);
        var state = tile.getState();
        if (((state === TileState.LOADED && tile.hifi) ||
            state === TileState.ERROR || state === TileState.ABORT) &&
            tileUid in this.tileListenerKeys_) {
            unlistenByKey(this.tileListenerKeys_[tileUid]);
            delete this.tileListenerKeys_[tileUid];
        }
        if (state === TileState.LOADED || state === TileState.ERROR) {
            this.updateExecutorGroup_(tile, pixelRatio, projection);
            if (this.tileImageNeedsRender_(tile, pixelRatio, projection)) {
                this.renderTileImageQueue_[tileUid] = tile;
            }
        }
    };
    /**
     * @inheritDoc
     */
    CanvasVectorTileLayerRenderer.prototype.getTile = function (z, x, y, pixelRatio, projection) {
        var tile = /** @type {import("../../VectorRenderTile.js").default} */ (_super.prototype.getTile.call(this, z, x, y, pixelRatio, projection));
        if (tile.getState() < TileState.LOADED) {
            var tileUid = getUid(tile);
            if (!(tileUid in this.tileListenerKeys_)) {
                var listenerKey = listen(tile, EventType.CHANGE, this.prepareTile.bind(this, tile, pixelRatio, projection));
                this.tileListenerKeys_[tileUid] = listenerKey;
            }
        }
        else {
            this.prepareTile(tile, pixelRatio, projection);
        }
        return tile;
    };
    /**
     * @inheritdoc
     */
    CanvasVectorTileLayerRenderer.prototype.isDrawableTile = function (tile) {
        return _super.prototype.isDrawableTile.call(this, tile) && tile.hasContext(this.getLayer());
    };
    /**
     * @inheritDoc
     */
    CanvasVectorTileLayerRenderer.prototype.getTileImage = function (tile) {
        return tile.getImage(this.getLayer());
    };
    /**
     * @inheritDoc
     */
    CanvasVectorTileLayerRenderer.prototype.prepareFrame = function (frameState, layerState) {
        var layerRevision = this.getLayer().getRevision();
        if (this.renderedLayerRevision_ != layerRevision) {
            this.renderedTiles.length = 0;
        }
        this.renderedLayerRevision_ = layerRevision;
        return _super.prototype.prepareFrame.call(this, frameState, layerState);
    };
    /**
     * @param {import("../../VectorRenderTile.js").default} tile Tile.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../../proj/Projection.js").default} projection Projection.
     * @private
     */
    CanvasVectorTileLayerRenderer.prototype.updateExecutorGroup_ = function (tile, pixelRatio, projection) {
        var layer = /** @type {import("../../layer/VectorTile.js").default} */ (this.getLayer());
        var revision = layer.getRevision();
        var renderOrder = layer.getRenderOrder() || null;
        var builderState = tile.getReplayState(layer);
        if (!builderState.dirty && builderState.renderedRevision == revision &&
            builderState.renderedRenderOrder == renderOrder && builderState.renderedZ === tile.sourceZ) {
            return;
        }
        var source = layer.getSource();
        var sourceTileGrid = source.getTileGrid();
        var tileGrid = source.getTileGridForProjection(projection);
        var zoom = tile.tileCoord[0];
        var resolution = tileGrid.getResolution(zoom);
        var tileExtent = tileGrid.getTileCoordExtent(tile.wrappedTileCoord);
        var sourceTiles = tile.load();
        var layerUid = getUid(layer);
        var executorGroups = tile.executorGroups[layerUid];
        if (executorGroups) {
            for (var i = 0, ii = executorGroups.length; i < ii; ++i) {
                executorGroups[i].dispose();
            }
        }
        tile.executorGroups[layerUid] = [];
        var _loop_1 = function (t, tt) {
            var sourceTile = sourceTiles[t];
            if (sourceTile.getState() != TileState.LOADED) {
                return "continue";
            }
            var sourceTileCoord = sourceTile.tileCoord;
            var sourceTileExtent = sourceTileGrid.getTileCoordExtent(sourceTileCoord);
            var sharedExtent = getIntersection(tileExtent, sourceTileExtent);
            var bufferedExtent = equals(sourceTileExtent, sharedExtent) ? null :
                buffer(sharedExtent, layer.getRenderBuffer() * resolution, this_1.tmpExtent);
            builderState.dirty = false;
            var builderGroup = new CanvasBuilderGroup(0, sharedExtent, resolution, pixelRatio, !!this_1.declutterTree_);
            var squaredTolerance = getSquaredRenderTolerance(resolution, pixelRatio);
            /**
             * @param {import("../../Feature.js").FeatureLike} feature Feature.
             * @this {CanvasVectorTileLayerRenderer}
             */
            var render = function (feature) {
                var styles;
                var styleFunction = feature.getStyleFunction() || layer.getStyleFunction();
                if (styleFunction) {
                    styles = styleFunction(feature, resolution);
                }
                if (styles) {
                    var dirty = this.renderFeature(feature, squaredTolerance, styles, builderGroup);
                    this.dirty_ = this.dirty_ || dirty;
                    builderState.dirty = builderState.dirty || dirty;
                }
            };
            var features = sourceTile.getFeatures();
            if (renderOrder && renderOrder !== builderState.renderedRenderOrder) {
                features.sort(renderOrder);
            }
            for (var i = 0, ii = features.length; i < ii; ++i) {
                var feature = features[i];
                if (!bufferedExtent || intersects(bufferedExtent, feature.getGeometry().getExtent())) {
                    render.call(this_1, feature);
                }
            }
            var executorGroupInstructions = builderGroup.finish();
            // no need to clip when the render tile is covered by a single source tile
            var replayExtent = layer.getDeclutter() && sourceTiles.length === 1 ?
                null :
                sharedExtent;
            var renderingReplayGroup = new CanvasExecutorGroup(replayExtent, resolution, pixelRatio, source.getOverlaps(), this_1.declutterTree_, executorGroupInstructions, layer.getRenderBuffer());
            tile.executorGroups[layerUid].push(renderingReplayGroup);
        };
        var this_1 = this;
        for (var t = 0, tt = sourceTiles.length; t < tt; ++t) {
            _loop_1(t, tt);
        }
        builderState.renderedRevision = revision;
        builderState.renderedZ = tile.sourceZ;
        builderState.renderedRenderOrder = renderOrder;
    };
    /**
     * @inheritDoc
     */
    CanvasVectorTileLayerRenderer.prototype.forEachFeatureAtCoordinate = function (coordinate, frameState, hitTolerance, callback, thisArg) {
        var resolution = frameState.viewState.resolution;
        var rotation = frameState.viewState.rotation;
        hitTolerance = hitTolerance == undefined ? 0 : hitTolerance;
        var layer = this.getLayer();
        var source = layer.getSource();
        var tileGrid = source.getTileGridForProjection(frameState.viewState.projection);
        /** @type {!Object<string, boolean>} */
        var features = {};
        var renderedTiles = /** @type {Array<import("../../VectorRenderTile.js").default>} */ (this.renderedTiles);
        var found;
        var i, ii;
        for (i = 0, ii = renderedTiles.length; i < ii; ++i) {
            var tile = renderedTiles[i];
            if (!this.declutterTree_) {
                // When not decluttering, we only need to consider the tile that contains the given
                // coordinate, because each feature will be rendered for each tile that contains it.
                var tileExtent = tileGrid.getTileCoordExtent(tile.wrappedTileCoord);
                if (!containsCoordinate(tileExtent, coordinate)) {
                    continue;
                }
            }
            var executorGroups = tile.executorGroups[getUid(layer)];
            for (var t = 0, tt = executorGroups.length; t < tt; ++t) {
                var executorGroup = executorGroups[t];
                found = found || executorGroup.forEachFeatureAtCoordinate(coordinate, resolution, rotation, hitTolerance, {},
                /**
                 * @param {import("../../Feature.js").FeatureLike} feature Feature.
                 * @return {?} Callback result.
                 */
                function (feature) {
                    var key = feature.getId();
                    if (key === undefined) {
                        key = getUid(feature);
                    }
                    if (!(key in features)) {
                        features[key] = true;
                        return callback.call(thisArg, feature, layer);
                    }
                }, null);
            }
        }
        return found;
    };
    /**
     * @param {import("../../VectorTile.js").default} tile Tile.
     * @param {import("../../PluggableMap.js").FrameState} frameState Frame state.
     * @return {import("../../transform.js").Transform} transform Transform.
     * @private
     */
    CanvasVectorTileLayerRenderer.prototype.getReplayTransform_ = function (tile, frameState) {
        var layer = this.getLayer();
        var source = layer.getSource();
        var tileGrid = source.getTileGrid();
        var tileCoord = tile.tileCoord;
        var tileResolution = tileGrid.getResolution(tileCoord[0]);
        var viewState = frameState.viewState;
        var pixelRatio = frameState.pixelRatio;
        var renderResolution = viewState.resolution / pixelRatio;
        var tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent);
        var center = viewState.center;
        var origin = getTopLeft(tileExtent);
        var size = frameState.size;
        var offsetX = Math.round(pixelRatio * size[0] / 2);
        var offsetY = Math.round(pixelRatio * size[1] / 2);
        return composeTransform(this.tmpTransform_, offsetX, offsetY, tileResolution / renderResolution, tileResolution / renderResolution, viewState.rotation, (origin[0] - center[0]) / tileResolution, (center[1] - origin[1]) / tileResolution);
    };
    /**
     * @param {import("../../events/Event.js").default} event Event.
     */
    CanvasVectorTileLayerRenderer.prototype.handleFontsChanged_ = function (event) {
        var layer = this.getLayer();
        if (layer.getVisible() && this.renderedLayerRevision_ !== undefined) {
            layer.changed();
        }
    };
    /**
     * Handle changes in image style state.
     * @param {import("../../events/Event.js").default} event Image style change event.
     * @private
     */
    CanvasVectorTileLayerRenderer.prototype.handleStyleImageChange_ = function (event) {
        this.renderIfReadyAndVisible();
    };
    /**
     * @inheritDoc
     */
    CanvasVectorTileLayerRenderer.prototype.renderFrame = function (frameState, layerState) {
        _super.prototype.renderFrame.call(this, frameState, layerState);
        var layer = /** @type {import("../../layer/VectorTile.js").default} */ (this.getLayer());
        var viewHints = frameState.viewHints;
        var hifi = !(viewHints[ViewHint.ANIMATING] || viewHints[ViewHint.INTERACTING]);
        var renderMode = layer.getRenderMode();
        if (renderMode === VectorTileRenderType.IMAGE) {
            this.renderTileImages_(hifi, frameState);
            return this.container_;
        }
        var context = this.overlayContext_;
        var declutterReplays = layer.getDeclutter() ? {} : null;
        var source = layer.getSource();
        var replayTypes = VECTOR_REPLAYS[renderMode];
        var pixelRatio = frameState.pixelRatio;
        var rotation = frameState.viewState.rotation;
        var size = frameState.size;
        // set forward and inverse pixel transforms
        makeScale(this.overlayPixelTransform_, 1 / pixelRatio, 1 / pixelRatio);
        makeInverse(this.inverseOverlayPixelTransform_, this.overlayPixelTransform_);
        // resize and clear
        var canvas = context.canvas;
        var width = Math.round(size[0] * pixelRatio);
        var height = Math.round(size[1] * pixelRatio);
        if (canvas.width != width || canvas.height != height) {
            canvas.width = width;
            canvas.height = height;
            var canvasTransform = transformToString(this.overlayPixelTransform_);
            if (canvas.style.transform !== canvasTransform) {
                canvas.style.transform = canvasTransform;
            }
        }
        else {
            context.clearRect(0, 0, width, height);
        }
        if (declutterReplays) {
            this.declutterTree_.clear();
        }
        var tiles = this.renderedTiles;
        var tileGrid = source.getTileGridForProjection(frameState.viewState.projection);
        var clips = [];
        for (var i = tiles.length - 1; i >= 0; --i) {
            var tile = /** @type {import("../../VectorRenderTile.js").default} */ (tiles[i]);
            if (tile.getState() == TileState.ABORT) {
                continue;
            }
            var tileCoord = tile.tileCoord;
            var tileExtent = tileGrid.getTileCoordExtent(tile.wrappedTileCoord);
            var worldOffset = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent)[0] - tileExtent[0];
            var transform = this.getRenderTransform(frameState, width, height, worldOffset);
            var executorGroups = tile.executorGroups[getUid(layer)];
            for (var t = 0, tt = executorGroups.length; t < tt; ++t) {
                var executorGroup = executorGroups[t];
                if (!executorGroup.hasExecutors(replayTypes)) {
                    // sourceTile has no instructions of the types we want to render
                    continue;
                }
                var currentZ = tile.tileCoord[0];
                var zs = void 0, currentClip = void 0;
                if (!declutterReplays) {
                    zs = [];
                    currentClip = executorGroup.getClipCoords(transform);
                    context.save();
                    // Create a clip mask for regions in this low resolution tile that are
                    // already filled by a higher resolution tile
                    for (var j = 0, jj = clips.length; j < jj; ++j) {
                        var clip = clips[j];
                        if (currentZ < zs[j]) {
                            context.beginPath();
                            // counter-clockwise (outer ring) for current tile
                            context.moveTo(currentClip[0], currentClip[1]);
                            context.lineTo(currentClip[2], currentClip[3]);
                            context.lineTo(currentClip[4], currentClip[5]);
                            context.lineTo(currentClip[6], currentClip[7]);
                            // clockwise (inner ring) for higher resolution tile
                            context.moveTo(clip[6], clip[7]);
                            context.lineTo(clip[4], clip[5]);
                            context.lineTo(clip[2], clip[3]);
                            context.lineTo(clip[0], clip[1]);
                            context.clip();
                        }
                    }
                }
                executorGroup.execute(context, transform, rotation, {}, hifi, replayTypes, declutterReplays);
                if (!declutterReplays) {
                    context.restore();
                    clips.push(currentClip);
                    zs.push(currentZ);
                }
            }
        }
        if (declutterReplays) {
            replayDeclutter(declutterReplays, context, rotation, hifi);
        }
        var opacity = layerState.opacity;
        if (opacity !== parseFloat(canvas.style.opacity)) {
            canvas.style.opacity = opacity;
        }
        // Now that we have rendered the tiles we have already, let's prepare new tile images
        // for the next frame
        this.renderTileImages_(hifi, frameState);
        return this.container_;
    };
    /**
     * @param {boolean} hifi We have time to render a high fidelity map image.
     * @param {import('../../PluggableMap.js').FrameState} frameState Frame state.
     */
    CanvasVectorTileLayerRenderer.prototype.renderTileImages_ = function (hifi, frameState) {
        // When we don't have time to render hifi, only render tiles until we have used up
        // half of the frame budget of 16 ms
        for (var uid in this.renderTileImageQueue_) {
            if (!hifi && Date.now() - frameState.time > 8) {
                break;
            }
            var tile = this.renderTileImageQueue_[uid];
            frameState.animate = true;
            delete this.renderTileImageQueue_[uid];
            var layer = /** @type {import("../../layer/VectorTile.js").default} */ (this.getLayer());
            if (this.declutterTree_ && layer.getRenderMode() === VectorTileRenderType.IMAGE) {
                this.declutterTree_.clear();
            }
            this.renderTileImage_(tile, frameState.pixelRatio, frameState.viewState.projection);
        }
        clear(this.renderTileImageQueue_);
    };
    /**
     * @param {import("../../Feature.js").FeatureLike} feature Feature.
     * @param {number} squaredTolerance Squared tolerance.
     * @param {import("../../style/Style.js").default|Array<import("../../style/Style.js").default>} styles The style or array of styles.
     * @param {import("../../render/canvas/BuilderGroup.js").default} executorGroup Replay group.
     * @return {boolean} `true` if an image is loading.
     */
    CanvasVectorTileLayerRenderer.prototype.renderFeature = function (feature, squaredTolerance, styles, executorGroup) {
        if (!styles) {
            return false;
        }
        var loading = false;
        if (Array.isArray(styles)) {
            for (var i = 0, ii = styles.length; i < ii; ++i) {
                loading = renderFeature(executorGroup, feature, styles[i], squaredTolerance, this.handleStyleImageChange_, this) || loading;
            }
        }
        else {
            loading = renderFeature(executorGroup, feature, styles, squaredTolerance, this.handleStyleImageChange_, this);
        }
        return loading;
    };
    /**
     * @param {import("../../VectorRenderTile.js").default} tile Tile.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../../proj/Projection.js").default} projection Projection.
     * @return {boolean} A new tile image was rendered.
     * @private
     */
    CanvasVectorTileLayerRenderer.prototype.tileImageNeedsRender_ = function (tile, pixelRatio, projection) {
        var layer = /** @type {import("../../layer/VectorTile.js").default} */ (this.getLayer());
        var replayState = tile.getReplayState(layer);
        var revision = layer.getRevision();
        var sourceZ = tile.sourceZ;
        return replayState.renderedTileRevision !== revision || replayState.renderedTileZ !== sourceZ;
    };
    /**
     * @param {import("../../VectorRenderTile.js").default} tile Tile.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../../proj/Projection.js").default} projection Projection.
     * @private
     */
    CanvasVectorTileLayerRenderer.prototype.renderTileImage_ = function (tile, pixelRatio, projection) {
        var layer = /** @type {import("../../layer/VectorTile.js").default} */ (this.getLayer());
        var replayState = tile.getReplayState(layer);
        var revision = layer.getRevision();
        var executorGroups = tile.executorGroups[getUid(layer)];
        replayState.renderedTileRevision = revision;
        replayState.renderedTileZ = tile.sourceZ;
        var tileCoord = tile.wrappedTileCoord;
        var z = tileCoord[0];
        var source = layer.getSource();
        var tileGrid = source.getTileGridForProjection(projection);
        var resolution = tileGrid.getResolution(z);
        var context = tile.getContext(layer);
        var size = source.getTilePixelSize(z, pixelRatio, projection);
        context.canvas.width = size[0];
        context.canvas.height = size[1];
        var tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent);
        for (var i = 0, ii = executorGroups.length; i < ii; ++i) {
            var executorGroup = executorGroups[i];
            var pixelScale = pixelRatio / resolution;
            var transform = resetTransform(this.tmpTransform_);
            scaleTransform(transform, pixelScale, -pixelScale);
            translateTransform(transform, -tileExtent[0], -tileExtent[3]);
            executorGroup.execute(context, transform, 0, {}, true, IMAGE_REPLAYS[layer.getRenderMode()]);
        }
    };
    /**
     * @inheritDoc
     */
    CanvasVectorTileLayerRenderer.prototype.getDataAtPixel = function (pixel, frameState, hitTolerance) {
        var data = _super.prototype.getDataAtPixel.call(this, pixel, frameState, hitTolerance);
        if (data) {
            return data;
        }
        var renderPixel = applyTransform(this.inverseOverlayPixelTransform_, pixel.slice());
        var context = this.overlayContext_;
        try {
            data = context.getImageData(Math.round(renderPixel[0]), Math.round(renderPixel[1]), 1, 1).data;
        }
        catch (err) {
            if (err.name === 'SecurityError') {
                // tainted canvas, we assume there is data at the given pixel (although there might not be)
                return new Uint8Array();
            }
            return data;
        }
        if (data[3] === 0) {
            return null;
        }
        return data;
    };
    return CanvasVectorTileLayerRenderer;
}(CanvasTileLayerRenderer));
export default CanvasVectorTileLayerRenderer;
//# sourceMappingURL=VectorTileLayer.js.map


text:
NS_ASSUME_NONNULL_BEGIN

@interface JKPhotoPicker : NSObject

+ (void)showWithConfiguration:(void(^)(JKPhotoConfiguration *configuration))configuration
              completeHandler:(void(^)(NSArray <JKPhotoItem *> *photoItems, NSArray<PHAsset *> *selectedAssetArray))completeHandler;
@end

NS_ASSUME_NONNULL_END

redpajama_set_name: RedPajamaGithub


text:
package jp.go.aist.six.vuln.repository.scap.nvd;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.io.File;
import java.util.List;
import org.junit.Test;

public class NvdDataFeedTest
{

    @Test
    public void testListYearlyFeedIds()
    {
        List<String>  list = NvdDataFeed.listYealyFeedIds();
        System.out.println( "yearly feed ID list=" + list );
        assertThat( list, notNullValue() );
        assertThat( list.get( 0 ), is( String.valueOf( NvdDataFeed.OLDEST_FEED_YEAR ) ) );
    }

    @Test
    public void testListYearlyFeedUrls()
    {
        List<String>  list = NvdDataFeed.listYearlyXmlFeedUrls();
        System.out.println( "yearly feed XML URL list=" + list );
        assertThat( list, notNullValue() );
//        assertThat( list.get( 0 ), is( String.valueOf( NvdDataFeed.OLDEST_FEED_YEAR ) ) );
    }

    private static final String  _XML_FEED_2014_FILENAME_ = "nvdcve-2.0-2014.xml";

    @Test
    public void testListYearlyXmlFeedFiles()
    {
        File  dir = new File( "src/test/resources/nvd/xml/nist" );
        assertTrue( dir.exists() );

        List<File>  list = NvdDataFeed.listYearlyXmlFeedFiles( dir );
        System.out.println( "yearly feed XML file list=" + list );
        assertThat( list, notNullValue() );

        boolean  file_found = false;
        for (File  file : list) {
            String  filename = file.getName();
            if (filename.equals( _XML_FEED_2014_FILENAME_ )) {
                file_found = true;
                break;
            }
        }
        assertTrue( file_found );
    }

}
//


text:
class FavoriteProject < ActiveRecord::Base
  belongs_to :user
  belongs_to :project
end


text:
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _

EMBED_TYPES = (
    ('video', 'Video'),
    ('photo', 'Photo'),
    ('link', 'Link'),
    ('rich', 'Rich'),
)

class Embed(models.Model):
    """
    When embed code is fetched from a provider (eg, youtube) we cache that code
    in the database so we don't need to ask for it again.

    This model is used for caching the embed html code. It also stores some
    metadata which gets displayed in the editor.

    If an instance of this model is deleted, it will be automatically refetched
    next time the embed code is needed.
    """
    url = models.URLField()
    max_width = models.SmallIntegerField(null=True, blank=True)
    type = models.CharField(max_length=10, choices=EMBED_TYPES)
    html = models.TextField(blank=True)
    title = models.TextField(blank=True)
    author_name = models.TextField(blank=True)
    provider_name = models.TextField(blank=True)
    thumbnail_url = models.URLField(max_length=255, null=True, blank=True)
    width = models.IntegerField(null=True, blank=True)
    height = models.IntegerField(null=True, blank=True)
    last_updated = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('url', 'max_width')
        verbose_name = _('embed')
        verbose_name_plural = _('embeds')

    @property
    def ratio(self):
        if self.width and self.height:
            return self.height / self.width

    @property
    def ratio_css(self):
        ratio = self.ratio
        if ratio:
            return str(ratio * 100) + "%"

    @property
    def is_responsive(self):
        if not getattr(settings, 'WAGTAILEMBEDS_RESPONSIVE_HTML', False):
            return False
        return self.ratio is not None

    def __str__(self):
        return self.url


text:
Simple university course-work implemented through the use of MVVM architectural pattern, leveraging the data-bindings provided by the WPF platform.

![enter image description here](http://s18.postimg.org/v11dlwdfd/image.jpg)

![enter image description here](http://s7.postimg.org/mstzdrhjf/image.jpg)

![enter image description here](http://s23.postimg.org/544e63a3v/image.jpg)

![enter image description here](http://s21.postimg.org/nm3lo73hz/image.jpg)

![enter image description here](http://s27.postimg.org/vql36qb1f/image.jpg)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NConsoleMenu;
using NConsoleMenu.Sample.Examples.Procedures;
using NConsoleMenu.Sample.Examples.Recording;

namespace NConsoleMenu.Sample.Examples
{
	class ExamplesMenu : CMenu
	{
		public ExamplesMenu ()
		{
			Selector = "examples";
			PromptCharacter = "examples>";

			Add (new MI_Add ());

			Add (new MI_Echo ());
			Add (new MI_ComplexArgument ());
			Add (new MI_If ());
			Add (new MI_Pause ());
			Add (new MI_Stopwatch ());

			var frs = new FileRecordStore ();
			Add (new MI_Record (frs));
			Add (new MI_Replay (this, frs));

			var procmgr = new ProcManager ();
			Add (new MI_Proc (procmgr));
			Add (new MI_Call (this, procmgr));
			Add (new MI_Return (this, procmgr));
			Add (new MI_Goto (procmgr));

			OnRun += m => {
				Console.Write ("Example menu - ");
				m.CQ.ImmediateInput ("help");
			};
		}
	}
}


text:
import { LinkCategory } from './link-category';

export class LinkType {
  id: string;
  type: string;
  attributes: {
    'description': string
    'forward_name': string,
    'name': string,
    'reverse_name': string,
    'topology': string,
    'version': number
  };
  relationships: {
    // 'link_category': LinkCategory,
    'link_category': {
      'data': {
        'id': string,
        'type': string
      }
    }
    'source_type': {
      'data': {
        'id': string,
        'type': string
      }
    },
    'target_type': {
      'data': {
        'id': string,
        'type': string
      }
    }
  };
}

export class MinimizedLinkType {
  name: string;
  linkId: string;
  linkType: string;
}


text:
class Admin::TopicalEventsController < Admin::BaseController
  helper_method :model_class, :model_name, :human_friendly_model_name

  before_action :load_object, only: %i[show edit]
  before_action :build_object, only: [:new]
  before_action :build_associated_objects, only: %i[new edit]
  before_action :destroy_blank_social_media_accounts, only: %i[create update]

  def show; end

  def index
    @topical_events = model_class.order(:name)
  end

  def new; end

  def create
    @topical_event = model_class.new(object_params)
    if @topical_event.save
      redirect_to [:admin, @topical_event], notice: "#{human_friendly_model_name} created"
    else
      render action: "new"
    end
  end

  def edit; end

  def update
    @topical_event = TopicalEvent.friendly.find(params[:id])
    if @topical_event.update(object_params)
      if object_params[:topical_event_featurings_attributes]
        redirect_to [:admin, @topical_event, :topical_event_featurings], notice: "Order of featured items updated"
      else
        redirect_to [:admin, TopicalEvent.new], notice: "#{human_friendly_model_name} updated"
      end
    else
      render action: "edit"
    end
  end

  def destroy
    @topical_event = model_class.friendly.find(params[:id])
    @topical_event.delete!
    if @topical_event.deleted?
      redirect_to [:admin, model_class], notice: "#{human_friendly_model_name} destroyed"
    else
      redirect_to [:admin, model_class], alert: "Cannot destroy #{human_friendly_model_name} with associated content"
    end
  end

  def human_friendly_model_name
    model_name.humanize
  end

  def build_object
    @topical_event = model_class.new
  end

  def load_object
    @topical_event = model_class.friendly.find(params[:id])
  end

  def model_name
    model_class.name.underscore
  end

private

  def model_class
    TopicalEvent
  end

  def build_associated_objects
    @topical_event.social_media_accounts.build
  end

  def destroy_blank_social_media_accounts
    if params[:topical_event][:social_media_accounts_attributes]
      params[:topical_event][:social_media_accounts_attributes].each_pair do |_key, account|
        if account[:social_media_service_id].blank? && account[:url].blank?
          account[:_destroy] = "1"
        end
      end
    end
  end

  def object_params
    params.require(model_name).permit(
      :name,
      :summary,
      :description,
      :logo,
      :logo_alt_text,
      :logo_cache,
      :remove_logo,
      :start_date,
      :end_date,
      related_topical_event_ids: [],
      topical_event_membership_attributes: %i[id ordering],
      social_media_accounts_attributes: %i[social_media_service_id url _destroy id],
      featured_links_attributes: %i[title url _destroy id],
      topical_event_organisations_attributes: %i[id lead lead_ordering],
    )
  end
end


text:
{% extends "base.html" %}

{% block title %}Search Results{% endblock %}

{% block content %}

Search Results

You searched for "{{keywords}}"

In the US Mainstream Media online there have {{ sentenceCount }} sentences matching your search so far this year.

{% endblock %}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.css" />
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
  <link href="app.css" rel="stylesheet">

  <link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="96x96" href="favicon-96x96.png">
  <link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png">
  <link rel="icon" type="image/png" sizes="16x16" href="favicon.ico">
  <title>Texplorer</title>

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          Toggle navigation

        </button>
        Texplorer

Home

About

Contact


text:
package org.apache.crunch.examples;

import org.apache.crunch.DoFn;
import org.apache.crunch.Emitter;
import org.apache.crunch.PCollection;
import org.apache.crunch.PTable;
import org.apache.crunch.Pipeline;
import org.apache.crunch.impl.mr.MRPipeline;
import org.apache.crunch.lib.Aggregate;
import org.apache.crunch.types.writable.Writables;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.Serializable;

public class WordCount extends Configured implements Tool, Serializable {
  public int run(String[] args) throws Exception {
    if(args.length != 3) {
      System.err.println();
      System.err.println("Usage: " + this.getClass().getName() + " [generic options] input output");
      System.err.println();
      GenericOptionsParser.printGenericCommandUsage(System.err);
      return 1;
    }
    // Create an object to coordinate pipeline creation and execution.
    Pipeline pipeline = new MRPipeline(WordCount.class, getConf());
    // Reference a given text file as a collection of Strings.
    PCollection<String> lines = pipeline.readTextFile(args[1]);

    // Define a function that splits each line in a PCollection of Strings into a
    // PCollection made up of the individual words in the file.
    PCollection<String> words = lines.parallelDo(new DoFn<String, String>() {
      public void process(String line, Emitter<String> emitter) {
        for (String word : line.split("\\s+")) {
          emitter.emit(word);
        }
      }
    }, Writables.strings()); // Indicates the serialization format

    // The count method applies a series of Crunch primitives and returns
    // a map of the unique words in the input PCollection to their counts.
    // Best of all, the count() function doesn't need to know anything about
    // the kind of data stored in the input PCollection.
    PTable<String, Long> counts = words.count();

    // Instruct the pipeline to write the resulting counts to a text file.
    pipeline.writeTextFile(counts, args[2]);
    // Execute the pipeline as a MapReduce.
    pipeline.done();
    return 0;
  }

  public static void main(String[] args) throws Exception {
    ToolRunner.run(new Configuration(), new WordCount(), args);
  }
}


text:
#pragma once

namespace mqsProvider
{
	class SharedMemoryAccess
	{
	public:
		SharedMemoryAccess(void);
		virtual ~SharedMemoryAccess(void);
		bool bind(void);
		void detach(void);

		void* sharedMemoryPtr(void);
	private:
		void* m_sharedMemoryPtr;
		virtual void* specificBind(void) = 0;
		virtual void specificDetach(void) = 0;
	};
}//namespace mqsProvider


text:
#pragma once
#include <aws/securityhub/SecurityHub_EXPORTS.h>
#include <aws/securityhub/SecurityHubRequest.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace SecurityHub
{
namespace Model
{

  /**
   */
  class AWS_SECURITYHUB_API EnableSecurityHubRequest : public SecurityHubRequest
  {
  public:
    EnableSecurityHubRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "EnableSecurityHub"; }

    Aws::String SerializePayload() const override;

    /**
     *
The tags to add to the hub resource when you enable Security Hub.

     */
    inline const Aws::Map<Aws::String, Aws::String>& GetTags() const{ return m_tags; }

    /**
     *
The tags to add to the hub resource when you enable Security Hub.

     */
    inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; }

    /**
     *
The tags to add to the hub resource when you enable Security Hub.

     */
    inline void SetTags(const Aws::Map<Aws::String, Aws::String>& value) { m_tagsHasBeenSet = true; m_tags = value; }

    /**
     *
The tags to add to the hub resource when you enable Security Hub.

     */
    inline void SetTags(Aws::Map<Aws::String, Aws::String>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }

    /**
     *
The tags to add to the hub resource when you enable Security Hub.

     */
    inline EnableSecurityHubRequest& WithTags(const Aws::Map<Aws::String, Aws::String>& value) { SetTags(value); return *this;}

    /**
     *
The tags to add to the hub resource when you enable Security Hub.

     */
    inline EnableSecurityHubRequest& WithTags(Aws::Map<Aws::String, Aws::String>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
The tags to add to the hub resource when you enable Security Hub.

     */
    inline EnableSecurityHubRequest& AddTags(const Aws::String& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; }

    /**
     *
The tags to add to the hub resource when you enable Security Hub.

     */
    inline EnableSecurityHubRequest& AddTags(Aws::String&& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; }

    /**
     *
The tags to add to the hub resource when you enable Security Hub.

     */
    inline EnableSecurityHubRequest& AddTags(const Aws::String& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; }

    /**
     *
The tags to add to the hub resource when you enable Security Hub.

     */
    inline EnableSecurityHubRequest& AddTags(Aws::String&& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), std::move(value)); return *this; }

    /**
     *
The tags to add to the hub resource when you enable Security Hub.

     */
    inline EnableSecurityHubRequest& AddTags(const char* key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; }

    /**
     *
The tags to add to the hub resource when you enable Security Hub.

     */
    inline EnableSecurityHubRequest& AddTags(Aws::String&& key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; }

    /**
     *
The tags to add to the hub resource when you enable Security Hub.

     */
    inline EnableSecurityHubRequest& AddTags(const char* key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; }

    /**
     *
Whether to enable the security standards that Security Hub has designated as
     * automatically enabled. If you do not provide a value for
     * EnableDefaultStandards, it is set to true. To not
     * enable the automatically enabled standards, set
     * EnableDefaultStandards to false.

     */
    inline bool GetEnableDefaultStandards() const{ return m_enableDefaultStandards; }

    /**
     *
Whether to enable the security standards that Security Hub has designated as
     * automatically enabled. If you do not provide a value for
     * EnableDefaultStandards, it is set to true. To not
     * enable the automatically enabled standards, set
     * EnableDefaultStandards to false.

     */
    inline bool EnableDefaultStandardsHasBeenSet() const { return m_enableDefaultStandardsHasBeenSet; }

    /**
     *
Whether to enable the security standards that Security Hub has designated as
     * automatically enabled. If you do not provide a value for
     * EnableDefaultStandards, it is set to true. To not
     * enable the automatically enabled standards, set
     * EnableDefaultStandards to false.

     */
    inline void SetEnableDefaultStandards(bool value) { m_enableDefaultStandardsHasBeenSet = true; m_enableDefaultStandards = value; }

    /**
     *
Whether to enable the security standards that Security Hub has designated as
     * automatically enabled. If you do not provide a value for
     * EnableDefaultStandards, it is set to true. To not
     * enable the automatically enabled standards, set
     * EnableDefaultStandards to false.

     */
    inline EnableSecurityHubRequest& WithEnableDefaultStandards(bool value) { SetEnableDefaultStandards(value); return *this;}

  private:

    Aws::Map<Aws::String, Aws::String> m_tags;
    bool m_tagsHasBeenSet = false;

    bool m_enableDefaultStandards;
    bool m_enableDefaultStandardsHasBeenSet = false;
  };

} // namespace Model
} // namespace SecurityHub
} // namespace Aws


text:
package org.eclipse.ceylon.compiler.java.test.interop;

import org.eclipse.ceylon.common.NonNull;
//NOTE: DO NOT REMOVE, apparently we generate a Class type in this damn package
import java.lang.Class;

public class ClassLiteral {
    public class MemberClass {}
    public static class StaticMemberClass {}
    @NonNull
    public static String classString(Class<?> c) {
        return c.toString();
    }
}


text:
package gov.hhs.onc.sdcct.data.db.impl;

import com.github.sebhoss.warnings.CompilerWarnings;
import gov.hhs.onc.sdcct.beans.IdentifiedBean;
import gov.hhs.onc.sdcct.data.db.DbObjectType;
import gov.hhs.onc.sdcct.data.db.security.DbAuthority;
import gov.hhs.onc.sdcct.data.db.security.DbPrivilegeType;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.HSQLDialect;
import org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo;
import org.hibernate.engine.jdbc.dialect.spi.DialectResolver;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hsqldb.persist.HsqlDatabaseProperties;

public class SdcctHsqlDialect extends HSQLDialect {
    public static class SdcctHsqlDialectResolver extends AbstractDbService implements DialectResolver {
        public final static SdcctHsqlDialectResolver INSTANCE = new SdcctHsqlDialectResolver();

        private final static long serialVersionUID = 0L;

        @Nullable
        @Override
        public Dialect resolveDialect(DialectResolutionInfo info) {
            return (info.getDatabaseName().equals(HsqlDatabaseProperties.PRODUCT_NAME) ? SdcctHsqlDialect.INSTANCE : null);
        }
    }

    public static class SdcctHsqlDialectResolverContributor extends AbstractDbServiceContributor<SdcctHsqlDialectResolver> {
        public SdcctHsqlDialectResolverContributor() {
            super(SdcctHsqlDialectResolver.class);
        }

        @Override
        @SuppressWarnings({ CompilerWarnings.RAWTYPES })
        public SdcctHsqlDialectResolver initiateService(Map configValues, ServiceRegistryImplementor serviceRegistry) {
            serviceRegistry.locateServiceBinding(DialectResolver.class).setService(SdcctHsqlDialectResolver.INSTANCE);

            return SdcctHsqlDialectResolver.INSTANCE;
        }
    }

    public final static SdcctHsqlDialect INSTANCE = new SdcctHsqlDialect();

    private final static String ARG_DELIM = ", ";

    private final static String CREATE_SQL_FORMAT_PREFIX = "create ";
    private final static String GRANT_SQL_FORMAT_PREFIX = "grant ";

    private final static String GRANT_TO_SQL_FORMAT_SUFFIX = "to \"%s\";";

    private final static String CREATE_ROLE_SQL_FORMAT = CREATE_SQL_FORMAT_PREFIX + "role \"%s\";";
    private final static String CREATE_USER_SQL_FORMAT = CREATE_SQL_FORMAT_PREFIX + "user \"%s\" password '%s';";
    private final static String GRANT_ON_SQL_FORMAT = GRANT_SQL_FORMAT_PREFIX + "%s on %s %s " + GRANT_TO_SQL_FORMAT_SUFFIX;
    private final static String GRANT_ROLE_SQL_FORMAT = GRANT_SQL_FORMAT_PREFIX + "\"%s\"" + GRANT_TO_SQL_FORMAT_SUFFIX;

    public String getGrantOnString(DbAuthority authority, String ... granteeNames) {
        return this.getGrantOnString(authority.getPrivileges(), authority.getObjectType(), authority.getObjectName(), granteeNames);
    }

    public String getGrantOnString(Set<DbPrivilegeType> privileges, DbObjectType objType, String name, String ... granteeNames) {
        return String.format(GRANT_ON_SQL_FORMAT, privileges.stream().map(IdentifiedBean::getId).collect(Collectors.joining(ARG_DELIM)), objType.getId(), name,
            StringUtils.join(granteeNames, ARG_DELIM));
    }

    public String getGrantRoleString(String name, String ... granteeNames) {
        return String.format(GRANT_ROLE_SQL_FORMAT, name, StringUtils.join(granteeNames, ARG_DELIM));
    }

    public String getCreateRoleString(String name) {
        return String.format(CREATE_ROLE_SQL_FORMAT, name);
    }

    public String getCreateUserString(String name, String pass) {
        return String.format(CREATE_USER_SQL_FORMAT, name, pass);
    }
}


text:
title: OnMasterTableViewCreated
page_title: OnMasterTableViewCreated | RadGrid for ASP.NET AJAX Documentation
description: OnMasterTableViewCreated
slug: grid/client-side-programming/events/onmastertableviewcreated
tags: onmastertableviewcreated
published: True
position: 46
---

# OnMasterTableViewCreated

##

Sys.EventArgs OnMasterTableViewCreated Property

>note To get or set property values for client API properties, you must call property accessor methods that are named with the get_ and set_ prefixes. For example, to get or set a value for a property such as [cancel](http://msdn.microsoft.com/en-us/library/bb310859.aspx), you call the get_cancel or set_cancel.
>

This event is fired after the MasterTableView is created.

|  **Fired by**  | RadGrid |
| ------ | ------ |
| **Arguments** |N/A|
| **Can be canceled** |No|

Example:

````ASP.NET
	    <telerik:RadGrid ID="RadGrid1" runat="server">
	        <ClientSettings>
	            <ClientEvents OnMasterTableViewCreated="MasterTableViewCreated" />
	        </ClientSettings>
	    </telerik:RadGrid>
````

````JavaScript
	        function MasterTableViewCreated(sender, eventArgs) {
	            alert("MasterTableView was created");
	        }
````


text:
require 'csv'

module Mine
  module App
    class Accumulator < Xref
      include Enumerable

      KEY_DELIM = '^'

      attr_accessor :sequence, :current_key

      def initialize(*)
        super

        self.sequence = '00000'
      end

      def get(key)
        super composite(key)
      end

      def add(key, *values)
        self.current_key = composite(key)

        super current_key, *values
      end

      def <<(value)
        dict[get_current_key] << value

        self
      end

      def +(values)
        dict[get_current_key] += [ values ].flatten

        self
      end

      def current
        dict[current_key]
      end

      #def assign(key_value_pairs)
      #  key_value_pairs.each_slice(2) do |(key, values)|
      #    add key, *[values].flatten
      #  end
      #end

      def each
        (dict.dict.keys.sort).each {|key| yield dict[key] }
      end

      def csv
        map &:to_csv
      end

      def write(path)
        File.open csv_path(path), 'w' do |stream|
          stream.write csv.join
        end
      end

      private

      CSV_EXT = '.csv'
      def csv_path(path)
        path + (path.end_with?(CSV_EXT) ? '' : CSV_EXT)
      end

      def get_current_key
        current_key or raise "No key present. Must first call #add"
      end

      def composite(key)
        to_key(key) * KEY_DELIM
      end

      def to_key(key)
        [ key ].flatten.map {|element| element or next_sequence }
      end

      def next_sequence
        sequence.succ!.dup
      end
    end
  end
end


text:
.demo-swipe {
  padding: 20px 10px;
}

.no-select {
  pointer-events: none;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace ChronicNetCore.Handlers
{
    public class ComplexHandler
    {
        readonly HandlerPattern[] _patterns;
        public IHandler BaseHandler { get; private set; }

        public ComplexHandler(IHandler handler, IEnumerable<HandlerPattern> patterns)
        {
            BaseHandler = handler;
            _patterns = patterns.ToArray();
        }

        public bool Match(IList<Token> tokens, HandlerRegistry registry)
        {
            var tokenIndex = 0;
            foreach (var pattern in _patterns)
            {
                var isOptional = pattern.IsOptional;
                var isRequired = !isOptional;
                var thereAreNoMoreTokens = tokenIndex == tokens.Count;

                if (pattern is TagPattern)
                {
                    var match = tokenIndex < tokens.Count &&
                        tokens[tokenIndex].IsTaggedAs((pattern as TagPattern).TagType);
                    if (match == false && isRequired)
                    {
                        return false;
                    }
                    if (match)
                    {
                        tokenIndex++;
                    }
                }
                else if (pattern is RepeatPattern)
                {
                    var repetition = pattern as RepeatPattern;
                    int advancement;
                    var match = repetition.Match(tokens.Skip(tokenIndex).ToList(), out advancement);
                    if (match == false && isRequired)
                    {
                        return false;
                    }
                    if (match)
                    {
                        tokenIndex += advancement;
                    }
                }
                else if (pattern is HandlerTypePattern)
                {
                    if (isOptional && thereAreNoMoreTokens)
                    {
                        return true;
                    }
                    var subHandlers = registry.GetHandlers((pattern as HandlerTypePattern).Type);
                    foreach (var handler in subHandlers)
                    {
                        if (handler.Match(tokens.Skip(tokenIndex).ToList(), registry))
                        {
                            return true;
                        }
                    }
                }
            }

            if (tokenIndex != tokens.Count)
            {
                return false;
            }
            return true;
        }

        public override string ToString()
        {
            return string.Format("{0} => {1}",
                String.Join("", _patterns.Select(pattern => pattern.ToString())),
                ((BaseHandler != null) ? BaseHandler.GetType().Name : "<null>"));
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>TIL.LY - Today I Learned</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/grayscale.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

                        About

                        Download

                        Contact

TIL.LY

An experiment in encouraging regular reflection and presence through the use of a microdiary webapp and chatbot.

About

The brain cheats when it comes to happiness.

According to psychologist Daniel Kahneman, it focuses on two things about an event, the emotional peak and the end. He declares in his TED talk that "We don't choose between experiences, we choose between memories of experiences."

In the study A "Present" for the Future: The Unexpected Value of Rediscovery, Harvard Business School researchers discovered that the documentation of the everyday might seem trivial, but provides unexpected happiness because over time, we can come to see the ordinary past as extraordinary.

TIL.LY (Today I Learned) is an experiment in encouraging daily presence, reflection, and documentation of the everyday. Using text analysis (with Alchemy's Natural Language Processing) it resurfaces your past memories over time with animated GIFs from Giphy.

Download TIL.LY

You can download source code for TIL.LY at Github. The Chatbot requires the Webapp and Backend to be set up first.

                    TIL.LY Webapp and Backend
                    TIL.LY Chatbot

Contact

Feel free to email us to provide feedback or provide suggestions.

                         Other projects from Song


text:
<!DOCTYPE html>
<html>
  <head>
    <title>Skip Tasks</title>
    <link rel="shortcut icon" href="/dist/favicon.ico" />
  </head>
  <body class="body-sk">
    <task-scheduler-scaffold-sk title="Skip Tasks">
      <skip-tasks-sk></skip-tasks-sk>
    </task-scheduler-scaffold-sk>
  </body>
</html>


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>org.apache.solr.handler.loader Class Hierarchy (Solr 6.3.0 API)</title>
<meta name="date" content="2016-11-02">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.apache.solr.handler.loader

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.apache.solr.handler.loader.ContentStreamLoader

org.apache.solr.handler.loader.CSVLoader

org.apache.solr.handler.loader.JavabinLoader

org.apache.solr.handler.loader.JsonLoader

org.apache.solr.handler.loader.XMLLoader

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

          Copyright © 2000-2016 Apache Software Foundation.  All Rights Reserved.


text:
import React, { Component } from "react";
import {
  Appear,
  BlockQuote,
  Cite,
  Deck,
  Fill,
  Heading,
  Layout,
  Link,
  ListItem,
  List,
  Quote,
  Slide,
  Spectacle,
  Text
} from "spectacle";

import preloader from "spectacle/lib/utils/preloader";
import createTheme from "spectacle/lib/themes/default";

const images = {
  city: "a-url"
};

// $FlowExpectedError
preloader(10);
preloader(images);

// $FlowExpectedError
const badTheme = createTheme("white");
const theme = createTheme(
  {
    primary: "white",
    secondary: "#1F2022",
    tertiary: "#03A9FC",
    quartenary: "#CECECE"
  },
  {
    primary: "Montserrat",
    secondary: "Helvetica"
  }
);

class BadSpectacle extends Component<*> {
  render() {
    // $FlowExpectedError
    return <Spectacle theme="white" />;
  }
}

class GoodSpectacle extends Component<*> {
  callback() {
    alert("Callback: " + JSON.stringify(arguments));
  }

  render() {
    return (
      <Spectacle>
        <Deck transition={["zoom", "slide"]} transitionDuration={500}>
          <Slide transition={["zoom"]} bgColor="primary">
            <Heading size={1} fit caps lineHeight={1} textColor="black">
              Spectacle
            </Heading>
            <Heading size={1} fit caps>
              A ReactJS Presentation Library
            </Heading>
            <Heading size={1} fit caps textColor="black">
              Where You Can Write Your Decks In JSX
            </Heading>
            <Link href="https://github.com/FormidableLabs/spectacle">
              <Text bold caps textColor="tertiary">
                View on Github
              </Text>
            </Link>
            <Text textSize="1.5em" margin="20px 0px 0px" bold>
              Hit Your Right Arrow To Begin!
            </Text>
          </Slide>
          <Slide
            transition={["slide"]}
            bgColor="black"
            notes="You can even put notes on your slide. How awesome is that?"
          >
            <Heading size={2} caps fit textColor="primary" textFont="primary">
              Wait what?
            </Heading>
          </Slide>
          <Slide transition={["slide"]} bgDarken={0.75}>
            <Appear fid="1">
              <Heading size={1} caps fit textColor="primary">
                Full Width
              </Heading>
            </Appear>
            <Appear fid="2">
              <Heading size={1} caps fit textColor="tertiary">
                Adjustable Darkness
              </Heading>
            </Appear>
            <Appear fid="3">
              <Heading size={1} caps fit textColor="primary">
                Background Imagery
              </Heading>
            </Appear>
          </Slide>
          <Slide transition={["zoom", "fade"]} bgColor="primary">
            <Heading caps fit>
              Flexible Layouts
            </Heading>
            <Layout>
              <Fill>
                <Heading
                  size={4}
                  caps
                  textColor="secondary"
                  bgColor="white"
                  margin={10}
                >
                  Left
                </Heading>
              </Fill>
              <Fill>
                <Heading
                  size={4}
                  caps
                  textColor="secondary"
                  bgColor="white"
                  margin={10}
                >
                  Right
                </Heading>
              </Fill>
            </Layout>
          </Slide>
          <Slide transition={["slide"]} bgColor="black">

              <Quote>Wonderfully formatted quotes</Quote>
              Ken Wheeler

          </Slide>
          <Slide transition={["slide", "spin"]} bgColor="primary">
            <Heading caps fit size={1} textColor="tertiary">
              Smooth
            </Heading>
            <Heading caps fit size={1} textColor="secondary">
              Combinable Transitions
            </Heading>
          </Slide>
          <Slide transition={["fade"]} bgColor="secondary" textColor="primary">
            <List>
              <Appear>
                <ListItem>Inline style based theme system</ListItem>
              </Appear>
              <Appear>
                <ListItem>Autofit text</ListItem>
              </Appear>
              <Appear>
                <ListItem>Flexbox layout system</ListItem>
              </Appear>
              <Appear>
                <ListItem>React-Router navigation</ListItem>
              </Appear>
              <Appear>
                <ListItem>PDF export</ListItem>
              </Appear>
              <Appear>
                <ListItem>And...</ListItem>
              </Appear>
            </List>
          </Slide>
        </Deck>
      </Spectacle>
    );
  }
}


text:
using System;

namespace vm.Aspects.Wcf.Behaviors.AuthorizationManager
{
    /// <summary>
    /// Class AllowOpenIdUnauthenticatedAttribute. This class cannot be inherited.
    /// Specifies that the method of the interface or class or the single method to which the attribute is applied can be called unauthenticated.
    /// </summary>
    /// <seealso cref="System.Attribute" />
    [AttributeUsage(
        AttributeTargets.Class |
        AttributeTargets.Interface |
        AttributeTargets.Method,
        AllowMultiple = false,
        Inherited = false)]
    public sealed class AllowUnauthenticatedAttribute : Attribute
    {
        /// <summary>
        /// The default role to be assigned to the unauthenticated principal.
        /// </summary>
        public const string DefaultName = "Anonymous";
        /// <summary>
        /// The default role to be assigned to the unauthenticated principal.
        /// </summary>
        public const string DefaultRole = "Guest";

        /// <summary>
        /// Gets the name of the unauthenticated principal.
        /// </summary>
        public string Name { get; }

        /// <summary>
        /// Gets the role of the unauthenticated principal.
        /// </summary>
        public string Role { get; }

        /// <summary>
        /// Gets a value indicating whether unauthenticated calls are allowed.
        /// </summary>
        public bool UnauthenticatedCallsAllowed { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="AllowUnauthenticatedAttribute" /> class.
        /// </summary>
        /// <param name="name">The name of the unauthenticated principal.</param>
        /// <param name="role">The role of the unauthenticated principal.</param>
        /// <param name="unauthenticatedCallsAllowed">if set to <c>true</c> unauthenticated calls are allowed.</param>
        /// <exception cref="System.ArgumentException">The argument cannot be null, empty string or consist of whitespace characters only. - name</exception>
        public AllowUnauthenticatedAttribute(
            string name = DefaultName,
            string role = DefaultRole,
            bool unauthenticatedCallsAllowed = true)
        {
            if (name.IsNullOrWhiteSpace())
                throw new ArgumentException("The argument cannot be null, empty string or consist of whitespace characters only.", nameof(name));

            Name                        = name;
            Role                        = role;
            UnauthenticatedCallsAllowed = unauthenticatedCallsAllowed;
        }
    }
}


text:
package com.google.ads.googleads.v10.resources;

public final class AdGroupCriterionLabelProto {
  private AdGroupCriterionLabelProto() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistryLite registry) {
  }

  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions(
        (com.google.protobuf.ExtensionRegistryLite) registry);
  }
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v10_resources_AdGroupCriterionLabel_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v10_resources_AdGroupCriterionLabel_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static  com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\nAgoogle/ads/googleads/v10/resources/ad_" +
      "group_criterion_label.proto\022\"google.ads." +
      "googleads.v10.resources\032\037google/api/fiel" +
      "d_behavior.proto\032\031google/api/resource.pr" +
      "oto\"\246\003\n\025AdGroupCriterionLabel\022M\n\rresourc" +
      "e_name\030\001 \001(\tB6\340A\005\372A0\n.googleads.googleap" +
      "is.com/AdGroupCriterionLabel\022R\n\022ad_group" +
      "_criterion\030\004 \001(\tB1\340A\005\372A+\n)googleads.goog" +
      "leapis.com/AdGroupCriterionH\000\210\001\001\022:\n\005labe" +
      "l\030\005 \001(\tB&\340A\005\372A \n\036googleads.googleapis.co" +
      "m/LabelH\001\210\001\001:\214\001\352A\210\001\n.googleads.googleapi" +
      "s.com/AdGroupCriterionLabel\022Vcustomers/{" +
      "customer_id}/adGroupCriterionLabels/{ad_" +
      "group_id}~{criterion_id}~{label_id}B\025\n\023_" +
      "ad_group_criterionB\010\n\006_labelB\214\002\n&com.goo" +
      "gle.ads.googleads.v10.resourcesB\032AdGroup" +
      "CriterionLabelProtoP\001ZKgoogle.golang.org" +
      "/genproto/googleapis/ads/googleads/v10/r" +
      "esources;resources\242\002\003GAA\252\002\"Google.Ads.Go" +
      "ogleAds.V10.Resources\312\002\"Google\\Ads\\Googl" +
      "eAds\\V10\\Resources\352\002&Google::Ads::Google" +
      "Ads::V10::Resourcesb\006proto3"
    };
    descriptor = com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
          com.google.api.FieldBehaviorProto.getDescriptor(),
          com.google.api.ResourceProto.getDescriptor(),
        });
    internal_static_google_ads_googleads_v10_resources_AdGroupCriterionLabel_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_google_ads_googleads_v10_resources_AdGroupCriterionLabel_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v10_resources_AdGroupCriterionLabel_descriptor,
        new java.lang.String[] { "ResourceName", "AdGroupCriterion", "Label", "AdGroupCriterion", "Label", });
    com.google.protobuf.ExtensionRegistry registry =
        com.google.protobuf.ExtensionRegistry.newInstance();
    registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
    registry.add(com.google.api.ResourceProto.resource);
    registry.add(com.google.api.ResourceProto.resourceReference);
    com.google.protobuf.Descriptors.FileDescriptor
        .internalUpdateFileDescriptor(descriptor, registry);
    com.google.api.FieldBehaviorProto.getDescriptor();
    com.google.api.ResourceProto.getDescriptor();
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
<?php namespace Mico\Services\Validators;

class ItemValidator extends Validator {

	public static $rules = array(
		'save' => array(
			'name' => 'required'
		),
		'create' => array(),
		'update' => array()
	);

	public static $customMessages = array();
}


text:
class AlbumNameSerializer < ApplicationSerializer
  attributes :locale, :name, :default, :original

  def type
    'album-names'
  end
end


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="lang" content="en" />
    <meta name="author" content="Jorix" />
    <meta name="description" content="Example of OpenLayers to load KML data and StyleMap with normal and highlight styles" />
    <meta name="keywords" content="OpenLayers, kml, popup, feature, StyleMap, highlight" />
    <link rel="stylesheet" href="http://jorix.github.com/OL-Ragbag/examples/github-pages/forkme_banner.css" type="text/css">

    <title>Example of OpenLayers to load KML data & StyleMap with "normal" and "highlight" styles</title>
    <link rel="stylesheet" href="http://dev.openlayers.org/theme/default/style.css" type="text/css">
    <link rel="stylesheet" href="http://dev.openlayers.org/examples/style.css" type="text/css">

Example of OpenLayers to load KML data & StyleMap with "normal" and "highlight" styles

    View on GitHub

        kml, popup, feature, StyleMap, highlight

      Demonstrates loading a KML extracting attributes and StyleMap with "normal" and "highlight" styles.


text:
import os
import lightgbm as lgb
import numpy as np
import pandas as pd
from sklearn.model_selection import RandomizedSearchCV, StratifiedShuffleSplit

# Dataset
DATASET_FOLDER_PATH = os.path.join(
    os.path.expanduser("~"), "Documents/Dataset/Gene Expression Prediction")
MODEL_FOLDER_PATH = os.path.join(DATASET_FOLDER_PATH, "model")
SUBMISSION_FOLDER_PATH = os.path.join(DATASET_FOLDER_PATH, "submission")

def load_dataset():
    # Read csv files
    x_train = pd.read_csv(os.path.join(DATASET_FOLDER_PATH,
                                       "train/x_train.csv")).as_matrix()
    x_test = pd.read_csv(os.path.join(DATASET_FOLDER_PATH,
                                      "test/x_test.csv")).as_matrix()
    y_train = pd.read_csv(os.path.join(DATASET_FOLDER_PATH,
                                       "train/y_train.csv")).as_matrix()

    # Remove the first column
    x_train = x_train[:, 1:]
    x_test = x_test[:, 1:]
    y_train = y_train[:, 1:]

    # Every 100 rows correspond to one gene. Extract all 100-row-blocks into a list using np.split.
    num_genes_train = x_train.shape[0] / 100
    num_genes_test = x_test.shape[0] / 100
    x_train = np.split(x_train, num_genes_train)
    x_test = np.split(x_test, num_genes_test)

    # Reshape by raveling each 100x5 array into a 500-length vector
    x_train = [g.ravel() for g in x_train]
    x_test = [g.ravel() for g in x_test]

    # Convert data from list to array
    x_train = np.array(x_train)
    y_train = np.array(y_train)
    x_test = np.array(x_test)
    y_train = np.ravel(y_train)

    return x_train, y_train, x_test

def run():
    print("Creating folder ...")
    os.makedirs(MODEL_FOLDER_PATH, exist_ok=True)
    os.makedirs(SUBMISSION_FOLDER_PATH, exist_ok=True)

    print("Loading dataset ...")
    x_train, y_train, x_test = load_dataset()

    print("Performing parameter optimization ...")
    # estimator = lgb.LGBMClassifier()
    # param_grid = {
    #     "num_leaves": [31, 63, 127, 255],
    #     "learning_rate": [0.01, 0.05, 0.1],
    #     "n_estimators": [50, 100, 200],
    #     "subsample" : [0.8, 0.9, 1],
    #     "colsample_bytree" : [0.8, 0.9, 1],
    #     "reg_alpha" : [0, 0.1, 0.5],
    #     "objective" : ["binary"]
    # }
    # randomizedsearch_object = RandomizedSearchCV(estimator, param_grid, n_iter=100, cv=5, scoring="roc_auc", refit=False, verbose=3)
    # randomizedsearch_object.fit(x_train, y_train)
    # print("Best score is: {}".format(randomizedsearch_object.best_score_))
    # print("Best parameters are: {}".format(randomizedsearch_object.best_params_))
    # Best score is: 0.9176406673636928
    # Best parameters are: {'subsample': 0.9, 'reg_alpha': 0, 'objective': 'binary', 'num_leaves': 255, 'n_estimators': 200, 'learning_rate': 0.05, 'colsample_bytree': 0.9}
    best_params = {
        "num_leaves": 255,
        "learning_rate": 0.05,
        "subsample": 0.9,
        "colsample_bytree": 0.9,
        "reg_alpha": 0,
        "objective": "binary",
        "metric": "auc"
    }

    prediction_array_list = []
    cv_object = StratifiedShuffleSplit(n_splits=100,
                                       test_size=0.2,
                                       random_state=0)
    for cv_index, (train_index,
                   valid_index) in enumerate(cv_object.split(x_train, y_train),
                                             start=1):
        submission_file_path = os.path.join(
            SUBMISSION_FOLDER_PATH, "submission_{}.csv".format(cv_index))
        if not os.path.isfile(submission_file_path):
            model_file_path = os.path.join(MODEL_FOLDER_PATH,
                                           "model_{}.txt".format(cv_index))
            if not os.path.isfile(model_file_path):
                train_data = lgb.Dataset(x_train[train_index],
                                         label=y_train[train_index])
                validation_data = lgb.Dataset(x_train[valid_index],
                                              label=y_train[valid_index],
                                              reference=train_data)
                model = lgb.train(params=best_params,
                                  train_set=train_data,
                                  num_boost_round=1000000,
                                  valid_sets=[validation_data],
                                  early_stopping_rounds=100)
                model.save_model(model_file_path,
                                 num_iteration=model.best_iteration)

            assert os.path.isfile(model_file_path)
            print("Loading weights from {}".format(
                os.path.basename(model_file_path)))
            model = lgb.Booster(model_file=model_file_path)

            # Generate prediction
            prediction_array = np.expand_dims(model.predict(x_test), axis=-1)
            prediction_array_list.append(prediction_array)

            # Save prediction to disk
            submission_file_content = pd.DataFrame(np.hstack(
                (np.expand_dims(np.arange(len(prediction_array)), axis=-1) + 1,
                 prediction_array)),
                                                   columns=[
                                                       "GeneId", "Prediction"
                                                   ])
            submission_file_content.GeneId = submission_file_content.GeneId.astype(
                int)
            submission_file_content.to_csv(submission_file_path, index=False)
            print("Submission saved at {}".format(submission_file_path))
        else:
            # Load prediction
            prediction_array = np.expand_dims(
                pd.read_csv(submission_file_path).as_matrix()[:, 1], axis=-1)
            prediction_array_list.append(prediction_array)

    # Ensemble predictions
    for ensemble_func, ensemble_func_name in zip(
        [np.max, np.min, np.mean, np.median], ["max", "min", "mean", "median"]):
        submission_file_path = os.path.join(
            SUBMISSION_FOLDER_PATH,
            "submission_{}.csv".format(ensemble_func_name))
        if not os.path.isfile(submission_file_path):
            prediction_array = ensemble_func(prediction_array_list, axis=0)

            # Save prediction to disk
            submission_file_content = pd.DataFrame(np.hstack(
                (np.expand_dims(np.arange(len(prediction_array)), axis=-1) + 1,
                 prediction_array)),
                                                   columns=[
                                                       "GeneId", "Prediction"
                                                   ])
            submission_file_content.GeneId = submission_file_content.GeneId.astype(
                int)
            submission_file_content.to_csv(submission_file_path, index=False)
            print("Submission saved at {}".format(submission_file_path))

    print("All done!")

if __name__ == "__main__":
    run()


text:
namespace base {

// Do not assert in this function since it is used by the asssertion code!
std::string SysWideToUTF8(const std::wstring& wide) {
  return SysWideToMultiByte(wide, CP_UTF8);
}

// Do not assert in this function since it is used by the asssertion code!
std::wstring SysUTF8ToWide(StringPiece utf8) {
  return SysMultiByteToWide(utf8, CP_UTF8);
}

std::string SysWideToNativeMB(const std::wstring& wide) {
  return SysWideToMultiByte(wide, CP_ACP);
}

std::wstring SysNativeMBToWide(StringPiece native_mb) {
  return SysMultiByteToWide(native_mb, CP_ACP);
}

// Do not assert in this function since it is used by the asssertion code!
std::wstring SysMultiByteToWide(StringPiece mb, uint32_t code_page) {
  if (mb.empty())
    return std::wstring();

  int mb_length = static_cast<int>(mb.length());
  // Compute the length of the buffer.
  int charcount = MultiByteToWideChar(code_page, 0,
                                      mb.data(), mb_length, NULL, 0);
  if (charcount == 0)
    return std::wstring();

  std::wstring wide;
  wide.resize(static_cast<size_t>(charcount));
  MultiByteToWideChar(code_page, 0, mb.data(), mb_length, &wide[0], charcount);

  return wide;
}

// Do not assert in this function since it is used by the asssertion code!
std::string SysWideToMultiByte(const std::wstring& wide, uint32_t code_page) {
  int wide_length = static_cast<int>(wide.length());
  if (wide_length == 0)
    return std::string();

  // Compute the length of the buffer we'll need.
  int charcount = WideCharToMultiByte(code_page, 0, wide.data(), wide_length,
                                      NULL, 0, NULL, NULL);
  if (charcount == 0)
    return std::string();

  std::string mb;
  mb.resize(static_cast<size_t>(charcount));
  WideCharToMultiByte(code_page, 0, wide.data(), wide_length,
                      &mb[0], charcount, NULL, NULL);

  return mb;
}

}  // namespace base


text:
<!doctype html>

   <meta charset="utf-8">
   <title>107 Animations</title>
   <link rel="icon" href="../../img/dragon.ico">

   <link type="text/css" rel="stylesheet" href="css/tutorial.css">

Tutorial 107 - Animations

Powered by Babylon.js

Licensed under Apache 2.0

   </div

      <canvas id="renderCanvas"></canvas>


text:
#ifndef TASK_HPP
#define TASK_HPP

#include <base/integer.hpp>

namespace SASIAE {
  using namespace ::Aversive::Base;
  using namespace ::Aversive;

  typedef void(*TaskFunc)(void);

  //! \brief Define the period and priority of a function called by the scheduler
  class Task {
  protected:
    TaskFunc _func;

    u32 _period;
    u8 _priority;
    bool _unique;

  public:
    //! \brief Default constructor
    inline Task(void)
      : _func(0), _period(0), _priority(0), _unique(true) {
    }

    //! \brief Task constructor
    inline Task(TaskFunc f)
      : _func(f), _period(0), _priority(0), _unique(true) {
    }

    //! \brief Copy Constructor
    inline Task(const Task& other)
      : _func(other._func), _period(other._period),
        _priority(other._priority), _unique(other._unique) {
    }

    //! \brief Copy operation
    inline Task& operator=(const Task& other) {
      _func = other._func;
      _period = other._period;
      _priority = other._priority;
      _unique = other._unique;
      return *this;
    }

    //! \brief Set the interval of time during two task call (in microseconds)
    inline void setPeriod(u32 period_us) {
      _period = period_us;
    }

    //! \brief Set the priority of the task
    /*!

    If two tasks may be executed at the same time, the first to be
    called is the one with the greatest priority

  */
    inline void setPriority(u8 priority) {
      _priority = priority;
    }

    //! \brief Enable periodicity
    inline void setRepeat(void) {
      _unique = false;
    }

    //! \brief Disable periodicity, the task will be removed once executed
    inline void setUnique(void) {
      _unique = true;
    }

    inline u32 period(void) const {
      return _period;
    }

    inline bool isUnique(void) const {
      return _unique;
    }

    inline bool operator==(const Task& other) const {
      return _func == other._func;
    }

    inline void operator()(void) const {
      if(_func) {
          _func();
        }
    }
  };

}

#endif//TASK_HPP


text:
{% extends "pages/default.html" %}

{% block pagecontent %}
<div class='jumbotron'>
   {{ page.content }}
</div>
{% endblock %}

{% block bottomcontent %}
{% endblock %}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TimeyWimey;
using TimeyWimey.Abstractions;

namespace TimeyWimey.Tests
{
	[TestClass]
	public class DateTimeExtensionTests
	{

		[TestMethod]
		public void DateTime_ChangeKind_ChangesKind()
		{
			var time = new DateTime(2016, 03, 17, 13, 0, 0, DateTimeKind.Unspecified);
			var utcExpected = new DateTime(2016, 03, 17, 13, 0, 0, DateTimeKind.Utc);
			var localExpected = new DateTime(2016, 03, 17, 13, 0, 0, DateTimeKind.Local);

			var actual = time.ChangeKind(DateTimeKind.Utc);
			Assert.AreEqual(utcExpected, actual);

			actual = time.ChangeKind(DateTimeKind.Local);
			Assert.AreEqual(localExpected, actual);
		}

		[TestMethod]
		public void DateTime_ChangeKind_DoesNothingWhenKindMatches()
		{
			var time = new DateTime(2016, 03, 17, 13, 0, 0, DateTimeKind.Local);
			var localExpected = new DateTime(2016, 03, 17, 13, 0, 0, DateTimeKind.Local);

			var actual = time.ChangeKind(DateTimeKind.Local);
			Assert.AreEqual(localExpected, actual.ChangeKind(DateTimeKind.Local));
		}

		#region IsFuture

		[TestMethod]
		public void DateTime_IsFuture_ReturnsTrueForFutureDate()
		{
			Assert.AreEqual(true, DateTime.Now.AddHours(1).IsFuture());
		}

		[TestMethod]
		public void DateTime_IsFuture_ReturnsFalseForNow()
		{
			Assert.AreEqual(false, DateTime.Now.IsFuture());
		}

		[TestMethod]
		public void DateTime_IsFuture_ReturnsFalseForPast()
		{
			Assert.AreEqual(false, DateTime.Now.AddDays(-1).IsFuture());
		}

		[ExpectedException(typeof(ArgumentNullException))]
		[TestMethod]
		public void DateTime_IsFuture_ThrowsOnNullClock()
		{
			Assert.AreEqual(false, DateTime.Now.AddDays(-1).IsFuture(null));
		}

		[TestMethod]
		public void DateTime_IsFuture_CustomClock_ReturnsTrueForFutureDate()
		{
			var mockClock = new MockClock();
			mockClock.SetTime(new DateTimeOffset(2017, 02, 21, 22, 39, 00, DateTimeOffset.Now.Offset), false);

			var testTime = new DateTime(2017, 02, 21, 22, 40, 00);
			Assert.AreEqual(true, testTime.IsFuture(mockClock));
		}

		[TestMethod]
		public void DateTime_IsFuture_CustomClock_ReturnsFalseForNow()
		{
			var mockClock = new MockClock();
			mockClock.SetTime(new DateTimeOffset(2017, 02, 21, 22, 39, 00, DateTimeOffset.Now.Offset), false);

			var testTime = new DateTime(2017, 02, 21, 22, 39, 00);
			Assert.AreEqual(false, testTime.IsFuture(mockClock));
		}

		[TestMethod]
		public void DateTime_IsFuture_CustomClock_ReturnsFalseForPast()
		{
			var mockClock = new MockClock();
			mockClock.SetTime(new DateTimeOffset(2017, 02, 21, 22, 39, 00, DateTimeOffset.Now.Offset), false);

			var testTime = new DateTime(2017, 02, 21, 22, 00, 00);
			Assert.AreEqual(false, testTime.IsFuture(mockClock));
		}

		#endregion

		#region IsPast

		[TestMethod]
		public void DateTime_IsPast_ReturnsFalseForFutureDate()
		{
			Assert.AreEqual(false, DateTime.Now.AddHours(1).IsPast());
		}

		[TestMethod]
		public void DateTime_IsPast_ReturnsFalseForNow()
		{
			Assert.AreEqual(false, DateTime.Now.IsPast());
		}

		[TestMethod]
		public void DateTime_IsPast_ReturnsTrueForPast()
		{
			Assert.AreEqual(true, DateTime.Now.AddDays(-1).IsPast());
		}

		[ExpectedException(typeof(ArgumentNullException))]
		[TestMethod]
		public void DateTime_IsPast_ThrowsOnNullClock()
		{
			Assert.AreEqual(false, DateTime.Now.AddDays(-1).IsPast(null));
		}

		[TestMethod]
		public void DateTime_IsPast_CustomClock_ReturnsFalseForFutureDate()
		{
			var mockClock = new MockClock();
			mockClock.SetTime(new DateTimeOffset(2017, 02, 21, 22, 39, 00, DateTimeOffset.Now.Offset), false);

			var testTime = new DateTime(2017, 02, 21, 22, 40, 00);
			Assert.AreEqual(false, testTime.IsPast(mockClock));
		}

		[TestMethod]
		public void DateTime_IsPast_CustomClock_ReturnsFalseForNow()
		{
			var mockClock = new MockClock();
			mockClock.SetTime(new DateTimeOffset(2017, 02, 21, 22, 39, 00, DateTimeOffset.Now.Offset), false);

			var testTime = new DateTime(2017, 02, 21, 22, 39, 00);
			Assert.AreEqual(false, testTime.IsPast(mockClock));
		}

		[TestMethod]
		public void DateTime_IsPast_CustomClock_ReturnsTrueForPast()
		{
			var mockClock = new MockClock();
			mockClock.SetTime(new DateTimeOffset(2017, 02, 21, 22, 39, 00, DateTimeOffset.Now.Offset), false);

			var testTime = new DateTime(2017, 02, 21, 22, 00, 00);
			Assert.AreEqual(true, testTime.IsPast(mockClock));
		}

		#endregion

		#region Truncation

		[TestMethod]
		public void DateTime_TruncateToSeconds_DoesNothingWhenMillsecondsZero()
		{
			var d = new DateTime(2017, 05, 29, 13, 23, 57, 0, DateTimeKind.Local);
			Assert.AreEqual(new DateTime(2017, 05, 29, 13, 23, 57, 0, DateTimeKind.Local), d.TruncateToSeconds());
		}

		[TestMethod]
		public void DateTime_TruncateToSeconds_RemovesMilliseconds()
		{
			var d = new DateTime(2017, 05, 29, 13, 23, 57, 432, DateTimeKind.Local);
			Assert.AreEqual(new DateTime(2017, 05, 29, 13, 23, 57, 0, DateTimeKind.Local), d.TruncateToSeconds());
		}

		[TestMethod]
		public void DateTime_TruncateToMinutes_DoesNothingWhenSecondsAndMillsecondsZero()
		{
			var d = new DateTime(2017, 05, 29, 13, 23, 0, 0, DateTimeKind.Local);
			Assert.AreEqual(new DateTime(2017, 05, 29, 13, 23, 0, 0, DateTimeKind.Local), d.TruncateToMinutes());
		}

		[TestMethod]
		public void DateTime_TruncateToMinutes_RemovesSecondsAndMilliseconds()
		{
			var d = new DateTime(2017, 05, 29, 13, 23, 57, 432, DateTimeKind.Local);
			Assert.AreEqual(new DateTime(2017, 05, 29, 13, 23, 0, 0, DateTimeKind.Local), d.TruncateToMinutes());
		}

		[TestMethod]
		public void DateTime_TruncateToHours_DoesNothingWhenMinutesSecondsAndMillsecondsZero()
		{
			var d = new DateTime(2017, 05, 29, 13, 0, 0, 0, DateTimeKind.Local);
			Assert.AreEqual(new DateTime(2017, 05, 29, 13, 0, 0, 0, DateTimeKind.Local), d.TruncateToHours());
		}

		[TestMethod]
		public void DateTime_TruncateToMinutes_RemovesMinutesSecondsAndMilliseconds()
		{
			var d = new DateTime(2017, 05, 29, 13, 23, 57, 432, DateTimeKind.Local);
			Assert.AreEqual(new DateTime(2017, 05, 29, 13, 0, 0, 0, DateTimeKind.Local), d.TruncateToHours());
		}

		#endregion

	}
}


text:
	                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-3" ng-click="isCollapsed = !isCollapsed">
	                    Toggle navigation

	                </button>

	                        a.c. Note

	                        Home

User Detail

User List

Logout

	                        Notes

Note List

Create Note

	                        To Dos

ToDo List

Create ToDo

		                	Themes

Default

cerulean

cosmo

custom

cyborg

darkly

flatly

journal

lumen

paper

readable

sandstone

simplex

slate

spacelab

superhero

united

yeti

		                	Languages

简体中文

English


text:
```shell
cp OPTIONS SOURCE DEST
```

| Option | Description |
| --- | --- |
| `-R` `-r` | Copy directories recursively. |
| `-p` | Preserve most metadata. |
| `-a` | Archive mode (keep metadata, recursive). |
| `-u` | Update mode (skip files that are newer on the receiver). |


text:
FactoryGirl.define do
  factory :user do
    nome 'Joao da Silva'
    email 'joao@silva.com'
    cpf '12345678909'
  end
end


text:
Solicitud de Programa Presupuestario

             MISION

Evaluar la educación obligatoria, así como cordinar y regular las tareas de evaluación en el marco del Sistema Nacional de Evaluación Edicativa (SNEE) y aportar directrices de mejora con el fin de contribuir al cumplimiento del derecho a una educación de calidad con equidad.

            VISION

El Instituto es un organismo reconocido por su autoridad  en materia de evaluación, por la solidez técnica de sus productos y por sus aportaciones  a las decisiones de política educativa del Estado Mexicano.

Objetivo(s) Estratégico(s):

                        <md-button class="md-raised md-primary" type="submit" ng-click="">
                             Agregar
                        </md-button>

                            <select class="form-control selectdate" name="clave" required>
                                <option value="">Seleccione</option>
                                <option value="1">El SNEE funciona de manera eficaz mediente la cordinación del instituto y la implementación de la Política Nacional de Evaluación de la Evaluación de la Educación en un marco de responsabilidad concurrentes</option>
                            </select>

1.El SNEE funciona de manera eficaz mediente la cordinación del instituto y la implementación de la Política Nacional de Evaluación de la Evaluación de la Educación en un marco de responsabilidad

2.El SNEE funciona de manera eficaz mediente la cordinación del instituto y la implementación de la Política Nacional de Evaluación de la Evaluación de la Educación en un marco de responsabilidad

3.El SNEE funciona de manera eficaz mediente la cordinación del instituto y la implementación de la Política Nacional de Evaluación de la Evaluación de la Educación en un marco de responsabilidad

4.El SNEE funciona de manera eficaz mediente la cordinación del instituto y la implementación de la Política Nacional de Evaluación de la Evaluación de la Educación en un marco de responsabilidad

5.El SNEE funciona de manera eficaz mediente la cordinación del instituto y la implementación de la Política Nacional de Evaluación de la Evaluación de la Educación en un marco de responsabilidad

                Programa Presupuestario:

                    <md-button class="md-raised" ng-click="ctrlCBP.showDetailSearchBudgetProgram('Selección de Programa Presupuestario')">
                        Editar
                    </md-button>
                    <md-button class="md-raised" ng-click="ctrlCBP.showDetailSearchBudgetProgram('Selección de Programa Presupuestario')">
                        Seleccionar
                    </md-button>

                    Programa Presupuestario:

                            M001-Actividades de apoyo administrativo

                        Objetivo del Programa Presupuestario:

                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario,
                            Apoyar al proceso presupuestario.

                <md-button class="md-raised" ng-click="">Registrar</md-button>
                <md-button class="md-raised" ng-click="">Limpiar</md-button>

                            Año
                            Programa Presupuestario
                            Objetivo del Programa Presupuestario

                            2017
                            M001-Actividades de apoyo administrativo
                            Apoyar al proceso presupuestario para mejorar la eficiencia

                            2017
                            M002-Actividades de apoyo administrativo
                            Apoyar al proceso presupuestario para mejorar la eficiencia

                            2017
                            M003-Actividades de apoyo administrativo
                            Apoyar al proceso presupuestario para mejorar la eficiencia

        <md-dialog-actions class="btn-actions pading1015">
            <md-button class="btn" type="submit">Guardar</md-button>
        </md-dialog-actions>