text:
{% load bootstrap3 %}
{% load i18n %}

<!DOCTYPE html>

    <title>
      Speakerfight -
      {% block head_title %}{% endblock head_title %}
    </title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="{{ STATIC_URL }}img/speakerfight.ico"/>

    <link href="{{ STATIC_URL }}css/libs/bootstrap/bootstrap.css" rel="stylesheet" />
    <link href="{{ STATIC_URL }}css/libs/bootstrap/bootstrap-overrides.css" type="text/css" rel="stylesheet" />

    <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/layout.css" />
    <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/elements.css" />
    <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/icons.css" />

    <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/libs/font-awesome.css" />

    <link rel="stylesheet" href="{{ STATIC_URL }}css/index.css" type="text/css" media="screen" />

    {% comment %}

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css' />

    {% endcomment %}

    {% block head %} {% endblock head %}

        {% if redirect_field_value %}

                {% trans "You need to be logged in to continue to the next step." %}
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

        {% endif %}

        {% bootstrap_messages messages %}

        {% block content %}{% endblock content %}

    {% include "footer.html" %}


text:
import d_lang from "dojo/_base/lang";
import declare from "dojo/_base/declare";
import ct_lang from "ct/_lang";
import when from "apprt-core/when";
import Deferred from "dojo/Deferred";
import Sequence from "ct/Sequence";
import Hash from "ct/Hash";
import SpatialQuery from "store-api/SpatialQuery";
import { createComplexQueryEngine, toQueryResult } from "store-api/utils";

/*
 * This class provides a caching store. All used field values will be cached in a memory store.
 */
export default declare([], {
    /**
     * Defines if geometry will be cached
     */
    _cache: null,
    _geometryCache: null,
    // Default value for ags
    maxFeaturesLimit: 500,
    // IDs managed in this store
    idList: null,
    masterStore: null,
    initialQuery: null,
    querySequenz: null,

    constructor(args) {
        args = args || {};
        ct_lang.hasProp(args, "masterStore", true, "CachingStore: No master store defined!");
        ct_lang.hasProp(args, "idList", true, "CachingStore: No IDs defined!");
        d_lang.mixin(this, args);
        this.idProperty = this.masterStore.idProperty;
        this._cache = [];
        this._geometryCache = new Hash();
        // Check that idList is not undefined
        if (!this.idList) {
            this.idList = [];
        }
    },

    deactivate() {
        const geometryCache = this._geometryCache;
        geometryCache.clear();
        this._geometryCache = null;
        this._cache = null;
        this.idProperty = null;
    },

    getInitialQuery() {
        return this.initialQuery;
    },

    _addItemToCache(item, offset) {
        const idList = this.idList;
        const idPropName = this.idProperty;
        const id = item[idPropName];
        const pos = idList.indexOf(id);
        // update geometry cache
        this._updateGeometryCache(item, offset);
        this._cache[pos] = item;
    },

    _updateGeometryCache(item, offset) {
        const geometry = item.geometry;
        if (geometry) {
            const geometryCache = this._geometryCache;
            const itemId = item[this.idProperty];
            const offsetMap = geometryCache.contains(offset) ? geometryCache.get(offset) : new Hash();
            offsetMap.set(itemId, geometry);
            geometryCache.set(offset, offsetMap);
            //console.debug("CachingStore: Caching geometry for item '" + itemId + "' at offset " + offset);
        }
    },

    getMetadata(object) {
        return this.masterStore.getMetadata(object);
    },

    getIdentity(object) {
        return this.masterStore.getIdentity(object);
    },

    _getAllMasterStoreFields() {
        //console.debug("CachingStore: Retrieving all fields from store metadata");
        return when(this.masterStore.getMetadata(), (metadata) => {
            const allFields = {};
            let geometryField;
            const fieldsFromMetadata = metadata.fields || [];
            fieldsFromMetadata.forEach((field) => {
                const fieldName = field.name;
                if (fieldName) {
                    allFields[fieldName] = true;
                    if (field.type === "geometry") {
                        geometryField = field.name;
                    }
                }
            });
            if (!fieldsFromMetadata.some((field) =>
                // TODO: why this check?
                !field.name.indexOf(geometryField + "."))) {
                delete allFields[geometryField];
            }
            return allFields;
        });
    },

    _getItems(itemIds, opts) {
        itemIds = (itemIds instanceof Array) ? itemIds : [itemIds];
        if (!itemIds.length) {
            return [];
        }
        let serverMax = this.maxFeaturesLimit;
        const masterStore = this.masterStore;
        // direct support for MapServerLayerStore
        const maxRecordCount = masterStore.maxRecordCount;
        if (maxRecordCount !== undefined && serverMax > maxRecordCount) {
            serverMax = maxRecordCount;
        }
        // check if we need to split the request due to the ags limit!
        if (serverMax > 0 && itemIds.length > serverMax) {
            const sequence = new Sequence();
            for (let i = 0; i < itemIds.length; i += serverMax) {
                sequence.add((function (i, serverMax) {
                    const tempIds = itemIds.slice(i, i + serverMax);
                    //console.debug("CachingStore: Querying items for IDs: " + tempIds);
                    const query = this._buildQuery(tempIds);
                    return () => {
                        const options = this._fixCount(opts, tempIds);
                        return masterStore.query(query, options);
                    };
                }).call(this, i, serverMax));
            }
            return when(sequence.start(), (results) => {
                let result = [];
                results.forEach((r) => {
                    result = result.concat(r);
                });
                result.total = result.length;
                return result;
            });
        } else {
            const query = this._buildQuery(itemIds);
            const options = this._fixCount(opts, itemIds);
            return this.masterStore.query(query, options);
        }
    },

    _fixCount(opts, itemIds) {
        const options = Object.assign({}, opts);
        options.count = itemIds.length;

        //suppress count request in MapServerLayerStore
        if (this.masterStore.enablePagination) {
            options.total = itemIds.length;
        }

        return options;
    },

    _buildQuery(itemIds) {
        // All fields
        const idProperty = this.idProperty;
        const query = {};
        const isArray = itemIds instanceof Array;
        query[idProperty] = {
            $in: isArray ? itemIds : [itemIds]
        };
        return query;
    },

    _isGeometryRequired(options, defaultRequired) {
        const opts = options || {};
        const fields = opts.fields || {};
        return ct_lang.chk(fields.geometry, defaultRequired);
    },

    _getGeometryFromCache(id, offset) {
        const geometryCache = this._geometryCache;
        const itemsForOffset = geometryCache.get(offset || 0);
        //TODO: -> check lower limits?
        return itemsForOffset && itemsForOffset.get(id);
    },

    _isSpatialQuery(query) {
        return SpatialQuery.isSpatialQuery(query);
    },

    _getItemsFromCache(query, options = {}) {
        //console.debug("CachingStore: Querying items from cache...");
        const cache = this._cache;
        if (options.suggestContains === undefined) {
            // Use suggestContains like defined in master
            options.suggestContains = ct_lang.chk(this.masterStore.suggestContains, true);
        }
        return createComplexQueryEngine(query, options)(cache);
    },

    _getGeometryForItems(items, options) {
        // Fetch geometry for items
        const idProperty = this.idProperty;
        const opts = Object.assign({}, options || {});
        opts.fields = {
            geometry: true
        };
        // Ensure that not * properties are fetched!
        opts.fields[this.idProperty] = true;
        const geom = opts.geometry || (opts.geometry = {});
        const offset = geom.maxAllowableOffset = this._getOffset(opts);

        // Check if geometry is already fetched for some items
        const itemsWithoutGeom = items.filter((item) => {
            const id = item[idProperty];
            return !this._getGeometryFromCache(id, offset);
        });
        const itemIds = itemsWithoutGeom.map((item) => item[idProperty]);
        //console.debug("CachingStore: Querying geometries for items with IDs:", itemIds);
        return when(this._getItems(itemIds, Object.assign({}, opts, {
            start: undefined,
            count: undefined
        })), (results) => {
            (results || []).forEach((item) => {
                this._updateGeometryCache(item, offset);
            });
            // Merge geometry with existing items
            const resultItems = items.map((item) => {
                const id = item[idProperty];
                const geom = this._getGeometryFromCache(id, offset);
                return d_lang.mixin({}, item, {
                    geometry: geom
                });
            });
            resultItems.total = resultItems.length;
            return resultItems;
        });
    },

    _getItemsForQuery(query, options) {
        // First query org store for query matching ids, inside our id restriction
        // TODO: remove id query if query has already an $id operator!
        if (!SpatialQuery.usesOperator(query, options, "$in", this.idProperty)) {
            const idQuery = this._buildQuery(this.idList);
            query = {
                $and: [idQuery, query]
            };
        }
        // Only fetch ids
        const opts = Object.assign({}, options || {});
        opts.fields = {};
        opts.fields[this.idProperty] = true;
        const queryResult = this.masterStore.query(query, opts);
        return when(queryResult, (result) => {
            // Now get properties from populated cache
            const items = [];
            const cache = this._cache;
            const idProperty = this.idProperty;
            result.forEach((item) => {
                const itemId = item[idProperty];
                const result = cache.find(cacheEntry => cacheEntry[idProperty] === itemId);
                if (result) {
                    items[items.length] = result;
                }
            });
            items.total = ct_lang.chk(result.total, queryResult.total);
            return items;
        });
    },

    // Query for items
    query(query, options) {
        const opts = options || {};
        const initialQuery = this.initialQuery;
        if (initialQuery && initialQuery.options.geometry && !opts.geometry) {
            // Ensure outSR parameter always
            // MAPAPPS-2855
            opts.geometry = initialQuery.options.geometry;
        }
        let r;
        if (!this._checkIfCacheIsPopulated()) {
            r = when(this._populateCache(), () => this._synchronizedQueryOnCache(query, opts));
        } else {
            r = this._synchronizedQueryOnCache(query, opts);
        }
        return toQueryResult(r);
    },

    _synchronizedQueryOnCache(query, opts) {
        let cancelled = false;
        let queryPromise;
        const d = new Deferred(function () {
            cancelled = true;
            queryPromise?.cancel?.();
            queryPromise = undefined;
        });
        const q = function () {
            return cancelled ? [] : queryPromise = when(this._queryOnCache(query, opts), function (r) {
                cancelled || d.resolve(r);
            }, function (e) {
                cancelled || d.reject(e);
            });
        };
        // Sequence is only used to control the waiting
        let seq = this.querySequence;
        if (seq && !seq.finished) {
            seq.add(q, this);
        } else {
            seq = this.querySequence = new Sequence();
            seq.add(q, this);
            seq.start();
        }
        return d;
    },

    _queryOnCache(query, opts) {
        let itemsDef;
        // This is required if a spatial query is performed
        // (in case the cache is populated with items containing no geometry)
        const isSpatialQuery = this._isSpatialQuery(query);
        const offset = this._getOffset(opts);
        if (isSpatialQuery && this._geometryMissingInCachedItems(offset, query, opts)) {
            itemsDef = this._getItemsForQuery(query, opts);
        } else {
            itemsDef = this._getItemsFromCache(query, opts);
        }
        return when(itemsDef, (items) => {
            // Re-check since items may have been retrieved from service including the geometry
            if (this._isGeometryRequired(opts, false) && items.length > 0) {
                //console.debug("CachingStore: Fetching geometries...");
                items = this._getGeometryForItems(items, opts);
            }
            items.total = ct_lang.chk(items.total, items.length);
            return items;
        });
    },

    _geometryMissingInCachedItems(offset, query, opts) {
        const idProperty = this.idProperty;
        const requestedIds = new Set();
        // This works only because we know,that $in is mostly used
        // TODO: better try a different approach -> e.g. apply query without geometry and check then the missing
        //  geometries?
        SpatialQuery.findOperators(query, opts, "$in", idProperty).forEach((astNode) => {
            astNode.v.forEach((id) => {
                requestedIds.add(id);
            });
        });
        const cache = this._cache;
        return cache.some((cacheEntry) => {
            const id = cacheEntry[idProperty];
            // Side effect geometry is required for ComplexQuery in memory evaluation
            const hasGeometry = !!(cacheEntry.geometry = this._getGeometryFromCache(id, offset));
            if (requestedIds.size) {
                return !hasGeometry && requestedIds.has(id);
            }
            return !hasGeometry;
        });
    },

    _getOffset(options) {
        const opts = options || {};
        return ct_lang.chkProp(opts.geometry, "maxAllowableOffset", 0);
    },

    _checkIfCacheIsPopulated() {
        const cache = this._cache;
        return (!this._fetchCache) && cache.length === this.idList.length && !cache.dirty;
    },

    _populateCache() {
        // Ensure that external cancel, don't break this fetch cache
        let cancelled = false;
        // We need an own deferred, because _fetchCache is shared between all queries, and cancel should not break it!
        const d = new Deferred(function () {
            cancelled = true;
        });

        const onError = (e) => {
            this._fetchCache = undefined;
            throw e;
        };

        const fetchCache = this._fetchCache
            || (this._fetchCache = when(this._getAllMasterStoreFields(), (allFields) => {
                // The idea is that this updates only all attributes of the features, but not the geometry
                // block request for geometry in this place
                allFields["geometry"] = false;
                // Ensure that id property is in field list
                allFields[this.idProperty] = true;
                const opts = {
                    fields: allFields
                };
                const initialQuery = this.initialQuery;
                if (initialQuery && initialQuery.options.geometry) {
                    // Ensure outSR parameter is to populate cache query
                    // MAPAPPS-2855
                    opts.geometry = initialQuery.options.geometry;
                }
                let ids = this.idList;
                const cache = this._cache;
                if (cache.length) {
                    // Invalidate case!
                    ids = ids.filter((id, i) => !cache[i]);
                }
                return when(this._getItems(ids, opts), (results) => {
                    results.forEach((result) => {
                        this._addItemToCache(result, 0);
                    });
                    results.total = results.length;
                    this._fetchCache = null;
                    this._cache.dirty = false;
                    return results;
                }, onError);
            }, onError));

        when(fetchCache, function () {
            if (!cancelled) {
                d.resolve();
            }
        }, function () {
            if (!cancelled) {
                d.reject();
            }
        });

        return d;
    },

    // returns full item
    get(id, options) {
        //console.debug("CachingStore: get() called for ID '" + id + "'");
        if (!this._checkIfCacheIsPopulated()) {
            if (this.idList.indexOf(id) < 0) {
                return Promise.reject(new Error("item not found"));
            }
            // return result directly from master store
            return this.masterStore.get(id, options);
        }
        const query = this._buildQuery(id);
        let items = this._getItemsFromCache(query, options);
        if (this._isGeometryRequired(options, true)) {
            items = this._getGeometryForItems(items, options);
        }
        return when(items, (items) => items[0]);
    },

    // Removes an item
    remove(id) {
        //console.debug("CachingStore: Removing item with ID '" + id + "'");
        const cache = this._cache;
        const dirty = cache.dirty;
        const idList = this.idList;
        this.invalidate(id);

        const index = idList.indexOf(id);
        if (index >= 0) {
            idList.splice(index, 1);
            cache.splice(index, 1);
        }

        cache.dirty = dirty;
        return true;
    },

    invalidate(id) {
        // Check if id is in cache
        const comp = {};
        comp[this.idProperty] = id;
        const i = this.idList.indexOf(id);
        this._cache[i] = null;
        this._cache.dirty = true;
        // Cleaning geometry cache
        const geometryCache = this._geometryCache;
        geometryCache.getKeys().forEach((offset) => {
            const entry = geometryCache.get(offset);
            if (entry.contains(id)) {
                //console.debug("CachingStore: Removing geometry from cache for offset '" + offset + "'");
                entry.remove(id);
            }
        });
    }
});

