text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
    <meta charset="utf-8"/>
    <title>API Documentation</title>
    <meta name="author" content=""/>
    <meta name="description" content=""/>

    <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css"
          rel="stylesheet">
    <link href="https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet">
    <link href="../css/prism.css" rel="stylesheet" media="all"/>
    <link href="../css/template.css" rel="stylesheet" media="all"/>

    <link rel="shortcut icon" href="../images/favicon.ico"/>
    <link rel="apple-touch-icon" href="../images/apple-touch-icon.png"/>
    <link rel="apple-touch-icon" sizes="72x72" href="../images/apple-touch-icon-72x72.png"/>
    <link rel="apple-touch-icon" sizes="114x114" href="../images/apple-touch-icon-114x114.png"/>

            Wheels

                            API Documentation

\Wheels

                            Диаграммы

                                     Иерархия классов

                            Отчёты

                                     Ошибки 306

                                     Markers 3

    \

    Wheels

            Config

                            Schema

                                            Option

                                                            Type

Tarray

Tbool

Tboolean

Tdouble

Tfloat

Tint

Tinteger

Tmixed

Tnull

Tnumber

Treal

Tstring

Exception

Type

Exception

Option

Exception

Schema

            Typo

                            Module

                                            Smile

                                                            Kolobok

Standart

Kolobok

                                            Emoticon

Skype

                                            Punct

Dash

Quote

                                            Url

Ssh

Twitter

Align

Code

Emoticon

Exception

Filepath

Html

Math

Nobr

Punct

Space

Symbol

Url

Exception

Module

Text

Utility

            Utility

IDNA

Config

Exception

Loader

Typo

FineDiffOp

FineDiffDeleteOp

FineDiffInsertOp

FineDiffReplaceOp

FineDiffCopyOp

FineDiffOps

FineDiff

            \Wheels\Typo\Module

            \Wheels\Typo\Module
            Code

Программный код.

Использует тег <code> для отображения одной или нескольких строк текста, который представляет собой
            программный код.
            Сюда относятся имена переменных, ключевые слова, тексты функции и т.д.

Summary

                    Методы

                    Свойства

                    Константы

                    validateOption()

                    __construct()

                    getDefaultOptions()

                    setOption()

                    setOptionsFromFile()

                    setOptions()

                    setDefaultOptions()

                    setConfigDir()

                    getOption()

                    getOrder()

                    getModule()

                    addModule()

                    removeModule()

                    resetStage()

                    setNextStage()

                    setStage()

                    processStage()

                    applyRules()

                    getConfigSchema()

                    throwException()

                    $typo

                    $text

                    $config_section

                    INDENT_SPACE

                    INDENT_TAB

                    REPLACER

                    stageA()

                    stageD()

                    onChangeOption()

                    checkTextType()

                    checkOptionExists()

                    getStageMethod()

                    getStages()

                    pregHelpers()

                    getModuleClassname()

                    $_default_options

                    $_order

                    $_options

                    $_config_schema

                    $area

                    $_modules

                    $_stage

                    $_config

                    N/A

                    No private methods found

                    No private properties found

                    N/A

File

Wheels\Typo\Module\Code.php

Package

\Default

Class hierarchy

\Wheels\Typo\Module

\Wheels\Typo\Module\Code

Tags

                    todo

Константы

INDENT_SPACE

INDENT_SPACE

Пробелы.

Tags

                    todo

INDENT_TAB

INDENT_TAB

Табуляция.

Tags

                    todo

REPLACER

REPLACER

Tags

                    todo

Свойства

$typo

$typo : \Wheels\Typo

Типограф, использующий данный модуль.

Type

            \Wheels\Typo

Inherited from

\Wheels\Typo\Module

Tags

                    todo

$text

$text : \Wheels\Typo\Text

Текст.

Type

            \Wheels\Typo\Text

Inherited from

\Wheels\Typo\Module

Tags

                    todo

$config_section

$config_section

Inherited from

\Wheels\Typo\Module

Tags

                    todo

$_default_options

$_default_options : array

Настройки по умолчанию.

Type

            array

Tags

                    todo

$_order

$_order : array

Приоритет выполнения стадий

Type

            array

Inherited from

\Wheels\Typo\Module

Tags

                    todo

$_options

$_options : array

Настройки.

Type

            array

Inherited from

\Wheels\Typo\Module

Tags

                    todo

$_config_schema

$_config_schema : array

Описание конфигурации модуля.

Type

            array

Inherited from

\Wheels\Typo\Module

Tags

                    todo

$area

$area : string[]

Область работы модуля.

Type

            string[]

Inherited from

\Wheels\Typo\Module

Tags

                    todo

$_modules

$_modules : \Wheels\Typo\Module[]

Используемые модули.

Type

            \Wheels\Typo\Module[]

Inherited from

\Wheels\Typo\Module

Tags

                    todo

$_stage

$_stage : int

Текущая стадия.

Type

            int

Inherited from

\Wheels\Typo\Module

Tags

                    todo

$_config

$_config : \Wheels\Config

Конфигурационный INI файл.

Type

            \Wheels\Config

Inherited from

\Wheels\Typo\Module

Tags

                    todo

Методы

validateOption()

validateOption(string $name, mixed $value)

Проверка значения параметра (с возможной корректировкой).

Параметры

                    string
                    $name

Название параметра.

                    mixed
                    $value

Значение параметра.

Inherited from

\Wheels\Typo\Module

Tags

                    todo

__construct()

__construct(string|array $options, \Wheels\Typo $typo)

Установливает значения параметров настроек по умолчанию,
                затем установливает заданные значения параметров настроек.

Параметры

                    string|array
                    $options

Массив настроек или название секции в файле настроек.

                    \Wheels\Typo
                    $typo

Типограф, использующий данный модуль.

Inherited from

\Wheels\Typo\Module

Uses

\Wheels\Typo\Module::setOptions()

\Wheels\Typo\Module::getDefaultOptions()

Tags

                    todo

getDefaultOptions()

getDefaultOptions() : array

Возвращает массив значений параметров по умолчанию.

Returns

            array

Inherited from

\Wheels\Typo\Module

Tags

                    todo

setOption()

setOption(string $name, mixed $value)

Установливает значение параметра настроек.

Параметры

                    string
                    $name

Название параметра.

                    mixed
                    $value

Значение параметра.

Throws

\Wheels\Typo\Exception

Inherited from

\Wheels\Typo\Module

Tags

                    todo

setOptionsFromFile()

setOptionsFromFile( $section)

Параметры

                    $section

Inherited from

\Wheels\Typo\Module

Tags

                    todo

setOptions()

setOptions(string|array $options) : void

Установливает значения параметров настроек.

Параметры

                    string|array
                    $options

Массив настроек или название секции в файле настроек.

Throws

\Wheels\Typo\Exception

Inherited from

\Wheels\Typo\Module

Uses

\Wheels\Typo\Module::setOption()

Tags

                    todo

setDefaultOptions()

setDefaultOptions()

Установливает значения параметров настроек по умолчанию.

Inherited from

\Wheels\Typo\Module

Tags

                    todo

setConfigDir()

setConfigDir( $dir)

Параметры

                    $dir

Inherited from

\Wheels\Typo\Module

Tags

                    todo

getOption()

getOption(string $name) : mixed

Возвращает значение параметра.

Параметры

                    string
                    $name

Название параметра.

Throws

\Wheels\Typo\Exception

Returns

            mixed

Inherited from

\Wheels\Typo\Module

Tags

                    todo

getOrder()

getOrder() : int

Возвращает приоритет выполнения текущей стадии.

Returns

            int

Inherited from

\Wheels\Typo\Module

Tags

                    todo

getModule()

getModule(string $name) : \Wheels\Typo\Module

Возвращает модуль с заданным именем.

Параметры

                    string
                    $name

Имя модуля (полное или частичное имя класса модуля).

Returns

            \Wheels\Typo\Module
            —
Модуль с заданным именем либо NULL, если модуль

 с таким именем класса не найден среди используемых.

Inherited from

\Wheels\Typo\Module

Tags

                    todo

addModule()

addModule(\Wheels\Typo\Module|string $name, string|array $options)

Добавляет модуль.

Параметры

                    \Wheels\Typo\Module|string
                    $name

Модуль или его имя.

                    string|array
                    $options

Throws

\Wheels\Typo\Exception

Inherited from

\Wheels\Typo\Module

Tags

                    todo

removeModule()

removeModule(string $name) : void

Удаляет модуль.

Параметры

                    string
                    $name

Название модуля.

Throws

\Wheels\Typo\Exception

Inherited from

\Wheels\Typo\Module

Tags

                    todo

resetStage()

resetStage()

Inherited from

\Wheels\Typo\Module

Tags

                    todo

setNextStage()

setNextStage()

Inherited from

\Wheels\Typo\Module

Tags

                    todo

setStage()

setStage(int $stage) : bool

Устанавливает стадию работы, сортирует используемые модули по приоритетам выполнения.

Параметры

                    int
                    $stage

Стадия работы.

Returns

            bool

Inherited from

\Wheels\Typo\Module

Tags

                    todo

processStage()

processStage() : void

Запускает выполнение текущей стадии.

Inherited from

\Wheels\Typo\Module

Uses

\Wheels\Typo\Module::getStageMethod()

\Wheels\Typo\Module::getOrder();

Tags

                    todo

applyRules()

applyRules(array $rules, array $helpers,  $text) : void|string

Применяет правила к тексту.

Параметры

                    array
                    $rules

Набор правил.

                    array
                    $helpers

Вспомогательные элементы регулярных выражений.

                    $text

Returns

            void|string

Inherited from

\Wheels\Typo\Module

Tags

                    todo

getConfigSchema()

getConfigSchema()

        static

Inherited from

\Wheels\Typo\Module

Tags

                    todo

throwException()

throwException(int $code, string $message, \Wheels\Typo\Exception $previous) : void

Выбрасывает исключение.

Параметры

                    int
                    $code

Код состояния.

                    string
                    $message

Сообщение.

                    \Wheels\Typo\Exception
                    $previous

Предыдущее исключение.

Throws

\Wheels\Typo\Exception

        static

Inherited from

\Wheels\Typo\Module

Tags

                    todo

stageA()

stageA()

Стадия A.

Заменяет все блоки <code>...</code> на соответствующие заменители.

Tags

                    todo

stageD()

stageD()

Стадия C.

Восстанавливает блоки <code>...</code>.

Tags

                    todo

onChangeOption()

onChangeOption(string $name, mixed $value)

Обработчик события изменения значения параметра.

Параметры

                    string
                    $name

Название параметра.

                    mixed
                    $value

Значение параметра.

Inherited from

\Wheels\Typo\Module

Tags

                    todo

checkTextType()

checkTextType()

Inherited from

\Wheels\Typo\Module

Tags

                    todo

checkOptionExists()

checkOptionExists(string $name) : bool

Проверяет существование параметра настроек.

Параметры

                    string
                    $name

Название параметра.

Returns

            bool
            —
Вовзращает true, если параметр с таким именем существует, иначе - false.

Inherited from

\Wheels\Typo\Module

Tags

                    todo

getStageMethod()

getStageMethod() : string

Вовзращает имя метода текущей стадии.

Returns

            string

Inherited from

\Wheels\Typo\Module

Tags

                    todo

getStages()

getStages() : array

Возвращает массив имён всех стадий.

Returns

            array

        static

