text:
// We don't support a native 'xml' fetch because XMLHttpRequest.responseXML
// doesn't work within web workers.

/** Begin a series of fetches. Options:

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    {
      callback : function () {...},
      errorCallback : function (why) {...},

      // Options are 'remote', 'local', and 'permissive'
      //  'remote' parses on the server
      //  'local' gives better error messages
      //  'permissive' allows comments, trailing commas, and `backquote multiline strings`
      jsonParser: 'local',

      // If true, append '?' to each URL when fetching to force
      // it to be reloaded from the server, or at least validated.
      // Defaults to false.
      forceReload : false
    }
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Invoke \a callback when all fetch() calls have been processed,
    or \a errorCallback when the first fails.  */
function LoadManager(options) {

    options = options || {};

    // Map from url to:
    // {
    //   raw      : result of the fetch
    //   status   : 'loading', 'success', 'failure'
    //   post     : Map from post-processing functions (and null) to:
    //      {
    //            value: value
    //            callbacks: array of callbacks to invoke when data arrives and is post-processed
    //            errorCallbacks: etc.
    //      }
    // }

    this.resource = new Map();
    this.crossOrigin = 'anonymous';
    this.pendingRequests = 0;

    // 'accepting requests', 'loading', 'complete', 'failure'
    this.status = 'accepting requests';

    this.forceReload = options.forceReload || false;

    // Invoke when pendingRequests hits zero if status is not 'failure'
    this.callback = options.callback;
    this.errorCallback = options.errorCallback;
    this.jsonParser = options.jsonParser || 'local';
}

/** Invoked internally when a request is complete, or in rare cases by
    code that must explicitly manage the request count because of async
    processing. */
LoadManager.prototype.markRequestCompleted = function (url, message, success) {
    --this.pendingRequests;

    if (success) {
        if ((this.pendingRequests === 0) && (this.status === 'loading')) {
            this.status = 'complete';
            // Throw away all of the data
            this.resource = null;
            if (this.callback) { this.callback(); }
        }
    } else {
        this.status = 'failure';
        this.resource = null;
        if (this.errorCallback) { this.errorCallback(message + ' for ' + url); }
    }
};

/**
   Invoke \a callback on the contents of \a url after the specified
   post-processing function, or \a errorCallback on failure. Results
   are cached both before and *after* post-processing, so that there
   is no duplication of the HTTP request, the post processing, or any
   of the storage.

   Set \a postProcessing to null to get the raw result in the callback.

   \param url String, mandatory
   \param type Type of data at the URL: 'text', 'json', 'arraybuffer', or 'image' (uses Image)
   \param postProcess(rawData, url) function
   \param callback(data, rawData, url, postProcess)
   \param errorCallback(reason, url) optional. Invoked on failure if some other load has not already failed.
   \param warningCallback() optional.
   \param forceReload Boolean, optional. Defaults to LoadManage.forceReload

   You will receive a failure if the post process fails.
 */
LoadManager.prototype.fetch = function (url, type, postProcess, callback, errorCallback, warningCallback, forceReload) {
    console.assert(typeof type === 'string', 'type must be a string');
    console.assert((typeof postProcess === 'function') || !postProcess,
                   'postProcess must be a function, null, or undefined');
    if (forceReload === undefined) { forceReload = this.forceReload; }
    if (this.status === 'failure') { return; }
    const LM = this;

    console.assert(this.status !== 'complete',
                   'Cannot call LoadManager.fetch() after LoadManager.end()');

    let rawEntry = this.resource.get(url);

    if (! rawEntry) {
        ++this.pendingRequests;

        // Not in the cache, so create it
        rawEntry = {
            url:            url,
            raw:            undefined,
            status:         'loading',
            failureMessage: undefined,
            post:           new Map()
        };

        this.resource.set(url, rawEntry);

        function onLoadSuccess() {
            if (LM.status === 'failure') { return; }

            try {
                // Run all post processing and callbacks
                for (let [p, v] of rawEntry.post) {
                    v.value = p ? p(rawEntry.raw, rawEntry.url) : rawEntry.raw;

                    for (let c of v.callbackArray) {
                        // Note that callbacks may trigger their own loads, which
                        // increase LM.pendingRequests
                        if (c) { c(v.value, rawEntry.raw, rawEntry.url, p); }
                    }
                }
                rawEntry.status = 'success';
                LM.markRequestCompleted(rawEntry.url, '', true);
            } catch (e) {
                console.dir(e);
                rawEntry.failureMessage = '' + e;
                onLoadFailure();
            }

        }

        function onLoadFailure() {
            if (LM.status === 'failure') { return; }
            rawEntry.status = 'failure';

            // Run all failure callbacks
            for (let [p, v] of rawEntry.post) {
                for (let c of v.errorCallbackArray) {
                    if (c) { c(rawEntry.failureMessage, rawEntry.url); }
                }
            }

            LM.markRequestCompleted(rawEntry.url, rawEntry.failureMessage, false);
        }

        // Fire off the asynchronous request
        if (type === 'image') {
            const image = new Image();
            rawEntry.raw = image;
            if (LM.crossOrigin) {
                // Allow loading from other domains and reading the pixels (CORS).
                // Works only if the other site allows it; which github does and
                // for which we can use a proxy and an XMLHttpRequest as an
                // annoying workaround if necessary.
                image.crossOrigin = LM.crossOrigin;
            }
            image.onload = onLoadSuccess;
            image.onerror = onLoadFailure;
            image.src = url + (forceReload ? ('?refresh=' + Date.now()) : '');
        } else {
            const xhr = new XMLHttpRequest();

            // Force a check for the latest file using a query string
            xhr.open('GET', url + (forceReload ? ('?refresh=' + Date.now()) : ''), true);

            if (LM.forceReload) {
                // Set headers attempting to force a real refresh;
                // Chrome still doesn't always obey these in some
                // recent versions, which is why we also set the
                // query above.
                xhr.setRequestHeader('cache-control', 'no-cache, must-revalidate, post-check=0, pre-check=0');
                xhr.setRequestHeader('cache-control', 'max-age=0');
                xhr.setRequestHeader('expires', '0');
                xhr.setRequestHeader('expires', 'Tue, 01 Jan 1980 1:00:00 GMT');
                xhr.setRequestHeader('pragma', 'no-cache');
            }

            if ((LM.jsonParser !== 'remote') && (type === 'json')) {
                xhr.responseType = 'text';
            } else {
                xhr.responseType = type;
            }

            xhr.onload = function() {
                const status = xhr.status;
                if (status === 200) {
                    if (xhr.response !== undefined) {
                        // now parse
                        if ((LM.jsonParser !== 'remote') && (type === 'json')) {
                            try {
                                rawEntry.raw = LM.parseJSON(xhr.response, url, warningCallback);
                                onLoadSuccess();
                            } catch (e) {
                                rawEntry.failureMessage = '' + e;
                                rawEntry.failureMessage = rawEntry.failureMessage.replace(/position (\d*)/, function (match, pos) {
                                    const chr = parseInt(pos);
                                    const line = (xhr.response.substring(0, chr).match(/\n/g)||[]).length + 1;
                                    return 'line ' + line;
                                });
                                onLoadFailure();
                            }
                        } else {
                            rawEntry.raw = xhr.response;
                            onLoadSuccess();
                        }
                    } else {
                        rawEntry.failureMessage = "File was in the incorrect format";
                        onLoadFailure();
                    }
                } else {
                    rawEntry.failureMessage = "Server returned error " + status;
                    onLoadFailure();
                }
            };

            xhr.onerror = function (e) {
                rawEntry.failureMessage = xhr.statusText;
                onLoadFailure();
            };

            try {
                xhr.send();
            } catch (e) {
                rawEntry.failureMessage = '' + e;
                onLoadFailure();
            }
        } // if XMLHttp
    }

    let postEntry = rawEntry.post.get(postProcess);
    if (! postEntry) {
        // This is the first use of this post processing
        if (rawEntry.status === 'success') {
            // Run the post processing right now
            postEntry = {
                value: postProcess ? postProcess(rawEntry.raw, rawEntry.url) : rawEntry.raw,
            };
            if (callback) { callback(postEntry.value, rawEntry.raw, url, postProcess); }
        } else if (rawEntry.status === 'failure') {
            if (errorCallback) { errorCallback(rawEntry.failureMessage, url); }
        } else {
            // Schedule the callback
            postEntry = {
                value: null,
                callbackArray: [callback],
                errorCallbackArray: [errorCallback]
            };
        }
        rawEntry.post.set(postProcess, postEntry);
    } else if (rawEntry.status === 'success') {
        // Run the callback now
        if (callback) { callback(postEntry.value, rawEntry.raw, url, postProcess); }
    } else if (rawEntry.status === 'failure') {
        // Run the callback now
        if (errorCallback) { errorCallback(rawEntry.failureMessage, url); }
    } else {
        // Schedule the callback
        postEntry.callbackArray.push(callback);
        postEntry.errorCallbackArray.push(errorCallback);
    }
}

/** The URL is used only for reporting warnings (not errors) */
LoadManager.prototype.parseJSON = function (text, url, warningCallback) {
    if (this.jsonParser === 'permissive') {
        return WorkJSON.parse(text);
    } else {
        return JSON.parse(text);
    }
}

/**
    Call after the last fetch.
*/
LoadManager.prototype.end = function () {
    if (this.status !== 'failure') {
        console.assert(this.status === 'accepting requests');

        if (this.pendingRequests === 0) {
            // Immediately invoke the callback
            this.status = 'complete';
            // Throw away all of the data
            this.resource = null;
            if (this.callback) { this.callback(); }
        } else {
            // Tell the loading callbacks that they
            // should invoke the completion callback.
            this.status = 'loading';
        }
    }
}

/** Fetch a single url without a LoadManager instance. */
LoadManager.fetchOne = function (options, ...args) {
    console.assert(typeof options === 'object', 'First argument must be an options argument');
    const manager = new LoadManager(options);
    manager.fetch(...args);
    manager.end();
}


text:
module ActiveadminResque::DelayedJobs
  def self.register_page
    ActiveAdmin.register_page "Resque Delayed Jobs" do
      menu parent: 'Resque', label: "Delayed Jobs", priority: 5

      content do
        render 'admin/resque/schedule/delayed_jobs', resque: Resque, start: 0
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text: select c_date, c_integer, max(c_integer) over() from j7 order by 1, 2, 3;


text:
'use strict';