redpajama_set_name: RedPajamaGithub


text:
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using WordHunt.Data.Connection;
using WordHunt.Games.Repository;
using WordHunt.Models.Games.Creation;
using System;
using WordHunt.Games.Broadcaster;

namespace WordHunt.Games.Creation
{
    public interface IGameCreator
    {
        Task<GameCreateResult> CreateGame(GameCreate game);
        Task<GameCreateResult> CreateGameBasedOnAnother(int gameId);
    }

    public class GameCreator : IGameCreator
    {
        private readonly IGameCreatorValidator validator;
        private readonly IDbTransactionProvider transactionProvider;
        private readonly IGameRepository gameRepository;
        private readonly IGameTeamRepository gameTeamRepository;
        private readonly IGameStatusRepository gameStatusRepository;
        private readonly IGameFieldsGenerator gameFieldsGenerator;
        private readonly IRandomWordRepository randomWordRepository;
        private readonly IGameFieldRepository gameFieldRepository;
        private readonly IGameTeamsGenerator gameTeamsGenerator;
        private readonly IEventBroadcaster eventBroadcaster;

        public GameCreator(IGameCreatorValidator validator,
            IDbTransactionProvider transactionProvider,
            IGameRepository gameRepository,
            IGameTeamRepository gameTeamRepository,
            IGameStatusRepository gameStatusRepository,
            IGameFieldsGenerator gameFieldsGenerator,
            IRandomWordRepository randomWordRepository,
            IGameFieldRepository gameFieldRepository,
            IGameTeamsGenerator gameTeamsGenerator,
            IEventBroadcaster eventBroadcaster)
        {
            this.validator = validator;
            this.transactionProvider = transactionProvider;
            this.gameRepository = gameRepository;
            this.gameTeamRepository = gameTeamRepository;
            this.gameStatusRepository = gameStatusRepository;
            this.gameFieldsGenerator = gameFieldsGenerator;
            this.randomWordRepository = randomWordRepository;
            this.gameFieldRepository = gameFieldRepository;
            this.gameTeamsGenerator = gameTeamsGenerator;
            this.eventBroadcaster = eventBroadcaster;
        }

        public async Task<GameCreateResult> CreateGame(GameCreate game)
        {
            await validator.ValidateGame(game);
            var createdGame = await gameRepository.SaveNewGame(game);

            var teamsToCreate = await gameTeamsGenerator.GenerateTeams(createdGame.Id, game.Teams);
            await CreateGameData(createdGame, teamsToCreate);

            return new GameCreateResult()
            {
                GameId = createdGame.Id
            };
        }

        public async Task<GameCreateResult> CreateGameBasedOnAnother(int gameId)
        {
            var game = await gameRepository.CreatedBasedOnGame(gameId);

            var teamsToCreate = await gameTeamsGenerator.GenerateTeamsBasedOnGame(game.Id, gameId);
            await CreateGameData(game, teamsToCreate);

            eventBroadcaster.RestartGame(new Models.Events.GameRestarted()
            {
                GameId = game.Id,
                OldGameId = gameId
            });

            return new GameCreateResult()
            {
                GameId = game.Id
            };
        }

        private async Task CreateGameData(GameCreated game, IEnumerable<GameTeamCreate> teamsToCreate)
        {
            await validator.ValidateTeams(teamsToCreate);
            var teams = await gameTeamRepository.CreateGameTeams(teamsToCreate);

            var firstTeamId = await gameTeamRepository.GetFirstTeamId(game.Id);
            await gameStatusRepository.CreateInitialGameStatus(game.Id, firstTeamId);

            var fieldCount = game.BoardHeight * game.BoardWidth;
            var words = await randomWordRepository.GetRandomWords(game.LanguageId, fieldCount);
            var fields = gameFieldsGenerator.GenerateFields(game, teams, words);
            await validator.ValidateFields(fields);
            await gameFieldRepository.SaveGameFields(fields);
        }
    }
}


text:
package thistle.runner.validtestclasses;

import thistle.Describe;
import thistle.When;

@Describe("something")
public class TestClassWithWhen {

    public static boolean init = false;
    public static boolean whenCalled = false;

    {
        whenCalled = false;
        init = true;
    }

    @When("")
    public void w1() {
        whenCalled = true;
    }

}


text:
<?php

    if (!class_exists('DOPBSPViewsBackEndDiscountItems')){
        class DOPBSPViewsBackEndDiscountItems extends DOPBSPViewsBackEndDiscount{
            /*
             * Constructor
             */
            function __construct(){
            }

            /*
             * Returns discount items template.
             *
             * @param args (array): function arguments
             *                      * id (integer): discount ID
             *                      * language (string): discount language
             *
             * @return discount items HTML
             */
            function template($args = array()){
                global $wpdb;
                global $DOPBSP;

                $id = $args['id'];
                $language = isset($args['language']) && $args['language'] != '' ? $args['language']:$DOPBSP->classes->backend_language->get();
?>

                    <a href="javascript:DOPBSPBackEndDiscountItem.add(<?php echo $id; ?>, '<?php echo $language; ?>')" class="dopbsp-button dopbsp-add"><?php echo $DOPBSP->text('DISCOUNTS_DISCOUNT_ADD_ITEM_SUBMIT'); ?>

<?php echo $DOPBSP->text('DISCOUNTS_DISCOUNT_ITEMS'); ?>

<?php
                $items = $wpdb->get_results($wpdb->prepare('SELECT * FROM '.$DOPBSP->tables->discounts_items.' WHERE discount_id=%d ORDER BY position ASC',
                                                           $id));

                if ($wpdb->num_rows > 0){
                    foreach($items as $item){
                        $DOPBSP->views->backend_discount_item->template(array('item' => $item,
                                                                      'language' => $language));
                    }
                }
?>

<?php
            }
        }
    }


text:
Company

      We at NEOMED strive for Customer Satisfaction.