Inherited from

\Wheels\Typo\Module

Tags

                    todo

pregHelpers()

pregHelpers(string|string[] $pattern, array $helpers) : void

Раскрывает вспомогательные элементы регулярных выражений.

Параметры

                    string|string[]
                    $pattern

Регулярное выражение или массив регулярных выражений.

                    array
                    $helpers

Вспомогательные элементы регулярных выражений.

        static

Inherited from

\Wheels\Typo\Module

Tags

                    staticvar

array $std_helpers Стандартные вспомогательные элементы регулярных выражений.

                    todo

getModuleClassname()

getModuleClassname(string $name) : string

Возвращает название класса по имени модуля.

Параметры

                    string
                    $name

Название модуля.

Returns

            string

        static

Inherited from

\Wheels\Typo\Module

Tags

                    todo

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Code.php

\Wheels

Class Hierarchy Diagram

Ошибки

Markers

                Documentation is powered by phpDocumentor  and authored
                on March 30th, 2014 at 20:05.


text:
#include "TexturePool.h"
#include <vxEngineLib/ResourceAspectInterface.h>
#include <vxEngineLib/Graphics/Texture.h>

namespace TexturePoolCpp
{
	void uploadTextureData(const u8* pixels, u32 w, u32 h, u32 index, u32 dataSize, u8 isCommitted, vx::gl::Texture* texture)
	{
		if (isCommitted == 0)
		{
			vx::gl::TextureCommitDescription desc;
			desc.miplevel = 0;
			desc.offset = vx::uint3(0, 0, index);
			desc.size = vx::uint3(w, h, 1);
			desc.commit = 1;
			texture->commit(desc);
		}

		/*vx::gl::TextureSubImageDescription desc;
		desc.size = vx::uint3(w, h, 1);
		desc.miplevel = 0;
		desc.offset = vx::uint3(0, 0, index);
		desc.dataType = vx::gl::DataType::Unsigned_Byte;
		desc.p = pixels;

		texture->subImage(desc);*/
		vx::gl::TextureCompressedSubImageDescription desc;
		desc.size = vx::uint3(w, h, 1);
		desc.offset = vx::uint3(0, 0, index);
		desc.miplevel = 0;
		desc.p = pixels;
		desc.dataSize = dataSize;
		texture->subImageCompressed(desc);
	}
}

TexturePool::TexturePool()
	:m_indices(),
	m_entries(),
	m_firstFreeEntry(0),
	m_freeEntries(0),
	m_texture()
{

}

TexturePool::~TexturePool()
{

}

void TexturePool::initialize(const vx::uint3 &textureDim, vx::gl::TextureFormat format)
{
	auto textureCount = textureDim.z;
	m_indices.reserve(textureCount);
	m_entries = std::make_unique<std::pair<u16, u16>[]>(textureCount);
	for (u32 i = 0; i < textureCount; ++i)
	{
		m_entries[i].first = i + 1;
		m_entries[i].second = 0;
	}

	m_firstFreeEntry = 0;
	m_freeEntries = textureCount;

	vx::gl::TextureDescription desc;
	desc.size = textureDim;
	desc.miplevels = 1;
	desc.format = format;
	desc.sparse = 1;
	desc.type = vx::gl::TextureType::Texture_2D_Array;

	m_texture.create(desc);
	m_texture.makeTextureResident();
}

void TexturePool::shutdown()
{
	m_texture.destroy();
}

bool TexturePool::addTexture(const vx::StringID &sid, ResourceAspectInterface* resourceAspect, u32* index)
{
	auto texture = resourceAspect->getTexture(sid);

	return addTexture(sid, *texture, index);
}

bool TexturePool::addTexture(const vx::StringID &sid, const Graphics::Texture &texture, u32* index)
{
	if (m_freeEntries == 0)
		return false;

	auto currentIndex = m_firstFreeEntry;
	m_firstFreeEntry = m_entries[currentIndex].first;
	auto isCommitted = m_entries[currentIndex].second;

	auto &face = texture.getFace(0);
	auto dim = face.getDimension();
	auto dataSize = face.getSize();

	m_entries[currentIndex].second = 1;

	TexturePoolCpp::uploadTextureData(face.getPixels(), dim.x, dim.y, currentIndex, dataSize, isCommitted, &m_texture);

	m_indices.insert(sid, currentIndex);
	*index = currentIndex;

	--m_freeEntries;

	return true;
}

bool TexturePool::getTextureIndex(const vx::StringID &sid, ResourceAspectInterface* resourceAspect, u32* index)
{
	bool result = false;

	auto it = m_indices.find(sid);
	if (it == m_indices.end())
	{
		result = addTexture(sid, resourceAspect, index);
	}
	else
	{
		*index = (*it);
		result = true;
	}

	return result;
}

bool TexturePool::getTextureIndex(const vx::StringID &sid, const Graphics::Texture &texture, u32* index)
{
	bool result = false;

	auto it = m_indices.find(sid);
	if (it == m_indices.end())
	{
		result = addTexture(sid, texture, index);
	}
	else
	{
		*index = (*it);
		result = true;
	}

	return result;
}

u32 TexturePool::getTextureId(const vx::StringID &sid) const
{
	u32 id = 0;

	auto it = m_indices.find(sid);
	if (it != m_indices.end())
	{
		id = m_texture.getId();
	}

	return id;
}

u64 TexturePool::getTextureHandle() const
{
	return m_texture.getTextureHandle();
}

redpajama_set_name: RedPajamaGithub


text:
    @link([
        'href' => apply_filters('Modularity/Module/Posts/Permalink', get_permalink($post), $post)
    ])

                @if (in_array('image', $posts_fields) && $post->image && !get_field('posts_display_magazine_show_image_on_first_post_only', $ID))

                        @image([
                            'src'=> $post->image,
                            'alt' => $post->post_title
                        ])
                        @endimage

                @endif

                    @if (in_array('title', $posts_fields))
                        @typography([
                            "element" => "h4",
                        ])
                            {{$post->post_title}}
                        @endtypography

                    @endif

                    @if (in_array('date', $posts_fields))
                        @date([
                            'action' => 'formatDate',
                            'timestamp' => $post->humanReadableTime ? $post->humanReadableTime : apply_filters('Modularity/Module/Posts/Date', get_the_time(get_option('date_format'), $post->ID) . ' ' . get_the_time(get_option('time_format'), $post->ID), $post->ID, $post->post_type, $posts_display_as)
                        ])
                        @enddate

                    @endif

                    @if (is_array($post->terms) && !empty($post->terms))
                        -
                        @foreach ($post->terms as $term)
                            @typography([
                                "element" => "span",
                            ])
                                {{$term->name}}
                            @endtypography

                        @endforeach
                    @endif

                    @if (in_array('excerpt', $posts_fields))
                        {!! isset(get_extended($post->post_content)['main']) ? apply_filters('the_excerpt', wp_trim_words(wp_strip_all_tags(strip_shortcodes(get_extended($post->post_content)['main'])), 15, null)) : '' !!}
                    @endif

    @endbutton


text:
using Tweetinvi.Models;

namespace Tweetinvi.Events
{
    public enum UserReadMessageConversationInResultOf
    {
        /// <summary>
        /// This case should not happen and is here in case Twitter changes when they trigger the MessageRead event.
        /// If you happen to receive this mode, please report to Tweetinvi your case ideally with the associated json.
        /// </summary>
        Unknown = 0,

        /// <summary>
        /// Another user has read a message sent by the account user
        /// </summary>
        AnotherUserReadingConversation,
    }

    /// <summary>
    /// Event information when a user reads a private message conversation.
    /// </summary>
    public class UserReadMessageConversationEvent : BaseAccountActivityEventArgs<UserReadMessageConversationInResultOf>
    {
        public UserReadMessageConversationEvent(
            AccountActivityEvent activityEvent,
            IUser userWhoReadTheMessageConversation,
            IUser userWhoWroteTheMessage,
            string lastReadEventId)
            : base(activityEvent)
        {
            UserWhoReadTheMessageConversation = userWhoReadTheMessageConversation;
            UserWhoWroteTheMessage = userWhoWroteTheMessage;
            LastReadEventId = lastReadEventId;

            InResultOf = GetInResultOf();
        }

        /// <summary>
        /// The user who read the message
        /// </summary>
        public IUser UserWhoReadTheMessageConversation { get; }

        /// <summary>
        /// The user who sent the message that just got read
        /// </summary>
        public IUser UserWhoWroteTheMessage { get; }

        /// <summary>
        /// An identifier of the read action
        /// </summary>
        public string LastReadEventId { get; }

        private UserReadMessageConversationInResultOf GetInResultOf()
        {
            if (UserWhoReadTheMessageConversation.Id != AccountUserId && UserWhoWroteTheMessage.Id == AccountUserId)
            {
                return UserReadMessageConversationInResultOf.AnotherUserReadingConversation;
            }

            return UserReadMessageConversationInResultOf.Unknown;
        }
    }
}


text:
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import './Header.css'

class Header extends Component {
  render() {
    return (

          <Link to="/" className="Header-logo"></Link>

    )
  }
}

export default Header


text:
(function (exports) {

}(typeof exports === 'undefined' ? this._ = {}: exports));


text:
import numpy as np
from numpy.testing import assert_allclose, assert_equal

from .. import pick_types, Evoked
from ..io import _BaseRaw
from ..io.constants import FIFF
from ..bem import fit_sphere_to_headshape

def _get_data(x, ch_idx):
    """Helper to get the (n_ch, n_times) data array"""
    if isinstance(x, _BaseRaw):
        return x[ch_idx][0]
    elif isinstance(x, Evoked):
        return x.data[ch_idx]

def assert_meg_snr(actual, desired, min_tol, med_tol=500., msg=None):
    """Helper to assert channel SNR of a certain level

    Mostly useful for operations like Maxwell filtering that modify
    MEG channels while leaving EEG and others intact.
    """
    from nose.tools import assert_true
    picks = pick_types(desired.info, meg=True, exclude=[])
    others = np.setdiff1d(np.arange(len(actual.ch_names)), picks)
    if len(others) > 0:  # if non-MEG channels present
        assert_allclose(_get_data(actual, others),
                        _get_data(desired, others), atol=1e-11, rtol=1e-5,
                        err_msg='non-MEG channel mismatch')
    actual_data = _get_data(actual, picks)
    desired_data = _get_data(desired, picks)
    bench_rms = np.sqrt(np.mean(desired_data * desired_data, axis=1))
    error = actual_data - desired_data
    error_rms = np.sqrt(np.mean(error * error, axis=1))
    snrs = bench_rms / error_rms
    # min tol
    snr = snrs.min()
    bad_count = (snrs < min_tol).sum()
    msg = ' (%s)' % msg if msg != '' else msg
    assert_true(bad_count == 0, 'SNR (worst %0.2f) < %0.2f for %s/%s '
                'channels%s' % (snr, min_tol, bad_count, len(picks), msg))
    # median tol
    snr = np.median(snrs)
    assert_true(snr >= med_tol, 'SNR median %0.2f < %0.2f%s'
                % (snr, med_tol, msg))

def _dig_sort_key(dig):
    """Helper for sorting"""
    return 10000 * dig['kind'] + dig['ident']