angular.module('crewcoveryFeedbackApp')
  .controller('OauthButtonsCtrl', function($window) {
    this.loginOauth = function(provider) {
      $window.location.href = '/auth/' + provider;
    };
  });


text:
require 'dm-core'

class Invoiceable
  include DataMapper::Resource

  property :id, Serial
  property :invoicing_system_id, String, :default => 'AGF10P270'

  belongs_to :invoice
  belongs_to :attendee

  attr_writer :price

  @@descriptions = {'AGF10P270' => 'Place',
                    'AGF10P220' => 'Early',
                    'AGF10P0' => 'Place Gratuite',
                    'AGF10D40' => 'Diner',
                    'AGF10D0' => 'Diner Gratuit'}

  def price
    return @price if @price
    invoicing_system_id =~ /AGF10(\D+)(\d+)/
    self.price = Integer($2) if $2
    @price
  end

  def description
    "#{invoicing_system_id} - #{Invoiceable.describe(invoicing_system_id)} - #{attendee.full_name}"
  end

  def self.describe(invoicing_system_id)
    description = @@descriptions[invoicing_system_id]
    description = '' unless description
    description
  end
end


text:
SETTINGS_FILE = "RESTer.sublime-settings"
SYNTAX_FILE = "Packages/RESTer HTTP Client/http.tmLanguage"


text:
<!doctype html>

<link  rel="stylesheet" type="text/css" href="Css/form.css">
<link  rel="javascript" type="text/css" href="js/javascript.js">
<meta charset="utf-8">
<title>IMedia Contact</title>

Contact

Team

Services

Home

<form id="contact-form" action="IM Project.html" method="post">

Get in touch

Fill in the form below, and we'll get back to you within 24 hours.

                        Name: (required)
                        <input placeholder="Please enter your name" type="text" tabindex="1" required autofocus>

                        Email: (required)
                        <input placeholder="Please enter your email address" type="email" tabindex="2" required>

                        Telephone: (required)
                        <input placeholder="Please enter your number" type="tel" tabindex="3" required>

                        Message: (required)
                        <textarea placeholder="Include all the details you can" tabindex="5" required></textarea>

                <button name="submit" type="submit" id="contact-submit" onClick="subvalue('submit');checksub();" >Send Email</button>

</form>


text:
<?php

namespace DoctrineORMModule\Options;

use DoctrineORMModule\Options\DBALConfiguration;
use Doctrine\ORM\Mapping\NamingStrategy;
use Zend\Stdlib\Exception\InvalidArgumentException;

/**
 * Configuration options for an ORM Configuration
 *
 * @license MIT
 * @link    http://www.doctrine-project.org/
 * @author  Kyle Spraggs <theman@spiffyjr.me>
 * @author  Marco Pivetta <ocramius@gmail.com>
 */
class Configuration extends DBALConfiguration
{
    /**
     * Set the cache key for the metadata cache. Cache key
     * is assembled as "doctrine.cache.{key}" and pulled from
     * service locator.
     *
     * @var string
     */
    protected $metadataCache = 'array';

    /**
     * Set the cache key for the query cache. Cache key
     * is assembled as "doctrine.cache.{key}" and pulled from
     * service locator.
     *
     * @var string
     */
    protected $queryCache = 'array';

    /**
     * Set the driver key for the metadata driver. Driver key
     * is assembeled as "doctrine.driver.{key}" and pulled from
     * service locator.
     *
     * @var string
     */
    protected $driver = 'orm_default';

    /**
     * Automatic generation of proxies (disable for production!)
     *
     * @var bool
     */
    protected $generateProxies = true;

    /**
     * Proxy directory.
     *
     * @var string
     */
    protected $proxyDir = 'data';

    /**
     * Proxy namespace.
     *
     * @var string
     */
    protected $proxyNamespace = 'DoctrineORMModule\Proxy';

    /**
     * Entity alias map.
     *
     * @var array
     */
    protected $entityNamespaces = array();

    /**
     * Keys must be function names and values the FQCN of the implementing class.
     * The function names will be case-insensitive in DQL.
     *
     * @var array
     */
    protected $datetimeFunctions = array();

    /**
     * Keys must be function names and values the FQCN of the implementing class.
     * The function names will be case-insensitive in DQL.
     *
     * @var array
     */
    protected $stringFunctions = array();

    /**
     * Keys must be function names and values the FQCN of the implementing class.
     * The function names will be case-insensitive in DQL.
     *
     * @var array
     */
    protected $numericFunctions = array();

    /**
     * Keys must be the name of the custom filter and the value must be
     * the class name for the custom filter.
     *
     * @var array
     */
    protected $filters = array();

    /**
     * Keys must be the name of the query and values the DQL query string.
     *
     * @var array
     */
    protected $namedQueries = array();

    /**
     * Keys must be the name of the query and the value is an array containing
     * the keys 'sql' for native SQL query string and 'rsm' for the Query\ResultSetMapping.
     *
     * @var array
     */
    protected $namedNativeQueries = array();

    /**
     * Keys must be the name of the custom hydration method and the value must be
     * the class name for the custom hydrator
     *
     * @var array
     */
    protected $customHydrationModes = array();

    /**
     * Naming strategy or name of the naming strategy service to be set in ORM
     * configuration (if any)
     *
     * @var string|null|NamingStrategy
     */
    protected $namingStrategy;

    /**
     * @param  array $datetimeFunctions
     * @return self
     */
    public function setDatetimeFunctions($datetimeFunctions)
    {
        $this->datetimeFunctions = $datetimeFunctions;

        return $this;
    }

    /**
     * @return array
     */
    public function getDatetimeFunctions()
    {
        return $this->datetimeFunctions;
    }

    /**
     * @param  string $driver
     * @return self
     */
    public function setDriver($driver)
    {
        $this->driver = $driver;

        return $this;
    }

    /**
     * @return string
     */
    public function getDriver()
    {
        return "doctrine.driver.{$this->driver}";
    }

    /**
     * @param  array $entityNamespaces
     * @return self
     */
    public function setEntityNamespaces($entityNamespaces)
    {
        $this->entityNamespaces = $entityNamespaces;

        return $this;
    }

    /**
     * @return array
     */
    public function getEntityNamespaces()
    {
        return $this->entityNamespaces;
    }

    /**
     * @param  boolean $generateProxies
     * @return self
     */
    public function setGenerateProxies($generateProxies)
    {
        $this->generateProxies = $generateProxies;

        return $this;
    }

    /**
     * @return boolean
     */
    public function getGenerateProxies()
    {
        return $this->generateProxies;
    }

    /**
     * @param  string $metadataCache
     * @return self
     */
    public function setMetadataCache($metadataCache)
    {
        $this->metadataCache = $metadataCache;

        return $this;
    }

    /**
     * @return string
     */
    public function getMetadataCache()
    {
        return "doctrine.cache.{$this->metadataCache}";
    }

    /**
     * @param  array $namedNativeQueries
     * @return self
     */
    public function setNamedNativeQueries($namedNativeQueries)
    {
        $this->namedNativeQueries = $namedNativeQueries;

        return $this;
    }

    /**
     * @return array
     */
    public function getNamedNativeQueries()
    {
        return $this->namedNativeQueries;
    }

    /**
     * @param  array $namedQueries
     * @return self
     */
    public function setNamedQueries($namedQueries)
    {
        $this->namedQueries = $namedQueries;

        return $this;
    }

    /**
     * @return array
     */
    public function getNamedQueries()
    {
        return $this->namedQueries;
    }

    /**
     * @param  array $numericFunctions
     * @return self
     */
    public function setNumericFunctions($numericFunctions)
    {
        $this->numericFunctions = $numericFunctions;

        return $this;
    }

    /**
     * @return array
     */
    public function getNumericFunctions()
    {
        return $this->numericFunctions;
    }

    /**
     *
     * @param array $filters
     * @return self
     */
    public function setFilters($filters) {
        $this->filters = $filters;

        return $this;
    }

    /**
     *
     * @return array
     */
    public function getFilters() {
        return $this->filters;
    }

    /**
     * @param  string $proxyDir
     * @return self
     */
    public function setProxyDir($proxyDir)
    {
        $this->proxyDir = $proxyDir;

        return $this;
    }

    /**
     * @return string
     */
    public function getProxyDir()
    {
        return $this->proxyDir;
    }

    /**
     * @param  string $proxyNamespace
     * @return self
     */
    public function setProxyNamespace($proxyNamespace)
    {
        $this->proxyNamespace = $proxyNamespace;

        return $this;
    }

    /**
     * @return string
     */
    public function getProxyNamespace()
    {
        return $this->proxyNamespace;
    }

    /**
     * @param  string $queryCache
     * @return self
     */
    public function setQueryCache($queryCache)
    {
        $this->queryCache = $queryCache;

        return $this;
    }

    /**
     * @return string
     */
    public function getQueryCache()
    {
        return "doctrine.cache.{$this->queryCache}";
    }

    /**
     * @param  array $stringFunctions
     * @return self
     */
    public function setStringFunctions($stringFunctions)
    {
        $this->stringFunctions = $stringFunctions;

        return $this;
    }

    /**
     * @return array
     */
    public function getStringFunctions()
    {
        return $this->stringFunctions;
    }

    /**
     * @param array $modes
     * @return self
     */
    public function setCustomHydrationModes($modes)
    {
        $this->customHydrationModes = $modes;

        return $this;
    }

    /**
     * @return array
     */
    public function getCustomHydrationModes()
    {
        return $this->customHydrationModes;
    }

    /**
     * @param string|null|NamingStrategy $namingStrategy
     * @return self
     * @throws InvalidArgumentException when the provided naming strategy does not fit the expected type
     */
    public function setNamingStrategy($namingStrategy)
    {
        if (
            null === $namingStrategy
            || is_string($namingStrategy)
            || $namingStrategy instanceof NamingStrategy
        ) {
            $this->namingStrategy = $namingStrategy;

            return $this;
        }

        throw new InvalidArgumentException(sprintf(
            'namingStrategy must be either a string, a Doctrine\ORM\Mapping\NamingStrategy '
                . 'instance or null, %s given',
            is_object($namingStrategy) ? get_class($namingStrategy) : gettype($namingStrategy)
        ));
    }

    /**
     * @return string|null|NamingStrategy
     */
    public function getNamingStrategy()
    {
        return $this->namingStrategy;
    }
}


text:
import { withTheme } from '../config';
import { Input, InputProps } from './Input';

export { Input };
export type { InputProps };
export default withTheme(Input, 'Input');