Company

              Company content goes here.

              We know the importance of life - because we truly care.

                We are fully committed to our customers and business relationships. We are always optimistic because we believe that we have the right competence and ever-lasting support. We push ourselves to find out interesting ways to solve problems.

              Neomed is headquarted in Hyderabad - and rapidly grows its service footprint.

              Neomed currently has core business operations in Andhra Pradesh and Telangana. We are focused to expand our service to other states like Karnataka, Tamil Nadu, Jharkand, etc.

Our Team

              Management Team content goes here.

 PNV Suresh Kumar

Managing Director

 A Kishore Kumar

Managing Director

History

            History content goes here.


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace OpenSource.Data.HashFunction
{
    /// <summary>
    /// An internal state of an iteratively computable hash function value.
    /// </summary>
    public interface IBlockTransformer
    {
        /// <summary>
        /// Clones this transformer's internal state to a new, unassociated instance of this transformer.
        /// </summary>
        /// <returns>A new, unassociated instance of this transformer.</returns>
        IBlockTransformer Clone();

        /// <summary>
        /// Updates the internal state of this transformer with the given data.
        /// </summary>
        /// <param name="data">The data to process into this transformer's internal state.</param>
        /// <exception cref="ArgumentNullException"><paramref name="data"/></exception>
        /// <exception cref="InvalidOperationException">A previous transformation cancellation has resulted in an undefined internal state.</exception>
        void TransformBytes(byte[] data);

        /// <summary>
        /// Updates the internal state of this transformer with the given data.
        /// </summary>
        /// <param name="data">The data to process into this transformer's internal state.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> to cease processing of the provided data.</param>
        /// <exception cref="ArgumentNullException"><paramref name="data"/></exception>
        /// <exception cref="TaskCanceledException">The <paramref name="cancellationToken"/> was canceled.</exception>
        /// <exception cref="InvalidOperationException">A previous transformation cancellation has resulted in an undefined internal state.</exception>
        void TransformBytes(byte[] data, CancellationToken cancellationToken);

        /// <summary>
        /// Updates the internal state of this transformer with the given data.
        /// </summary>
        /// <param name="data">The data to process into this transformer's internal state.</param>
        /// <param name="offset">The offset from which to begin using the data.</param>
        /// <param name="count">The number of bytes to use as data.</param>
        /// <exception cref="ArgumentNullException"><paramref name="data"/></exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/>;Offset must be a value greater than or equal to zero and less than the length of the array minus one.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/>;Count must be a value greater than zero and less than the the remaining length of the array after the offset value.</exception>
        /// <exception cref="InvalidOperationException">A previous transformation cancellation has resulted in an undefined internal state.</exception>
        void TransformBytes(byte[] data, int offset, int count);

        /// <summary>
        /// Updates the internal state of this transformer with the given data.
        /// </summary>
        /// <param name="data">The data to process into this transformer's internal state.</param>
        /// <param name="offset">The offset from which to begin using the data.</param>
        /// <param name="count">The number of bytes to use as data.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> to cease processing of the provided data.</param>
        /// <exception cref="ArgumentNullException"><paramref name="data"/></exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/>;Offset must be a value greater than or equal to zero and less than the length of the array minus one.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/>;Count must be a value greater than zero and less than the the remaining length of the array after the offset value.</exception>
        /// <exception cref="TaskCanceledException">The <paramref name="cancellationToken"/> was canceled.</exception>
        /// <exception cref="InvalidOperationException">A previous transformation cancellation has resulted in an undefined internal state.</exception>
        void TransformBytes(byte[] data, int offset, int count, CancellationToken cancellationToken);

        /// <summary>
        /// Updates the internal state of this transformer with the given data.
        /// </summary>
        /// <param name="data">The data to process into this transformer's internal state.</param>
        /// <exception cref="ArgumentException">data must be an ArraySegment of Count > 0.;<paramref name="data"/></exception>
        /// <exception cref="InvalidOperationException">A previous transformation cancellation has resulted in an undefined internal state.</exception>
        void TransformBytes(ArraySegment<byte> data);

        /// <summary>
        /// Updates the internal state of this transformer with the given data.
        /// </summary>
        /// <param name="data">The data to process into this transformer's internal state.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> to cease processing of the provided data.</param>
        /// <exception cref="ArgumentException">data must be an ArraySegment of Count > 0.;<paramref name="data"/></exception>
        /// <exception cref="TaskCanceledException">The <paramref name="cancellationToken"/> was canceled.</exception>
        /// <exception cref="InvalidOperationException">A previous transformation cancellation has resulted in an undefined internal state.</exception>
        void TransformBytes(ArraySegment<byte> data, CancellationToken cancellationToken);

        /// <summary>
        /// Completes any finalization processing and returns the resulting <see cref="IHashValue"/>.
        /// </summary>
        /// <remarks>Internal state will remain unmodified, therefore this method will not invalidate future calls to any TransformBytes or FinalizeHashValue.</remarks>
        /// <exception cref="InvalidOperationException">A previous transformation cancellation has resulted in an undefined internal state.</exception>
        IHashValue FinalizeHashValue();

        /// <summary>
        /// Completes any finalization processing and returns the resulting <see cref="IHashValue"/>.
        /// </summary>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> to cease any final processing.</param>
        /// <remarks>Internal state will remain unmodified, therefore this method will not invalidate future calls to any other TransformBytes or FinalizeHashValue.</remarks>
        /// <exception cref="TaskCanceledException">The <paramref name="cancellationToken"/> was canceled.</exception>
        /// <exception cref="InvalidOperationException">A previous transformation cancellation has resulted in an undefined internal state.</exception>
        IHashValue FinalizeHashValue(CancellationToken cancellationToken);
    }
}


text:
package one.nio.net;

public class SslOption<T> {
    public static final SslOption<byte[]> PEER_CERTIFICATE = new SslOption<>(1, byte[].class);
    public static final SslOption<Object[]> PEER_CERTIFICATE_CHAIN = new SslOption<>(2, Object[].class);
    public static final SslOption<String> PEER_SUBJECT = new SslOption<>(3, String.class);
    public static final SslOption<String> PEER_ISSUER = new SslOption<>(4, String.class);
    public static final SslOption<String> VERIFY_RESULT = new SslOption<>(5, String.class);

    public static final SslOption<Boolean> SESSION_REUSED = new SslOption<>(6, Boolean.class);
    public static final SslOption<Integer> SESSION_TICKET = new SslOption<>(7, Integer.class);

    public static final SslOption<String> CURRENT_CIPHER = new SslOption<>(8, String.class);

    final int id;
    final Class<T> type;

    private SslOption(int id, Class<T> type) {
        this.id = id;
        this.type = type;
    }

    @Override
    public int hashCode() {
        return id;
    }

    @Override
    public String toString() {
        return "SslOption(" + id + ")";
    }
}


text:
<?php
declare(strict_types = 1);

namespace Siesta\Validator;

use Siesta\Contract\EntityValidator;
use Siesta\Model\DataModel;
use Siesta\Model\Entity;
use Siesta\Model\ValidationLogger;
use Siesta\Util\ArrayUtil;

/**
 * @author Gregor Müller
 */
class DefaultEntityValidator implements EntityValidator
{

    const ERROR_INVALID_CLASS_NAME = "Entity '%s' has invalid class name '%s'";

    const ERROR_INVALID_CLASS_NAME_CODE = 1100;

    const ERROR_INVALID_NAMESPACE = "Entity '%s' has invalid class namespace '%s'";

    const ERROR_INVALID_NAMESPACE_CODE = 1101;

    const ERROR_INVALID_TABLE = "Entity '%s' has invalid table name '%s'";

    const ERROR_INVALID_TABLE_CODE = 1102;

    const ERROR_DUPLICATE_ATT_REF_COL = "Entity '%s' has duplicate attribute/reference/collection '%s'";

    const ERROR_DUPLICATE_ATT_REF_COL_CODE = 1103;

    const ERROR_DUPLICATE_DB_NAME = "Entity '%s' has duplicate database column '%s'";

    const ERROR_DUPLICATE_DB_NAME_CODE = 1104;

    const ERROR_DUPLICATE_INDEX = "Entity '%s' has duplicate index '%s'";

    const ERROR_DUPLICATE_INDEX_CODE = 1105;

    /**
     * @var DataModel
     */
    protected $dataModel;

    /**
     * @var Entity
     */
    protected $entity;

    /**
     * @var ValidationLogger
     */
    protected $logger;

    /**
     * @param DataModel $dataModel
     * @param Entity $entity
     * @param ValidationLogger $logger
     */
    public function validate(DataModel $dataModel, Entity $entity, ValidationLogger $logger)
    {
        $this->dataModel = $dataModel;
        $this->entity = $entity;
        $this->logger = $logger;

        $this->validateClassname();
        $this->validateNamespace();
        $this->validateTable();
        $this->validateAttributeReferenceCollectionUnique();
        $this->validateAttributeDBNamesUnique();
        $this->validateIndexNameUnique();

    }

    /**
     * @return string
     */
    protected function getEntityName()
    {
        return $this->entity->getClassShortName();
    }

    /**
     * @param string $text
     * @param int $code
     */
    protected function error(string $text, int $code)
    {
        $this->logger->error($text, $code);
    }