def assert_dig_allclose(info_py, info_bin):
    # test dig positions
    dig_py = sorted(info_py['dig'], key=_dig_sort_key)
    dig_bin = sorted(info_bin['dig'], key=_dig_sort_key)
    assert_equal(len(dig_py), len(dig_bin))
    for ii, (d_py, d_bin) in enumerate(zip(dig_py, dig_bin)):
        for key in ('ident', 'kind', 'coord_frame'):
            assert_equal(d_py[key], d_bin[key])
        assert_allclose(d_py['r'], d_bin['r'], rtol=1e-5, atol=1e-5,
                        err_msg='Failure on %s:\n%s\n%s'
                        % (ii, d_py['r'], d_bin['r']))
    if any(d['kind'] == FIFF.FIFFV_POINT_EXTRA for d in dig_py):
        R_bin, o_head_bin, o_dev_bin = fit_sphere_to_headshape(info_bin)
        R_py, o_head_py, o_dev_py = fit_sphere_to_headshape(info_py)
        assert_allclose(R_py, R_bin)
        assert_allclose(o_dev_py, o_dev_bin, rtol=1e-5, atol=1e-3)  # mm
        assert_allclose(o_head_py, o_head_bin, rtol=1e-5, atol=1e-3)  # mm


text:
//! author="Igor Markov"

/*  The basic Pseudo-random Number Generator
  This class should be a model for all other pseudo-random
  generators (not necessarily >number< generators)

CHANGES
  970821 ilm   rid class RandomNumberGenerator of two [ambiguous] conversion
                   (unsigned and double). Instead derived two new classes
                   RandomUnsigned and RandmDouble which have the same
                   interface and respective conversions.
  970821 ilm   all private members/methods of RNG made protected
                   so that it is good as base class for RandomGenerators
  970821 ilm   added unsigned RNG::operator() (unsigned N) const to
                   RandomUnsigned for STL conformance
  971009 mro   extensive changes including making all end-user RNG classes
                   templates, making the internal random engine r250/r1279,
               adding RandomRawUnsigned, RandomRawDouble, RandomNormal
  971113 mro   added seed logging
  971114 mro   added SeedCleaner class, got rid of "Old" kernel
  971215 mro   moved SeedCleaner and SeedHandler classes to abkseed.h
  990617 mro   extensive expansion of seed-handling mechanism:  now
                  allows tripartite seeds for locally independent
                  RNGs.  Also improved selection of initial nondeterministic
                  seed and added support for verbosity.
*/
//! CHANGES="abkrand.h 970821 ilm   rid class RandomNumberGenerator of two
//[ambiguous] conversion (unsigned and double). Instead derived two new classes
// RandomUnsigned and RandmDouble which have the same interface and respective
// conversions.  970821 ilm   all private members/methods of RNG made protected
// so that it is good as base class for RandomGenerators 970821 ilm   added
// unsigned RNG::operator() (unsigned N) const to RandomUnsigned for STL
// conformance 971009 mro   extensive changes including making all end-user RNG
// classes templates, making the internal random engine r250/r1279, adding
// RandomRawUnsigned, RandomRawDouble, RandomNormal 971113 mro   added seed
// logging 971114 mro   added SeedCleaner class, got rid of "Old" kernel 971215
// mro   moved SeedCleaner and SeedHandler classes to abkseed.h   990617 mro
// extensive expansion of seed-handling mechanism:  now allows tripartite seeds
// for locally independent RNGs.  Also improved selection of initial
// nondeterministic seed and added support for verbosity. "

#ifndef _ABKRAND_H_
#define _ABKRAND_H_

#include "abkseed.h"
#include "abkassert.h"
#include "verbosity.h"
#include <iostream>
#include <cmath>

/* These classes are actually typedefed in the bottom of this class;
 statements are rather verbose, therefore not included here  -ILM

class RandomNumberGenerator;
class RandomUnsigned;
class RandomDouble;

typedef RandomNumberGenerator RNG;

 IMPORTANT:

 All random "kernel" classes MUST be derived from RandomRoot
*/

//: All random "kernel" classes MUST be derived from RandomRoot
class RandomRoot {
       private:
        SeedHandler _handler;

       protected:
        unsigned _seed;
        Verbosity _verb;
        RandomRoot(unsigned seed = UINT_MAX, Verbosity verb = Verbosity("silent")) : _handler(seed), _verb(verb) {
                _seed = _handler._seed;
                if (verb.getForMajStats()) std::cout << "_seed = " << _seed << std::endl;
        }

        RandomRoot(const char *locIdent, unsigned counterOverride = UINT_MAX, Verbosity verb = Verbosity("silent"));

       public:
        static const double randTick;  //    = 1/(0xffffffff + 1.0); // 2^-32
        unsigned getSeed() const {
                abkfatal(!_handler._isSeedMultipartite,
                         "can't use getSeed() "
                         "with multipartite seed");
                return _seed;
        }

        static unsigned getExternalSeed();
        const char *getLocIdent() const;
        unsigned getCounter() const;

        const Verbosity &getVerbosity() const { return _verb; }
};

//:  Currently implemented are based on the r250 (or r1279)
//   Tausworthe shift-register algorithm.  The periods are enormously
//   longer than the 32-bit linear congruential RNGs we were using.
//   Short periods can be a problem even if you don't exhaust them,
//   because you have a significant chance that the sequences produced
//   by two different seeds will overlap in the global sequence of
//   the RNG, and therefore not be independent.
class Tausworthe : public RandomRoot {
       private:
        unsigned _encryptWithSeed(unsigned clear);
        // the reason for the function is to be able
        // to "encrypt" a buffer value in a way dependent on
        // the seed, so that the initial state of the buffer
        // depends very chaotically on the seed.
        // returns (clear XOR _seed)^17 mod cryptMod
        void _encryptBufWithSeed();

        void _encryptBufMultipartiteSeed();

        unsigned _multmod(unsigned x, unsigned y);
        // returns x*y mod cryptMod
        unsigned _bufferSize;
        unsigned _tauswortheQ;
        mutable unsigned *_buffer;
        mutable unsigned _cursor;

       protected:
        Tausworthe(unsigned bufSize, unsigned Q, unsigned *preloads, unsigned seed = UINT_MAX, Verbosity verb = Verbosity("silent")) : RandomRoot(seed, verb), _bufferSize(bufSize), _tauswortheQ(Q), _preloads(preloads) {
                _buffer = new unsigned[bufSize];
                for (unsigned i = 0; i != bufSize; i++) _buffer[i] = 0;
                _encryptBufWithSeed();
        }

        Tausworthe(unsigned bufSize, unsigned Q, unsigned *preloads, const char *locIdent, unsigned counterOverride = UINT_MAX, Verbosity verb = Verbosity("silent")) : RandomRoot(locIdent, counterOverride, verb), _bufferSize(bufSize), _tauswortheQ(Q), _preloads(preloads) {
                _buffer = new unsigned[bufSize];
                for (unsigned i = 0; i != bufSize; i++) _buffer[i] = 0;
                _encryptBufMultipartiteSeed();
        }

        ~Tausworthe() { delete[] _buffer; }
        inline unsigned _getRawUnsigned() {
                // the function is the genuine "raw" engine for the RNG
                {
                        unsigned retval;
                        int otherPoint = _cursor - _tauswortheQ;
                        if (otherPoint < 0) otherPoint += _bufferSize;

                        retval = _buffer[_cursor] ^= _buffer[otherPoint];
                        if (++_cursor >= _bufferSize) _cursor = 0;

                        return retval;
                }
        }
        double _getRawDouble() { return randTick * _getRawUnsigned(); }
        unsigned *_preloads;
};

//: Existing engine classes: RandomKernel250 is derived from Tausworthe.
//    This is not necessary for future engine classes, and indeed
//    if your generator is not Tausworthe-style then please
//    don't derive it from Tausworthe as that would be confusing.
class RandomKernel250 : public Tausworthe {

       protected:
        RandomKernel250(unsigned seed = UINT_MAX, Verbosity verb = Verbosity("silent"));

        RandomKernel250(const char *locIdent, unsigned counterOverride = UINT_MAX, Verbosity verb = Verbosity("silent"));
};
//: The other existing engine class derived form Tausworthe.
class RandomKernel1279 : public Tausworthe {

       protected:
        RandomKernel1279(unsigned seed = UINT_MAX, Verbosity verb = Verbosity("silent"));

        RandomKernel1279(const char *locIdent, unsigned counterOverride = UINT_MAX, Verbosity verb = Verbosity("silent"));
};

//: Base template class of RandomUnsignT, RandomDoubleT, RandomRawUnsignT
//  RandomRawDoubleT and so on
template <class RK>
class RandomNumberGeneratorT : public RK {
       protected:
        double _dLowerB, _dUpperB, _dDelta;
        unsigned _lowerB, _upperB, _delta;

        unsigned _getUnsignedRand();
        double _getDoubleRand();

       public:
        RandomNumberGeneratorT(double _lowerBdry, double _upperBdry, unsigned seedN = UINT_MAX, Verbosity verb = Verbosity("silent")) : RK(seedN, verb), _dLowerB(_lowerBdry), _dUpperB(_upperBdry), _dDelta(_upperBdry - _lowerBdry), _lowerB(unsigned(_lowerBdry)), _upperB(unsigned(_upperBdry)) {
                abkfatal(_lowerBdry < _upperBdry, " Invalid range for random number generator");
                abkfatal(_dDelta > 1e-4, " Range too small for random number generator ");
                _delta = unsigned(_dDelta);
                if (_dDelta < 1) _delta = 1;
        }

        RandomNumberGeneratorT(double _lowerBdry, double _upperBdry, const char *locIdent, unsigned counterOverride = UINT_MAX, Verbosity verb = Verbosity("silent")) : RK(locIdent, counterOverride, verb), _dLowerB(_lowerBdry), _dUpperB(_upperBdry), _dDelta(_upperBdry - _lowerBdry), _lowerB(unsigned(_lowerBdry)), _upperB(unsigned(_upperBdry)) {
                abkfatal(_lowerBdry < _upperBdry, " Invalid range for random number generator");
                abkfatal(_dDelta > 1e-4, " Range too small for random number generator ");
                _delta = unsigned(_dDelta);
                if (_dDelta < 1) _delta = 1;
        }

        unsigned operator()(unsigned N) { return RK::_getRawUnsigned() % N; }
};

//: To override the seed , do something like RandomUnsigned ru(0,19,257);
//    where 0 is the lower limit (inclusive), 19 the upper limit (strict),
//    and 257 the seed. (So it goes from 0 to 18 inclusive.)
//    If you want the seed set by the system clock, or by seeds.in, use
//    RandomUnsigned ru(0,19);
//  To make a local independent RNG object, use the *second* ctor
//    below, passing a local identifier.  Suggestion:  If your
//    RNG is called _rng and is a member of MyClass, pass
//    the string "MyClass::_rng".  If it's a local variable
//    called rng in the method MyClass::myMethod(), pass
//    the string "MyClass::myMethod(),_rng".  In this way
//    you will get the same string of random values independently
//    of how many RNG objects have been created in other people's
//    code (it will keep track of the number of RNG objects created
//    specifically with *your* string.
//  Just as you can override the seed in the older ctor, you can
//    override the counter with the ctor supporting local independence.
//    This may be useful for debugging if you need to reproduce exactly
//    what happened in a particular segment of code.
template <class RK>
class RandomUnsignedT : public RandomNumberGeneratorT<RK> {
       public:
        RandomUnsignedT(double _lowerBdry, double _upperBdry, unsigned seedN = UINT_MAX, Verbosity verb = Verbosity("silent")) : RandomNumberGeneratorT<RK>(_lowerBdry, _upperBdry, seedN, verb) {}