text:
class AdditionalCodeTypeDescription < Sequel::Model
  plugin :oplog, primary_key: :additional_code_type_id
  plugin :conformance_validator

  set_primary_key [:additional_code_type_id]

  many_to_one :additional_code_type, key: :additional_code_type_id
  many_to_one :language
end


text:
using namespace std;

ThreadPool<maskedArguments> myThreadPool(NUM_OF_THREADS,&negaScoutWrapper);

search_result allResults[64][16*2-2];

atomic<int32_t> galpha_pl;
atomic<player>  gpl;
atomic<bool>    ch_search;
atomic<bool>    go_search;

template<player pl, bool mainThread>
int32_t negaScout(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta){
#ifndef NDEBUG
    ++totalNodes;
#endif

    //An ftasame sta katw katw fyla tote gyrname thn katastash
    if(depth == 0){
#ifndef NDEBUG
        ++horizonNodes;
#endif
        int32_t temp = veryVeryGreedyAndStupidEvaluationFunction(board);
        temp = (pl == NORMAL) ? temp : -temp;
        return temp;
    }

    uint64 hash = board.getHash();

    int32_t alph = alpha, bet = beta;
    //alpha beta are passed by reference!!!
    int kiMove = tt.retrieveTTEntry(hash, depth, alph, bet, pl == PLACER);
    if (alph >= bet) {
        return alph;
    }

    int bmove = -1;

    bool firstChild = true;

    MoveIterator_t<BitBoard_t, pl, mainThread> mIt(board);

    if (mainThread){
        galpha_pl = alph;
        gpl       = pl;
        ch_search = true;
    }

    int iter = 0;
    bool cont_cond;
    while( (cont_cond = (firstChild || (ch_search && go_search))) ){//assignment
        tlocal_search_result tmp_r = mIt.searchNextChild(board, kiMove,
            depth-1, alph, bet, firstChild, &(allResults[depth][iter].score));
        kiMove = -1;
        if (tmp_r.move == -1) break;                //and rt.score is invalid

        firstChild = false; //set this here
        if(mainThread){//Template if
            if(tmp_r.move < 0) {
                allResults[depth][iter].move  = -(2+tmp_r.move);
                ++iter;
                continue;
            }
        }
        //tmp_r.move is always non-negative if a valid move was played

        //Setting firstChild here permits skipping the rest of current iteration
        //if score must be ignored for now

        //possible set a continue here such that if a new thread is used for
        //subtree search, to skip score checking ?
        //if (tmp_r.move < -1) continue;

        //move played!

        if (tmp_r.score >= bet){
            tt.addTTEntry(hash, depth, tmp_r.move, tmp_r.score, pl==PLACER, Cut_Node);
            return bet;                                 //fail-hard beta cut-off
        }
        if ((!mainThread) && pl != gpl && tmp_r.score >= -galpha_pl){
            if (bmove >= 0){
                tt.addTTEntry(hash, depth, bmove, alph, pl==PLACER, Cut_Node);
            }
            return -galpha_pl;//((pl == NORMAL) ? (int32_t) gbeta__pl : -galpha_pl);//MAX_TT_SCORE;
        }

        if (tmp_r.score > alph){                        //better move found
            if (mainThread){
                galpha_pl = +tmp_r.score;
            }
            alph  = tmp_r.score;
            bmove = tmp_r.move;
            assert(bmove >= 0);
        }
    }

    //Wait for threads to finish and merge scores here
    if(mainThread){
        bool unfinished;
        do {
            unfinished = false;
            for (int i = 0 ; i < iter ; ++i){
                if (allResults[depth][i].score == 0) {
                    unfinished = true;
                } else if (allResults[depth][i].move >= 0){
                    tlocal_search_result tmp_r;

                    tmp_r.score = allResults[depth][i].score;
                    tmp_r.move  = allResults[depth][i].move;
                    allResults[depth][i].move = -5;

                    if (tmp_r.score >= bet){
                        ch_search = false;
                        for (int j = 0 ; j < iter ; ++j){
                            while(allResults[depth][j].score == 0 && allResults[depth][j].move >= 0){
                                this_thread::yield();
                            }
                            if (allResults[depth][j].score > tmp_r.score){
                                tmp_r.score = allResults[depth][j].score;
                                tmp_r.move  = allResults[depth][j].move;
                            }
                        }
                        tt.addTTEntry(hash, depth, tmp_r.move, tmp_r.score, pl==PLACER, Cut_Node);
                        return bet;                             //fail-hard beta cut-off
                    }

                    if (tmp_r.score > alph){                    //better move found
                        galpha_pl = tmp_r.score;
                        alph  = tmp_r.score;
                        bmove = tmp_r.move;
                        assert(bmove >= 0);
                    }
                }
            }
            if (unfinished){
                this_thread::yield();
            }
        } while (unfinished);
    }

    if (firstChild){ //no move was available, this is a leaf node, return score
        board.assert_state();
        assert(pl == NORMAL);
#ifndef NDEBUG
        ++horizonNodes;
#endif
        bool a;
        return board.getHigherTile(&a) << 2;
    }

    NodeType nt = PV__Node;
    if (bmove < 0){                                     //All-Node
        nt    = All_Node;
        bmove = 0;
    } else if (!cont_cond){
        nt = Cut_Node;
    }
    tt.addTTEntry(hash, depth, bmove, alph, pl == PLACER, nt);
    return alph;
}

template<player other, bool mainThread>
int32_t search_deeper(BitBoard_t &board, int32_t depth, int32_t alpha,
                                                int32_t beta, bool firstChild){
    int32_t score;
    if(firstChild == true){
        score = -negaScout<other, mainThread>(board, depth, -beta, -alpha);
    } else {
        score = -negaScout<other, mainThread>(board, depth, -alpha-1, -alpha);
        if(alpha < score){
            score = -negaScout<other, mainThread>(board, depth, -beta, -alpha);
        }
    }
    return score;
}

void negaScoutWrapper(maskedArguments args){
    int32_t data;
    if (args.pl == player::PLACER){
        data = search_deeper<player::PLACER,false>(args.board, args.depth, args.alpha, args.beta, args.firstChild);
    } else {
        data = search_deeper<player::NORMAL,false>(args.board, args.depth, args.alpha, args.beta, args.firstChild);
    }
    assert(data!=0);
    *(args.writeResult) = data;
}

template<player other>
void spawnThread(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild, atomic<int32_t> *score){
    maskedArguments args;
    args.pl = other;
    args.alpha = alpha;
    args.beta = beta;
    args.depth = depth;
    args.board = board;
    args.firstChild = firstChild;
    args.writeResult = score;

    myThreadPool.useNewThread(args);
}

int32_t veryVeryGreedyAndStupidEvaluationFunction(BitBoard_t boardForEv){
    bool inCorner = false;
    int32_t v2 = boardForEv.getHigherTile(&inCorner);
    int32_t score = (v2 << 8) + 1;
    if(inCorner){
        score += boardForEv.getMaxCornerChain() << 8; // +2 = 9!!!
        score <<= 2;
    }
    score += boardForEv.getMaxChain() << 6;
    int tmp = boardForEv.countFreeTiles() - 7;
    tmp = (tmp < 0) ? -tmp : tmp;
    score += (7-tmp) << 2;
    score += boardForEv.countTileTypes() << 2;
    assert(score >= 0);
    return score;
}

template int32_t negaScout<player::PLACER, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta);
template int32_t negaScout<player::NORMAL, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta);
template int32_t negaScout<player::PLACER, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta);
template int32_t negaScout<player::NORMAL, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta);
template int32_t search_deeper<player::PLACER, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::NORMAL, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::PLACER, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::NORMAL, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);


text:
========================
Team and repository tags
========================

.. image:: https://governance.openstack.org/tc/badges/i18n.svg
    :target: https://governance.openstack.org/tc/reference/tags/index.html

.. Change things from this point on

OpenStack I18n
==============

Internationalization (I18n) is essential to make OpenStack ubiquitous.
The mission of OpenStack I18n team is to make OpenStack
ubiquitously accessible to people of all language backgrounds,
by enhancing OpenStack software internationalization,
providing translation, maintaining a translation platform and
managing translation process for better quality of outcomes.

About this repository
---------------------

This repository maintains useful assets for the I18n team,
including the contribution guide, the terminologies and so on.

Getting in touch
----------------

Mailing List
  We use openstack-i18n@lists.openstack.org as the mailing list.

IRC
  We all hang out on #openstack-i18n IRC channel on OFTC.

Team Meeting
  We have a bi-weekly `meeting`_ on Thursdays at alternating times.

.. _`meeting`: https://wiki.openstack.org/wiki/Meetings/I18nTeamMeeting


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:descendantFocusability="beforeDescendants">

    <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="15dp"
            android:paddingTop="15dp"
            android:paddingBottom="15dp"
            android:paddingRight="15dp"
            android:background="@drawable/selector_card_background"
            android:descendantFocusability="afterDescendants">

        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="56sp"
                android:id="@+id/textMemberLine"/>
        <LinearLayout
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
            <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/memberName"
                    android:id="@+id/labelMemberName"
                    />
            <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/memberLevel"
                    android:id="@+id/labelMemberLevel"/>
            <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/memberPoints"
                    android:id="@+id/labelMemberPoints"/>
            <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/memberLevelProgress"
                    android:id="@+id/labelMemberLevelProgress"/>
        </LinearLayout>
        <LinearLayout
                android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
            <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/textMemberName"/>
            <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/textMemberLevel"/>
            <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/textMemberPoints"/>
            <ProgressBar
                    style="?android:attr/progressBarStyleHorizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/progressLevel"
                    android:layout_gravity="center_horizontal"/>
        </LinearLayout>
    </LinearLayout>
</FrameLayout>


text:
from django.apps import AppConfig
from django.utils.translation import ugettext, ugettext_lazy

class LocalConfig(AppConfig):
    name="mmg.jobtrak.profile"
    # Translators: Admin Backend - Name of Profile app (appears in the header bar)
    verbose_name=ugettext_lazy("Profile")


text:
layout: post
title:  "Videos - Applications of Machine Learning"
author: james
date: Sun, 17 Jun 2018 12:07:22 -0600
description: Some neat applications of machine learning.
---

## MarI/O
Evolving a neural network with a genetic algorithm to learn to kick butt in Super Mario World.