    /**
     *
     */
    protected function validateClassname()
    {
        $className = $this->getEntityName();
        if (preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $className)) {
            return;
        }
        $error = sprintf(self::ERROR_INVALID_CLASS_NAME, $className, $className);
        $this->error($error, self::ERROR_INVALID_CLASS_NAME_CODE);

    }

    /**
     *
     */
    protected function validateNamespace()
    {
        $namespace = $this->entity->getNamespaceName();
        if (preg_match('/^((?:\\\\{0,1}\\w+|\\w+\\\\{1,2})(?:\\w+\\\\{0,2})+)$/', $namespace) === 1) {
            return;
        }
        $error = sprintf(self::ERROR_INVALID_NAMESPACE, $this->getEntityName(), $namespace);
        $this->error($error, self::ERROR_INVALID_NAMESPACE_CODE);
    }

    /**
     *
     */
    protected function validateTable()
    {
        $tableName = $this->entity->getTableName();
        if ($tableName !== null) {
            return;
        }
        $error = sprintf(self::ERROR_INVALID_TABLE, $this->getEntityName(), $tableName);
        $this->error($error, self::ERROR_INVALID_TABLE_CODE);

    }

    protected function validateAttributeReferenceCollectionUnique()
    {
        $duplicateNameList = [];
        $nameList = [];

        foreach ($this->entity->getAttributeList() as $attribute) {
            $this->checkDuplicate($nameList, $duplicateNameList, $attribute->getPhpName());
        }

        foreach ($this->entity->getReferenceList() as $reference) {
            $this->checkDuplicate($nameList, $duplicateNameList, $reference->getName());
        }

        foreach ($this->entity->getCollectionList() as $collection) {
            $this->checkDuplicate($nameList, $duplicateNameList, $collection->getName());
        }

        foreach ($this->entity->getCollectionManyList() as $collectionMany) {
            $this->checkDuplicate($nameList, $duplicateNameList, $collectionMany->getName());
        }

        foreach ($duplicateNameList as $duplicateName) {
            $error = sprintf(self::ERROR_DUPLICATE_ATT_REF_COL, $this->getEntityName(), $duplicateName);
            $this->error($error, self::ERROR_DUPLICATE_ATT_REF_COL_CODE);
        }
    }

    /**
     *
     */
    protected function validateAttributeDBNamesUnique()
    {

        $duplicateNameList = [];
        $nameList = [];
        foreach ($this->entity->getAttributeList() as $attribute) {
            $this->checkDuplicate($nameList, $duplicateNameList, $attribute->getDBName());
        }

        foreach ($duplicateNameList as $duplicateName) {
            $error = sprintf(self::ERROR_DUPLICATE_DB_NAME, $this->getEntityName(), $duplicateName);
            $this->error($error, self::ERROR_DUPLICATE_DB_NAME_CODE);
        }

    }

    /**
     *
     */
    protected function validateIndexNameUnique()
    {
        $duplicateNameList = [];
        $nameList = [];
        foreach ($this->entity->getIndexList() as $index) {
            $this->checkDuplicate($nameList, $duplicateNameList, $index->getName());
        }
        foreach ($duplicateNameList as $duplicateName) {
            $error = sprintf(self::ERROR_DUPLICATE_INDEX, $this->getEntityName(), $duplicateName);
            $this->error($error, self::ERROR_DUPLICATE_INDEX_CODE);
        }
    }

    /**
     * @param array $nameList
     * @param array $duplicateNameList
     * @param $name
     */
    protected function checkDuplicate(array &$nameList, array &$duplicateNameList, $name)
    {
        $existing = ArrayUtil::getFromArray($nameList, $name);
        if ($existing) {
            $duplicateNameList[] = $name;
        }
        $nameList[$name] = true;
    }
}


text:
#ifndef GRAPH_MARKBASEPOS_GRAPH_HH
#define GRAPH_MARKBASEPOS_GRAPH_HH

#include "split-helpers.hh"
#include "coverage-graph.hh"
#include "../OT/Layout/GPOS/MarkBasePos.hh"
#include "../OT/Layout/GPOS/PosLookupSubTable.hh"

namespace graph {

struct AnchorMatrix : public OT::Layout::GPOS_impl::AnchorMatrix
{
  bool sanitize (graph_t::vertex_t& vertex, unsigned class_count) const
  {
    int64_t vertex_len = vertex.obj.tail - vertex.obj.head;
    if (vertex_len < AnchorMatrix::min_size) return false;

    return vertex_len >= AnchorMatrix::min_size +
        OT::Offset16::static_size * class_count * this->rows;
  }

  bool shrink (gsubgpos_graph_context_t& c,
               unsigned this_index,
               unsigned old_class_count,
               unsigned new_class_count)
  {
    if (new_class_count >= old_class_count) return false;
    auto& o = c.graph.vertices_[this_index].obj;
    unsigned base_count = rows;
    o.tail = o.head +
             AnchorMatrix::min_size +
             OT::Offset16::static_size * base_count * new_class_count;

    // Reposition links into the new indexing scheme.
    for (auto& link : o.real_links.writer ())
    {
      unsigned index = (link.position - 2) / 2;
      unsigned base = index / old_class_count;
      unsigned klass = index % old_class_count;
      if (klass >= new_class_count)
        // should have already been removed
        return false;

      unsigned new_index = base * new_class_count + klass;

      link.position = (char*) &(this->matrixZ[new_index]) - (char*) this;
    }

    return true;
  }

  unsigned clone (gsubgpos_graph_context_t& c,
                  unsigned this_index,
                  unsigned start,
                  unsigned end,
                  unsigned class_count)
  {
    unsigned base_count = rows;
    unsigned new_class_count = end - start;
    unsigned size = AnchorMatrix::min_size +
                    OT::Offset16::static_size * new_class_count * rows;
    unsigned prime_id = c.create_node (size);
    if (prime_id == (unsigned) -1) return -1;
    AnchorMatrix* prime = (AnchorMatrix*) c.graph.object (prime_id).head;
    prime->rows = base_count;

    auto& o = c.graph.vertices_[this_index].obj;
    int num_links = o.real_links.length;
    for (int i = 0; i < num_links; i++)
    {
      const auto& link = o.real_links[i];
      unsigned old_index = (link.position - 2) / OT::Offset16::static_size;
      unsigned klass = old_index % class_count;
      if (klass < start || klass >= end) continue;

      unsigned base = old_index / class_count;
      unsigned new_klass = klass - start;
      unsigned new_index = base * new_class_count + new_klass;

      unsigned child_idx = link.objidx;
      c.graph.add_link (&(prime->matrixZ[new_index]),
                        prime_id,
                        child_idx);

      auto& child = c.graph.vertices_[child_idx];
      child.remove_parent (this_index);

      o.real_links.remove (i);
      num_links--;
      i--;
    }

    return prime_id;
  }
};

struct MarkArray : public OT::Layout::GPOS_impl::MarkArray
{
  bool sanitize (graph_t::vertex_t& vertex) const
  {
    int64_t vertex_len = vertex.obj.tail - vertex.obj.head;
    unsigned min_size = MarkArray::min_size;
    if (vertex_len < min_size) return false;

    return vertex_len >= get_size ();
  }

  bool shrink (gsubgpos_graph_context_t& c,
               const hb_hashmap_t<unsigned, unsigned>& mark_array_links,
               unsigned this_index,
               unsigned new_class_count)
  {
    auto& o = c.graph.vertices_[this_index].obj;
    for (const auto& link : o.real_links)
      c.graph.vertices_[link.objidx].remove_parent (this_index);
    o.real_links.reset ();

    unsigned new_index = 0;
    for (const auto& record : this->iter ())
    {
      unsigned klass = record.klass;
      if (klass >= new_class_count) continue;

      (*this)[new_index].klass = klass;
      unsigned position = (char*) &record.markAnchor - (char*) this;
      unsigned* objidx;
      if (!mark_array_links.has (position, &objidx))
      {
        new_index++;
        continue;
      }

      c.graph.add_link (&(*this)[new_index].markAnchor, this_index, *objidx);
      new_index++;
    }

    this->len = new_index;
    o.tail = o.head + MarkArray::min_size +
             OT::Layout::GPOS_impl::MarkRecord::static_size * new_index;
    return true;
  }

  unsigned clone (gsubgpos_graph_context_t& c,
                  unsigned this_index,
                  const hb_hashmap_t<unsigned, unsigned>& pos_to_index,
                  hb_set_t& marks,
                  unsigned start_class)
  {
    unsigned size = MarkArray::min_size +
                    OT::Layout::GPOS_impl::MarkRecord::static_size *
                    marks.get_population ();
    unsigned prime_id = c.create_node (size);
    if (prime_id == (unsigned) -1) return -1;
    MarkArray* prime = (MarkArray*) c.graph.object (prime_id).head;
    prime->len = marks.get_population ();

    unsigned i = 0;
    for (hb_codepoint_t mark : marks)
    {
      (*prime)[i].klass = (*this)[mark].klass - start_class;
      unsigned offset_pos = (char*) &((*this)[mark].markAnchor) - (char*) this;
      unsigned* anchor_index;
      if (pos_to_index.has (offset_pos, &anchor_index))
        c.graph.move_child (this_index,
                            &((*this)[mark].markAnchor),
                            prime_id,
                            &((*prime)[i].markAnchor));

      i++;
    }

    return prime_id;
  }
};

struct MarkBasePosFormat1 : public OT::Layout::GPOS_impl::MarkBasePosFormat1_2<SmallTypes>
{
  bool sanitize (graph_t::vertex_t& vertex) const
  {
    int64_t vertex_len = vertex.obj.tail - vertex.obj.head;
    return vertex_len >= MarkBasePosFormat1::static_size;
  }

  hb_vector_t<unsigned> split_subtables (gsubgpos_graph_context_t& c,
                                         unsigned parent_index,
                                         unsigned this_index)
  {
    hb_set_t visited;

    const unsigned base_coverage_id = c.graph.index_for_offset (this_index, &baseCoverage);
    const unsigned base_size =
        OT::Layout::GPOS_impl::PairPosFormat1_3<SmallTypes>::min_size +
        MarkArray::min_size +
        AnchorMatrix::min_size +
        c.graph.vertices_[base_coverage_id].table_size ();

    hb_vector_t<class_info_t> class_to_info = get_class_info (c, this_index);

    unsigned class_count = classCount;
    auto base_array = c.graph.as_table<AnchorMatrix> (this_index,
                                                      &baseArray,
                                                      class_count);
    if (!base_array) return hb_vector_t<unsigned> ();
    unsigned base_count = base_array.table->rows;

    unsigned partial_coverage_size = 4;
    unsigned accumulated = base_size;
    hb_vector_t<unsigned> split_points;

    for (unsigned klass = 0; klass < class_count; klass++)
    {
      class_info_t& info = class_to_info[klass];
      partial_coverage_size += OT::HBUINT16::static_size * info.marks.get_population ();
      unsigned accumulated_delta =
          OT::Layout::GPOS_impl::MarkRecord::static_size * info.marks.get_population () +
          OT::Offset16::static_size * base_count;

      for (unsigned objidx : info.child_indices)
        accumulated_delta += c.graph.find_subgraph_size (objidx, visited);

      accumulated += accumulated_delta;
      unsigned total = accumulated + partial_coverage_size;

      if (total >= (1 << 16))
      {
        split_points.push (klass);
        accumulated = base_size + accumulated_delta;
        partial_coverage_size = 4 + OT::HBUINT16::static_size * info.marks.get_population ();
        visited.clear (); // node sharing isn't allowed between splits.
      }
    }

    const unsigned mark_array_id = c.graph.index_for_offset (this_index, &markArray);
    split_context_t split_context {
      c,
      this,
      c.graph.duplicate_if_shared (parent_index, this_index),
      std::move (class_to_info),
      c.graph.vertices_[mark_array_id].position_to_index_map (),
    };

    return actuate_subtable_split<split_context_t> (split_context, split_points);
  }

 private:

  struct class_info_t {
    hb_set_t marks;
    hb_vector_t<unsigned> child_indices;
  };

  struct split_context_t {
    gsubgpos_graph_context_t& c;
    MarkBasePosFormat1* thiz;
    unsigned this_index;
    hb_vector_t<class_info_t> class_to_info;
    hb_hashmap_t<unsigned, unsigned> mark_array_links;