        RandomUnsignedT(double _lowerBdry, double _upperBdry, const char *locIdent, unsigned counterOverride = UINT_MAX, Verbosity verb = Verbosity("silent")) : RandomNumberGeneratorT<RK>(_lowerBdry, _upperBdry, locIdent, counterOverride, verb) {}
        operator unsigned() { return RandomNumberGeneratorT<RK>::_getUnsignedRand(); }

        using result_type = unsigned;
        static constexpr result_type max() { return std::numeric_limits<result_type>::max(); }
        static constexpr result_type min() { return std::numeric_limits<result_type>::min(); }
        result_type operator()() { return static_cast<unsigned>(*this); }

};

//: Everything is exactly analogous to RandomUnsigned as above,
//    replacing "unsigned" by "double" in the first two parameters
//    to the constructor, and in that you cast to double to get
//    the random value.
template <class RK>
class RandomDoubleT : public RandomNumberGeneratorT<RK> {
       public:
        RandomDoubleT(double _lowerBdry, double _upperBdry, unsigned seedN = UINT_MAX, Verbosity verb = Verbosity("silent")) : RandomNumberGeneratorT<RK>(_lowerBdry, _upperBdry, seedN, verb) {};

        RandomDoubleT(double _lowerBdry, double _upperBdry, const char *locIdent, unsigned counterOverride = UINT_MAX, Verbosity verb = Verbosity("silent")) : RandomNumberGeneratorT<RK>(_lowerBdry, _upperBdry, locIdent, counterOverride, verb) {};
        operator double() { return RandomNumberGeneratorT<RK>::_getDoubleRand(); }
};

/*
//: The next two "raw" classes do not accept ranges.
// RandomRawUnsigned takes as its range all possible unsigned values.
// RandomRawDouble returns a value in [0,1) with 32 significant bits.  They
should
// be slightly faster than RandomUnsigned and RandomDouble, which
// adjust for ranges.
*/
template <class RK>
class RandomRawUnsignedT_impl : public RK {
       public:
        RandomRawUnsignedT_impl(unsigned seedN = UINT_MAX, Verbosity verb = Verbosity("silent")) : RK(seedN, verb) {};

        RandomRawUnsignedT_impl(const char *locIdent, unsigned counterOverride = UINT_MAX, Verbosity verb = Verbosity("silent")) : RK(locIdent, counterOverride, verb) {};

        operator unsigned() { return RK::_getRawUnsigned(); }
        unsigned operator()(unsigned N) { return RK::_getRawUnsigned() % N; }
};

template <class RK>
class RandomRawUnsignedT {

        RandomRawUnsignedT_impl<RK> *_impl;
        std::string _locIdent;
        unsigned _seedN, _counterOverride;
        Verbosity _verb;
        bool _haveLoc;

        void create(void) {
                if (_haveLoc)
                        _impl = new RandomRawUnsignedT_impl<RK>(_locIdent.c_str(), _counterOverride, _verb);
                else
                        _impl = new RandomRawUnsignedT_impl<RK>(_seedN, _verb);
        }

       public:
        using result_type = unsigned;
        static constexpr result_type max() { return std::numeric_limits<result_type>::max(); }
        static constexpr result_type min() { return std::numeric_limits<result_type>::min(); }
        result_type operator()() { return static_cast<unsigned>(*this); }

        RandomRawUnsignedT(unsigned seedN = UINT_MAX, Verbosity verb = Verbosity("silent")) : _impl(NULL), _seedN(seedN), _verb(verb), _haveLoc(false) {}

        RandomRawUnsignedT(const char *locIdent, unsigned counterOverride = UINT_MAX, Verbosity verb = Verbosity("silent")) : _impl(NULL), _locIdent(locIdent), _counterOverride(counterOverride), _verb(verb), _haveLoc(true) {}

        ~RandomRawUnsignedT() { delete _impl; }

        operator unsigned() {
                if (_impl == NULL) create();
                return static_cast<unsigned>(*_impl);
        }

        unsigned operator()(unsigned N) {
                if (_impl == NULL) create();
                return _impl->operator()(N);
        }

        unsigned getSeed() {
                if (_impl == NULL) create();
                return _impl->getSeed();
        }
};

//:
template <class RK>
class RandomRawDoubleT : public RK {
       public:
        RandomRawDoubleT(unsigned seedN = UINT_MAX, Verbosity verb = Verbosity("silent")) : RK(seedN, verb) {};

        RandomRawDoubleT(const char *locIdent, unsigned counterOverride = UINT_MAX, Verbosity verb = Verbosity("silent")) : RK(locIdent, counterOverride, verb) {};

        operator double() { return RK::_getRawDouble(); }
        unsigned operator()(unsigned N) { return RK::_getRawUnsigned() % N; }
};

//:
//    The constructor of class accepts two values (mean, standard deviation)
//    or three (overriding the seed):
//
//    RandomNormal rn(4.0,2.0);
//    RandomNormal rn(4.0,2.0,14);
//
//    The values of rn will be normally distributed (Gaussian, bell curve)
//    with mean 4.0 and standard deviation 2.0.
template <class RK>
class RandomNormalT : public RK {
       private:
        double _mu;
        double _sigma;
        mutable bool _cacheFull;
        mutable double _cachedValue;

       public:
        RandomNormalT<RK>(double mean, double stdDev, unsigned seed = UINT_MAX, Verbosity verb = Verbosity("silent")) : RK(seed, verb), _mu(mean), _sigma(stdDev), _cacheFull(false), _cachedValue(0.0) {}

        RandomNormalT<RK>(double mean, double stdDev, const char *locIdent, unsigned counterOverride = UINT_MAX, Verbosity verb = Verbosity("silent")) : RK(locIdent, counterOverride, verb), _mu(mean), _sigma(stdDev), _cacheFull(false), _cachedValue(0.0) {}

        operator double();
};

// This class generates pairs of binormal deviates
// (see "Numerical Recipes in C", second edition, section 14.5)
// with specified means, standard deviations, and correlations.
// Each time the getPair() method is called, a new pair
// of deviates is returned.  The "first" element of the
// pair has mean equal to "mean1" and standard deviation
// equal to "stdDev1"; mutatatis mutandis for the "second"
// element.

template <class RK>
class RandomNormCorrPairsT {
       private:
        RandomNormalT<RK> _norm;
        const double _mu1, _mu2;
        const double _sigma1, _sigma2;
        const double _rho;
        const double _c;  // we'll use x1+_c*x2 and x1-_c*x2,
                          // where x1, x2 are indep. unit normal deviates

        const double _a1, _a2, _b1, _b2;  // intermed values useful to precalc

       public:
        RandomNormCorrPairsT<RK>(double mean1, double stdDev1, double mean2, double stdDev2, double correlation, unsigned seed = UINT_MAX, Verbosity verb = Verbosity("silent")) : _norm(0, 1, seed, verb), _mu1(mean1), _mu2(mean2), _sigma1(stdDev1), _sigma2(stdDev2), _rho(correlation), _c(sqrt((1 - _rho) / (1 + _rho))), _a1(_sigma1 / sqrt(1 + _c * _c)), _a2(_sigma2 / sqrt(1 + _c * _c)), _b1(_sigma1 * _c / sqrt(1 + _c * _c)), _b2(_sigma2 * _c / sqrt(1 + _c * _c)) {}

        RandomNormCorrPairsT<RK>(double mean1, double stdDev1, double mean2, double stdDev2, double correlation, const char *locIdent, unsigned counterOverride = UINT_MAX, Verbosity verb = Verbosity("silent")) : _norm(0, 1, locIdent, counterOverride, verb), _mu1(mean1), _mu2(mean2), _sigma1(stdDev1), _sigma2(stdDev2), _rho(correlation), _c(sqrt((1 - _rho) / (1 + _rho))), _a1(_sigma1 / sqrt(1 + _c * _c)), _a2(_sigma2 / sqrt(1 + _c * _c)), _b1(_sigma1 * _c / sqrt(1 + _c * _c)), _b2(_sigma2 * _c / sqrt(1 + _c * _c)) {}

        std::pair<double, double> getPair();
};

// This RNG gives multinormally-distributed X_0, X_1,...,X_{n-1}
// with specified pairwise correlations.
template <class RK>
class RandomNormCorrTuplesT {
       private:
        // helper function; _rho_ij includes only upper-triangular elements
        // i.e. _rho_ij[i][j] is not really rho_ij but
        // rather rho_{i,i+j+1}
        // return value is success
        bool _findBasis(const std::vector<std::vector<double> > &_rho_ij, std::vector<std::vector<double> > &_v_ij);

        const unsigned _n;  // number of variates
        std::vector<RandomNormalT<RK> *> _norm_j;
        std::vector<double> _y_j;  // scratch space; fill with normal values
        // then transform with _v_ij
        const std::vector<double> _mu_i;
        const std::vector<double> _sigma_i;
        std::vector<std::vector<double> > _v_ij;

        bool _bad;  // will be set if _findBasis() fails

       public:
        RandomNormCorrTuplesT<RK>(const std::vector<double> &means, const std::vector<double> &stdDevs,

                                  // Note:  corrs[i][j] is the desired
                                  // correlation between X_i and
                                  // X_{i+j+1} (i.e. only upper-triangular
                                  // elements are included
                                  const std::vector<std::vector<double> > &corrs, const char *locIdent, unsigned counterOverride = UINT_MAX, Verbosity verb = Verbosity("silent"));

        ~RandomNormCorrTuplesT();

        void getTuple(std::vector<double> &tuple);
        bool bad() const { return _bad; }
};
/* -------------------------   IMPLEMENTATIONS  ----------------------- */
// I don't seem to be able to get any compiler to instantiate these
// methods from a template database.  I don't understand why.
// If it's figured out, then the following "#include" can be
// conditioned on the compiler
// mro 011029

#include "abkrand_templ.cxx"

typedef RandomDoubleT<RandomKernel250> RandomDouble;
typedef RandomDoubleT<RandomKernel1279> RandomDouble1279;
typedef RandomUnsignedT<RandomKernel250> RandomUnsigned;
typedef RandomUnsignedT<RandomKernel1279> RandomUnsigned1279;
typedef RandomRawDoubleT<RandomKernel250> RandomRawDouble;
typedef RandomRawDoubleT<RandomKernel1279> RandomRawDouble1279;
typedef RandomRawUnsignedT<RandomKernel250> RandomRawUnsigned;
typedef RandomRawUnsignedT<RandomKernel1279> RandomRawUnsigned1279;
typedef RandomNormalT<RandomKernel250> RandomNormal;
typedef RandomNormalT<RandomKernel1279> RandomNormal1279;
typedef RandomNumberGeneratorT<RandomKernel250> RandomNumberGenerator;
typedef RandomNumberGeneratorT<RandomKernel1279> RandomNumberGenerator1279;
typedef RandomNumberGenerator RNG;
typedef RandomNumberGenerator1279 RNG1279;
typedef RandomNormCorrPairsT<RandomKernel250> RandomNormCorrPairs;
typedef RandomNormCorrPairsT<RandomKernel1279> RandomNormCorrPairs1279;
typedef RandomNormCorrTuplesT<RandomKernel250> RandomNormCorrTuples;
typedef RandomNormCorrTuplesT<RandomKernel1279> RandomNormCorrTuples1279;