[MarI/O - Machine Learning for Video Games](https://www.youtube.com/watch?v=qv6UVOQ0F44)

## Quadrotor Control
Controlling a quadrotor with a neural network trained via reinforcement learning techniques.

[Control of a Quadrotor with Reinforcement Learning](https://www.youtube.com/watch?v=T0A9voXzhng)

## RC Car Drifting
Learning to drift an RC car using reinforcement learning.

[Autonomous Drifting using Machine Learning](https://www.youtube.com/watch?v=opsmd5yuBF0)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Simple Sidebar - Start Bootstrap Template</title>

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

    <link href="css/simple-sidebar.css" rel="stylesheet">

                    CAR WASH

                Registration

                Find score

                About

                Services

                Contact

Car Wash

Keep your vehicle looking its best..

                    <form action="" method="post" name="form" class="form-horizontal">

                            Number:

                                <input type="text" id="name" name="num" placeholder="car number"/>

                                <button type="submit" class="btn btn-default" name="submit">Check</button>

                    </form>


text:
'use strict'

var path = require('path'),
    models = require(path.resolve('./config/lib/sequelize')).models,
    redisClient = require(path.resolve('./config/lib/redis')).client;

const arrayDelimiter = '<>';
const metadataDelimiter = ':';

function loadAllChannelStreams() {
    return models.channels.findAll({
        attributes: ['id', 'company_id']
    }).then(function(channels) {
        let promiseArr = [];
        channels.forEach(element => {
            promiseArr.push(loadChannelStreamsToRedis(element.company_id, element.id));
        });

        return Promise.all(promiseArr);
    });
}

function loadChannelStreamsToRedis(companyId, channelId, clearOnEmpty) {
    return new Promise(function(resolve, reject) {
        models.channel_stream.findAll({
            attributes: ['id', 'channel_id', 'stream_source_id', 'stream_url', 'stream_mode', 'stream_resolution', 'token', 'token_provider', 'is_octoshape', 'thumbnail_url'],
            where: {channel_id: channelId}
        }).then(function(streams) {
            let redisKey = companyId + ':channels:' + channelId + ':streams';
            if (streams.length == 0) {
                if (clearOnEmpty) {
                    redisClient.del(redisKey, function(err) {
                        if (err) {
                            reject({code:500, message: 'Clearing streams in redis failed'});
                        }
                        else {
                            resolve();
                        }
                    })
                    return;
                }
                resolve();
                return;
            }

            let channelStreams = '';

            for (let i = 0; i < streams.length; i++) {
                let stream = streams[i];
                let streamMetadata = stream.stream_source_id + metadataDelimiter + stream.stream_mode + metadataDelimiter + stream.stream_resolution;
                let row = streamMetadata + '-' + JSON.stringify(stream);
                if (i < stream.length - 1) {
                    row += arrayDelimiter;
                }

                channelStreams += row;
            }

            redisClient.set(redisKey, channelStreams, function(err) {
                if (err) {
                    reject(err);
                }
                else {
                    resolve();
                }
            });

        }).catch(function(err) {
            reject(err);
        });
    });
}

function getChannelStreams(companyId, channelId, sourceId, streamMode, resolution) {
    return new Promise(function(resolve, reject) {
        let redisKey = companyId + ':channels:' + channelId + ':streams';
        redisClient.get(redisKey, function(err, streamRawArray) {
            if (err) {
                reject(err);
                return;
            }

            if (!streamRawArray) {
                reject({code:400, message: 'Channel has no streams loaded in memory'});
                return;
            }

            let streamRows = streamRawArray.split(arrayDelimiter);
            for (let i = 0; i < streamRows.length; i++) {
                let streamRaw = streamRows[i];
                let metaAndStreamArr = streamRaw.split('-');
                let metadata = metaAndStreamArr[0].split(metadataDelimiter);
                if (metadata[0] == sourceId.toString() && metadata[1] == streamMode && metadata[2].indexOf(resolution.toString()) !== -1) {
                    let stream = JSON.parse(metaAndStreamArr[1]);
                    resolve(stream);
                    return;
                }
            }
            reject({code:400, message: 'Channel has no streams loaded in memory'});
        });
    });
}

module.exports = {
    loadChannelStreamsToRedis,
    loadAllChannelStreams,
    getChannelStreams
}


text:
namespace SharpMap.Geometries
{
    /// <summary>
    /// A MultiSurface is a two-dimensional geometric collection whose elements are surfaces. The interiors of any
    /// two surfaces in a MultiSurface may not intersect. The boundaries of any two elements in a MultiSurface may
    /// intersect at most at a finite number of points.
    /// </summary>
    /// <remarks>
    /// MultiSurface is a non-instantiable class in this specification, it defines a set of methods for its subclasses and
    /// is included for reasons of extensibility. The instantiable subclass of MultiSurface is MultiPolygon,
    /// corresponding to a collection of Polygons.
    /// </remarks>
    public abstract class MultiSurface : GeometryCollection
    {
        /// <summary>
        /// The area of this Surface, as measured in the spatial reference system of this Surface.
        /// </summary>
        public abstract double Area { get; }

        /// <summary>
        /// The mathematical centroid for this Surface as a Point.
        /// The result is not guaranteed to be on this Surface.
        /// </summary>
        public abstract Point Centroid { get; }

        /// <summary>
        /// A point guaranteed to be on this Surface.
        /// </summary>
        public abstract Point PointOnSurface { get; }

        /// <summary>
        ///  The inherent dimension of this Geometry object, which must be less than or equal to the coordinate dimension.
        /// </summary>
        public override int Dimension
        {
            get { return 2; }
        }
    }
}


text:
using System;
using LibGD;
using NUnit.Framework;

[TestFixture]
public class GlobalMembersBug00079
{
    [Test]
    public void TestBug00079()
	{
		gdImageStruct im;
        string path = new string(new char[1024]);

		im = gd.gdImageCreateTrueColor(300, 300);
		gd.gdImageFilledRectangle(im, 0,0, 299,299, 0xFFFFFF);

		gd.gdImageSetAntiAliased(im, 0x000000);
		gd.gdImageArc(im, 300, 300, 600,600, 0, 360, GlobalMembersGdtest.DefineConstants.gdAntiAliased);

		path = string.Format("{0}/gdimagearc/bug00079_exp.png", GlobalMembersGdtest.DefineConstants.GDTEST_TOP_DIR);
		if (GlobalMembersGdtest.gdTestImageCompareToFile(GlobalMembersGdtest.__FILE__, GlobalMembersGdtest.__LINE__, null, (path), (im)) == 0)
		{
            Assert.Fail("{0} failed\n", path);
		}

		gd.gdImageDestroy(im);
	}
}


text:
<?php
require_once("include/conn.php");
//*****************************************************************************************
if(isset($_POST["ac"]) && $_POST["ac"]=="add")
{
	$cat = intval($_POST["cat"]);
	$title=trim($_POST["title"]);//标题
	$author=trim($_POST["author"]);//作者
	$source=trim($_POST["source"]);//来源
	$orderby=intval($_POST["orderby"]);//排序
	$keywords=trim($_POST["keywords"]);
	$description=trim($_POST["description"]);
	$content=addslashes($_POST["content"]);//内容
	$addate=time();

	//向数据库添加一条文章
	$sql="insert into {$db_prefix}news(cat,title,author,source,keywords,description,content,addate,orderby) values($cat,'$title','$author','$source','$keywords','$description','$content',$addate,$orderby)";
	if(mysql_query($sql))
	{
		$message=urlencode("添加成功!");
		$url="news_manage.php";
		echo "";
		exit();
	}else
	{
		$message=urlencode("添加失败!");
		echo "";
		exit();
	}
}else
{
	$sql = "select * from {$db_prefix}site where id=1";
	$result = mysql_query($sql);
	$row = mysql_fetch_assoc($result);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href='css/public.css' rel='stylesheet' type='text/css'>

<title>新闻管理</title>

	  新闻管理

		  新闻管理首页  |  添加新闻

<form action="" method="post" name="form1" id="form1" onsubmit="return checkForm()">

		添加新闻内容

	<tr class="tdbg" <?php echo $onmouseover?>>
		新闻分类:

		<select name="cat">
			<?php
			$sql2 = "select * from {$db_prefix}class_news";
			$result2 = mysql_query($sql2);
			while($row2=mysql_fetch_assoc($result2))
			{
				echo "<option value='".$row2["id"]."'>".$row2["classname"]."</option>";
			}
			?>
		</select>

	<tr class="tdbg" <?php echo $onmouseover?>>
		标    题:
		<input name="title" type="text" id="title" style="width:500px;" />
	    *

	<tr class="tdbg" <?php echo $onmouseover?>>
	  作    者:
	  <input name="author" type="text" id="author" value="admin" size="15" />
      *
      来源:
      <input name="source" type="text" id="source" value="<?php echo $row["source"]?>" size="15" />
      *
	  排序:
	  <input name="orderby" type="text" id="orderby" value="50" size="5" />

	<tr class="tdbg" <?php echo $onmouseover?>>
	  关键词:
	  <input name="keywords" style="width:500px;" type="text" id="keywords" size="50" maxlength="100" />

	<tr class="tdbg" <?php echo $onmouseover?>>
	  网页描述:
	  <textarea name="description" style="width:100%;height:60px;" id="description"></textarea>

	<tr class="tdbg" <?php echo $onmouseover?>>
		内    容:

		<textarea id="content" name="content" style="width:100%;height:300px;visibility:hidden;"></textarea>

	<tr class="tdbg" <?php echo $onmouseover?>>

			<input type="submit" name="submit" value="添加" />
			<input type="hidden" name="ac" value="add" />
			<input type="button" onclick="javascript:history.go(-1)" value="返回" />

</form>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion

namespace CatapultGame
{
    internal class Player : DrawableGameComponent
    {
        #region Variables/Fields
        protected CatapultGame curGame;
        protected SpriteBatch spriteBatch;

        // Constants used for calculating shot strength
        public const float MinShotStrength = 150;
        public const float MaxShotStrength = 400;

        // Public variables used by Gameplay class
        public Catapult Catapult { get; set; }
        public int Score { get; set; }
        public string Name { get; set; }
        public int Health { get; set; }

        public Player Enemy
        {
            set
            {
                Catapult.Enemy = value;
                Catapult.Self = this;
            }
        }

        public bool IsActive { get; set; }
        #endregion

        #region Initialization
        public Player(Game game)
            : base(game)
        {
            curGame = (CatapultGame)game;
        }

        public Player(Game game, SpriteBatch screenSpriteBatch)
            : this(game)
        {
            spriteBatch = screenSpriteBatch;
        }

        public override void Initialize()
        {
            Score = 0;
            Health = 100;

            base.Initialize();
        }
        #endregion

        #region Update and Render
        public override void Update(GameTime gameTime)
        {
            // Update catapult related to the player
            Catapult.Update(gameTime);
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            // Draw related catapults
            Catapult.Draw(gameTime);
            base.Draw(gameTime);
        }
        #endregion
    }
}


text:
alias sg='script/generate'
alias sd='script/destroy'


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BLL.Factory;
using BLL.IBLL.Base;

namespace BLL.Factory.Base
{
    public class SystemMenuBLLFactory
    {
        public static readonly SystemMenuBLLFactory Instance = new SystemMenuBLLFactory();
        private DataSourceType dataSourceType;

        public SystemMenuBLLFactory()
        {
            this.dataSourceType = FactoryLayerDefine.Instance.GetDataSourceType();
        }

        public ISystemMenu GetISystemMenuBLL()
        {
            //ISystemMenu iSystemMenuBll = null;

            //if (this.dataSourceType == DataSourceType.DAL)
            //{
            //    iSystemMenuBll = new BLL.DAL.Base.SystemMenu();
            //}

            string accessorFullName = "BLL.DAL.Base.SystemMenu,BLL";

            //動態創建實例類型
            try
            {
                Type accessorType = Type.GetType(accessorFullName, false);
                return (ISystemMenu)Activator.CreateInstance(accessorType);
            }
            catch (Exception ex)
            {

                throw ex;
            }

            //return iSystemMenuBll;
        }
    }
}


text:
const headerNavLinks = [
  { href: "/blog", title: "Blog" },
  { href: "/projects", title: "Projects" },
  { href: "/about", title: "About me" },
];

export default headerNavLinks;


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

namespace GeneticAlgorithm
{
    public class GeneticAlgorithm
	{
		/// <summary>
		/// Default constructor sets mutation rate to 5%, crossover to 80%, population to 100,
		/// and generations to 2000.
		/// </summary>
		public GeneticAlgorithm()
		{
			InitialValues();
			MutationRate = 0.05;
			CrossoverRate = 0.80;
			PopulationSize = 100;
			GenerationSize = 2000;
		}

		public GeneticAlgorithm(double crossoverRate,
				  double mutationRate,
				  int populationSize,
				  int generationSize,
				  int genomeSize)
		{
			InitialValues();
			MutationRate = mutationRate;
			CrossoverRate = crossoverRate;
			PopulationSize = populationSize;
			GenerationSize = generationSize;
			GenomeSize = genomeSize;
		}

		public GeneticAlgorithm(int genomeSize)
		{
			InitialValues();
			GenomeSize = genomeSize;
		}

		public void InitialValues()
		{
			Elitism = false;
		}

		/// <summary>
		/// Method which starts the GA executing.
		/// </summary>
		public void Go()
		{

			if (GenomeSize == 0)
				throw new IndexOutOfRangeException("Genome size not set");

			FitnessTable = new List<double>();
			CurrentGeneration = new List<Genome>(GenerationSize);
			NextGeneration = new List<Genome>(GenerationSize);
			Genome.MutationRate = MutationRate;

			CreateGenomes();
			RankPopulation();

			for (int i = 0; i < GenerationSize; i++)
			{
				CreateNextGeneration();
				double fitness = RankPopulation();

				if (i % 100 == 0)
				{
					Console.WriteLine("Generation " + i + ", Best Fitness: " + fitness);
				}
			}

		}

		private int TournamentSelection()
        {
            //  Choose random 5 genomes -> choose best out of 5
            var tmp = new List<Tuple<int,double>>();
            for (int i=0; i<5; i++)
            {
                var position = random.Next(FitnessTable.Count - 1);
                tmp.Add(new Tuple<int,double>(position, FitnessTable[position]));
            }

            var best = tmp.OrderByDescending(o => o.Item2).First().Item1;

            return best;
        }

		/// <summary>
		/// Rank population and sort in order of fitness.
		/// </summary>
		private double RankPopulation()
		{
			TotalFitness = 0.0;
			foreach (Genome g in CurrentGeneration)
			{
				g.Fitness = FitnessFunction.GetFitness(g.Genes);
				TotalFitness += g.Fitness;
			}
			CurrentGeneration.Sort(delegate (Genome x, Genome y)
			{
				return Comparer<double>.Default.Compare(x.Fitness, y.Fitness);
			});

			//  now sorted in order of fitness.
			double fitness = 0.0;
			FitnessTable.Clear();
			foreach (Genome t in CurrentGeneration)
			{
				fitness += t.Fitness;
				FitnessTable.Add(t.Fitness);
			}

			return FitnessTable[FitnessTable.Count - 1];
		}

		/// <summary>
		/// Create the *initial* genomes by repeated calling the supplied fitness function
		/// </summary>
		private void CreateGenomes()
		{
			for (int i = 0; i < PopulationSize; i++)
			{
				Genome g = new Genome(GenomeSize);
				CurrentGeneration.Add(g);
			}
		}

		private void CreateNextGeneration()
		{
			NextGeneration.Clear();
			Genome g = null;
			if (Elitism)
				g = CurrentGeneration[PopulationSize - 1].DeepCopy();

			for (int i = 0; i < PopulationSize; i += 2)
			{
				int pidx1 = TournamentSelection();
				int pidx2 = TournamentSelection();
				Genome parent1, parent2, child1, child2;
				parent1 = CurrentGeneration[pidx1];
				parent2 = CurrentGeneration[pidx2];

				if (random.NextDouble() < CrossoverRate)
				{
					parent1.Crossover(ref parent2, out child1, out child2);
				}
				else
				{
					child1 = parent1;
					child2 = parent2;
				}
				child1.Mutate();
				child2.Mutate();

				NextGeneration.Add(child1);
				NextGeneration.Add(child2);
			}
			if (Elitism && g != null)
				NextGeneration[0] = g;

			CurrentGeneration.Clear();
			foreach (Genome ge in NextGeneration)
				CurrentGeneration.Add(ge);
		}

		public double MutationRate { get; set; }
		public double CrossoverRate { get; set; }
		public int PopulationSize { get; set; }
		public int GenerationSize { get; set; }
		public int GenomeSize { get; set; }
		public double TotalFitness { get; set; }
		public bool Elitism { get; set; }

		public List<Genome> CurrentGeneration;
		public List<Genome> NextGeneration;
		public List<double> FitnessTable;

		static Random random = new Random();

		public IFitnessFunction FitnessFunction { get; set; }

		public void GetBest(out double[] values, out double fitness)
		{
			Genome g = CurrentGeneration[PopulationSize - 1];
			values = new double[g.Length];
			g.GetValues(ref values);
			fitness = g.Fitness;
		}

		public void GetWorst(out double[] values, out double fitness)
		{
			GetNthGenome(0, out values, out fitness);
		}

		public void GetNthGenome(int n, out double[] values, out double fitness)
		{
			if (n < 0 || n > PopulationSize - 1)
				throw new ArgumentOutOfRangeException("n too large, or too small");
			Genome g = CurrentGeneration[n];
			values = new double[g.Length];
			g.GetValues(ref values);
			fitness = g.Fitness;
		}
	}

}


text:
package com.symbolplay.tria.screens.playscore;

import java.util.Comparator;

import com.badlogic.gdx.utils.Array;
import com.symbolplay.gamelibrary.util.GameUtils;
import com.symbolplay.tria.net.TriaServiceAccessor;
import com.symbolplay.tria.net.TriaServiceScoreListener;
import com.symbolplay.tria.persistence.GameData;
import com.symbolplay.tria.persistence.userdata.HighScoreData;
import com.symbolplay.tria.screens.general.ScoreLines;

public final class PlayScoreAccessor {

    private static final Comparator<HighScoreData> HIGH_SCORE_COMPARATOR;

    private final GameData gameData;
    private final TriaServiceAccessor triaServiceAccessor;

    private PlayScoreListener playScoreListener;

    static {
        HIGH_SCORE_COMPARATOR = new Comparator<HighScoreData>() {

            @Override
            public int compare(HighScoreData s1, HighScoreData s2) {
                return -GameUtils.compareInteger(s1.getScore(), s2.getScore());
            }
        };
    }

    public PlayScoreAccessor(GameData gameData, TriaServiceAccessor triaServiceAccessor) {
        this.gameData = gameData;

        this.triaServiceAccessor = triaServiceAccessor;
        triaServiceAccessor.addScoreListener(new TriaServiceScoreListener() {

            @Override
            public void scoresReceived(Array<HighScoreData> scoresData) {
                Array<PlayScoreData> playScoresData = getPlayScoresDataFromHighScoresData(scoresData);
                notifyScoreReceived(playScoresData);
            }

            @Override
            public void error(String message) {
            }
        });

        playScoreListener = null;
    }

    public void requestScores() {
        String selectedScoreLines = gameData.getGamePreferences().getSelectedScoreLines();

        if (ScoreLines.LOCAL.equals(selectedScoreLines)) {
            requestLocalScore();
        } else if (ScoreLines.GLOBAL.equals(selectedScoreLines)) {
            requestGlobalScore();
        } else {
            notifyScoreReceived(null);
        }
    }

    private void requestLocalScore() {
        Array<HighScoreData> highScoresData = gameData.getAchievementsData().getHighScores();
        Array<PlayScoreData> playScoresData = getPlayScoresDataFromHighScoresData(highScoresData);
        notifyScoreReceived(playScoresData);
    }

    private void requestGlobalScore() {
        triaServiceAccessor.requestGlobalScores();
    }

    private Array<PlayScoreData> getPlayScoresDataFromHighScoresData(Array<HighScoreData> highScoresData) {

        Array<HighScoreData> highScoresDataSorted = new Array<HighScoreData>(highScoresData);
        highScoresDataSorted.sort(HIGH_SCORE_COMPARATOR);

        Array<PlayScoreData> playScoresData = new Array<PlayScoreData>(true, highScoresData.size);

        int rank = 1;
        for (HighScoreData highScoreData : highScoresData) {
            int score = highScoreData.getScore();
            if (score > 0) {
                PlayScoreData playScoreData = new PlayScoreData(rank, highScoreData.getName(), score);
                playScoresData.add(playScoreData);
            }
            rank++;
        }

        return playScoresData;
    }

    public void setPlayScoreListener(PlayScoreListener playScoreListener) {
        this.playScoreListener = playScoreListener;
    }

    private void notifyScoreReceived(Array<PlayScoreData> playScores) {
        if (playScoreListener != null) {
            playScoreListener.scoreReceived(playScores);
        }
    }
}


text:
"""Tools for MLS generation"""

import numpy as np

from ._max_len_seq_inner import _max_len_seq_inner

__all__ = ['max_len_seq']

# These are definitions of linear shift register taps for use in max_len_seq()
_mls_taps = {2: [1], 3: [2], 4: [3], 5: [3], 6: [5], 7: [6], 8: [7, 6, 1],
             9: [5], 10: [7], 11: [9], 12: [11, 10, 4], 13: [12, 11, 8],
             14: [13, 12, 2], 15: [14], 16: [15, 13, 4], 17: [14],
             18: [11], 19: [18, 17, 14], 20: [17], 21: [19], 22: [21],
             23: [18], 24: [23, 22, 17], 25: [22], 26: [25, 24, 20],
             27: [26, 25, 22], 28: [25], 29: [27], 30: [29, 28, 7],
             31: [28], 32: [31, 30, 10]}

def max_len_seq(nbits, state=None, length=None, taps=None):
    """
    Maximum length sequence (MLS) generator.

    Parameters
    ----------
    nbits : int
        Number of bits to use. Length of the resulting sequence will
        be ``(2**nbits) - 1``. Note that generating long sequences
        (e.g., greater than ``nbits == 16``) can take a long time.
    state : array_like, optional
        If array, must be of length ``nbits``, and will be cast to binary
        (bool) representation. If None, a seed of ones will be used,
        producing a repeatable representation. If ``state`` is all
        zeros, an error is raised as this is invalid. Default: None.
    length : int, optional
        Number of samples to compute. If None, the entire length
        ``(2**nbits) - 1`` is computed.
    taps : array_like, optional
        Polynomial taps to use (e.g., ``[7, 6, 1]`` for an 8-bit sequence).
        If None, taps will be automatically selected (for up to
        ``nbits == 32``).

    Returns
    -------
    seq : array
        Resulting MLS sequence of 0's and 1's.
    state : array
        The final state of the shift register.

    Notes
    -----
    The algorithm for MLS generation is generically described in:

        https://en.wikipedia.org/wiki/Maximum_length_sequence

    The default values for taps are specifically taken from the first
    option listed for each value of ``nbits`` in:

        http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm

    .. versionadded:: 0.15.0

    Examples
    --------
    MLS uses binary convention:

    >>> from scipy.signal import max_len_seq
    >>> max_len_seq(4)[0]
    array([1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0], dtype=int8)

    MLS has a white spectrum (except for DC):

    >>> import matplotlib.pyplot as plt
    >>> from numpy.fft import fft, ifft, fftshift, fftfreq
    >>> seq = max_len_seq(6)[0]*2-1  # +1 and -1
    >>> spec = fft(seq)
    >>> N = len(seq)
    >>> plt.plot(fftshift(fftfreq(N)), fftshift(np.abs(spec)), '.-')
    >>> plt.margins(0.1, 0.1)
    >>> plt.grid(True)
    >>> plt.show()

    Circular autocorrelation of MLS is an impulse:

    >>> acorrcirc = ifft(spec * np.conj(spec)).real
    >>> plt.figure()
    >>> plt.plot(np.arange(-N/2+1, N/2+1), fftshift(acorrcirc), '.-')
    >>> plt.margins(0.1, 0.1)
    >>> plt.grid(True)
    >>> plt.show()

    Linear autocorrelation of MLS is approximately an impulse:

    >>> acorr = np.correlate(seq, seq, 'full')
    >>> plt.figure()
    >>> plt.plot(np.arange(-N+1, N), acorr, '.-')
    >>> plt.margins(0.1, 0.1)
    >>> plt.grid(True)
    >>> plt.show()

    """
    if taps is None:
        if nbits not in _mls_taps:
            known_taps = np.array(list(_mls_taps.keys()))
            raise ValueError('nbits must be between %s and %s if taps is None'
                             % (known_taps.min(), known_taps.max()))
        taps = np.array(_mls_taps[nbits], np.intp)
    else:
        taps = np.unique(np.array(taps, np.intp))[::-1]
        if np.any(taps < 0) or np.any(taps > nbits) or taps.size < 1:
            raise ValueError('taps must be non-empty with values between '
                             'zero and nbits (inclusive)')
        taps = np.ascontiguousarray(taps)  # needed for Cython
    n_max = (2**nbits) - 1
    if length is None:
        length = n_max
    else:
        length = int(length)
        if length < 0:
            raise ValueError('length must be greater than or equal to 0')
    # We use int8 instead of bool here because NumPy arrays of bools
    # don't seem to work nicely with Cython
    if state is None:
        state = np.ones(nbits, dtype=np.int8, order='c')
    else:
        # makes a copy if need be, ensuring it's 0's and 1's
        state = np.array(state, dtype=bool, order='c').astype(np.int8)
    if state.ndim != 1 or state.size != nbits:
        raise ValueError('state must be a 1-D array of size nbits')
    if np.all(state == 0):
        raise ValueError('state must not be all zeros')

    seq = np.empty(length, dtype=np.int8, order='c')
    state = _max_len_seq_inner(taps, state, nbits, length, seq)
    return seq, state


text:
document.write( '<select id="uiViewUser"></select>' );
document.write( '<input id="uiPass" />' );


text:
<?php

namespace ZFTest\Rest\Factory;

use PHPUnit_Framework_TestCase as TestCase;
use ReflectionObject;
use Zend\ServiceManager\ServiceManager;
use ZF\Rest\Factory\OptionsListenerFactory;
use ZF\Rest\Listener\OptionsListener;

class OptionsListenerFactoryTest extends TestCase
{
    public function setUp()
    {
        $this->services = new ServiceManager();
        $this->factory  = new OptionsListenerFactory();
    }

    public function seedConfigService()
    {
        return ['zf-rest' => [
            'some-controller' => [
                'listener'                => 'SomeListener',
                'route_name'              => 'api.rest.some',
                'route_identifer_name'    => 'some_id',
                'entity_class'            => 'SomeEntity',
                'entity_http_methods'     => ['GET', 'PATCH', 'DELETE'],
                'collection_name'         => 'some',
                'collection_http_methods' => ['GET', 'POST'],
            ],
        ]];
    }

    public function testFactoryCreatesOptionsListenerFromRestConfiguration()
    {
        $config = $this->seedConfigService();
        $this->services->setService('config', $config);

        $listener = $this->factory->createService($this->services);

        $this->assertInstanceOf(OptionsListener::class, $listener);

        $r = new ReflectionObject($listener);
        $p = $r->getProperty('config');
        $p->setAccessible(true);
        $instanceConfig = $p->getValue($listener);
        $this->assertEquals($config['zf-rest'], $instanceConfig);
    }
}


text:
@interface BMRegistrationVC ()

@end

@implementation BMRegistrationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    [self setupNavBar];
    [self setupTextFields];
    [self setupFacebookLoginAndSignUp];
}

-(void)setupNavBar {

    [self.navBar setupForRegiatrationVC];
    [self.navBar.leftBtn addTarget:self action:@selector(closeBtnPressed) forControlEvents:UIControlEventTouchUpInside];

    [self.navBar.registrationSegment addTarget:self action:@selector(segmentValueChanged:) forControlEvents:UIControlEventValueChanged];
}

-(void)setupTextFields {
    self.emailTextField = [[UITextField alloc]initWithFrame:CGRectMake(50, 84, CGRectGetWidth(self.view.frame)-100, 50)];
    self.emailTextField.placeholder = @"EMAIL";
    self.emailTextField.font = [UIFont BMTextFontWithSize:16];
    self.emailTextField.keyboardType = UIKeyboardTypeEmailAddress;
    self.emailTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.emailTextField.autocorrectionType = UITextAutocorrectionTypeNo;
    [self.view addSubview:self.emailTextField];

    UIView *underlineOne = [[UIView alloc]initWithFrame:CGRectMake(50, CGRectGetMaxY(self.emailTextField.frame)-6, CGRectGetWidth(self.view.bounds)-100, 1)];
    underlineOne.backgroundColor = [UIColor BMLightGrey];
    [self.view addSubview:underlineOne];

    self.passwordTextField = [[UITextField alloc]initWithFrame:CGRectMake(50, 134, CGRectGetWidth(self.view.frame)-100, 50)];
    self.passwordTextField.placeholder = @"PASSWORD";
    self.passwordTextField.font = [UIFont BMTextFontWithSize:16];
    self.passwordTextField.secureTextEntry = YES;
    [self.view addSubview:self.passwordTextField];

    UIView *underlineTwo = [[UIView alloc]initWithFrame:CGRectMake(50, CGRectGetMaxY(self.passwordTextField.frame)-6, CGRectGetWidth(self.view.bounds)-100, 1)];
    underlineTwo.backgroundColor = [UIColor BMLightGrey];
    [self.view addSubview:underlineTwo];

    self.actionBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.actionBtn setTitle:@"LOGIN" forState:UIControlStateNormal];
    self.actionBtn.frame = CGRectMake(50, CGRectGetMaxY(self.passwordTextField.frame)+30, CGRectGetWidth(self.view.bounds)-100, 40);
    self.actionBtn.titleLabel.font = [UIFont BMTitleFontBoldWithSize:24];
    [self.actionBtn addTarget:self action:@selector(actionBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.actionBtn];
}

-(void)closeBtnPressed {
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)segmentValueChanged:(UISegmentedControl *)sender {
    if (sender.selectedSegmentIndex == 0) {
        [self.actionBtn setTitle:@"LOGIN" forState:UIControlStateNormal];
    }
    else {
        [self.actionBtn setTitle:@"SIGN UP" forState:UIControlStateNormal];
    }
}

-(void)actionBtnPressed:(UIButton *)sender {
    if (![self isValidEmail:self.emailTextField.text]) {
        [SVProgressHUD showErrorWithStatus:@"Please enter a valid email"];
    }
    else if (self.passwordTextField.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"Please enter a valid password"];
    }
    else {
        sender.enabled = NO;
        if (self.navBar.registrationSegment.selectedSegmentIndex == 0) {
            [SVProgressHUD showWithStatus:@"Logging in"];
            [[BMUserManager shared]loginWithEmail:self.emailTextField.text password:self.passwordTextField.text returned:^(PFUser *user, NSError *error) {
                if (error) {
                    [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                }
                else {
                    [SVProgressHUD showSuccessWithStatus:@"Logged in"];
                    [self closeBtnPressed];
                }
                sender.enabled = YES;
            }];
        }
        else {
            [SVProgressHUD showWithStatus:@"Signing up"];
            [[BMUserManager shared]signupWithEmail:self.emailTextField.text password:self.passwordTextField.text returned:^(PFUser *user, NSError *error) {
                if (error) {
                    [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                }
                else {
                    [SVProgressHUD showSuccessWithStatus:@"Welcome!"];
                    [self closeBtnPressed];
                }
                sender.enabled = YES;
            }];
        }
    }
}

- (BOOL)isValidEmail:(NSString *)string {
    if (!string || string.length > 0) {
        NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
        if ([emailTest evaluateWithObject:string] == YES) {
            return YES;
        }
        else {
            return NO;
        }
    }
    else
    {
        return NO;
    }
}

-(void)setupFacebookLoginAndSignUp {
    self.facebookBtn = [[FBSDKLoginButton alloc]init];
    self.facebookBtn.frame = CGRectMake(50, CGRectGetMaxY(self.actionBtn.frame)+30, CGRectGetWidth(self.view.bounds)-100, 40);
    self.facebookBtn.readPermissions = @[@"public_profile", @"email", @"user_friends"];
    [self.view addSubview:self.facebookBtn];
    self.facebookBtn.delegate = self;
}

- (void)  loginButton:(FBSDKLoginButton *)loginButton
didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                error:(NSError *)error {

    if(error) {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        return;
    }

    [self loginToParseFBWithToken:result.token];

}

-(void)loginToParseFBWithToken: (FBSDKAccessToken *)accessToken {

    // Log In (create/update currentUser) with FBSDKAccessToken
    [PFFacebookUtils logInInBackgroundWithAccessToken:accessToken
                                                block:^(PFUser *user, NSError *error) {
                                                    if (!user) {
                                                        NSLog(@"Uh oh. There was an error logging in.");
                                                    } else {
                                                        NSLog(@"User logged in through Facebook!");
                                                    }
                                                }];
}
-(void)loginButtonDidLogOut:(FBSDKLoginButton *)loginButton {

}

@end


text:
// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    'jquery',
    'base/js/namespace',
    'base/js/utils',
    'base/js/dialog',
    'codemirror/lib/codemirror',
    'codemirror/mode/meta',
    'bootstrap',
], function($, IPython, utils, dialog, CodeMirror) {
    "use strict";

    var MenuBar = function (selector, options) {
        /**
         * Constructor
         *
         * A MenuBar Class to generate the menubar of IPython notebook
         *
         * Parameters:
         *  selector: string
         *  options: dictionary
         *      Dictionary of keyword arguments.
         *          codemirror: CodeMirror instance
         *          contents: ContentManager instance
         *          events: $(Events) instance
         *          base_url : string
         *          file_path : string
         */
        options = options || {};
        this.base_url = options.base_url || utils.get_body_data("baseUrl");
        this.selector = selector;
        this.editor = options.editor;
        this.events = options.events;
        this.save_widget = options.save_widget;

        if (this.selector !== undefined) {
            this.element = $(selector);
            this.bind_events();
        }
        this._load_mode_menu();
        Object.seal(this);
    };

    MenuBar.prototype.bind_events = function () {
        var that = this;
        var editor = that.editor;

        //  File
        this.element.find('#new-file').click(function () {
            var w = window.open();
            // Create a new file in the current directory
            var parent = utils.url_path_split(editor.file_path)[0];
            editor.contents.new_untitled(parent, {type: "file"}).then(
                function (data) {
                    w.location = utils.url_join_encode(
                        that.base_url, 'edit', data.path
                    );
                },
                function(error) {
                    w.close();
                    dialog.modal({
                        title : 'Creating New File Failed',
                        body : "The error was: " + error.message,
                        buttons : {'OK' : {'class' : 'btn-primary'}}
                    });
                }
            );
        });
        this.element.find('#save-file').click(function () {
            editor.save();
        });
        this.element.find('#rename-file').click(function () {
            that.save_widget.rename();
        });

        // Edit
        this.element.find('#menu-find').click(function () {
            editor.codemirror.execCommand("find");
        });
        this.element.find('#menu-replace').click(function () {
            editor.codemirror.execCommand("replace");
        });
        this.element.find('#menu-keymap-default').click(function () {
            editor.update_codemirror_options({
                vimMode: false,
                keyMap: 'default'
            });
        });
        this.element.find('#menu-keymap-sublime').click(function () {
            editor.update_codemirror_options({
                vimMode: false,
                keyMap: 'sublime'
            });
        });
        this.element.find('#menu-keymap-emacs').click(function () {
            editor.update_codemirror_options({
                vimMode: false,
                keyMap: 'emacs'
            });
        });
        this.element.find('#menu-keymap-vim').click(function () {
            editor.update_codemirror_options({
                vimMode: true,
                keyMap: 'vim'
            });
        });

        // View
        this.element.find('#menu-line-numbers').click(function () {
            var current = editor.codemirror.getOption('lineNumbers');
            var value = Boolean(1-current);
            editor.update_codemirror_options({lineNumbers: value});
        });

        this.events.on("config_changed.Editor", function () {
            var keyMap = editor.codemirror.getOption('keyMap') || "default";
            that.element.find(".selected-keymap").removeClass("selected-keymap");
            that.element.find("#menu-keymap-" + keyMap).addClass("selected-keymap");
        });

        this.events.on("mode_changed.Editor", function (evt, modeinfo) {
            that.element.find("#current-mode")
                .text(modeinfo.name)
                .attr(
                    'title',
                    "The current language is " + modeinfo.name
                );
        });
    };

    MenuBar.prototype._load_mode_menu = function () {
        var list = this.element.find("#mode-menu");
        var editor = this.editor;
        function make_set_mode(info) {
            return function () {
                editor.set_codemirror_mode(info);
            };
        }
        for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
            var info = CodeMirror.modeInfo[i];
            list.append($("<li>").append(
                $("<a>").attr("href", "#")
                    .text(info.name)
                    .click(make_set_mode(info))
                    .attr('title',
                        "Set language to " + info.name
                    )
            ));
        }
    };

    return {'MenuBar': MenuBar};
});


text:
package org.onosproject.drivers.server.devices.cpu;

import java.util.Map;
import java.util.HashMap;

/**
 * Representation of a CPU vendor.
 */
public enum CpuVendor {

    INTEL("GenuineIntel"),
    AMD("AuthenticAMD");

    private String vendor;

    // Statically maps CPU vendor names to enum types
    private static final Map<String, CpuVendor> MAP =
        new HashMap<String, CpuVendor>();
    static {
        for (CpuVendor cv : CpuVendor.values()) {
            MAP.put(cv.toString().toLowerCase(), cv);
        }
    }

    private CpuVendor(String vendor) {
        this.vendor = vendor;
    }

    public static CpuVendor getByName(String cv) {
        return MAP.get(cv.toLowerCase());
    }

    @Override
    public String toString() {
        return this.vendor;
    }

}


text:
@CHARSET "UTF-8";
body {color: #474a51; font-weight: 500; margin: 0 auto; padding: 0; width: 760px; font-family: "나눔고딕", Verdana, sans-serif; background: #f4f4ed; line-height: 1.6;}
body strong {font-weight: 900;}
body a {color: #2f73ff; font-weight: bold;}
body a:hover {color: #306575;}

/* 배너 스타일 */
#banner1 {width: 760px; text-align: center; margin-top: 10px; background-color: white;}
.banner2, .banner3 {width: 160px; margin-bottom: 10px;}
#league_esl #banner1 img {width: 760px;}
#league_clanbase #banner1 {background: #300000;}

/* 헤더 스타일 */
#header {background: #383d44; padding-bottom: 10px; border-right: 5px solid #7b828c; border-bottom: 5px solid #555; border-left: 1px solid #888; line-height: 0.8; padding-top: 10px;}
#header em {font-size: 30%; font-style: normal; margin-left: 4px; color: #7b828c;}
#header h1 {margin-left: 130px; margin-top: 10px; font-size: 600%;}
#header a {font-family: "Arial Black", helvetica, sans-serif; color: silver;}
#login, #logout {text-align: center; width: 750px; background-color: #e0e0d5; padding: 5px; margin-top: 10px; font-size: 120%;}
#login a, #logout a {cursor: pointer;}
#login #loginForm, #login #registerForm {text-align: right; margin-right: 300px;}
#login #loginForm input, #login #registerForm input {width: 100px;}
#login #loginForm .btn {width: 60px;}
#login #registerForm .btn {width: 40px;}

/* 네비게이션 스타일 */
#wrap {float: left; width: 155px; margin-top: 10px; margin-left: 5px;}
#sidebar {width: 159px; margin: 0; margin-bottom: 10px; background: #383d44;}
#sidebar ul {list-style: none; padding: 0;}
#sidebar a, #sidebar h2 {font: bold 11px/16px arial, helvetica, sans-serif; display:block; border-width: 1px; border-style: solid; border-color: #ccc #888 #555 #bbb; margin: 0; padding: 2px 3px;}
#sidebar h2 {color: #fff; background: #383d44; text-transform: uppercase;}
#sidebar a {color: #383d44; background: #7b828c;}
#sidebar a:hover {color: #306575; background: #fff;}
#sidebar ul ul ul {position: absolute; top: 0; left: 0;}
#sidebar ul ul ul a {background: #777;}
#sidebar li {position: relative;}
#sidebar ul ul ul {position: absolute; top: 0; left: 100%; width: 100%;}
div#sidebar ul ul ul, div#sidebar ul ul li:hover ul ul {display: none;}
div#sidebar ul ul li:hover ul, div#sidebar ul ul ul li:hover ul {display: block;}

/* 네비게이션 - 프로필 스타일 */
#wrap #profile {text-align: center; width: 155px; font-size: 1.2em; border: 2px solid #e0e0d5; margin-bottom: 10px;}
#wrap #profile .writePost {font-size: 1em;}
#wrap #profile .ccl {padding: 5px;}
#wrap #profile form {margin-top: 5px; text-align: right;}
#wrap #profile form p {margin-right: 10px;}
#wrap #profile form .login {width: 100px;}

/* 메인 컨텐츠 스타일 */
#content {float: right; width: 580px; background: #f4f4ed; font-size: 120%; margin: 10px 10px 10px 10px;}
#content h2 {font-size: 120%;}
#content h3 {color: #085829;}
#content strong {color: #2f7375;}
#content .imgRight {float: right;}
#content .contents img {vertical-align: middle;}
#content .display .left {margin: 10px 10px 5px 10px;}
#content .display .right {margin: 10px 10px 0px 0px;}
#content .left {float: left;}
#content .right {float: right;}
#content .display .right {text-align: right;}
#content .display .writer {line-height: 1; font-size: 90%; word-spacing: -1px;}
#content .contents {clear: both; border-top: 2px dotted #e0e0d5; margin: 10px; margin-top: 0; padding-top: 10px;}
#content .border {margin: 0 5px 10px 5px; border: 2px solid #e0e0d5;}
#content .contents h3, #content .contents p, #content .contents dl dt, #content .contents dl dd {margin-bottom: 10px;}
#content .contents dl dt {font-weight: bold;}
#content .contents dl dd {margin-left: 5px;}
#content .footer {text-align: center; padding: 10px;}
#content .category {padding: 0 10px; margin-bottom: 0; color: #383d44;; background-color: #e0e0d5; border: none;}
#content .innerFooter {clear: both; background-color: #e0e0d5; text-align: right;}
#content .innerFooter img, #content .btn {cursor: pointer; margin-right: 5px; vertical-align: middle;}
#content form {margin: 0px; text-align: left;}
#content form .postForm {width: 340px; margin-bottom: 5px;}
#content .border form {vertical-align: middle; margin-top: 5px;}

#writePost #content form .category, #modifyPost #content form .category {padding: 0; margin: 0; background: silver; text-align: left;}
#writePost #content form .category h3, #modifyPost #content form .category h3 {margin-left: 5px; color: white;}
#writePost #content form textarea, #modifyPost #content form textarea {border: 2px solid silver; padding: 0; margin: 0; width: 562px;}
#homepage #content .empty {text-align: center; margin: 50px 0; font-weight: bold; clear: both;}
#content .empty {text-align: center; margin: 10px 0; font-weight: bold; clear: both; margin-top: 100px;}
#content #commentForm {width: 566px; margin: 0; margin-top: -5px;}
#content .comment {margin-bottom: 10px;}
#content form textarea {width: 540px; height: 70px; padding: 5;}
#writePost #content form textarea {height: 500px;}

/* 메인 컨텐츠 - 탭 스타일 */
/*
#tab {float: left; width: 100%; margin: 0; padding: 10px 0 0 46px; list-style: none;}
#tab li {float: left; margin: 0; padding: 0;}
#tab a {float: left; display: block; margin: 0 1px 0 0; padding: 0 8px 0 8px; color: #f4f4ed; border: 2px solid #e0e0d5; border-bottom: none; background: #383d44;}
#content #wrap_tab {position: relative; top: -20px; left: -30px; margin-top: 10px;}
#league_esl #content .empty, #league_clanbase #content .empty {margin-top: 100px;}
#league_esl #content .display .left, #league_clanbase #content .display .left {margin-top: -3px;}
#tab a:hover, body#league_esl #tab_esl a, body#league_clanbase #tab_clanbase a {background: #f4f4ed; color: #306575;}
*/
/* 메인 컨텐츠 - 방명록 스타일 */
#guestbook #userName, #guestbook #userPassword {width: 100px;}
#guestbook #content form textarea {width: 535px; height: 70px; padding: 5px;}
#guestbook #content .inputBox {margin: 5px 0 5px 5px;}
#guestbook #content form input, #content form textarea {font-family: "나눔고딕", Vernada, sans-serif; font-size: 100%;}
#guestbook #content .right input {width: 100px;}
#guestbook #content form {width: 566px;}


text:
function spiralLSystem
% L-system made of spiral
% When prompt appear for iteration start with low iteration then increase
% it, otherwise a high value of iteration will execution run for longer
% time and take more memory. Start from 1 then increase number of iteration
% For good qaulity image,export the figure to EPS and convert it to PDF.

% Get l system data
lSystemData = getLsystemData;
[nRow, nColumn] = size(lSystemData);
% get user input from command window
choice = getUserInput(['Enter a choice from 1 to ' num2str(nColumn) ...
    ':'] , 1, nColumn);

angle = lSystemData(choice).angle;
motif = lSystemData(choice).motif;
MAX_ITERATION = lSystemData(choice).maxIteration;

nIteration = getUserInput(['Enter number of iteration from 1 to ' ...
    num2str(MAX_ITERATION) ':'], 1, MAX_ITERATION);

motif_len = length(motif);
motif_len_2 = motif_len+1;
% This loop expands the base motif based on the number of iterations
for n = 1:nIteration
    angle1 = zeros([4*length(angle),1]);
    for m = 1:length(angle)
        angle1(motif_len_2*m-motif_len:motif_len_2*m) = [angle(m) motif];
    end
    angle = angle1;
end

% Make a spiral, flip it and connect both of its the ends.
nPointSpiral = 100;
x = zeros(length(angle)*nPointSpiral, 1);
y = x;
phi2 = linspace(0,2*pi,nPointSpiral/2);
[sx,sy] = pol2cart(phi2,phi2);
sx = (sx - 2*pi)/(2*pi);
sx = [sx -fliplr(sx)]+1;
sy = [sy -fliplr(sy)]/(2*pi);
[sphi,rho] = cart2pol((sx)',(sy)');
xtemp = 0;
ytemp = 0;
phi = 0;
n = 1;
% Loop to replace angles with spiral
for k = 1:nPointSpiral:length(x)
    phi = phi+angle(n);
    [x1,y1] = pol2cart(sphi+phi,rho);
    x(k:(k+(nPointSpiral-1)),1) = xtemp + x1;
    y(k:(k+(nPointSpiral-1)),1) = ytemp + y1;
    xtemp = xtemp + x1(nPointSpiral,1);
    ytemp = ytemp + y1(nPointSpiral,1);
    n = n+1;
end

% black color
figure
line(x, y,'color','k');
axis equal off
set(gcf,'color',[1 1 1]);

% color
figure
nColor = 32;
cmap = makeColorMap(rand(1,3), rand(1,3), rand(1,3), nColor);
colormap(cmap);

% Color each spiral differently and when colors are over then repeat.
for n = 1:nPointSpiral:length(x)
    line(x(n:(n+(nPointSpiral-1))),y((n:(n+(nPointSpiral-1))))...
        ,'color',cmap(mod(n,nColor)+1,:));
end
axis equal off
set(gcf,'color',[1 1 1]);
end

function lSystemData = getLsystemData
% Function return structure array of base, motif and maximum iteration.
% Iteration are limited due to memory and time.
lSystemData(1).angle = [0 pi/2 pi/2 pi/2];
lSystemData(1).motif = [60 -120 60]*pi/180;
lSystemData(1).maxIteration = 3;

%inverse koch
lSystemData(2).angle = [0, -2/3*pi, -2/3*pi];
lSystemData(2).motif = [-pi/3 2*pi/3 -pi/3];
lSystemData(2).maxIteration = 3;

%koch snowflake
lSystemData(3).angle = [0, -2/3*pi, -2/3*pi];
lSystemData(3).motif = [pi/3 -2*pi/3 pi/3];
lSystemData(3).maxIteration = 3;

lSystemData(4).angle = [0 pi/2 pi/2 pi/2];
lSystemData(4).motif = [-90 90 90 0 -90 -90 90]*pi/180;
lSystemData(4).maxIteration = 3;

lSystemData(5).angle = [0 90 90 90]*pi/180;
lSystemData(5).motif = [-90 90 90 -90]*pi/180;
lSystemData(5).maxIteration = 3;

%box fractal
lSystemData(6).angle = [0 90 90 90]*pi/180;
lSystemData(6).motif = [90 -90 -90 90]*pi/180;
lSystemData(6).maxIteration = 3;
end

function choice = getUserInput(promptStr, minNum, maxNum)
% return the user input and check the range of input
choice = input(promptStr);
if isempty(choice) || ~isnumeric(choice)
    error('enter a number');
elseif (choice < minNum) || (choice > maxNum)
    error(['enter a number between 1 to ' num2str(maxNum)]);
elseif isfloat(choice)
    %if choice is floating point value then truncate the fractional part
    choice = choice - mod(choice,1);
end
end


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

namespace CGSharp.Scenes
{
    public class Scene
    {
    }
}


text:
package io.atomix.core.map.impl;

import io.atomix.core.map.AsyncDistributedSortedMap;
import io.atomix.core.map.DistributedSortedMap;
import io.atomix.core.map.DistributedSortedMapBuilder;
import io.atomix.core.map.DistributedSortedMapConfig;
import io.atomix.primitive.PrimitiveManagementService;
import io.atomix.primitive.protocol.GossipProtocol;
import io.atomix.primitive.protocol.PrimitiveProtocol;
import io.atomix.primitive.protocol.map.SortedMapProtocol;
import io.atomix.primitive.proxy.ProxyClient;
import io.atomix.primitive.service.ServiceConfig;
import io.atomix.utils.concurrent.Futures;
import io.atomix.utils.serializer.Serializer;

import java.util.concurrent.CompletableFuture;

/**
 * Default distributed sorted map builder.
 */
public class DefaultDistributedSortedMapBuilder<K extends Comparable<K>, V> extends DistributedSortedMapBuilder<K, V> {
  public DefaultDistributedSortedMapBuilder(String name, DistributedSortedMapConfig config, PrimitiveManagementService managementService) {
    super(name, config, managementService);
  }

  @Override
  @SuppressWarnings("unchecked")
  public CompletableFuture<DistributedSortedMap<K, V>> buildAsync() {
    PrimitiveProtocol protocol = protocol();
    if (protocol instanceof GossipProtocol) {
      if (protocol instanceof SortedMapProtocol) {
        return managementService.getPrimitiveCache().getPrimitive(name, () ->
            CompletableFuture.completedFuture(((SortedMapProtocol) protocol).<K, V>newSortedMapDelegate(name, serializer(), managementService))
                .thenApply(set -> new GossipDistributedSortedMap<>(name, protocol, set)))
            .thenApply(AsyncDistributedSortedMap::sync);
      } else {
        return Futures.exceptionalFuture(new UnsupportedOperationException("Sets are not supported by the provided gossip protocol"));
      }
    } else {
      return newProxy(AtomicTreeMapService.class, new ServiceConfig())
          .thenCompose(proxy -> new AtomicNavigableMapProxy<K>((ProxyClient) proxy, managementService.getPrimitiveRegistry()).connect())
          .thenApply(map -> {
            Serializer serializer = serializer();
            return new TranscodingAsyncAtomicNavigableMap<K, V, byte[]>(
                map,
                value -> serializer.encode(value),
                bytes -> serializer.decode(bytes));
          }).thenApply(atomicMap -> new DelegatingAsyncDistributedSortedMap<>(atomicMap).sync());
    }
  }
}