    hb_set_t marks_for (unsigned start, unsigned end)
    {
      hb_set_t marks;
      for (unsigned klass = start; klass < end; klass++)
      {
        + class_to_info[klass].marks.iter ()
        | hb_sink (marks)
        ;
      }
      return marks;
    }

    unsigned original_count ()
    {
      return thiz->classCount;
    }

    unsigned clone_range (unsigned start, unsigned end)
    {
      return thiz->clone_range (*this, this->this_index, start, end);
    }

    bool shrink (unsigned count)
    {
      return thiz->shrink (*this, this->this_index, count);
    }
  };

  hb_vector_t<class_info_t> get_class_info (gsubgpos_graph_context_t& c,
                                            unsigned this_index)
  {
    hb_vector_t<class_info_t> class_to_info;

    unsigned class_count= classCount;
    class_to_info.resize (class_count);

    auto mark_array = c.graph.as_table<MarkArray> (this_index, &markArray);
    if (!mark_array) return hb_vector_t<class_info_t> ();
    unsigned mark_count = mark_array.table->len;
    for (unsigned mark = 0; mark < mark_count; mark++)
    {
      unsigned klass = (*mark_array.table)[mark].get_class ();
      class_to_info[klass].marks.add (mark);
    }

    for (const auto& link : mark_array.vertex->obj.real_links)
    {
      unsigned mark = (link.position - 2) /
                     OT::Layout::GPOS_impl::MarkRecord::static_size;
      unsigned klass = (*mark_array.table)[mark].get_class ();
      class_to_info[klass].child_indices.push (link.objidx);
    }

    unsigned base_array_id =
        c.graph.index_for_offset (this_index, &baseArray);
    auto& base_array_v = c.graph.vertices_[base_array_id];

    for (const auto& link : base_array_v.obj.real_links)
    {
      unsigned index = (link.position - 2) / OT::Offset16::static_size;
      unsigned klass = index % class_count;
      class_to_info[klass].child_indices.push (link.objidx);
    }

    return class_to_info;
  }

  bool shrink (split_context_t& sc,
               unsigned this_index,
               unsigned count)
  {
    DEBUG_MSG (SUBSET_REPACK, nullptr,
               "  Shrinking MarkBasePosFormat1 (%u) to [0, %u).",
               this_index,
               count);

    unsigned old_count = classCount;
    if (count >= old_count)
      return true;

    classCount = count;

    auto mark_coverage = sc.c.graph.as_mutable_table<Coverage> (this_index,
                                                                &markCoverage);
    if (!mark_coverage) return false;
    hb_set_t marks = sc.marks_for (0, count);
    auto new_coverage =
        + hb_zip (hb_range (), mark_coverage.table->iter ())
        | hb_filter (marks, hb_first)
        | hb_map_retains_sorting (hb_second)
        ;
    if (!Coverage::make_coverage (sc.c, + new_coverage,
                                  mark_coverage.index,
                                  4 + 2 * marks.get_population ()))
      return false;

    auto base_array = sc.c.graph.as_mutable_table<AnchorMatrix> (this_index,
                                                                 &baseArray,
                                                                 old_count);
    if (!base_array || !base_array.table->shrink (sc.c,
                                                  base_array.index,
                                                  old_count,
                                                  count))
      return false;

    auto mark_array = sc.c.graph.as_mutable_table<MarkArray> (this_index,
                                                              &markArray);
    if (!mark_array || !mark_array.table->shrink (sc.c,
                                                  sc.mark_array_links,
                                                  mark_array.index,
                                                  count))
      return false;

    return true;
  }

  // Create a new MarkBasePos that has all of the data for classes from [start, end).
  unsigned clone_range (split_context_t& sc,
                        unsigned this_index,
                        unsigned start, unsigned end) const
  {
    DEBUG_MSG (SUBSET_REPACK, nullptr,
               "  Cloning MarkBasePosFormat1 (%u) range [%u, %u).", this_index, start, end);

    graph_t& graph = sc.c.graph;
    unsigned prime_size = OT::Layout::GPOS_impl::MarkBasePosFormat1_2<SmallTypes>::static_size;

    unsigned prime_id = sc.c.create_node (prime_size);
    if (prime_id == (unsigned) -1) return -1;

    MarkBasePosFormat1* prime = (MarkBasePosFormat1*) graph.object (prime_id).head;
    prime->format = this->format;
    unsigned new_class_count = end - start;
    prime->classCount = new_class_count;

    unsigned base_coverage_id =
        graph.index_for_offset (sc.this_index, &baseCoverage);
    graph.add_link (&(prime->baseCoverage), prime_id, base_coverage_id);
    graph.duplicate (prime_id, base_coverage_id);

    auto mark_coverage = sc.c.graph.as_table<Coverage> (this_index,
                                                        &markCoverage);
    if (!mark_coverage) return false;
    hb_set_t marks = sc.marks_for (start, end);
    auto new_coverage =
        + hb_zip (hb_range (), mark_coverage.table->iter ())
        | hb_filter (marks, hb_first)
        | hb_map_retains_sorting (hb_second)
        ;
    if (!Coverage::add_coverage (sc.c,
                                 prime_id,
                                 2,
                                 + new_coverage,
                                 marks.get_population () * 2 + 4))
      return -1;

    auto mark_array =
        graph.as_table <MarkArray> (sc.this_index, &markArray);
    if (!mark_array) return -1;
    unsigned new_mark_array =
        mark_array.table->clone (sc.c,
                                 mark_array.index,
                                 sc.mark_array_links,
                                 marks,
                                 start);
    graph.add_link (&(prime->markArray), prime_id, new_mark_array);

    unsigned class_count = classCount;
    auto base_array =
        graph.as_table<AnchorMatrix> (sc.this_index, &baseArray, class_count);
    if (!base_array) return -1;
    unsigned new_base_array =
        base_array.table->clone (sc.c,
                                 base_array.index,
                                 start, end, this->classCount);
    graph.add_link (&(prime->baseArray), prime_id, new_base_array);

    return prime_id;
  }
};

struct MarkBasePos : public OT::Layout::GPOS_impl::MarkBasePos
{
  hb_vector_t<unsigned> split_subtables (gsubgpos_graph_context_t& c,
                                         unsigned parent_index,
                                         unsigned this_index)
  {
    switch (u.format) {
    case 1:
      return ((MarkBasePosFormat1*)(&u.format1))->split_subtables (c, parent_index, this_index);
#ifndef HB_NO_BORING_EXPANSION
    case 2: HB_FALLTHROUGH;
      // Don't split 24bit PairPos's.
#endif
    default:
      return hb_vector_t<unsigned> ();
    }
  }

  bool sanitize (graph_t::vertex_t& vertex) const
  {
    int64_t vertex_len = vertex.obj.tail - vertex.obj.head;
    if (vertex_len < u.format.get_size ()) return false;

    switch (u.format) {
    case 1:
      return ((MarkBasePosFormat1*)(&u.format1))->sanitize (vertex);
#ifndef HB_NO_BORING_EXPANSION
    case 2: HB_FALLTHROUGH;
#endif
    default:
      // We don't handle format 3 and 4 here.
      return false;
    }
  }
};

}

#endif  // GRAPH_MARKBASEPOS_GRAPH_HH


text:
package com.intellij.psi.impl.compiled;

import com.intellij.openapi.util.AtomicNotNullLazyValue;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.util.NullableLazyValue;
import com.intellij.openapi.util.VolatileNullableLazyValue;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.cache.TypeInfo;
import com.intellij.psi.impl.source.PsiClassReferenceType;
import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.impl.source.tree.TreeElement;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class ClsTypeElementImpl extends ClsElementImpl implements PsiTypeElement {
  @NonNls static final char VARIANCE_NONE = '\0';
  @NonNls static final char VARIANCE_EXTENDS = '+';
  @NonNls static final char VARIANCE_SUPER = '-';
  @NonNls static final char VARIANCE_INVARIANT = '*';
  @NonNls static final String VARIANCE_EXTENDS_PREFIX = "? extends ";
  @NonNls static final String VARIANCE_SUPER_PREFIX = "? super ";

  private final PsiElement myParent;
  private final String myTypeText;
  private final char myVariance;
  private final NullableLazyValue<ClsElementImpl> myChild;
  private final NotNullLazyValue<PsiType> myCachedType;

  public ClsTypeElementImpl(@NotNull PsiElement parent, @NotNull String typeText, char variance) {
    myParent = parent;
    myTypeText = TypeInfo.internFrequentType(typeText);
    myVariance = variance;
    myChild = new VolatileNullableLazyValue<ClsElementImpl>() {
      @Nullable
      @Override
      protected ClsElementImpl compute() {
        return calculateChild();
      }
    };
    myCachedType = new AtomicNotNullLazyValue<PsiType>() {
      @NotNull
      @Override
      protected PsiType compute() {
        return calculateType();
      }
    };
  }

  @Override
  @NotNull
  public PsiElement[] getChildren() {
    ClsElementImpl child = myChild.getValue();
    return child != null ? new PsiElement[]{child} : PsiElement.EMPTY_ARRAY;
  }

  @Override
  public PsiElement getParent() {
    return myParent;
  }

  @Override
  public String getText() {
    final String shortClassName = PsiNameHelper.getShortClassName(myTypeText);
    return decorateTypeText(shortClassName);
  }

  private String decorateTypeText(final String shortClassName) {
    switch (myVariance) {
      case VARIANCE_NONE:
        return shortClassName;
      case VARIANCE_EXTENDS:
        return VARIANCE_EXTENDS_PREFIX + shortClassName;
      case VARIANCE_SUPER:
        return VARIANCE_SUPER_PREFIX + shortClassName;
      case VARIANCE_INVARIANT:
        return "?";
      default:
        assert false : myVariance;
        return null;
    }
  }

  public String getCanonicalText() {
    return decorateTypeText(myTypeText);
  }

  @Override
  public void appendMirrorText(int indentLevel, @NotNull StringBuilder buffer) {
    buffer.append(decorateTypeText(myTypeText));
  }

  @Override
  public void setMirror(@NotNull TreeElement element) throws InvalidMirrorException {
    setMirrorCheckingType(element, JavaElementType.TYPE);

    ClsElementImpl child = myChild.getValue();
    if (child != null) {
      child.setMirror(element.getFirstChildNode());
    }
  }

  private boolean isArray() {
    return myTypeText.endsWith("[]");
  }

  private boolean isVarArgs() {
    return myTypeText.endsWith("...");
  }

  @Override
  @NotNull
  public PsiType getType() {
    return myCachedType.getValue();
  }

  @Override
  public PsiJavaCodeReferenceElement getInnermostComponentReferenceElement() {
    return null;
  }

  private ClsElementImpl calculateChild() {
    if (JavaPsiFacade.getInstance(getProject()).getElementFactory().createPrimitiveType(myTypeText) != null) {
      return null;
    }
    else if (isArray()) {
      return myVariance == VARIANCE_NONE
             ? new ClsTypeElementImpl(this, myTypeText.substring(0, myTypeText.length() - 2), myVariance)
             : new ClsTypeElementImpl(this, myTypeText, VARIANCE_NONE);
    }
    else if (isVarArgs()) {
      return new ClsTypeElementImpl(this, myTypeText.substring(0, myTypeText.length() - 3), myVariance);
    }
    else {
      return myVariance != VARIANCE_INVARIANT ? new ClsJavaCodeReferenceElementImpl(this, myTypeText) : null;
    }
  }

  private PsiType calculateType() {
    PsiType result = JavaPsiFacade.getInstance(getProject()).getElementFactory().createPrimitiveType(myTypeText);
    if (result != null) return result;

    ClsElementImpl childElement = myChild.getValue();
    if (childElement instanceof ClsTypeElementImpl) {
      if (isArray()) {
        switch (myVariance) {
          case VARIANCE_NONE:
            return ((PsiTypeElement)childElement).getType().createArrayType();
          case VARIANCE_EXTENDS:
            return PsiWildcardType.createExtends(getManager(), ((PsiTypeElement)childElement).getType());
          case VARIANCE_SUPER:
            return PsiWildcardType.createSuper(getManager(), ((PsiTypeElement)childElement).getType());
          default:
            assert false : myVariance;
            return null;
        }
      }
      else {
        assert isVarArgs() : this;
        return new PsiEllipsisType(((PsiTypeElement)childElement).getType());
      }
    }
    else if (childElement instanceof ClsJavaCodeReferenceElementImpl) {
      PsiClassReferenceType psiClassReferenceType = new PsiClassReferenceType((PsiJavaCodeReferenceElement)childElement, null);
      switch (myVariance) {
        case VARIANCE_NONE:
          return psiClassReferenceType;
        case VARIANCE_EXTENDS:
          return PsiWildcardType.createExtends(getManager(), psiClassReferenceType);
        case VARIANCE_SUPER:
          return PsiWildcardType.createSuper(getManager(), psiClassReferenceType);
        case VARIANCE_INVARIANT:
          return PsiWildcardType.createUnbounded(getManager());
        default:
          assert false : myVariance;
          return null;
      }
    }
    else {
      assert childElement == null : this;
      return PsiWildcardType.createUnbounded(getManager());
    }
  }

  @Override
  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof JavaElementVisitor) {
      ((JavaElementVisitor)visitor).visitTypeElement(this);
    }
    else {
      visitor.visitElement(this);
    }
  }

  @Override
  @NotNull
  public PsiAnnotation[] getAnnotations() {
    throw new UnsupportedOperationException();//todo
  }

  @Override
  public PsiAnnotation findAnnotation(@NotNull @NonNls String qualifiedName) {
    return PsiImplUtil.findAnnotation(this, qualifiedName);
  }

  @Override
  @NotNull
  public PsiAnnotation addAnnotation(@NotNull @NonNls String qualifiedName) {
    throw new UnsupportedOperationException();//todo
  }

  @Override
  @NotNull
  public PsiAnnotation[] getApplicableAnnotations() {
    return getAnnotations();
  }

  @Override
  public String toString() {
    return "PsiTypeElement:" + getText();
  }
}