/*typedef RandomRawUnsignedT<RandomKernelOld> RandomRawUnsignedOld; */
#endif


text:
var ModelTranslation = (function( $ ) {
    'use strict';

    $('document').ready(init);

    var $buttons;
    var $menu;
    var translated_items = {};
    var now_lang = 'de';
    var $doc = $(document);

    function init() {
        $menu = $('#page_form_lang_tabs.languagetabs_mixin');
        $buttons = $('input', $menu);
        guess_language();
        get_translated_items();
        $buttons.bind({ click: change_language });
        // official django custom event!
        $doc.on('formset:added', get_translated_items);
    };

    function add_class($items, css_class) {
        // if we dont do this, we cannot target like [class$=_lang], thus using [class*=_de], target main_description_en, when selecting de ...
        for(var i=0; i<$items.length; i++ ) {
            var $item = $($items[i]);
            $item.attr('class', css_class + ' ' + $item.attr('class'));
        }
    };

    function change_language(e) {
        e.preventDefault();
        var $button = $(this);
        var lang = $button.data('language');
        $buttons.removeClass('selected');
        $button.addClass('selected');
        add_class(translated_items[now_lang], 'pseudo-hidden');
        translated_items[lang].removeClass('pseudo-hidden');
        now_lang = lang;
    };

    function guess_language() {
        var cms_path = getQueryVariable('cms_path');
        if (cms_path) {
            // get pre selected language from cms path!
            // assume its /lang_code/whatever-slug/xy/
            var cms_path = decodeURIComponent(cms_path);
            var pieces = cms_path.split('/');
            if (pieces.length > 2) {
                var new_lang = pieces[1];
                var $new_selected = $buttons.filter("[data-language='" + new_lang + "']");
                if ($new_selected.length) {
                    $buttons.removeClass('selected');
                    $new_selected.addClass('selected');
                }
            }
        }
    };

    function get_translated_items() {
        for( var i = 0; i < $buttons.length; i++ ) {
            var $button = $( $buttons[i] );
            var lang = $button.data('language');
            if (translated_items[lang]) {
                translated_items[lang].removeClass('pseudo-hidden');
            }
            translated_items[lang] = $(
                // '.form-row[class*="_' + lang + '"][class*="field-"], td[class*="_' + lang + '"][class*="field-"], th:contains([' + lang + '])'
                '.form-row[class$="_' + lang + '"], td[class$="_' + lang + '"], th:contains([' + lang + '])'
            );
            if ($button.hasClass('selected') ) {
                now_lang = lang;
            } else {
                // TODO delay until ckeditor is loaded
                add_class(translated_items[lang], 'pseudo-hidden ');
            }
        }
    };

    // hate this! but this is a good solution, from
    // https://css-tricks.com/snippets/javascript/get-url-variables/
    function getQueryVariable(variable)
    {
           var query = window.location.search.substring(1);
           var vars = query.split("&");
           for (var i=0;i<vars.length;i++) {
                   var pair = vars[i].split("=");
                   if(pair[0] == variable){return pair[1];}
           }
           return(false);
    }

})( django.jQuery );


text:
package net.rk.splendid.dao.entities;

import net.rk.splendid.dto.GameState;
import net.rk.splendid.dto.PlayerState;
import net.rk.splendid.game.FactoryGenerator;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class OfyGameState {
  private OfyGameStatus gameStatus;
  private int round;
  private OfyBoard board;
  private Map<String, OfyPlayerState> playerState = new HashMap<>();

  private OfyGameState() {}

  public static GameState toDto(
      OfyGameState ofyGameState,
      OfyGameConfig ofyGameConfig,
      String playerToken) {
    List<String> playerTokensOrdered = ofyGameConfig.getPlayerTokensOrdered(playerToken);

    return new GameState(
        ofyGameState.gameStatus.name(),
        ofyGameState.round,
        getCurrentPlayerIndex(ofyGameState, ofyGameConfig.getPlayer(playerToken).getIndex()),
        OfyBoard.toDto(ofyGameState.board),
        playerTokensOrdered.stream()
            .map(ofyGameState.playerState::get)
            .map(OfyPlayerState::toDto)
            .toArray(PlayerState[]::new));
  }

  private static int getCurrentPlayerIndex(OfyGameState gameState, int currentPlayerIndex) {
    int playerCount = gameState.playerState.size();
    return (playerCount + gameState.round - currentPlayerIndex) % playerCount;
  }

  public OfyBoard getBoard() {
    return board;
  }

  public OfyPlayerState getPlayerState(String playerToken) {
    if (playerState.containsKey(playerToken)) {
      return playerState.get(playerToken);
    } else {
      throw new IllegalArgumentException("No player with token " + playerToken);
    }
  }

  public OfyGameStatus getGameStatus() {
    return gameStatus;
  }

  public void setGameStatus(OfyGameStatus gameStatus) {
    this.gameStatus = gameStatus;
  }

  public void incrementRound() {
    round++;
  }

  public static OfyGameState create(
      String[] playerRefs,
      FactoryGenerator factoryGenerator) {
    OfyGameState gameState = new OfyGameState();
    gameState.gameStatus = OfyGameStatus.UNKNOWN;
    gameState.round = 0;
    gameState.board = OfyBoard.create(factoryGenerator);
    gameState.playerState =
        Arrays.stream(playerRefs)
            .collect(Collectors.toMap(Function.identity(), ref -> OfyPlayerState.create()));
    return gameState;
  }

  public int getRound() {
    return round;
  }
}


text:
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netgraph.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <net/route.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netgraph/ng_ether.h>
#include <netgraph/ng_message.h>
#include <netgraph/ng_pppoe.h>
#include <netgraph/ng_socket.h>

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <sys/fcntl.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <termios.h>
#include <sys/time.h>
#include <syslog.h>
#include <unistd.h>

#include "layer.h"
#include "defs.h"
#include "mbuf.h"
#include "log.h"
#include "timer.h"
#include "lqr.h"
#include "hdlc.h"
#include "throughput.h"
#include "fsm.h"
#include "lcp.h"
#include "ccp.h"
#include "link.h"
#include "async.h"
#include "descriptor.h"
#include "physical.h"
#include "main.h"
#include "mp.h"
#include "chat.h"
#include "auth.h"
#include "chap.h"
#include "cbcp.h"
#include "datalink.h"
#include "slcompress.h"
#include "iplist.h"
#include "ncpaddr.h"
#include "ip.h"
#include "ipcp.h"
#include "filter.h"
#ifndef NORADIUS
#include "radius.h"
#endif
#include "ipv6cp.h"
#include "ncp.h"
#include "bundle.h"
#include "id.h"
#include "iface.h"
#include "route.h"
#include "ether.h"

#define PPPOE_NODE_TYPE_LEN (sizeof NG_PPPOE_NODE_TYPE - 1) /* "PPPoE" */

struct etherdevice {
  struct device dev;			/* What struct physical knows about */
  int cs;				/* Control socket */
  int connected;			/* Are we connected yet ? */
  int timeout;				/* Seconds attempting to connect */
  char hook[sizeof TUN_NAME + 11];	/* Our socket node hook */
  u_int32_t slot;			/* ifindex << 24 | unit */
};

#define device2ether(d) \
  ((d)->type == ETHER_DEVICE ? (struct etherdevice *)d : NULL)

unsigned
ether_DeviceSize(void)
{
  return sizeof(struct etherdevice);
}

static ssize_t
ether_Write(struct physical *p, const void *v, size_t n)
{
  struct etherdevice *dev = device2ether(p->handler);

  return NgSendData(p->fd, dev->hook, v, n) == -1 ? -1 : (ssize_t)n;
}

static ssize_t
ether_Read(struct physical *p, void *v, size_t n)
{
  char hook[sizeof TUN_NAME + 11];

  return NgRecvData(p->fd, v, n, hook);
}

static int
ether_RemoveFromSet(struct physical *p, fd_set *r, fd_set *w, fd_set *e)
{
  struct etherdevice *dev = device2ether(p->handler);
  int result;

  if (r && dev->cs >= 0 && FD_ISSET(dev->cs, r)) {
    FD_CLR(dev->cs, r);
    log_Printf(LogTIMER, "%s: fdunset(ctrl) %d\n", p->link.name, dev->cs);
    result = 1;
  } else
    result = 0;

  /* Careful... physical_RemoveFromSet() called us ! */

  p->handler->removefromset = NULL;
  result += physical_RemoveFromSet(p, r, w, e);
  p->handler->removefromset = ether_RemoveFromSet;

  return result;
}

static void
ether_Free(struct physical *p)
{
  struct etherdevice *dev = device2ether(p->handler);

  physical_SetDescriptor(p);
  if (dev->cs != -1)
    close(dev->cs);
  free(dev);
}

static const char *
ether_OpenInfo(struct physical *p)
{
  struct etherdevice *dev = device2ether(p->handler);

  switch (dev->connected) {
    case CARRIER_PENDING:
      return "negotiating";
    case CARRIER_OK:
      return "established";
  }

  return "disconnected";
}

static int
ether_Slot(struct physical *p)
{
  struct etherdevice *dev = device2ether(p->handler);

  return dev->slot;
}

static void
ether_device2iov(struct device *d, struct iovec *iov, int *niov,
                 int maxiov __unused, int *auxfd, int *nauxfd)
{
  struct etherdevice *dev;
  int sz = physical_MaxDeviceSize();

  iov[*niov].iov_base = d = realloc(d, sz);
  if (d == NULL) {
    log_Printf(LogALERT, "Failed to allocate memory: %d\n", sz);
    AbortProgram(EX_OSERR);
  }
  iov[*niov].iov_len = sz;
  (*niov)++;

  dev = device2ether(d);
  if (dev->cs >= 0) {
    *auxfd = dev->cs;
    (*nauxfd)++;
  }
}

static void
ether_MessageIn(struct etherdevice *dev)
{
  char msgbuf[sizeof(struct ng_mesg) + sizeof(struct ngpppoe_sts)];
  struct ng_mesg *rep = (struct ng_mesg *)msgbuf;
  struct ngpppoe_sts *sts = (struct ngpppoe_sts *)(msgbuf + sizeof *rep);
  char *end, unknown[14], sessionid[5];
  const char *msg;
  struct timeval t;
  fd_set *r;
  u_long slot;
  int asciilen, ret;

  if (dev->cs < 0)
    return;

  if ((r = mkfdset()) == NULL) {
    log_Printf(LogERROR, "DoLoop: Cannot create fd_set\n");
    return;
  }

  while (1) {
    zerofdset(r);
    FD_SET(dev->cs, r);
    t.tv_sec = t.tv_usec = 0;
    ret = select(dev->cs + 1, r, NULL, NULL, &t);

    if (ret <= 0)
      break;

    if (NgRecvMsg(dev->cs, rep, sizeof msgbuf, NULL) <= 0)
      break;

    if (rep->header.version != NG_VERSION) {
      log_Printf(LogWARN, "%ld: Unexpected netgraph version, expected %ld\n",
                 (long)rep->header.version, (long)NG_VERSION);
      break;
    }

    if (rep->header.typecookie != NGM_PPPOE_COOKIE) {
      log_Printf(LogWARN, "%ld: Unexpected netgraph cookie, expected %ld\n",
                 (long)rep->header.typecookie, (long)NGM_PPPOE_COOKIE);
      break;
    }

    asciilen = 0;
    switch (rep->header.cmd) {
      case NGM_PPPOE_SET_FLAG:	msg = "SET_FLAG";	break;
      case NGM_PPPOE_CONNECT:	msg = "CONNECT";	break;
      case NGM_PPPOE_LISTEN:	msg = "LISTEN";		break;
      case NGM_PPPOE_OFFER:	msg = "OFFER";		break;
      case NGM_PPPOE_SUCCESS:	msg = "SUCCESS";	break;
      case NGM_PPPOE_FAIL:	msg = "FAIL";		break;
      case NGM_PPPOE_CLOSE:	msg = "CLOSE";		break;
      case NGM_PPPOE_GET_STATUS:	msg = "GET_STATUS";	break;
      case NGM_PPPOE_ACNAME:
        msg = "ACNAME";
        if (setenv("ACNAME", sts->hook, 1) != 0)
          log_Printf(LogWARN, "setenv: cannot set ACNAME=%s: %m", sts->hook);
        asciilen = rep->header.arglen;
        break;
      case NGM_PPPOE_SESSIONID:
        msg = "SESSIONID";
        snprintf(sessionid, sizeof sessionid, "%04x", *(u_int16_t *)sts);
        if (setenv("SESSIONID", sessionid, 1) != 0)
          syslog(LOG_WARNING, "setenv: cannot set SESSIONID=%s: %m",
                 sessionid);
        /* Use this in preference to our interface index */
        slot = strtoul(sessionid, &end, 16);
        if (end != sessionid && *end == '\0')
            dev->slot = slot;
        break;
      default:
        snprintf(unknown, sizeof unknown, "<%d>", (int)rep->header.cmd);
        msg = unknown;
        break;
    }

    if (asciilen)
      log_Printf(LogPHASE, "Received NGM_PPPOE_%s (hook \"%.*s\")\n",
                 msg, asciilen, sts->hook);
    else
      log_Printf(LogPHASE, "Received NGM_PPPOE_%s\n", msg);

    switch (rep->header.cmd) {
      case NGM_PPPOE_SUCCESS:
        dev->connected = CARRIER_OK;
        break;
      case NGM_PPPOE_FAIL:
      case NGM_PPPOE_CLOSE:
        dev->connected = CARRIER_LOST;
        break;
    }
  }
  free(r);
}

static int
ether_AwaitCarrier(struct physical *p)
{
  struct etherdevice *dev = device2ether(p->handler);

  if (dev->connected != CARRIER_OK && !dev->timeout--)
    dev->connected = CARRIER_LOST;
  else if (dev->connected == CARRIER_PENDING)
    ether_MessageIn(dev);

  return dev->connected;
}

static const struct device baseetherdevice = {
  ETHER_DEVICE,
  "ether",
  1492,
  { CD_REQUIRED, DEF_ETHERCDDELAY },
  ether_AwaitCarrier,
  ether_RemoveFromSet,
  NULL,
  NULL,
  NULL,
  NULL,
  NULL,
  ether_Free,
  ether_Read,
  ether_Write,
  ether_device2iov,
  NULL,
  ether_OpenInfo,
  ether_Slot
};

struct device *
ether_iov2device(int type, struct physical *p, struct iovec *iov, int *niov,
                 int maxiov __unused, int *auxfd, int *nauxfd)
{
  if (type == ETHER_DEVICE) {
    struct etherdevice *dev = (struct etherdevice *)iov[(*niov)++].iov_base;

    dev = realloc(dev, sizeof *dev);	/* Reduce to the correct size */
    if (dev == NULL) {
      log_Printf(LogALERT, "Failed to allocate memory: %d\n",
                 (int)(sizeof *dev));
      AbortProgram(EX_OSERR);
    }

    if (*nauxfd) {
      dev->cs = *auxfd;
      (*nauxfd)--;
    } else
      dev->cs = -1;

    /* Refresh function pointers etc */
    memcpy(&dev->dev, &baseetherdevice, sizeof dev->dev);

    physical_SetupStack(p, dev->dev.name, PHYSICAL_FORCE_SYNCNOACF);
    return &dev->dev;
  }

  return NULL;
}

static int
ether_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
{
  struct physical *p = descriptor2physical(d);
  struct etherdevice *dev = device2ether(p->handler);
  int result;

  if (r && dev->cs >= 0) {
    FD_SET(dev->cs, r);
    log_Printf(LogTIMER, "%s(ctrl): fdset(r) %d\n", p->link.name, dev->cs);
    result = 1;
  } else
    result = 0;

  result += physical_doUpdateSet(d, r, w, e, n, 0);

  return result;
}

static int
ether_IsSet(struct fdescriptor *d, const fd_set *fdset)
{
  struct physical *p = descriptor2physical(d);
  struct etherdevice *dev = device2ether(p->handler);
  int result;

  result = dev->cs >= 0 && FD_ISSET(dev->cs, fdset);
  result += physical_IsSet(d, fdset);

  return result;
}

static void
ether_DescriptorRead(struct fdescriptor *d, struct bundle *bundle,
                     const fd_set *fdset)
{
  struct physical *p = descriptor2physical(d);
  struct etherdevice *dev = device2ether(p->handler);

  if (dev->cs >= 0 && FD_ISSET(dev->cs, fdset)) {
    ether_MessageIn(dev);
    if (dev->connected == CARRIER_LOST) {
      log_Printf(LogPHASE, "%s: Device disconnected\n", p->link.name);
      datalink_Down(p->dl, CLOSE_NORMAL);
      return;
    }
  }

  if (physical_IsSet(d, fdset))
    physical_DescriptorRead(d, bundle, fdset);
}

static struct device *
ether_Abandon(struct etherdevice *dev, struct physical *p)
{
  /* Abandon our node construction */
  close(dev->cs);
  close(p->fd);
  p->fd = -2;	/* Nobody else need try.. */
  free(dev);

  return NULL;
}