text:
<?php

/**
 * Gets the current stomp extension version
 *
 * @phpstub
 *
 * @return string It returns the current stomp extension version
 */
function stomp_version()
{
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 45(1): 51 (1993)

#### Original name
Urceolella triseptata Raitv. & R. Galán

### Remarks
null


text:
package org.collectionspace.chain.util.xtmpl;

import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import static org.junit.Assert.*;

public class TestXTmpl {
	private static final Logger log=LoggerFactory.getLogger(TestXTmpl.class);

	private Document getDocument(String in) throws DocumentException, IOException {
		String path=getClass().getPackage().getName().replaceAll("\\.","/");
		InputStream stream=Thread.currentThread().getContextClassLoader().getResourceAsStream(path+"/"+in);
		assertNotNull(stream);
		SAXReader reader=new SAXReader();
		Document doc=reader.read(stream);
		stream.close();
		return doc;
	}

	@SuppressWarnings("unchecked")
	@Test public void testBasic() throws Exception {
		Document doc=getDocument("tmpl1.xml");
		XTmplTmpl template=XTmplTmpl.compile(doc);
		XTmplDocument document=template.makeDocument();
		document.setText("c","hello-c");
		document.setContents("d",getDocument("tmpl2.xml").getRootElement());
		document.setTexts("x",new String[]{"y","z"});

		assertEquals("hi",document.getDocument().selectSingleNode("/a/b/d/e/f").getText());
		assertEquals("hello-c",document.getDocument().selectSingleNode("/a/b/c").getText());
		List<Node> x=document.getDocument().selectNodes("/a/b/w/x");
		assertEquals(2,x.size());
		assertEquals("y",x.get(0).getText());
		assertEquals("z",x.get(1).getText());
	}
}


text:
import json
import re
import scrapy
from locations.items import GeojsonPointItem
from scrapy.http import HtmlResponse

class ConcentraSpider(scrapy.Spider):
    name = "concentra"
    allowed_domains = ["concentra.com"]
    start_urls = (
        'https://www.concentra.com//sxa/search/results/?s={449ED3CA-26F3-4E6A-BF21-9808B60D936F}|{449ED3CA-26F3-4E6A-BF21-9808B60D936F}&sig=&v={D907A7FD-050F-4644-92DC-267C1FDE200C}&p=10000&g=45|-122&o=DistanceMi,Ascending',
    )

    def parse(self, response):
        data = json.loads(response.body_as_unicode())
        stores = data['Results']
        for store in stores:
            url = 'https://www.concentra.com{}'.format(store['Url'])

            lat, lon = None, None
            if 'Geospatial' in store:
                geospatial = store['Geospatial']
                if 'Latitude' in geospatial:
                    lat = geospatial['Latitude']
                if 'Longitude' in geospatial:
                    lon = geospatial['Longitude']

            # Most of the data is stored as an html blob inside the json
            # so build a new HtmlResponse from it which we can parse.
            html = HtmlResponse(
                url=url,
                body=store['Html'].encode('utf-8')
            )
            addr1 = html.xpath('//div[@class="field-addressline1"]/text()').extract_first()
            addr2 = html.xpath('//div[@class="field-addressline2"]/text()').extract_first()
            postcode = html.xpath('//span[@class="field-zipcode"]/text()').extract_first()
            phone = html.xpath('//div[@class="field-mainphone"]/text()').extract_first()
            state = html.xpath('//span[@class="field-stateabbreviation"]/text()').extract_first()
            city = html.xpath('//div[@class="field-centername"]/text()').extract_first()
            name = html.xpath('//div[@class="location-clinic-link"]/a/@title').extract_first()

            if addr1: addr1 = addr1.strip()
            if addr2: addr2 = addr2.strip()

            addr_full = None
            if addr1 and addr2:
                addr_full = ' '.join([addr1, addr2])
            elif addr1:
                addr_full = addr1

            properties = {}
            properties['ref'] = store['Id']
            properties['website'] = url

            if addr_full: properties['addr_full'] = addr_full
            if name: properties['name'] = name
            if city: properties['city'] = city
            if state: properties['state'] = state
            if postcode: properties['postcode'] = postcode
            if phone: properties['phone'] = phone.replace('.', '-')
            if lat: properties['lat'] = lat
            if lon: properties['lon'] = lon

            yield GeojsonPointItem(**properties)


text:
package ru.job4j.set;

/**
 * Класс для описания множества на основе хэш-таблицы
 * с решением коллизий методом линейного пробирования.
 * @author vkovrov
 * @version 0.1
 * @since 0.1
 * @param <E> тип хранимых в контейнере объектов.
 */
public class HashTableSet<E> {

    /**
     * Поле для структуры данных.
     */
    private E[] container;

    /**
     * Количество добавленных элементов.
     */
    private int counter = 0;

    /**
     * Конструктор класса.
     * @param size размер контейнера.
     */
    public HashTableSet(int size) {
        this.container = (E[]) new Object[size];
    }

    /**
     * Конструктор класса.
     */
    public HashTableSet() {
        this(10);
    }

    /**
     * Метод для добавления элемента.
     * @param e значение элемента.
     * @return добавился ли элемент.
     */
    public boolean add(E e) {
        boolean isPossible = true;
        if (counter >= container.length * 0.75) {
            this.increaseArray();
        }
        int hash = this.getHash(e);
        while (container[hash] != null) {
            if (!e.equals(container[hash])) {
                hash++;
                hash %= container.length;
            } else {
                isPossible = false;
                break;
            }
        }
        if (isPossible) {
            container[hash] = e;
            counter++;
        }
        return isPossible;
    }

    /**
     * Метод для проверки наличия элемента в контейнере.
     * @param e значение элемента.
     * @return существует ли элемент с таким значением в контейнере.
     */
    public boolean contains(E e) {
        boolean arrayContainsE = false;
        int hash = this.getHash(e);
        while (container[hash] != null) {
            if (e.equals(container[hash])) {
                arrayContainsE = true;
                break;
            }
            hash++;
            hash %= container.length;
        }
        return arrayContainsE;
    }

    /**
     * Метод для удаления элемента.
     * @param e значение элемента.
     * @return удалился ли элемент.
     */
    public boolean remove(E e) {
        boolean isRemoved = false;
        int hash = this.getHash(e);
        while (container[hash] != null) {
            if (e.equals(container[hash])) {
                container[hash] = null;
                counter--;
                isRemoved = true;
                break;
            }
            hash++;
            hash %= container.length;
        }
        return isRemoved;
    }

    /**
     * Метод для увеличения размера массива.
     */
    public void increaseArray() {
        E[] newArray = (E[]) new Object[container.length * 2];
        for (int i = 0; i < container.length; i++) {
            if (container[i] != null) {
                int newHash = container[i].hashCode() % newArray.length;
                while (newArray[newHash] != null) {
                    newHash++;
                    newHash %= newArray.length;
                }
                newArray[newHash] = container[i];
            }
        }
        container = newArray;
    }

    /**
     * Метод для генерации хеш-кода.
     * @param e объект.
     * @return хеш-код объекта.
     */
    public int getHash(E e) {
        return e.hashCode() % container.length;
    }
}


text:
<?php

namespace Zephir;

use Zephir\Documentation\File;
use Zephir\Documentation\Theme;
use Zephir\Documentation\NamespaceAccessor;
use Zephir\Logger;

/**
 * Documentation Generator
 */
class Documentation
{

    /**
     * @var Config
     */
    protected $config;

    /**
     * @var CompilerFile[]
     */
    protected $classes;

    /**
     * @var Theme
     */
    protected $theme;

    protected $logger;

    /**
     * @param CompilerFile[] $classes
     * @param Config $config
     * @param Logger $logger
     * @throws ConfigException
     * @throws Exception
     */
    public function __construct(array $classes, Config $config, Logger $logger)
    {
        ksort($classes);

        $this->config = $config;
        $this->classes = $classes;
        $this->logger  = $logger;

        $themeConfig = $config->get("theme", "api");
        $themeConfig["options"]["version"] = $config->get('version');

        if (!$themeConfig) {
            throw new ConfigException("Theme configuration is not present");
        }

        if (!isset($themeConfig["name"]) || !$themeConfig["name"]) {
            throw new ConfigException("There is no theme ");
        }

        $themeDir = realpath(ZEPHIRPATH . "/templates/Api/themes/" . $themeConfig["name"]);

        if (!file_exists($themeDir)) {
            throw new ConfigException("There is no theme name " . $themeConfig["name"]);
        }

        $outputDir = $this->config->get('path', 'api');
        $outputDir = str_replace('%version%', $this->config->get('version'), $outputDir);

        if (!$outputDir) {
            throw new ConfigException("Api path is not configured");
        }

        if (!file_exists($outputDir)) {
            if (!mkdir($outputDir, 0777, true)) {
                throw new Exception("Can't write output directory $outputDir");
            }
        }

        if (!is_writable($outputDir)) {
            throw new Exception("Can't write output directory $outputDir");
        }

        $this->theme = new Theme($themeDir, $outputDir, $themeConfig);
    }

    public function build()
    {
        $byNamespace = array();

        foreach ($this->classes as $className => $class) {
            // class files (class/ns1/n2/class.html)
            $cfile = new File\ClassFile($this->config, $class);
            $this->theme->drawFile($cfile);

            // class source file (source/ns1/n2/class.html)
            $sfile = new File\SourceFile($this->config, $class);
            $this->theme->drawFile($sfile);
        }

        // classes file (classes.html)
        $file = new File\ClassesFile($this->config, $this->classes);
        $this->theme->drawFile($file);

        $namespaceAccessor = new NamespaceAccessor($this->classes);
        $namespaceAccessor->build();

        $byNamespace = $namespaceAccessor->getByNamespace();

        foreach ($byNamespace as $namespaceName => $nh) {
            // namespace files (namespace/ns1/n2/namespace.html)
            $nfile = new File\NamespaceFile($this->config, $nh);
            $this->theme->drawFile($nfile);
        }

        // namespaces files (namespaces.html)
        $nsfile = new File\NamespacesFile($this->config, $namespaceAccessor);
        $this->theme->drawFile($nsfile);

        // index (index.html)
        $indexfile = new File\IndexFile($this->config, $namespaceAccessor);
        $this->theme->drawFile($indexfile);

        $this->theme->buildStaticDirectory();

        $JsonClassDef = $this->theme->buildJsonClassDefinition($this->classes, $namespaceAccessor);
        $this->theme->createFile("asset/api_definition.js", "var ZephirApi = $JsonClassDef;");
    }

    public static function classUrl($c)
    {
        if ($c instanceof ClassDefinition) {
            $cname = $c->getCompleteName();
        } else {
            $cname = $c;
        }

        return "/class/" . str_replace("\\", "/", $cname) . ".html";
    }

    public static function namespaceUrl($ns)
    {
        return "/namespace/" . str_replace("\\", "/", $ns) . ".html";
    }

    public static function sourceUrl(ClassDefinition $c)
    {
        return "/source/" . str_replace("\\", "/", $c->getCompleteName()) . ".html";
    }
}


text:
@implementation Status

@synthesize isAmiciShown;

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if( (self=[super init]))
    {
        [self setIsTouchEnabled:YES];

		// ask director the the window size
		CGSize size = [[CCDirector sharedDirector] winSize];

        int width = size.width;
        int height = 32;

        CCLayerColor* cLayer = [[CCLayerColor alloc] initWithColor:ccc4(0x00, 0x00, 0x00, 0x90) width:width height:height];
        cLayer.position = ccp(0, size.height - height);
        [self addChild: cLayer];

        [self setAmiciVisible:YES];
        [self showSettings:YES];
	}
	return self;
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)

    if (isAmiciShown == NO) {
        [amici release];
        amici = nil;
        [amiciLabel release];
        amiciLabel = nil;
    }

    if (settings) {
        [settings release];
        settings = nil;
    }

	// don't forget to call "super dealloc"
	[super dealloc];
}

- (void) setAmiciVisible: (BOOL) visible
{
    if (visible == YES) {
        int offX = 50;

        CGSize size = [[CCDirector sharedDirector] winSize];
        amici = [CCSprite spriteWithFile:@"amici.png"];
        amici.position = ccp(offX, size.height - 16);
        [self addChild:amici];

        // create and initialize a Label
        amiciLabel = [CCLabelTTF labelWithString:@"Amici" fontName:@"Courier" fontSize:14];
        amiciLabel.position = ccp(offX + amici.contentSize.width + 20, size.height - 16);
        [self addChild:amiciLabel];
    } else {
        [self removeChild:amici cleanup: YES];
        [self removeChild:amiciLabel cleanup: YES];
    }

    self.isAmiciShown = visible;
}

- (void) showSettings: (BOOL) visible
{
    if (visible == YES) {
        CGSize size = [[CCDirector sharedDirector] winSize];
        settings = [CCSprite spriteWithFile:@"pref32.png"];
        settings.position = ccp(size.width - settings.contentSize.width, size.height - 16);
        [self addChild:settings];
    } else {
        [self removeChild:settings cleanup: YES];
        settings = nil;
    }
}

- (void) doShot: (CGPoint) point
{
    NSLog(@"Shoot!");
    //BOOL show = (self.isAmiciShown ? NO : YES);
    //[self setAmiciVisible:show];
    //[self showSettings:show];

    NSLog(@"Shot poistion %f, %f", point.x, point.y);

    if ([Status hitTest: settings withPoint: point]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:SETTINGS_CLICKED_EVENTMSG object:self];
    }

}

+ (bool) hitTest: (CCSprite*) s withPoint: (CGPoint) pt
{
    return CGRectContainsPoint(s.boundingBox, pt);
}

@end


text:
import Mux from '@mux/mux-node'
const { Video } = new Mux()

export default async function assetHandler(req, res) {
  const { method } = req

  switch (method) {
    case 'GET':
      try {
        const asset = await Video.Assets.get(req.query.id)
        res.json({
          asset: {
            id: asset.id,
            status: asset.status,
            errors: asset.errors,
            playback_id: asset.playback_ids[0].id,
          },
        })
      } catch (e) {
        console.error('Request error', e)
        res.status(500).json({ error: 'Error getting upload/asset' })
      }
      break
    default:
      res.setHeader('Allow', ['GET'])
      res.status(405).end(`Method ${method} Not Allowed`)
  }
}


text:
DynamoDM's documentation!
=====================================

This documentation is comprised of tutorials, a reference section and cookbook
articles that explain different parts of the Object Document mapper.

Getting Started
---------------

  :doc:`Getting Started <tutorials/getting-started>`
  :doc:`Introduction <reference/introduction>`
  :doc:`Architecture <reference/architecture>`

Mapping Objects onto a Database
-------------------------------

* **Basic Reference**:
  :doc:`Objects and Attributes <reference/basic-mapping>`
  :doc:`References <reference/reference-mapping>`
  :doc:`Bi-Directional References <reference/bidirectional-references>`
  :doc:`Complex References <reference/complex-references>`
  :doc:`Indexes <reference/indexes>`
  :doc:`Inheritance <reference/inheritance-mapping>`

* **Embedded Data**:
  :doc:`Embedded <reference/embedded-mapping>`
  :doc:`Trees <reference/trees>`

* **Mapping Driver References**:
  :doc:`Docblock Annotations <reference/annotations-reference>`
  :doc:`XML <reference/xml-mapping>`
  :doc:`Metadata Drivers <reference/metadata-drivers>`

Working with Objects
--------------------

* **Basic Reference**:
  :doc:`Documents <reference/working-with-objects>`
  :doc:`Repositories <reference/document-repositories>`
  :doc:`Events <reference/events>`
  :doc:`Migrations <reference/migrating-schemas>`

* **Query Reference**:
  :doc:`Query Builder API <reference/query-builder-api>`
  :doc:`Filters <reference/filters>`
  :doc:`Priming References <reference/priming-references>`
  :doc:`Eager Cursors <reference/eager-cursors>`

Advanced Topics
---------------

* **Collections**:
  :doc:`Custom Collections <reference/custom-collections>`

* **Transactions and Concurrency**:
  :doc:`Transactions and Concurrency <reference/transactions-and-concurrency>`

* **Best Practices**:
  :doc:`Best Practices <reference/best-practices>`

* **Performance**:
  :doc:`Change Tracking Policies <reference/change-tracking-policies>`

Cookbook
--------

* **Examples**:
  :doc:`Soft Delete <cookbook/soft-delete-extension>`
  :doc:`Simple Search Engine <cookbook/simple-search-engine>`

* **Tricks**:
  :doc:`Blending Doctrine ORM and DynamoDM <cookbook/blending-doctrine-orm-and-dynamodm>`
  :doc:`Mapping classes to ORM and ODM <cookbook/mapping-classes-to-orm-and-odm>`

* **Implementation**:
  :doc:`Array Access <cookbook/implementing-array-access-for-domain-objects>`
  :doc:`Notify ChangeTracking Example <cookbook/implementing-the-notify-changetracking-policy>`
  :doc:`Using Wakeup Or Clone <cookbook/implementing-wakeup-or-clone>`
  :doc:`Validation <cookbook/validation-of-documents>`
  :doc:`Simple Search Engine <cookbook/simple-search-engine>`
  :doc:`Keeping Your Modules Independent <cookbook/resolve-target-document-listener>`


text:
/**
 * Created with JetBrains WebStorm.
 * User: k-nkgwj
 * Date: 13/01/23
 * Time: 3:32
 * To change this template use File | Settings | File Templates.
 */
CONFIG = {
  default:{
    requestThreshold:1,
    incrementalReduceThreshold:200,
    requestDatasetSize:50,
    mapSize:40,
    reduceSize:40,
    riseSize:40,
    clockCycle:30
  },
  autoStart:true,
  autoConnect:"auto",
  loadMapReduceLibrary:"mapreduce/mapreduce.js",
  verbose:true
};


text:
package com.leanplum.internal;

public class ShadowOperationQueue extends OperationQueue {

    private Runnable lastDelayedOperation;

    public ShadowOperationQueue() {
        super();
    }

    @Override
    public boolean addOperation(Runnable operation) {
        operation.run();
        return true;
    }