struct device *
ether_Create(struct physical *p)
{
  u_char rbuf[2048];
  struct etherdevice *dev;
  struct ng_mesg *resp;
  const struct hooklist *hlist;
  const struct nodeinfo *ninfo;
  char *path, *sessionid;
  const char *mode;
  size_t ifacelen;
  unsigned f;

  dev = NULL;
  path = NULL;
  ifacelen = 0;
  if (p->fd < 0 && !strncasecmp(p->name.full, NG_PPPOE_NODE_TYPE,
                                PPPOE_NODE_TYPE_LEN) &&
      p->name.full[PPPOE_NODE_TYPE_LEN] == ':') {
    const struct linkinfo *nlink;
    struct ngpppoe_init_data *data;
    struct ngm_mkpeer mkp;
    struct ngm_connect ngc;
    const char *iface, *provider;
    char etherid[12];
    int providerlen;
    char connectpath[sizeof dev->hook + 2];	/* .:<hook> */

    p->fd--;				/* We own the device - change fd */

    loadmodules(LOAD_VERBOSLY, "netgraph", "ng_ether", "ng_pppoe", "ng_socket",
                NULL);

    if ((dev = malloc(sizeof *dev)) == NULL)
      return NULL;

    iface = p->name.full + PPPOE_NODE_TYPE_LEN + 1;

    provider = strchr(iface, ':');
    if (provider) {
      ifacelen = provider - iface;
      provider++;
      providerlen = strlen(provider);
    } else {
      ifacelen = strlen(iface);
      provider = "";
      providerlen = 0;
    }

    /*
     * We're going to do this (where tunN is our tunnel device):
     *
     * .---------.
     * |  ether  |
     * | <iface> |                         dev->cs
     * `---------'                           |
     *  (orphan)                     p->fd   |
     *     |                           |     |
     *     |                           |     |
     * (ethernet)                      |     |
     * .---------.                  .-----------.
     * |  pppoe  |                  |  socket   |
     * | <iface> |(tunN)<---->(tunN)| <unnamed> |
     * `---------                   `-----------'
     *   (tunX)
     *     ^
     *     |
     *     `--->(tunX)
     */

    /* Create a socket node */
    if (ID0NgMkSockNode(NULL, &dev->cs, &p->fd) == -1) {
      log_Printf(LogWARN, "Cannot create netgraph socket node: %s\n",
                 strerror(errno));
      free(dev);
      p->fd = -2;
      return NULL;
    }

    /*
     * Ask for a list of hooks attached to the "ether" node.  This node should
     * magically exist as a way of hooking stuff onto an ethernet device
     */
    path = (char *)alloca(ifacelen + 2);
    sprintf(path, "%.*s:", (int)ifacelen, iface);
    if (NgSendMsg(dev->cs, path, NGM_GENERIC_COOKIE, NGM_LISTHOOKS,
                  NULL, 0) < 0) {
      log_Printf(LogWARN, "%s Cannot send a netgraph message: %s\n",
                 path, strerror(errno));
      return ether_Abandon(dev, p);
    }

    /* Get our list back */
    resp = (struct ng_mesg *)rbuf;
    if (NgRecvMsg(dev->cs, resp, sizeof rbuf, NULL) <= 0) {
      log_Printf(LogWARN, "Cannot get netgraph response: %s\n",
                 strerror(errno));
      return ether_Abandon(dev, p);
    }

    hlist = (const struct hooklist *)resp->data;
    ninfo = &hlist->nodeinfo;

    /* Make sure we've got the right type of node */
    if (strncmp(ninfo->type, NG_ETHER_NODE_TYPE,
                sizeof NG_ETHER_NODE_TYPE - 1)) {
      log_Printf(LogWARN, "%s Unexpected node type ``%s'' (wanted ``"
                 NG_ETHER_NODE_TYPE "'')\n", path, ninfo->type);
      return ether_Abandon(dev, p);
    }

    log_Printf(LogDEBUG, "List of netgraph node ``%s'' (id %x) hooks:\n",
               path, ninfo->id);

    /* look for a hook already attached.  */
    for (f = 0; f < ninfo->hooks; f++) {
      nlink = &hlist->link[f];

      log_Printf(LogDEBUG, "  Found %s -> %s\n", nlink->ourhook,
                 nlink->peerhook);

      if (!strcmp(nlink->ourhook, NG_ETHER_HOOK_ORPHAN) ||
          !strcmp(nlink->ourhook, NG_ETHER_HOOK_DIVERT)) {
        /*
         * Something is using the data coming out of this ``ether'' node.
         * If it's a PPPoE node, we use that node, otherwise we complain that
         * someone else is using the node.
         */
        if (!strcmp(nlink->nodeinfo.type, NG_PPPOE_NODE_TYPE))
          /* Use this PPPoE node ! */
          snprintf(ngc.path, sizeof ngc.path, "[%x]:", nlink->nodeinfo.id);
        else {
          log_Printf(LogWARN, "%s Node type ``%s'' is currently active\n",
                     path, nlink->nodeinfo.type);
          return ether_Abandon(dev, p);
        }
        break;
      }
    }

    if (f == ninfo->hooks) {
      /*
       * Create a new ``PPPoE'' node connected to the ``ether'' node using
       * the ``orphan'' and ``ethernet'' hooks
       */
      snprintf(mkp.type, sizeof mkp.type, "%s", NG_PPPOE_NODE_TYPE);
      snprintf(mkp.ourhook, sizeof mkp.ourhook, "%s", NG_ETHER_HOOK_ORPHAN);
      snprintf(mkp.peerhook, sizeof mkp.peerhook, "%s", NG_PPPOE_HOOK_ETHERNET);
      snprintf(etherid, sizeof etherid, "[%x]:", ninfo->id);

      log_Printf(LogDEBUG, "Creating PPPoE netgraph node %s%s -> %s\n",
                 etherid, mkp.ourhook, mkp.peerhook);

      if (NgSendMsg(dev->cs, etherid, NGM_GENERIC_COOKIE,
                    NGM_MKPEER, &mkp, sizeof mkp) < 0) {
        log_Printf(LogWARN, "%s Cannot create PPPoE netgraph node: %s\n",
                   etherid, strerror(errno));
        return ether_Abandon(dev, p);
      }

      snprintf(ngc.path, sizeof ngc.path, "%s%s", path, NG_ETHER_HOOK_ORPHAN);
    }

    snprintf(dev->hook, sizeof dev->hook, "%s%d",
             TUN_NAME, p->dl->bundle->unit);

    /*
     * Connect the PPPoE node to our socket node.
     * ngc.path has already been set up
     */
    snprintf(ngc.ourhook, sizeof ngc.ourhook, "%s", dev->hook);
    memcpy(ngc.peerhook, ngc.ourhook, sizeof ngc.peerhook);

    log_Printf(LogDEBUG, "Connecting netgraph socket .:%s -> %s:%s\n",
               ngc.ourhook, ngc.path, ngc.peerhook);
    if (NgSendMsg(dev->cs, ".:", NGM_GENERIC_COOKIE,
                  NGM_CONNECT, &ngc, sizeof ngc) < 0) {
      log_Printf(LogWARN, "Cannot connect PPPoE and socket netgraph "
                 "nodes: %s\n", strerror(errno));
      return ether_Abandon(dev, p);
    }

    /* Bring the Ethernet interface up */
    path[ifacelen] = '\0';	/* Remove the trailing ':' */
    if (!iface_SetFlags(path, IFF_UP))
      log_Printf(LogWARN, "%s: Failed to set the IFF_UP flag on %s\n",
                 p->link.name, path);

    snprintf(connectpath, sizeof connectpath, ".:%s", dev->hook);

    /* Configure node to 3Com mode if needed */
    if (p->cfg.pppoe_configured) {
      mode = p->cfg.nonstandard_pppoe ? NG_PPPOE_NONSTANDARD : NG_PPPOE_STANDARD;
      if (NgSendMsg(dev->cs, connectpath, NGM_PPPOE_COOKIE,
		NGM_PPPOE_SETMODE, mode, strlen(mode) + 1) == -1) {
        log_Printf(LogWARN, "``%s'': Cannot configure netgraph node: %s\n",
                 connectpath, strerror(errno));
        return ether_Abandon(dev, p);
      }
    }

    /* And finally, request a connection to the given provider */

    data = (struct ngpppoe_init_data *)alloca(sizeof *data + providerlen);
    snprintf(data->hook, sizeof data->hook, "%s", dev->hook);
    memcpy(data->data, provider, providerlen);
    data->data_len = providerlen;

    log_Printf(LogDEBUG, "Sending PPPOE_CONNECT to %s\n", connectpath);
    if (NgSendMsg(dev->cs, connectpath, NGM_PPPOE_COOKIE,
                  NGM_PPPOE_CONNECT, data, sizeof *data + providerlen) == -1) {
      log_Printf(LogWARN, "``%s'': Cannot start netgraph node: %s\n",
                 connectpath, strerror(errno));
      return ether_Abandon(dev, p);
    }

    /* Hook things up so that we monitor dev->cs */
    p->desc.UpdateSet = ether_UpdateSet;
    p->desc.IsSet = ether_IsSet;
    p->desc.Read = ether_DescriptorRead;

    memcpy(&dev->dev, &baseetherdevice, sizeof dev->dev);
    switch (p->cfg.cd.necessity) {
      case CD_VARIABLE:
        dev->dev.cd.delay = p->cfg.cd.delay;
        break;
      case CD_REQUIRED:
        dev->dev.cd = p->cfg.cd;
        break;
      case CD_NOTREQUIRED:
        log_Printf(LogWARN, "%s: Carrier must be set, using ``set cd %d!''\n",
                   p->link.name, dev->dev.cd.delay);
      case CD_DEFAULT:
        break;
    }

    dev->timeout = dev->dev.cd.delay;
    dev->connected = CARRIER_PENDING;
    /* This will be overridden by our session id - if provided by netgraph */
    dev->slot = GetIfIndex(path);
  } else {
    /* See if we're a netgraph socket */
    struct stat st;

    if (fstat(p->fd, &st) != -1 && (st.st_mode & S_IFSOCK)) {
      struct sockaddr_storage ssock;
      struct sockaddr *sock = (struct sockaddr *)&ssock;
      int sz;

      sz = sizeof ssock;
      if (getsockname(p->fd, sock, &sz) == -1) {
        log_Printf(LogPHASE, "%s: Link is a closed socket !\n", p->link.name);
        close(p->fd);
        p->fd = -1;
        return NULL;
      }

      if (sock->sa_family == AF_NETGRAPH) {
        /*
         * It's a netgraph node... We can't determine hook names etc, so we
         * stay pretty impartial....
         */
        log_Printf(LogPHASE, "%s: Link is a netgraph node\n", p->link.name);

        if ((dev = malloc(sizeof *dev)) == NULL) {
          log_Printf(LogWARN, "%s: Cannot allocate an ether device: %s\n",
                     p->link.name, strerror(errno));
          return NULL;
        }

        memcpy(&dev->dev, &baseetherdevice, sizeof dev->dev);
        dev->cs = -1;
        dev->timeout = 0;
        dev->connected = CARRIER_OK;
        *dev->hook = '\0';

        /*
         * If we're being envoked from pppoed(8), we may have a SESSIONID
         * set in the environment.  If so, use it as the slot
         */
        if ((sessionid = getenv("SESSIONID")) != NULL) {
          char *end;
          u_long slot;

          slot = strtoul(sessionid, &end, 16);
          dev->slot = end != sessionid && *end == '\0' ? slot : 0;
        } else
          dev->slot = 0;
      }
    }
  }

  if (dev) {
    physical_SetupStack(p, dev->dev.name, PHYSICAL_FORCE_SYNCNOACF);
    return &dev->dev;
  }

  return NULL;
}


text:
require "rails_helper"

describe UsersController do
  describe "PATCH #update_password" do
    def do_patch_update_password(update_password_params)
      patch :update_password, {
        :user => update_password_params
      }
    end

    let!(:user) { FactoryGirl.create(:user) }

    describe "user" do
      before (:each) do
        login_with(user)
      end

      it "should change the password" do
        expect{ do_patch_update_password(:current_password => user.password, :password => "newpassword", :password_confirmation => "newpassword") }.to change{user.password}.from("12345678").to("newpassword")
      end

      it "should redirect to the main page" do
        expect(do_patch_update_password(:current_password => user.password, :password => "newpassword", :password_confirmation => "newpassword")).to redirect_to root_path
      end

      it "should not change the password" do
        expect{ do_patch_update_password(:current_password => "fakepassword", :password => "newpassword", :password_confirmation => "newpassword") }.to_not change{user.password}.from("12345678")
      end

      it "should refresh the page" do
        expect(do_patch_update_password(:current_password => "fakepassword", :password => "newpassword", :password_confirmation => "newpassword")).to redirect_to edit_user_registration_path
      end
    end

    describe "guest" do
      it "should not do anything whatever parameter" do
        expect(do_patch_update_password(:current_password => "", :password => "newpassword", :password_confirmation => "newpassword")).to redirect_to new_user_session_path
        expect(do_patch_update_password(:current_password => "fakepassword", :password => "", :password_confirmation => "newpassword")).to redirect_to new_user_session_path
        expect(do_patch_update_password(:current_password => "fakepassword", :password => "newpassword", :password_confirmation => "")).to redirect_to new_user_session_path
        expect(do_patch_update_password(:current_password => "", :password => "", :password_confirmation => "newpassword")).to redirect_to new_user_session_path
        expect(do_patch_update_password(:current_password => "", :password => "newpassword", :password_confirmation => "")).to redirect_to new_user_session_path
        expect(do_patch_update_password(:current_password => "fakepassword", :password => "", :password_confirmation => "")).to redirect_to new_user_session_path
        expect(do_patch_update_password(:current_password => "", :password => "", :password_confirmation => "")).to redirect_to new_user_session_path
      end
    end
  end

  describe "PATCH #update_profile" do
    def do_patch_update_profile(update_profile_params)
      patch :update_info, {
        :user => update_profile_params
      }
    end

    let!(:user) { FactoryGirl.create(:user) }

    describe "user" do
      before (:each) do
        login_with(user)
      end

      it "should change profile information" do
        expect{ do_patch_update_profile(:name => "name", :surname => "surname", :birthday => Date.today) }.to change{user.name}.from(user.name).to("name")
        expect{ do_patch_update_profile(:name => "name", :surname => "surname", :birthday => Date.today) }.to change{user.surname}.from(user.surname).to("surname")
        expect{ do_patch_update_profile(:name => "name", :surname => "surname", :birthday => Date.today) }.to change{user.birthday}.from(user.birthday).to(Date.today)
      end

      it "should redirect to the main page" do
        expect(do_patch_update_profile(:name => "name", :surname => "surname", :birthday => Date.today)).to redirect_to root_path
      end
    end

    describe "guest" do
      it "should not do anything whatever parameter" do
        expect(do_patch_update_profile(:name => "name", :surname => "surname", :birthday => Date.today)).to redirect_to new_user_session_path
        expect(do_patch_update_profile(:name => "", :surname => "surname", :birthday => Date.today)).to redirect_to new_user_session_path
        expect(do_patch_update_profile(:name => "name", :surname => "", :birthday => Date.today)).to redirect_to new_user_session_path
        expect(do_patch_update_profile(:name => "", :surname => "", :birthday => Date.today)).to redirect_to new_user_session_path
        expect(do_patch_update_profile(:name => "name", :surname => "surname", :birthday => nil)).to redirect_to new_user_session_path
        expect(do_patch_update_profile(:name => "name", :surname => "", :birthday => nil)).to redirect_to new_user_session_path
        expect(do_patch_update_profile(:name => "", :surname => "surname", :birthday => nil)).to redirect_to new_user_session_path
        expect(do_patch_update_profile(:name => "", :surname => "", :birthday => nil)).to redirect_to new_user_session_path

      end
    end
  end

  describe "PATCH #update_email" do
    def do_patch_update_email(update_email_params)
      patch :update_email, {
        :user => update_email_params
      }
    end

    let! (:user) { FactoryGirl.create(:user) }

    describe "user" do
      before (:each) do
        login_with(user)
      end

      it "should change the email" do
        expect{ do_patch_update_email(:email => "newemail@email.it", :current_password => user.password) }.to change{user.email}.from(user.email).to("newemail@email.it")
      end

      it "should redirect to main page" do
        expect(do_patch_update_email(:email => "newemail@email.it", :current_password => user.password)).to redirect_to root_path
      end
    end

    describe "guest" do
      it "should not do anything whatever parameter" do
        expect(do_patch_update_email(:email => "newemail@email.it", :current_password => "password")).to redirect_to new_user_session_path
        expect(do_patch_update_email(:email => "newemail@email.it", :current_password => "")).to redirect_to new_user_session_path
        expect(do_patch_update_email(:email => "", :current_password => "password")).to redirect_to new_user_session_path
        expect(do_patch_update_email(:email => "", :current_password => "")).to redirect_to new_user_session_path
      end
    end
  end
end


text:
title: "leia"
fullname: "Princess Leia Organa"
mugshot: /img/authors/leia.jpg
link: http://www.starwars.com/databank/leia-organa
date: 2017-09-05T20:59:00-03:00
draft: false
---

Princess Leia Organa was one of the Rebel Alliance's greatest leaders, fearless on the battlefield and dedicated to ending the tyranny of the Empire.


text:
package org.apache.spark.sql.catalyst.expressions

import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.types._

class LiteralExpressionSuite extends SparkFunSuite with ExpressionEvalHelper {

  test("null") {
    checkEvaluation(Literal.create(null, BooleanType), null)
    checkEvaluation(Literal.create(null, ByteType), null)
    checkEvaluation(Literal.create(null, ShortType), null)
    checkEvaluation(Literal.create(null, IntegerType), null)
    checkEvaluation(Literal.create(null, LongType), null)
    checkEvaluation(Literal.create(null, FloatType), null)
    checkEvaluation(Literal.create(null, LongType), null)
    checkEvaluation(Literal.create(null, StringType), null)
    checkEvaluation(Literal.create(null, BinaryType), null)
    checkEvaluation(Literal.create(null, DecimalType.USER_DEFAULT), null)
    checkEvaluation(Literal.create(null, ArrayType(ByteType, true)), null)
    checkEvaluation(Literal.create(null, MapType(StringType, IntegerType)), null)
    checkEvaluation(Literal.create(null, StructType(Seq.empty)), null)
  }

  test("boolean literals") {
    checkEvaluation(Literal(true), true)
    checkEvaluation(Literal(false), false)
  }

  test("int literals") {
    List(0, 1, Int.MinValue, Int.MaxValue).foreach { d =>
      checkEvaluation(Literal(d), d)
      checkEvaluation(Literal(d.toLong), d.toLong)
      checkEvaluation(Literal(d.toShort), d.toShort)
      checkEvaluation(Literal(d.toByte), d.toByte)
    }
    checkEvaluation(Literal(Long.MinValue), Long.MinValue)
    checkEvaluation(Literal(Long.MaxValue), Long.MaxValue)
  }

  test("double literals") {
    List(0.0, -0.0, Double.NegativeInfinity, Double.PositiveInfinity).foreach { d =>
      checkEvaluation(Literal(d), d)
      checkEvaluation(Literal(d.toFloat), d.toFloat)
    }
    checkEvaluation(Literal(Double.MinValue), Double.MinValue)
    checkEvaluation(Literal(Double.MaxValue), Double.MaxValue)
    checkEvaluation(Literal(Float.MinValue), Float.MinValue)
    checkEvaluation(Literal(Float.MaxValue), Float.MaxValue)

  }

  test("string literals") {
    checkEvaluation(Literal(""), "")
    checkEvaluation(Literal("test"), "test")
    checkEvaluation(Literal("\0"), "\0")
  }

  test("sum two literals") {
    checkEvaluation(Add(Literal(1), Literal(1)), 2)
  }

  test("binary literals") {
    checkEvaluation(Literal.create(new Array[Byte](0), BinaryType), new Array[Byte](0))
    checkEvaluation(Literal.create(new Array[Byte](2), BinaryType), new Array[Byte](2))
  }

  test("decimal") {
    List(-0.0001, 0.0, 0.001, 1.2, 1.1111, 5).foreach { d =>
      checkEvaluation(Literal(Decimal(d)), Decimal(d))
      checkEvaluation(Literal(Decimal(d.toInt)), Decimal(d.toInt))
      checkEvaluation(Literal(Decimal(d.toLong)), Decimal(d.toLong))
      checkEvaluation(Literal(Decimal((d * 1000L).toLong, 10, 3)),
        Decimal((d * 1000L).toLong, 10, 3))
      checkEvaluation(Literal(BigDecimal(d.toString)), Decimal(d))
      checkEvaluation(Literal(new java.math.BigDecimal(d.toString)), Decimal(d))
    }
  }

  // TODO(davies): add tests for ArrayType, MapType and StructType
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.ops4j.kaiserkai</groupId>
        <artifactId>kaiserkai-reactor</artifactId>
        <version>0.1.0-SNAPSHOT</version>
    </parent>
    <artifactId>kaiserkai-web</artifactId>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>org.ops4j.kaiserkai</groupId>
            <artifactId>kaiserkai-rest-impl</artifactId>
            <version>${project.version}</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>kaiserkai-web</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>io.thorntail</groupId>
                <artifactId>thorntail-maven-plugin</artifactId>
                <version>${io.thorntail.version}</version>
                <configuration>
                    <fractions>cdi,jaxrs,ee-security,microprofile-config</fractions>
                    <hollow>true</hollow>
                    <properties>
                        <swarm.undertow.servers.default-server.http-listeners.default.max-post-size>99000000</swarm.undertow.servers.default-server.http-listeners.default.max-post-size>
                    </properties>
                </configuration>
                <executions>
                    <execution>
                        <id>package</id>
                        <goals>
                            <goal>package</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>io.fabric8</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <configuration>
                    <removeVolumes>true</removeVolumes>
                    <images>
                        <image>
                            <alias>kaiserkai</alias>
                            <name>ops4j/kaiserkai:%v</name>
                            <build>
                                <dockerFileDir>kaiserkai</dockerFileDir>
                                <assembly>
                                    <descriptorRef>artifact</descriptorRef>
                                </assembly>
                                <nocache>true</nocache>
                            </build>
                        </image>
                        <image>
                            <alias>kaiserkai-thorntail</alias>
                            <name>ops4j/kaiserkai-thorntail:%v</name>
                            <build>
                                <dockerFileDir>kaiserkai-thorntail</dockerFileDir>
                                <assembly>
                                    <inline xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2">
                                        <dependencySet>
                                            <useProjectArtifact>true</useProjectArtifact>
                                            <useTransitiveDependencies>false</useTransitiveDependencies>
                                            <outputDirectory>war</outputDirectory>
                                            <outputFileNameMapping>${artifact.artifactId}.${artifact.extension}</outputFileNameMapping>
                                        </dependencySet>
                                        <files>
                                            <file>
                                                <source>${project.build.directory}/kaiserkai-web-hollow-thorntail.jar</source>
                                                <outputDirectory>war</outputDirectory>
                                                <destName>kaiserkai-hollow-thorntail.jar</destName>
                                            </file>
                                        </files>
                                    </inline>
                                </assembly>
                                <nocache>true</nocache>
                            </build>
                        </image>
                    </images>
                </configuration>
                <executions>
                    <execution>
                        <id>build</id>
                        <goals>
                            <goal>build</goal>
                        </goals>
                        <phase>package</phase>
                    </execution>
                    <execution>
                        <id>push</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>push</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
const Readable = require('readable-stream');
const EventEmitter = require('events').EventEmitter;
const state = require('./state');
const commands = require('./command');

// base context

const Context = function(conn, loggerOptions = {}) {
  EventEmitter.call(this);

  const consoleDecorator = function(arrow, data) {
    return console.log(arrow, JSON.stringify(data));
  };
  this.log = (loggerOptions.logger) ?
    loggerOptions.logger :
    consoleDecorator;

  this.debug = loggerOptions.debug;
  this.conn = conn;
  this.stream = new Readable();
  this.stream.setEncoding('utf8');
  this.stream.wrap(this.conn);
  this.state = state.init;

  this.msg = '';
  this.variables = {};
  this.pending = null;

  const self = this;
  this.stream.on('readable', function() {
    // always keep the 'leftover' part of the message
    self.msg = self.read();
  });

  this.stream.on('error', this.emit.bind(this, 'error'));
  this.stream.on('close', this.emit.bind(this, 'close'));
};

require('util').inherits(Context, EventEmitter);

Context.prototype.read = function() {
  const buffer = this.stream.read();
  if (!buffer) return this.msg;

  this.msg += buffer;

  if (this.state === state.init) {
    // we don't have whole message
    if (this.msg.indexOf('\n\n') < 0) return this.msg;
    this.readVariables(this.msg);
  } else if (this.state === state.waiting) {
    // we don't have whole message
    if (this.msg.indexOf('\n') < 0) return this.msg;
    this.readResponse(this.msg);
  }

  return '';
};

Context.prototype.readVariables = function(msg) {
  const lines = msg.split('\n');

  lines.map(function(line) {
    const split = line.split(':');
    const name = split[0];
    const value = split[1];
    this.variables[name] = (value || '').trim();
  }, this);

  this.emit('variables', this.variables);
  this.setState(state.waiting);
};

Context.prototype.readResponse = function(msg) {
  const lines = msg.split('\n');

  lines.map(function(line) {
    this.readResponseLine(line);
  }, this);
};

Context.prototype.readResponseLine = function(line) {
  if (!line) return;

  // var parsed = /^(\d{3})(?: result=)(.*)/.exec(line);
  const parsed = /^(\d{3})(?: result=)([^(]*)(?:\((.*)\))?/.exec(line);

  if (!parsed) {
    return this.emit('hangup');
  }

  const response = {
    code: parseInt(parsed[1]),
    result: parsed[2].trim(),
  };
  if (parsed[3]) {
    response.value = parsed[3];
  }

  // our last command had a pending callback
  if (this.pending) {
    const pending = this.pending;
    this.pending = null;
    pending(null, response);
  }
  this.emit('response', response);
};

Context.prototype.setState = function(state) {
  this.state = state;
};

Context.prototype.send = function(msg, cb) {
  this.pending = cb;
  this.stream.write(msg);
};

Context.prototype.close = function() {
  this.conn.destroy();
  this.stream.end();
  return Promise.resolve();
};

Context.prototype.sendCommand = function(command) {
  if (this.debug) this.log('------->', {command: command});
  const self = this;
  return new Promise(function(resolve, reject) {
    self.send(command + '\n', function(err, result) {
      if (self.debug) self.log('<-------', {err: err, result: result});
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
};

Context.prototype.onEvent = function(event) {
  const self = this;
  return new Promise(function(resolve) {
    self.on(event, function(data) {
      resolve(data);
    });
  });
};

// additional agi commands

commands.forEach(function(command) {
  let str = '';
  Context.prototype[command.name] = function(...args) {
    if (command.params > 0) {
      // const args = [].slice.call(arguments, 0, command.params);
      str = command.command + ' ' +
        prepareArgs(args, command.paramRules, command.params).join(' ');
    } else {
      str = command.command;
    }
    return this.sendCommand(str);
  };
});

const prepareArgs = function(args, argsRules, count) {
  if (!argsRules || !count) {
    return args;
  }

  return (new Array(count)).fill(null)
      .map(function(arg, i) {
        arg = args[i] !== undefined && args[i] !== null ?
            args[i] :
            argsRules[i] && argsRules[i].default || '';
        const prepare = argsRules[i] && argsRules[i].prepare ||
          function(x) {
            return x;
          };

        return prepare(String(arg));
      });
};

// sugar commands

Context.prototype.dial = function(target, timeout, params) {
  return this.exec('Dial', target + ',' + timeout + ',' + params);
};

module.exports = Context;


text:
"use strict";

// converts the given hours to seconds
const hoursToSeconds = h => Math.round(h * 3600);

module.exports = hoursToSeconds;