    @Override
    public void addParallelOperation(Runnable operation) {
        operation.run();
    }

    @Override
    public void addUiOperation(Runnable operation) {
        operation.run();
    }

    @Override
    public boolean addOperationAfterDelay(Runnable operation, long delayMillis) {
        /**
         * Check if previous operation is the same to avoid stack overflow.
         * Mainly because of the RequestSender timer implementation.
         */
        if (operation.equals(lastDelayedOperation)) {
            lastDelayedOperation = null;
            return true;
        }
        lastDelayedOperation = operation;
        operation.run();
        return true;
    }
}


text:
Old SCIRun4 Tutorials
=====================

`Heart Ischemia Model <../_static/old_tutorials/IschemiaModelTutorial.pdf>`_

`Defibrillation Tutorial Model <../_static/old_tutorials/DefibrillationTutorial.pdf>`_

`BioMesh3D Meshing Pipeline <../_static/old_tutorials/BioMesh3DGuide.pdf>`_

`Forward/Inverse Toolkit <../_static/old_tutorials/ECGToolkitGuide.pdf>`_

`Electrical Brain Stimulation <../_static/old_tutorials/ElectricalBrainStimulationTutorial.pdf>`_

`Magnetical Brain Stimulation <../_static/old_tutorials/MagneticalBrainStimulationTutorial.pdf>`_


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * tests for server_status.lib.php
 *
 * @package PhpMyAdmin-test
 */

/*
 * Include to test.
 */
require_once 'libraries/Util.class.php';
require_once 'libraries/php-gettext/gettext.inc';
require_once 'libraries/url_generating.lib.php';
require_once 'libraries/ServerStatusData.class.php';
require_once 'libraries/server_status.lib.php';
require_once 'libraries/Theme.class.php';
require_once 'libraries/database_interface.inc.php';

/**
 * class PMA_ServerStatus_Test
 *
 * this class is for testing server_status.lib.php functions
 *
 * @package PhpMyAdmin-test
 */
class PMA_ServerStatus_Test extends PHPUnit_Framework_TestCase
{
    /**
     * Prepares environment for the test.
     *
     * @return void
     */
    public $ServerStatusData;

    /**
     * Test for setUp
     *
     * @return void
     */
    public function setUp()
    {
        $GLOBALS['cfg']['Server']['host'] = "localhost";
        $GLOBALS['cfg']['ShowHint'] = true;
        $GLOBALS['cfg']['ActionLinksMode'] = 'icons';
        $GLOBALS['PMA_PHP_SELF'] = PMA_getenv('PHP_SELF');
        $GLOBALS['replication_info']['master']['status'] = true;
        $GLOBALS['replication_info']['slave']['status'] = false;
        $GLOBALS['replication_types'] = array();

        $GLOBALS['table'] = "table";
        $GLOBALS['pmaThemeImage'] = 'image';

        //$_SESSION
        $_SESSION['PMA_Theme'] = PMA_Theme::load('./themes/pmahomme');
        $_SESSION['PMA_Theme'] = new PMA_Theme();

        //Mock DBI
        $dbi = $this->getMockBuilder('PMA_DatabaseInterface')
            ->disableOriginalConstructor()
            ->getMock();

        //this data is needed when PMA_ServerStatusData constructs
        $server_status = array(
            "Aborted_clients" => "0",
            "Aborted_connects" => "0",
            "Com_delete_multi" => "0",
            "Com_create_function" => "0",
            "Com_empty_query" => "0",
            "Com_execute_sql" => 2,
            "Com_stmt_execute" => 2,
        );

        $server_variables= array(
            "auto_increment_increment" => "1",
            "auto_increment_offset" => "1",
            "automatic_sp_privileges" => "ON",
            "back_log" => "50",
            "big_tables" => "OFF",
        );

        $fetchResult = array(
            array(
                "SHOW GLOBAL STATUS",
                0,
                1,
                null,
                0,
                $server_status
            ),
            array(
                "SHOW GLOBAL VARIABLES",
                0,
                1,
                null,
                0,
                $server_variables
            ),
            array(
                "SELECT concat('Com_', variable_name), variable_value "
                    . "FROM data_dictionary.GLOBAL_STATEMENTS",
                0,
                1,
                null,
                0,
                $server_status
            ),
        );

        $dbi->expects($this->any())->method('fetchResult')
            ->will($this->returnValueMap($fetchResult));

        $GLOBALS['dbi'] = $dbi;

        $this->ServerStatusData = new PMA_ServerStatusData();
    }

    /**
     * Test for PMA_getHtmlForServerStatus
     *
     * @return void
     * @group medium
     */
    public function testPMAGetHtmlForServerStatus()
    {
        //parameters
        $upTime = "10h";
        $bytes_received = 100;
        $bytes_sent = 200;
        $max_used_conn = 500;
        $aborted_conn = 200;
        $conn = 1000;
        $this->ServerStatusData->status['Uptime'] = $upTime;
        $this->ServerStatusData->status['Bytes_received'] = $bytes_received;
        $this->ServerStatusData->status['Bytes_sent'] = $bytes_sent;
        $this->ServerStatusData->status['Max_used_connections'] = $max_used_conn;
        $this->ServerStatusData->status['Aborted_connects'] = $aborted_conn;
        $this->ServerStatusData->status['Connections'] = $conn;

        //Call the test function
        $html = PMA_getHtmlForServerStatus($this->ServerStatusData);

        //validate 1: PMA_getHtmlForServerStateGeneralInfo
        //traffic: $bytes_received + $bytes_sent
        $traffic = $bytes_received + $bytes_sent;
        $traffic_html = 'Network traffic since startup: ' . $traffic . ' B';
        $this->assertContains(
            $traffic_html,
            $html
        );
        //updatetime
        $upTime_html = 'This MySQL server has been running for '
            . '0 days, 0 hours, 0 minutes and 10h seconds';
        $this->assertContains(
            $upTime_html,
            $html
        );
        //master state
        $master_html = 'This MySQL server works as master';
        $this->assertContains(
            $master_html,
            $html
        );

        //validate 2: PMA_getHtmlForServerStateTraffic
        $traffic_html = '
';
        $this->assertContains(
            $traffic_html,
            $html
        );
        //traffic hint
        $traffic_html = 'On a busy server, the byte counters may overrun';
        $this->assertContains(
            $traffic_html,
            $html
        );
        //$bytes_received
        $this->assertContains(
            '' . $bytes_received . ' B',
            $html
        );
        //$bytes_sent
        $this->assertContains(
            '' . $bytes_sent . ' B',
            $html
        );

        //validate 3: PMA_getHtmlForServerStateConnections
        $this->assertContains(
            'Connections	',
            $html
        );
        $this->assertContains(
            'ø per hour	',
            $html
        );
        $this->assertContains(
            '
',
            $html
        );
        $this->assertContains(
            'max. concurrent connections	',
            $html
        );
        //Max_used_connections
        $this->assertContains(
            '' . $max_used_conn,
            $html
        );
        $this->assertContains(
            'Failed attempts	',
            $html
        );
        //Aborted_connects
        $this->assertContains(
            '' . $aborted_conn,
            $html
        );
        $this->assertContains(
            'Aborted	',
            $html
        );

        $GLOBALS['replication_info']['master']['status'] = true;
        $GLOBALS['replication_info']['slave']['status'] = true;
        $this->ServerStatusData->status['Connections'] = 0;
        $html = PMA_getHtmlForServerStatus($this->ServerStatusData);

        $this->assertContains(
            'This MySQL server works as master and slave',
            $html
        );

        $GLOBALS['replication_info']['master']['status'] = false;
        $GLOBALS['replication_info']['slave']['status'] = true;
        $html = PMA_getHtmlForServerStatus($this->ServerStatusData);

        $this->assertContains(
            'This MySQL server works as slave',
            $html
        );
    }
}
?>


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

namespace LinqToDB.Reflection
{
	using Extensions;

	public class TypeAccessor<T> : TypeAccessor
	{
		static TypeAccessor()
		{
			// Create Instance.
			//
			var type = typeof(T);

			if (type.IsValueType)
			{
				_createInstance = () => default!;
			}
			else
			{
				var ctor = type.IsAbstract ? null : type.GetDefaultConstructorEx();

				if (ctor == null)
				{
					Expression<Func<T>> mi;

					if (type.IsAbstract) mi = () => ThrowAbstractException();
					else                     mi = () => ThrowException();

					var body = Expression.Call(null, ((MethodCallExpression)mi.Body).Method);

					_createInstance = Expression.Lambda<Func<T>>(body).Compile();
				}
				else
				{
					_createInstance = Expression.Lambda<Func<T>>(Expression.New(ctor)).Compile();
				}
			}

			_members.AddRange(type.GetPublicInstanceValueMembers());

			// Add explicit interface implementation properties support
			// Or maybe we should support all private fields/properties?
			//
			if (!type.IsInterface && !type.IsArray)
			{
				var interfaceMethods = type.GetInterfaces().SelectMany(ti => type.GetInterfaceMap(ti).TargetMethods)
					.ToList();

				if (interfaceMethods.Count > 0)
				{
					foreach (var pi in type.GetNonPublicPropertiesEx())
					{
						if (pi.GetIndexParameters().Length == 0)
						{
							var getMethod = pi.GetGetMethod(true);
							var setMethod = pi.GetSetMethod(true);

							if ((getMethod == null || interfaceMethods.Contains(getMethod)) &&
								(setMethod == null || interfaceMethods.Contains(setMethod)))
							{
								_members.Add(pi);
							}
						}
					}
				}
			}

			// ObjectFactory
			//
			var attr = type.GetFirstAttribute<ObjectFactoryAttribute>();

			if (attr != null)
				_objectFactory = attr.ObjectFactory;
		}

		static T ThrowException()
		{
			throw new LinqToDBException($"The '{typeof(T).FullName}' type must have default or init constructor.");
		}

		static T ThrowAbstractException()
		{
			throw new LinqToDBException($"Cant create an instance of abstract class '{typeof(T).FullName}'.");
		}

		static readonly List<MemberInfo> _members = new List<MemberInfo>();
		static readonly IObjectFactory?  _objectFactory;

		internal TypeAccessor()
		{
			// init members
			foreach (var member in _members)
				if (!member.GetMemberType().IsByRef)
					AddMember(new MemberAccessor(this, member, null));

			ObjectFactory = _objectFactory;
		}

		static readonly Func<T> _createInstance;
		public override object   CreateInstance()
		{
			return _createInstance()!;
		}

		public T Create()
		{
			return _createInstance();
		}

		public override Type Type => typeof(T);
	}
}


text:
@ParametersAreNonnullByDefault
package com.arpnetworking.logback.serialization.keyvalue;

import javax.annotation.ParametersAreNonnullByDefault;