text:
<?php

namespace HedgeBot\Plugins\BlackJack;

use HedgeBot\Core\HedgeBot;
use HedgeBot\Core\Plugins\Plugin as PluginBase;
use HedgeBot\Core\Traits\PropertyConfigMapping;
use HedgeBot\Core\API\IRC;
use HedgeBot\Core\API\Plugin;
use HedgeBot\Core\Events\CommandEvent;

/**
 * Class BlackJack
 * @package HedgeBot\Plugins\BlackJack
 */
class BlackJack extends PluginBase
{
    private $games = []; // Games, by channel
    private $currency; // Reference to the Currency plugin

    // Plugin configuration variables by channel
    private $deckCount = [];
    private $messages = [];
    private $houseName = [];
    private $blackjackMultiplicator = [];
    private $winMultiplicator = [];
    private $joinTimeout = [];

    // Plugin global configuration variables
    private $globalDeckCount;
    private $globalMessages;
    private $globalHouseName;
    private $globalBlackjackMultiplicator;
    private $globalWinMultiplicator;
    private $globalJoinTimeout;

    // Cards colors Unicode characters
    const CARDS_COLORS = [
        "\xE2\x99\xA0", // Spades
        "\xE2\x99\xA3", // Clubs
        "\xE2\x99\xA5", // Hearts
        "\xE2\x99\xA6"  // Diamonds
    ];

    // Cards values. A function will get each card numerary value from its name.
    const CARDS_VALUES = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];

    // Default parameters values
    const DEFAULT_DECK_COUNT = 6; // 6 decks is the default count for european casinos
    const DEFAULT_HOUSE_NAME = "the House";
    const DEFAULT_BLACKJACK_MULTIPLICATOR = 1.5;
    const DEFAULT_WIN_MULTIPLICATOR = 1;
    const DEFAULT_JOIN_TIMEOUT = 60;
    const DEFAULT_MESSAGES = [
        "init" => "A BlackJack game has been started ! Type !join <bet> to join the game !",
        "joinTimeout" => "The game will start in @timeout seconds or when a player types !start !",
        "joinStart" => "The game will start when a player types !start !",
        "gameReset" => "No player joined, the game is stopped. Try again later !",
        "gameInProgress" => "You can't do that, there's already a game in progress.",
        "noGame" => "There is no game currently in progress.",
        "alreadyInGame" => "You are already in the game.",
        "noPlayer" => "There is no player in the game.",
        "missingBet" => "You must enter a bet to join.",
        "notEnoughMoney" => "You don't have enough to bet this amount.",
        "hand" => "Hand for @player: @hand",
        "gameStarted" => "The game is started !",
        "playInstructions" => "To draw a card, type !draw. To stay with your hand, type !stay.",
        "notPlaying" => "You can't do that, you are not playing.",
        "playerBlackjack" => "Congratulations, @player ! You got a blackjack !",
        "playerLost" => "Sorry, @player, but you lost.",
        "houseTurn" => "Every player's turn is finished, now it's time for the house to play !",
        "finalHand" => "Final hand for @player: @hand",
        "houseLost" => "@houseName has lost.",
        "houseBlackjack" => "@houseName has a Blackjack !",
        "winnersList" => "Winners: @players",
        "blackjackList" => "Blackjacks: @players",
        "tiesList" => "Ties: @players",
        "noWinner" => "Nobody has won, bad luck !"
    ];

    //Traits
    use PropertyConfigMapping;

    /**
     * @return bool|void
     */
    public function init()
    {
        $this->currency = Plugin::get('Currency');
        $this->reloadConfig();

        $pluginManager = Plugin::getManager();
        $pluginManager->addRoutine($this, 'RoutineJoinTimeout');
    }

    /**
     *
     */
    public function RoutineJoinTimeout()
    {
        $time = time();
        foreach ($this->games as $channel => $game) {
            if ($game->getState() == Game::STATE_JOIN) {
                $joinTimeout = $this->getConfigParameter($channel, 'joinTimeout');
                if ($time - $game->getIdleTime() >= $joinTimeout) {
                    // If there is players, trigger a start command, else, reset the game
                    if (count($game->getPlayers()) > 0) {
                        $this->CommandStart(array('channel' => $channel), array());
                    } else {
                        $game->reset();
                        IRC::message($channel, $this->getConfigParameter($channel, 'messages.gameReset'));
                    }
                }
            }
        }
    }

    /**
     * Initializes a blackjack game. Basically, one game per channel at a time, and a game can be
     * reused after it has been finished, with the deck not being reinitialized.
     *
     * @param CommandEvent $ev
     * @return bool
     */
    public function CommandBlackJack(CommandEvent $ev)
    {
        // Create a game if it doesn't exist
        if (empty($this->games[$ev->channel])) {
            $this->games[$ev->channel] = new Game($ev->channel, $this);
        }

        $messages = $this->getConfigParameter($ev->channel, 'messages');
        $game = $this->games[$ev->channel];

        $initialized = $game->init(); // Initialize that s**t

        // Check if the game isn't already started
        if (!$initialized) {
            return IRC::reply($ev, $this->getConfigParameter($ev->channel, 'messages.gameInProgress'));
        }

        IRC::message($ev->channel, $this->getConfigParameter($ev->channel, 'messages.init'));

        // Show join timeout if necessary
        $joinTimeout = $this->getConfigParameter($ev->channel, 'joinTimeout');
        $startMessage = 'messages.joinStart';
        if ($joinTimeout > 0) {
            $startMessage = 'messages.joinTimeout';
        }

        $message = str_replace('@timeout', $joinTimeout, $this->getConfigParameter($ev->channel, $startMessage));
        IRC::message($ev->channel, $message);

        return true;
    }

    /**
     * Joins a game.
     * The player has to specify a bet for him to play.
     *
     * @param CommandEvent $ev
     * @return mixed
     */
    public function CommandJoin(CommandEvent $ev)
    {
        // Check the parameters are there
        if (!isset($ev->arguments[0]) || !is_numeric($ev->arguments[0])) {
            return IRC::reply($ev, $this->getConfigParameter($ev->channel, 'messages.missingBet'));
        }

        // Get the bet amount and the account balance for the player
        $bet = intval($ev->arguments[0]);
        $balance = $this->currency->getBalance($ev->channel, $ev->nick);

        // Check all there is to check on the game and the player.
        $canJoin = false;
        $errorMsg = null;
        if (empty($this->games[$ev->channel]) || $this->games[$ev->channel]->getState() == Game::STATE_IDLE) {
            $errorMsg = 'messages.noGame';
        } elseif ($this->games[$ev->channel]->getState() == Game::STATE_PLAY) {
            $errorMsg = 'messages.gameInProgress';
        } elseif ($balance < $bet) {
            $errorMsg = 'messages.notEnoughMoney';
        } else {
            $canJoin = true;
        }

        // If the player can't join the game, show the error and return.
        if (!$canJoin) {
            return IRC::reply($ev, $this->getConfigParameter($ev->channel, $errorMsg));
        }

        // Join the game and handle the errors.
        $result = $this->games[$ev->channel]->joinGame($ev->nick, $bet);

        if (!$result) {
            return IRC::reply($ev, $this->getConfigParameter($ev->channel, 'messages.alreadyInGame'));
        }

        // Remove the bet from the account of the player
        $this->currency->takeAmount($ev->channel, $ev->nick, $bet);
    }

    /**
     * Starts the game.
     * There has to be at least one player in the game to start it.
     *
     * @param CommandEvent $ev
     * @return mixed
     */
    public function CommandStart(CommandEvent $ev)
    {
        $channel = $ev->channel;

        // Checking that the game exists
        if (empty($this->games[$channel]) || $this->games[$channel]->getState() == Game::STATE_IDLE) {
            return IRC::message($channel, $this->getConfigParameter($channel, 'messages.noGame'));
        }

        // Checking that the game isn't already playing
        if ($this->games[$channel]->getState() == Game::STATE_PLAY) {
            return IRC::message($channel, $this->getConfigParameter($channel, 'messages.gameInProgress'));
        }

        // The game cannot start if there is no player entered.
        if (count($this->games[$channel]->getPlayers()) == 0) {
            return IRC::message($channel, $this->getConfigParameter($channel, 'messages.noPlayer'));
        }

        IRC::message($channel, $this->getConfigParameter($channel, 'messages.gameStarted'));

        $game = $this->games[$channel];
        $result = $game->startGame();
        $this->showHands($channel);

        $blackjacks = [];
        foreach ($game->getPlayers() as $player) {
            $player = $game->getPlayer($player);
            if ($player->status == Game::PLAYER_BLACKJACK) {
                $blackjacks[] = $player;
            }
        }

        // Handling players who have blackjacks
        if (!empty($blackjacks)) {
            // Preparing message
            $message = $this->getConfigParameter($channel, 'messages.playerBlackjack');

            // Giving the players who have blackjack its earnings and telling that they won
            foreach ($blackjacks as $player) {
                IRC::message($channel, str_replace('@player', $player->name, $message));
            }
        }

        // Show the instructions only if there is still players in the game
        if (!empty($game->getPlayers(true))) {
            IRC::message($channel, $this->getConfigParameter($channel, 'messages.playInstructions'));
        }
    }

    /**
     * Draws a card
     *
     * @param CommandEvent $ev
     * @return mixed
     */
    public function CommandDraw(CommandEvent $ev)
    {
        // Checking that there is a game
        if (empty($this->games[$ev->channel]) || $this->games[$ev->channel]->getState() != Game::STATE_PLAY) {
            return IRC::reply($ev, $this->getConfigParameter($ev->channel, 'messages.noGame'));
        }

        // Trying to draw
        $return = $this->games[$ev->channel]->draw($ev->nick);
        if (!$return) {
            return IRC::reply($ev, $this->getConfigParameter($ev->channel, 'messages.notPlaying'));
        }

        $this->showHand($ev->channel, $ev->nick);
        if ($this->games[$ev->channel]->getPlayer($ev->nick)->status == Game::PLAYER_LOST) {
            IRC::reply(
                $ev,
                str_replace('@player', $ev->nick, $this->getConfigParameter($ev->channel, 'messages.playerLost'))
            );
            $this->finishGameIfNecessary($ev->channel);
        }
    }

    /**
     * Ends a player's turn
     *
     * @param CommandEvent $ev
     * @return mixed
     */
    public function CommandStay(CommandEvent $ev)
    {
        // Checking that there is a game
        if (empty($this->games[$ev->channel]) || $this->games[$ev->channel]->getState() != Game::STATE_PLAY) {
            return IRC::reply($ev, $this->getConfigParameter($ev->channel, 'messages.noGame'));
        }

        // Trying to draw
        $return = $this->games[$ev->channel]->stay($ev->nick);
        if (!$return) {
            return IRC::reply($ev, $this->getConfigParameter($ev->channel, 'messages.notPlaying'));
        }

        $this->finishGameIfNecessary($ev->channel);
    }

    /**
     * Event on configuration update detection. Reloads the configuration.
     */
    public function CoreEventConfigUpdate()
    {
        $this->config = HedgeBot::getInstance()->config->get('plugin.Currency');
        $this->reloadConfig();
    }

    /**
     * Shows the hands of every player, with the house hand.
     *
     * @param string $channel The channel from which display the hands.
     * @return bool True if success, false otherwise (channel hasn't got a game or game isn't playing).
     */
    private function showHands($channel)
    {
        if (empty($this->games[$channel]) || $this->games[$channel]->getState() != Game::STATE_PLAY) {
            return false;
        }

        $players = $this->games[$channel]->getPlayers();

        foreach ($players as $player) {
            $this->showHand($channel, $player);
        }

        $this->showHouseHand($channel);

        return true;
    }

    /**
     *  Shows the hand of one player.
     *
     * @param string $channel The channel of the game
     * @param object $player The player's hand
     */
    private function showHand($channel, $player)
    {
        $handMessage = $this->getConfigParameter($channel, 'messages.hand');
        $playerObject = $this->games[$channel]->getPlayer($player, true);
        $hand = $playerObject->hand;
        $playerHandMessage = str_replace('@player', $player, $handMessage);
        $playerHandMessage = str_replace('@hand', join('  ', $hand), $playerHandMessage);
        IRC::message($channel, $playerHandMessage . ' (' . $playerObject->handValue . ')');
    }

    /**
     * Shows only the house hand.
     *
     * @param $channel
     * @param bool $hidden Hides the second card or not. Defaults to true
     * @param string $messageName
     */
    private function showHouseHand($channel, $hidden = true, $messageName = 'messages.hand')
    {
        $handMessage = $this->getConfigParameter($channel, $messageName);
        $house = $this->games[$channel]->getHouse(true);
        $houseHand = $house->hand;
        $handSuffix = " (" . $house->handValue . ")";

        if ($hidden) {
            $houseHand[1] = "??";
            $handSuffix = "";
        }

        $houseHandMessage = str_replace('@player', $this->getConfigParameter($channel, "houseName"), $handMessage);
        $houseHandMessage = str_replace('@hand', join('  ', $houseHand) . $handSuffix, $houseHandMessage);
        IRC::message($channel, $houseHandMessage);
    }

    /**
     * Finishes the game if everybody is staying or have lost.
     *
     * @param string $channel The channel on which to do that
     * @return bool
     */
    private function finishGameIfNecessary($channel)
    {
        if (empty($this->games[$channel]) || $this->games[$channel]->getState() != Game::STATE_PLAY) {
            return false;
        }

        // The game is still on when there is still active players
        if (count($this->games[$channel]->getPlayers(true)) > 0) {
            return true;
        }

        IRC::message($channel, $this->getConfigParameter($channel, 'messages.houseTurn'));

        // Finish the game
        $this->games[$channel]->finishGame();
        $this->showHouseHand($channel, false, 'messages.finalHand');

        // Setting all variables
        $house = $this->games[$channel]->getHouse(true);
        $bjRate = $this->getConfigParameter($channel, 'blackjackMultiplicator');
        $winners = [];
        $losers = [];
        $ties = [];
        $blackjacks = [];

        // Giving final scores and paying out
        foreach ($this->games[$channel]->getPlayers() as $player) {
            $player = $this->games[$channel]->getPlayer($player, true);
            switch ($player->status) {
                case Game::PLAYER_STAY:
                    if ($house->status == Game::PLAYER_LOST) {
                        $winners[] = $player;
                    } elseif ($house->status == Game::PLAYER_BLACKJACK) {
                        $losers[] = $player;
                    } else { // House is on stay
                        if ($house->handValue > $player->handValue) {
                            $losers[] = $player;
                        } elseif ($house->handValue < $player->handValue) {
                            $winners[] = $player;
                        } else {
                            $ties[] = $player;
                        }
                    }
                    break;
                case Game::PLAYER_LOST:
                    $losers[] = $player;
                    break;
                case Game::PLAYER_BLACKJACK:
                    if ($house->status == Game::PLAYER_BLACKJACK) {
                        $ties[] = $player;
                    } else {
                        $blackjacks[] = $player;
                    }
                    break;
            }
        }

        // Showing status of house + all the players
        $messageKey = null;
        if ($house->status == Game::PLAYER_LOST) {
            $messageKey = 'messages.houseLost';
        } elseif ($house->status == Game::PLAYER_BLACKJACK) {
            $messageKey = 'messages.houseBlackjack';
        }

        if (!empty($messageKey)) {
            $message = $this->getConfigParameter($channel, $messageKey);
            $houseName = $this->getConfigParameter($channel, 'houseName');
            $message = str_replace('@houseName', $this->getConfigParameter($channel, "houseName"), $message);
            IRC::message($channel, $message);
        }

        // Show players who won and give them their prize
        if (!empty($winners)) {
            $message = $this->getConfigParameter($channel, 'messages.winnersList');
            $winMultiplicator = $this->getConfigParameter($channel, 'winMultiplicator');

            $message = str_replace(
                '@players',
                join(', ', array_map(__CLASS__ . '::getPlayerName', $winners)),
                $message
            );
            IRC::message($channel, $message);

            foreach ($winners as $player) {
                $this->currency->giveAmount($channel, $player->name, $player->bet * (1 + $winMultiplicator));
            }
        }

        // Show players who got a blackjack and give them their prize
        if (!empty($blackjacks)) {
            $message = $this->getConfigParameter($channel, 'messages.blackjackList');
            $blackjackMultiplicator = $this->getConfigParameter($channel, 'blackjackMultiplicator');

            $messages = str_replace(
                '@players',
                join(', ', array_map(__CLASS__ . '::getPlayerName', $blackjacks)),
                $message
            );
            IRC::message($channel, $message);

            foreach ($blackjacks as $player) {
                $this->currency->giveAmount($channel, $player->name, $player->bet * (1 + $blackjackMultiplicator));
            }
        }

        // Show ties and give them their bet back
        if (!empty($ties)) {
            $message = $this->getConfigParameter($channel, 'messages.tiesList');

            $messages = str_replace('@players', join(', ', array_map(__CLASS__ . '::getPlayerName', $ties)), $message);
            IRC::message($channel, $message);

            foreach ($ties as $player) {
                $this->currency->giveAmount($channel, $player->name, $player->bet);
            }
        }

        // If there are no winners, show it
        if (empty($blackjacks) && empty($winners) && empty($ties)) {
            IRC::message($channel, $this->getConfigParameter($channel, 'messages.noWinner'));
        }
    }

    private function reloadConfig()
    {
        $parameters = [
            "deckCount",
            "houseName",
            "messages",
            "blackjackMultiplicator",
            "winMultiplicator",
            "joinTimeout"
        ];

        // Setting default values for scalars
        $this->globalDeckCount = self::DEFAULT_DECK_COUNT;
        $this->globalHouseName = self::DEFAULT_HOUSE_NAME;
        $this->globalMessages = self::DEFAULT_MESSAGES;
        $this->globalWinMultiplicator = self::DEFAULT_WIN_MULTIPLICATOR;
        $this->globalBlackjackMultiplicator = self::DEFAULT_BLACKJACK_MULTIPLICATOR;
        $this->globalJoinTimeout = self::DEFAULT_JOIN_TIMEOUT;

        $this->mapConfig($this->config, $parameters);
    }

    /**
     * @param $player
     * @return mixed
     */
    private static function getPlayerName($player)
    {
        return $player->name;
    }
}


text:
'''
VKeyboard
=========

.. image:: images/vkeyboard.jpg
    :align: right

.. versionadded:: 1.0.8

VKeyboard is an onscreen keyboard for Kivy. Its operation is intended to be
transparent to the user. Using the widget directly is NOT recommended. Read the
section `Request keyboard`_ first.

Modes
-----

This virtual keyboard has a docked and free mode:

* docked mode (:attr:`VKeyboard.docked` = True)
  Generally used when only one person is using the computer, like a tablet or
  personal computer etc.
* free mode: (:attr:`VKeyboard.docked` = False)
  Mostly for multitouch surfaces. This mode allows multiple virtual
  keyboards to be used on the screen.

If the docked mode changes, you need to manually call
:meth:`VKeyboard.setup_mode` otherwise the change will have no impact.
During that call, the VKeyboard, implemented on top of a
:class:`~kivy.uix.scatter.Scatter`, will change the
behavior of the scatter and position the keyboard near the target (if target
and docked mode is set).

Layouts
-------

The virtual keyboard is able to load a custom layout. If you create a new
layout and put the JSON in :file:`<kivy_data_dir>/keyboards/<layoutid>.json`,
you can load it by setting :attr:`VKeyboard.layout` to your layoutid.

The JSON must be structured like this::

    {
        "title": "Title of your layout",
        "description": "Description of your layout",
        "cols": 15,
        "rows": 5,

        ...
    }

Then, you need to describe the keys in each row, for either a "normal",
"shift" or a "special" (added in version 1.9.0) mode. Keys for this row
data must be named `normal_<row>`, `shift_<row>` and `special_<row>`.
Replace `row` with the row number.
Inside each row, you will describe the key. A key is a 4 element list in
the format::

    [ <text displayed on the keyboard>, <text to put when the key is pressed>,
      <text that represents the keycode>, <size of cols> ]

Here are example keys::

    # f key
    ["f", "f", "f", 1]
    # capslock
    ["\u21B9", "\t", "tab", 1.5]

Finally, complete the JSON::

    {
        ...
        "normal_1": [
            ["`", "`", "`", 1],    ["1", "1", "1", 1],    ["2", "2", "2", 1],
            ["3", "3", "3", 1],    ["4", "4", "4", 1],    ["5", "5", "5", 1],
            ["6", "6", "6", 1],    ["7", "7", "7", 1],    ["8", "8", "8", 1],
            ["9", "9", "9", 1],    ["0", "0", "0", 1],    ["+", "+", "+", 1],
            ["=", "=", "=", 1],    ["\u232b", null, "backspace", 2]
        ],

        "shift_1": [ ... ],
        "normal_2": [ ... ],
        "special_2": [ ... ],
        ...
    }

Request Keyboard
----------------

The instantiation of the virtual keyboard is controlled by the configuration.
Check `keyboard_mode` and `keyboard_layout` in the :doc:`api-kivy.config`.

If you intend to create a widget that requires a keyboard, do not use the
virtual keyboard directly, but prefer to use the best method available on
the platform. Check the :meth:`~kivy.core.window.WindowBase.request_keyboard`
method in the :doc:`api-kivy.core.window`.

If you want a specific layout when you request the keyboard, you should write
something like this (from 1.8.0, numeric.json can be in the same directory as
your main.py)::

    keyboard = Window.request_keyboard(
        self._keyboard_close, self)
    if keyboard.widget:
        vkeyboard = self._keyboard.widget
        vkeyboard.layout = 'numeric.json'

'''

__all__ = ('VKeyboard', )

from kivy import kivy_data_dir
from kivy.vector import Vector
from kivy.config import Config
from kivy.uix.scatter import Scatter
from kivy.uix.label import Label
from kivy.properties import ObjectProperty, NumericProperty, StringProperty, \
    BooleanProperty, DictProperty, OptionProperty, ListProperty
from kivy.logger import Logger
from kivy.graphics import Color, BorderImage, Canvas
from kivy.core.image import Image
from kivy.resources import resource_find
from kivy.clock import Clock

from os.path import join, splitext, basename
from os import listdir
from json import loads

default_layout_path = join(kivy_data_dir, 'keyboards')

class VKeyboard(Scatter):
    '''
    VKeyboard is an onscreen keyboard with multitouch support.
    Its layout is entirely customizable and you can switch between available
    layouts using a button in the bottom right of the widget.

    :Events:
        `on_key_down`: keycode, internal, modifiers
            Fired when the keyboard received a key down event (key press).
        `on_key_up`: keycode, internal, modifiers
            Fired when the keyboard received a key up event (key release).
    '''

    target = ObjectProperty(None, allownone=True)
    '''Target widget associated with the VKeyboard. If set, it will be used to
    send keyboard events. If the VKeyboard mode is "free", it will also be used
    to set the initial position.

    :attr:`target` is an :class:`~kivy.properties.ObjectProperty` instance and
    defaults to None.
    '''

    callback = ObjectProperty(None, allownone=True)
    '''Callback can be set to a function that will be called if the
    VKeyboard is closed by the user.

    :attr:`target` is an :class:`~kivy.properties.ObjectProperty` instance and
    defaults to None.
    '''

    layout = StringProperty(None)
    '''Layout to use for the VKeyboard. By default, it will be the
    layout set in the configuration, according to the `keyboard_layout`
    in `[kivy]` section.

    .. versionchanged:: 1.8.0
        If layout is a .json filename, it will loaded and added to the
        available_layouts.

    :attr:`layout` is a :class:`~kivy.properties.StringProperty` and defaults
    to None.
    '''

    layout_path = StringProperty(default_layout_path)
    '''Path from which layouts are read.

    :attr:`layout` is a :class:`~kivy.properties.StringProperty` and
    defaults to :file:`<kivy_data_dir>/keyboards/`
    '''

    available_layouts = DictProperty({})
    '''Dictionary of all available layouts. Keys are the layout ID, and the
    value is the JSON (translated into a Python object).

    :attr:`available_layouts` is a :class:`~kivy.properties.DictProperty` and
    defaults to {}.
    '''

    docked = BooleanProperty(False)
    '''Indicate whether the VKeyboard is docked on the screen or not. If you
    change it, you must manually call :meth:`setup_mode` otherwise it will have
    no impact. If the VKeyboard is created by the Window, the docked mode will
    be automatically set by the configuration, using the `keyboard_mode` token
    in `[kivy]` section.

    :attr:`docked` is a :class:`~kivy.properties.BooleanProperty` and defaults
    to False.
    '''

    margin_hint = ListProperty([.05, .06, .05, .06])
    '''Margin hint, used as spacing between keyboard background and keys
    content. The margin is composed of four values, between 0 and 1::

        margin_hint = [top, right, bottom, left]

    The margin hints will be multiplied by width and height, according to their
    position.

    :attr:`margin_hint` is a :class:`~kivy.properties.ListProperty` and
    defaults to [.05, .06, .05, .06]
    '''

    key_margin = ListProperty([2, 2, 2, 2])
    '''Key margin, used to create space between keys. The margin is composed of
    four values, in pixels::

        key_margin = [top, right, bottom, left]

    :attr:`key_margin` is a :class:`~kivy.properties.ListProperty` and defaults
    to [2, 2, 2, 2]
    '''

    background_color = ListProperty([1, 1, 1, 1])
    '''Background color, in the format (r, g, b, a). If a background is
    set, the color will be combined with the background texture.

    :attr:`background_color` is a :class:`~kivy.properties.ListProperty` and
    defaults to [1, 1, 1, 1].
    '''

    background = StringProperty(
        'atlas://data/images/defaulttheme/vkeyboard_background')
    '''Filename of the background image.

    :attr:`background` a :class:`~kivy.properties.StringProperty` and defaults
    to :file:`atlas://data/images/defaulttheme/vkeyboard_background`.
    '''

    background_disabled = StringProperty(
        'atlas://data/images/defaulttheme/vkeyboard_disabled_background')
    '''Filename of the background image when vkeyboard is disabled.

    .. versionadded:: 1.8.0

    :attr:`background_disabled` is a
    :class:`~kivy.properties.StringProperty` and defaults to
    :file:`atlas://data/images/defaulttheme/vkeyboard__disabled_background`.

    '''

    key_background_color = ListProperty([1, 1, 1, 1])
    '''Key background color, in the format (r, g, b, a). If a key background is
    set, the color will be combined with the key background texture.

    :attr:`key_background_color` is a :class:`~kivy.properties.ListProperty`
    and defaults to [1, 1, 1, 1].
    '''

    key_background_normal = StringProperty(
        'atlas://data/images/defaulttheme/vkeyboard_key_normal')
    '''Filename of the key background image for use when no touches are active
    on the widget.

    :attr:`key_background_normal` a :class:`~kivy.properties.StringProperty`
    and defaults to
    :file:`atlas://data/images/defaulttheme/vkeyboard_key_normal`.
    '''

    key_disabled_background_normal = StringProperty(
        'atlas://data/images/defaulttheme/vkeyboard_key_normal')
    '''Filename of the key background image for use when no touches are active
    on the widget and vkeyboard is disabled.

    ..versionadded:: 1.8.0

    :attr:`key_disabled_background_normal` a
    :class:`~kivy.properties.StringProperty` and defaults to
    :file:`atlas://data/images/defaulttheme/vkeyboard_disabled_key_normal`.

    '''

    key_background_down = StringProperty(
        'atlas://data/images/defaulttheme/vkeyboard_key_down')
    '''Filename of the key background image for use when a touch is active
    on the widget.

    :attr:`key_background_down` a :class:`~kivy.properties.StringProperty`
    and defaults to
    :file:`atlas://data/images/defaulttheme/vkeyboard_key_down`.
    '''

    background_border = ListProperty([16, 16, 16, 16])
    '''Background image border. Used for controlling the
    :attr:`~kivy.graphics.vertex_instructions.BorderImage.border` property of
    the background.

    :attr:`background_border` is a :class:`~kivy.properties.ListProperty` and
    defaults to [16, 16, 16, 16]
    '''

    key_border = ListProperty([8, 8, 8, 8])
    '''Key image border. Used for controlling the
    :attr:`~kivy.graphics.vertex_instructions.BorderImage.border` property of
    the key.

    :attr:`key_border` is a :class:`~kivy.properties.ListProperty` and
    defaults to [16, 16, 16, 16]
    '''

    # XXX internal variables
    layout_mode = OptionProperty('normal',
        options=('normal', 'shift', 'special'))
    layout_geometry = DictProperty({})
    have_capslock = BooleanProperty(False)
    have_shift = BooleanProperty(False)
    have_special = BooleanProperty(False)
    active_keys = DictProperty({})
    font_size = NumericProperty('20dp')
    font_name = StringProperty('data/fonts/DejaVuSans.ttf')
    repeat_touch = ObjectProperty(allownone=True)

    __events__ = ('on_key_down', 'on_key_up')

    def __init__(self, **kwargs):
        # XXX move to style.kv
        kwargs.setdefault('size_hint', (None, None))
        kwargs.setdefault('scale_min', .4)
        kwargs.setdefault('scale_max', 1.6)
        kwargs.setdefault('size', (700, 200))
        kwargs.setdefault('docked', False)
        self._trigger_update_layout_mode = Clock.create_trigger(
            self._update_layout_mode)
        self._trigger_load_layouts = Clock.create_trigger(
            self._load_layouts)
        self._trigger_load_layout = Clock.create_trigger(
            self._load_layout)
        self.bind(
            docked=self.setup_mode,
            have_shift=self._trigger_update_layout_mode,
            have_capslock=self._trigger_update_layout_mode,
            have_special=self._trigger_update_layout_mode,
            layout_path=self._trigger_load_layouts,
            layout=self._trigger_load_layout)
        super(VKeyboard, self).__init__(**kwargs)

        # load all the layouts found in the layout_path directory
        self._load_layouts()

        # ensure we have default layouts
        available_layouts = self.available_layouts
        if not available_layouts:
            Logger.critical('VKeyboard: unable to load default layouts')

        # load the default layout from configuration
        if self.layout is None:
            self.layout = Config.get('kivy', 'keyboard_layout')
        else:
            # ensure the current layout is found on the available layout
            self._trigger_load_layout()

        # update layout mode (shift or normal)
        self._trigger_update_layout_mode()

        # create a top layer to draw active keys on
        with self.canvas:
            self.background_key_layer = Canvas()
            self.active_keys_layer = Canvas()

    def on_disabled(self, intance, value):
        self.refresh_keys()

    def _update_layout_mode(self, *l):
        # update mode according to capslock and shift key
        mode = self.have_capslock != self.have_shift
        mode = 'shift' if mode else 'normal'
        if self.have_special:
            mode = "special"
        if mode != self.layout_mode:
            self.layout_mode = mode
            self.refresh(False)

    def _load_layout(self, *largs):
        # ensure new layouts are loaded first
        if self._trigger_load_layouts.is_triggered:
            self._load_layouts()
            self._trigger_load_layouts.cancel()

        value = self.layout
        available_layouts = self.available_layouts

        # it's a filename, try to load it directly
        if self.layout[-5:] == '.json':
            if value not in available_layouts:
                fn = resource_find(self.layout)
                self._load_layout_fn(fn, self.layout)

        if not available_layouts:
            return
        if value not in available_layouts and value != 'qwerty':
            Logger.error(
                'Vkeyboard: <%s> keyboard layout mentioned in '
                'conf file was not found, fallback on qwerty' %
                value)
            self.layout = 'qwerty'
        self.refresh(True)

    def _load_layouts(self, *largs):
        # first load available layouts from json files
        # XXX fix to be able to reload layout when path is changing
        value = self.layout_path
        for fn in listdir(value):
            self._load_layout_fn(join(value, fn),
                                 basename(splitext(fn)[0]))

    def _load_layout_fn(self, fn, name):
        available_layouts = self.available_layouts
        if fn[-5:] != '.json':
            return
        with open(fn, 'r') as fd:
            json_content = fd.read()
            layout = loads(json_content)
        available_layouts[name] = layout

    def setup_mode(self, *largs):
        '''Call this method when you want to readjust the keyboard according to
        options: :attr:`docked` or not, with attached :attr:`target` or not:

        * If :attr:`docked` is True, it will call :meth:`setup_mode_dock`
        * If :attr:`docked` is False, it will call :meth:`setup_mode_free`

        Feel free to overload these methods to create new
        positioning behavior.
        '''
        if self.docked:
            self.setup_mode_dock()
        else:
            self.setup_mode_free()

    def setup_mode_dock(self, *largs):
        '''Setup the keyboard in docked mode.

        Dock mode will reset the rotation, disable translation, rotation and
        scale. Scale and position will be automatically adjusted to attach the
        keyboard to the bottom of the screen.

        .. note::
            Don't call this method directly, use :meth:`setup_mode` instead.
        '''
        self.do_translation = False
        self.do_rotation = False
        self.do_scale = False
        self.rotation = 0
        win = self.get_parent_window()
        scale = win.width / float(self.width)
        self.scale = scale
        self.pos = 0, 0
        win.bind(on_resize=self._update_dock_mode)

    def _update_dock_mode(self, win, *largs):
        scale = win.width / float(self.width)
        self.scale = scale
        self.pos = 0, 0

    def setup_mode_free(self):
        '''Setup the keyboard in free mode.

        Free mode is designed to let the user control the position and
        orientation of the keyboard. The only real usage is for a multiuser
        environment, but you might found other ways to use it.
        If a :attr:`target` is set, it will place the vkeyboard under the
        target.

        .. note::
            Don't call this method directly, use :meth:`setup_mode` instead.
        '''
        self.do_translation = True
        self.do_rotation = True
        self.do_scale = True
        target = self.target
        if not target:
            return

        # NOTE all math will be done in window point of view
        # determine rotation of the target
        a = Vector(1, 0)
        b = Vector(target.to_window(0, 0))
        c = Vector(target.to_window(1, 0)) - b
        self.rotation = -a.angle(c)

        # determine the position of center/top of the keyboard
        dpos = Vector(self.to_window(self.width / 2., self.height))

        # determine the position of center/bottom of the target
        cpos = Vector(target.to_window(target.center_x, target.y))

        # the goal now is to map both point, calculate the diff between them
        diff = dpos - cpos

        # we still have an issue, self.pos represent the bounding box,
        # not the 0,0 coordinate of the scatter. we need to apply also
        # the diff between them (inside and outside coordinate matrix).
        # It's hard to explain, but do a scheme on a paper, write all
        # the vector i'm calculating, and you'll understand. :)
        diff2 = Vector(self.x + self.width / 2., self.y + self.height) - \
            Vector(self.to_parent(self.width / 2., self.height))
        diff -= diff2

        # now we have a good "diff", set it as a pos.
        self.pos = -diff

    def change_layout(self):
        # XXX implement popup with all available layouts
        pass

    def refresh(self, force=False):
        '''(internal) Recreate the entire widget and graphics according to the
        selected layout.
        '''
        self.clear_widgets()
        if force:
            self.refresh_keys_hint()
        self.refresh_keys()
        self.refresh_active_keys_layer()

    def refresh_active_keys_layer(self):
        self.active_keys_layer.clear()

        active_keys = self.active_keys
        layout_geometry = self.layout_geometry
        background = resource_find(self.key_background_down)
        texture = Image(background, mipmap=True).texture

        with self.active_keys_layer:
            Color(1, 1, 1)
            for line_nb, index in active_keys.values():
                pos, size = layout_geometry['LINE_%d' % line_nb][index]
                BorderImage(texture=texture, pos=pos, size=size,
                            border=self.key_border)

    def refresh_keys_hint(self):
        layout = self.available_layouts[self.layout]
        layout_cols = layout['cols']
        layout_rows = layout['rows']
        layout_geometry = self.layout_geometry
        mtop, mright, mbottom, mleft = self.margin_hint

        # get relative EFFICIENT surface of the layout without external margins
        el_hint = 1. - mleft - mright
        eh_hint = 1. - mtop - mbottom
        ex_hint = 0 + mleft
        ey_hint = 0 + mbottom

        # get relative unit surface
        uw_hint = (1. / layout_cols) * el_hint
        uh_hint = (1. / layout_rows) * eh_hint
        layout_geometry['U_HINT'] = (uw_hint, uh_hint)

        # calculate individual key RELATIVE surface and pos (without key
        # margin)
        current_y_hint = ey_hint + eh_hint
        for line_nb in range(1, layout_rows + 1):
            current_y_hint -= uh_hint
            # get line_name
            line_name = '%s_%d' % (self.layout_mode, line_nb)
            line_hint = 'LINE_HINT_%d' % line_nb
            layout_geometry[line_hint] = []
            current_x_hint = ex_hint
            # go through the list of keys (tuples of 4)
            for key in layout[line_name]:
                # calculate relative pos, size
                layout_geometry[line_hint].append([
                    (current_x_hint, current_y_hint),
                    (key[3] * uw_hint, uh_hint)])
                current_x_hint += key[3] * uw_hint

        self.layout_geometry = layout_geometry

    def refresh_keys(self):
        layout = self.available_layouts[self.layout]
        layout_rows = layout['rows']
        layout_geometry = self.layout_geometry
        w, h = self.size
        kmtop, kmright, kmbottom, kmleft = self.key_margin
        uw_hint, uh_hint = layout_geometry['U_HINT']

        for line_nb in range(1, layout_rows + 1):
            llg = layout_geometry['LINE_%d' % line_nb] = []
            llg_append = llg.append
            for key in layout_geometry['LINE_HINT_%d' % line_nb]:
                x_hint, y_hint = key[0]
                w_hint, h_hint = key[1]
                kx = x_hint * w
                ky = y_hint * h
                kw = w_hint * w
                kh = h_hint * h

                # now adjust, considering the key margin
                kx = int(kx + kmleft)
                ky = int(ky + kmbottom)
                kw = int(kw - kmleft - kmright)
                kh = int(kh - kmbottom - kmtop)

                pos = (kx, ky)
                size = (kw, kh)
                llg_append((pos, size))

        self.layout_geometry = layout_geometry
        self.draw_keys()

    def draw_keys(self):
        layout = self.available_layouts[self.layout]
        layout_rows = layout['rows']
        layout_geometry = self.layout_geometry
        layout_mode = self.layout_mode

        # draw background
        w, h = self.size

        background = resource_find(self.background_disabled
                                   if self.disabled else
                                   self.background)
        texture = Image(background, mipmap=True).texture
        self.background_key_layer.clear()
        with self.background_key_layer:
            Color(*self.background_color)
            BorderImage(texture=texture, size=self.size,
                        border=self.background_border)

        # XXX seperate drawing the keys and the fonts to avoid
        # XXX reloading the texture each time

        # first draw keys without the font
        key_normal = resource_find(self.key_background_disabled_normal
                                   if self.disabled else
                                   self.key_background_normal)
        texture = Image(key_normal, mipmap=True).texture
        with self.background_key_layer:
            for line_nb in range(1, layout_rows + 1):
                for pos, size in layout_geometry['LINE_%d' % line_nb]:
                        BorderImage(texture=texture, pos=pos, size=size,
                                    border=self.key_border)

        # then draw the text
        # calculate font_size
        font_size = int(w) / 46
        # draw
        for line_nb in range(1, layout_rows + 1):
            key_nb = 0
            for pos, size in layout_geometry['LINE_%d' % line_nb]:
                # retrieve the relative text
                text = layout[layout_mode + '_' + str(line_nb)][key_nb][0]
                l = Label(text=text, font_size=font_size, pos=pos, size=size,
                          font_name=self.font_name)
                self.add_widget(l)
                key_nb += 1

    def on_key_down(self, *largs):
        pass

    def on_key_up(self, *largs):
        pass

    def get_key_at_pos(self, x, y):
        w, h = self.size
        x_hint = x / w
        # focus on the surface without margins
        layout_geometry = self.layout_geometry
        layout = self.available_layouts[self.layout]
        layout_rows = layout['rows']
        mtop, mright, mbottom, mleft = self.margin_hint

        # get the line of the layout
        e_height = h - (mbottom + mtop) * h  # efficient height in pixels
        line_height = e_height / layout_rows  # line height in px
        y = y - mbottom * h
        line_nb = layout_rows - int(y / line_height)

        if line_nb > layout_rows:
            line_nb = layout_rows
        if line_nb < 1:
            line_nb = 1

        # get the key within the line
        key_index = ''
        current_key_index = 0
        for key in layout_geometry['LINE_HINT_%d' % line_nb]:
            if x_hint >= key[0][0] and x_hint < key[0][0] + key[1][0]:
                key_index = current_key_index
                break
            else:
                current_key_index += 1
        if key_index == '':
            return None

        # get the full character
        key = layout['%s_%d' % (self.layout_mode, line_nb)][key_index]

        return [key, (line_nb, key_index)]

    def collide_margin(self, x, y):
        '''Do a collision test, and return True if the (x, y) is inside the
        vkeyboard margin.
        '''
        mtop, mright, mbottom, mleft = self.margin_hint
        x_hint = x / self.width
        y_hint = y / self.height
        if x_hint > mleft and x_hint < 1. - mright \
                and y_hint > mbottom and y_hint < 1. - mtop:
            return False
        return True

    def process_key_on(self, touch):
        x, y = self.to_local(*touch.pos)
        key = self.get_key_at_pos(x, y)
        if not key:
            return

        key_data = key[0]
        displayed_char, internal, special_char, size = key_data
        line_nb, key_index = key[1]

        # save pressed key on the touch
        ud = touch.ud[self.uid] = {}
        ud['key'] = key

        # for caps lock or shift only:
        uid = touch.uid
        if special_char is not None:
            # Do not repeat special keys
            if special_char in ('capslock', 'shift', 'layout', 'special'):
                Clock.unschedule(self._start_repeat_key)
                self.repeat_touch = None
            if special_char == 'capslock':
                self.have_capslock = not self.have_capslock
                uid = -1
            elif special_char == 'shift':
                self.have_shift = True
            elif special_char == 'special':
                self.have_special = True
            elif special_char == 'layout':
                self.change_layout()

        # send info to the bus
        b_keycode = special_char
        b_modifiers = self._get_modifiers()
        self.dispatch('on_key_down', b_keycode, internal, b_modifiers)

        # save key as an active key for drawing
        self.active_keys[uid] = key[1]
        self.refresh_active_keys_layer()

    def process_key_up(self, touch):
        uid = touch.uid
        if self.uid not in touch.ud:
            return

        # save pressed key on the touch
        key_data, key = touch.ud[self.uid]['key']
        displayed_char, internal, special_char, size = key_data

        # send info to the bus
        b_keycode = special_char
        b_modifiers = self._get_modifiers()
        self.dispatch('on_key_up', b_keycode, internal, b_modifiers)

        if special_char == 'capslock':
            uid = -1

        if uid in self.active_keys:
            self.active_keys.pop(uid, None)
            if special_char == 'shift':
                self.have_shift = False
            elif special_char == 'special':
                self.have_special = False
            if special_char == 'capslock' and self.have_capslock:
                self.active_keys[-1] = key
            self.refresh_active_keys_layer()

    def _get_modifiers(self):
        ret = []
        if self.have_shift:
            ret.append('shift')
        if self.have_capslock:
            ret.append('capslock')
        return ret

    def _start_repeat_key(self, *kwargs):
        Clock.schedule_interval(self._repeat_key, 0.05)

    def _repeat_key(self, *kwargs):
        self.process_key_on(self.repeat_touch)

    def on_touch_down(self, touch):
        x, y = touch.pos
        if not self.collide_point(x, y):
            return
        if self.disabled:
            return True

        x, y = self.to_local(x, y)
        if not self.collide_margin(x, y):
            if self.repeat_touch is None:
                Clock.schedule_once(self._start_repeat_key, 0.5)
            self.repeat_touch = touch

            self.process_key_on(touch)
            touch.grab(self, exclusive=True)

        else:
            super(VKeyboard, self).on_touch_down(touch)
        return True

    def on_touch_up(self, touch):
        if touch.grab_current is self:
            self.process_key_up(touch)

            Clock.unschedule(self._start_repeat_key)
            if touch == self.repeat_touch:
                Clock.unschedule(self._repeat_key)
                self.repeat_touch = None

        return super(VKeyboard, self).on_touch_up(touch)

if __name__ == '__main__':
    from kivy.base import runTouchApp
    vk = VKeyboard(layout='azerty')
    runTouchApp(vk)

redpajama_set_name: RedPajamaGithub


text:
#include "helper.h"

#include <skb/skb.h>
#include <stdio.h>
#include <stdint.h>

/* allocate a single frame, mapping it into our vspace with given attributes */
void* alloc_map_frame(vregion_flags_t attr, size_t size, struct capref *retcap)
{
    struct capref frame;
    errval_t r;

    r = frame_alloc(&frame, size, NULL);
    assert(err_is_ok(r));
    void *va;
    r = vspace_map_one_frame_attr(&va, size, frame, attr,
                                  NULL, NULL);
    if (err_is_fail(r)) {
        DEBUG_ERR(r, "vspace_map_one_frame failed");
        return NULL;
    }

    if (retcap != NULL) {
        *retcap = frame;
    }

    return va;
}

/* Get APIC id for specified core */
errval_t get_apicid_from_core(coreid_t cid, uint8_t *apicid)
{
    static bool connected = false;
    errval_t err;
    unsigned int i;

    if (!connected) {
        err = skb_client_connect();
        if (err_is_fail(err)) {
            return err;
        }
        connected = true;
    }

    err = skb_execute_query("corename(%d,_,apic(ApicID)),write(ApicID).",
                            cid);
    if (err_is_fail(err)) {
        return err;
    }
    err = skb_read_output("%u.", &i);
    *apicid = i;
    return err;
}

/*****************************************************************************/
/* Bitmap based allocator */

/** Init allocator for n objects. */
bool bmallocator_init(struct bmallocator *alloc, size_t n)
{
    alloc->count = n;
    alloc->bitmap = calloc((n + BMALLOCATOR_BITS - 1) / BMALLOCATOR_BITS,
                           BMALLOCATOR_BITS / 8);
    return alloc->bitmap != NULL;
}

/** Release memory associated with allocator. */
void bmallocator_destroy(struct bmallocator *alloc)
{
    free(alloc->bitmap);
    alloc->bitmap = NULL;
}

/** Allocate object, return index in *n if successful (return true). */
bool bmallocator_alloc(struct bmallocator *alloc, size_t *n)
{
    size_t i;
    BMALLOCATOR_TYPE bit;
    size_t idx;

    // This could be improved
    for (i = 0; i < alloc->count; i++) {
        bit = 1 << (i % BMALLOCATOR_BITS);
        idx = i / BMALLOCATOR_BITS;

        if (!(alloc->bitmap[idx] & bit)) {
            alloc->bitmap[idx] |= bit;
            *n = i;
            return true;
        }
    }
    return false;
}

/** Free object n, return value indicates if it was allocated before. */
bool bmallocator_free(struct bmallocator *alloc, size_t n)
{
    bool result;
    BMALLOCATOR_TYPE bit;
    size_t idx;

    if (n >= alloc->count) {
        return false;
    }

    bit = (1 << (n % BMALLOCATOR_BITS));
    idx = n / BMALLOCATOR_BITS;

    result = alloc->bitmap[idx] & bit;
    alloc->bitmap[idx] &= ~bit;

    return result;
}


text:
<!DOCTYPE HTML>

        <title>Foodie</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

          <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0-rc5/angular-material.min.css">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

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

        <link href="https://fonts.googleapis.com/css?family=Convergence" rel="stylesheet">

        <meta name="viewport" content="width=device-width, initial-scale=1">
          <link href="https://cdn.rawgit.com/michalsnik/aos/2.1.1/dist/aos.css" rel="stylesheet">

  Foodie

 Here's how we used to talk to Alexa

 Alexa, buy me a {FoodType}

 Here's how to talk to Alexa now:

 Alexa, ask Foodie to text me the recipe for spaghetti.

 You can also say:

 Alexa, what's on my wish list?


text:
import { Component,Input, ViewChild } from '@angular/core';
import { CORE_DIRECTIVES,FORM_DIRECTIVES,ControlGroup, FormBuilder} from '@angular/common';
import { Router } from '@angular/router-deprecated';
import {VolumesLimits} from './volumes-limits';
import { SharedProgramService } from '../services/shared-program.service';
import { ProgramService } from '../services/program.service';
import {Sticky} from 'ng2-sticky-kit/ng2-sticky-kit';
import {PopupComponent} from '../../popup.component';

@Component({
  selector: 'volumes-limits',
  templateUrl: 'app/program/volumes-limits/volumes-limits.component.html',
  directives: [FORM_DIRECTIVES, CORE_DIRECTIVES,Sticky, PopupComponent],
  providers: []
})

export class VolumesLimitsComponent {
  volumesLimitsForm: ControlGroup;
  submitAttempted:boolean=false;
  @Input() volumesLimits: VolumesLimits;
  @ViewChild(PopupComponent) popup:PopupComponent;
  constructor(private sharedProgramService: SharedProgramService, private programService: ProgramService,
    private router: Router, private fb: FormBuilder) {
    this.volumesLimitsForm = this.fb.group({});
    this.volumesLimits = this.sharedProgramService.program.volumesLimits;
  }

  onClickSave() {
    this.volumesLimitsForm.markAsDirty();
    if(this.volumesLimitsForm.valid) {
      this.programService.savenew().then(program => {
          this.popup.showSuccessPopup('Program saved successfully','');
      }).catch(error => {
        let message = 'Unable to save program';
        let details:string='';
        for(let index in error.details) {
          details = details.concat(error.details[index] + '\n');
        }
        this.popup.showErrorPopup(message, details);
      });
    }
  }

  onClickNext() {
    this.submitAttempted = true;
    this.volumesLimitsForm.markAsDirty();
    if(this.volumesLimitsForm.valid) {
      this.router.navigate(['Customersupport']);
    }
   }

  onClickBack() {
    this.submitAttempted = true;
    this.volumesLimitsForm.markAsDirty();
    if(this.volumesLimitsForm.valid) {
      this.router.navigate(['Fees']);
    }
  }

  onClickClose() {
     this.router.navigate(['ProgramList']);
  }

  Tab(index:number) {
    this.submitAttempted = true;
    this.volumesLimitsForm.markAsDirty();
    if(this.volumesLimitsForm.valid) {
      switch(index) {
        case 1: this.router.navigate(['ProgramDetails']);break;
        case 2: this.router.navigate(['Productsetup']); break;
        case 3: this.router.navigate(['Fees']); break;
        case 4:this.router.navigate(['Volumesandlimits']);break;
        case 5:this.router.navigate(['Customersupport']);break;
      }
    }
  }
}


text:
from pymongo import MongoClient
import db

client = MongoClient(db.conn_string)
db = client.oscar

results = [["year","oscar","name","won","gross","gross per day","playdays","release date"]]

# find all nominees
for data in db.oscar_nominations.find():

	# loop cateogories
	for key in data:

		if key == "BEST PICTURE":

			# loop nominees
			for nominee in data[key]:

				item = [str(data["_id"]), key, nominee["name"].replace(",", ""), str(nominee["won"])]

				boxOfficeData = db.boxoffice_movies.find_one({"name": nominee["name"]})
				if boxOfficeData:

					# calculate days till the end of the year
					#approxDaysItRan = 365 - boxOfficeData["release"].timetuple().tm_yday

					lastDay = None

					# find gross at the end of the year
					if "history" in boxOfficeData:

						#for day in boxOfficeData["history"]:
						#	lastDay = day
						#
						#	if day["date"].day == 31 and day["date"].month == 12 and day["date"].year == boxOfficeData["release"].year:
						#		break
						lastDay = boxOfficeData["history"][-1]

					if lastDay:
						item.append(str(lastDay["grossToDate"]))
						item.append(str(int(lastDay["grossToDate"] / int(lastDay["dayNumber"]))))
						item.append(str(lastDay["dayNumber"]))
					else:
						item.append("")
						item.append("")
						item.append("")

					item.append(str(boxOfficeData["release"]))
				else:
					item.append("")
					item.append("")
					item.append("")
					item.append("")

				results.append(item)

for row in results:
	line = ""

	for cell in row:
		line += cell + ","

	print line


text:
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Xunit;
using System.IO;
using GME.MGA;
using Xunit.Sdk;
using CyPhy = ISIS.GME.Dsml.CyPhyML.Interfaces;

namespace DesignImporterTests
{
    public abstract class DesignImporterTestFixtureBase : IDisposable
    {
        public static String PathTest = Path.Combine(
            Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase.Substring("file:///".Length)),
            @"..\..\");

        public String AdmPath
        {
            get { return Path.GetDirectoryName(proj.ProjectConnStr.Substring(("MGA=".Length))); }
        }

        public DesignImporterTestFixtureBase()
        {
            String mgaConnectionString;
            GME.MGA.MgaUtils.ImportXMEForTest(Path.Combine(PathTest, pathXME), out mgaConnectionString);

            proj = new MgaProject();
            bool ro_mode;
            proj.Open(mgaConnectionString, out ro_mode);
            proj.EnableAutoAddOns(true);
        }

        public void Dispose()
        {
            proj.Save();
            proj.Close();
        }

        public MgaProject proj { get; private set; }

        public abstract String pathXME { get; }
    }

    public class RollingWheelFixture : DesignImporterTestFixtureBase
    {
        public override String pathXME
        {
            get { return "RollingWheel.xme"; }
        }
    }

    public class ImportWebGMEDesigns : IUseFixture<RollingWheelFixture>
    {
        [STAThread]
        public static int Main(string[] args)
        {
            int ret = Xunit.ConsoleClient.Program.Main(new string[]
            {
                Assembly.GetExecutingAssembly().CodeBase.Substring("file:///".Length),
                //"/noshadow",
            });
            Console.In.ReadLine();
            return ret;
        }

        //[Fact]
        public void TestRollingWheelWithFormula()
        {
            var admFilename = "WheelWithFormula.adm";
            avm.Design design;
            using (StreamReader streamReader = new StreamReader(Path.Combine(fixture.AdmPath, admFilename)))
                design = CyPhyDesignImporter.CyPhyDesignImporterInterpreter.DeserializeAvmDesignXml(streamReader);

            Assert.True(0 < design.RootContainer.Property.Count);

            proj.BeginTransactionInNewTerr();
            try
            {
                var importer = new CyPhyDesignImporter.AVMDesignImporter(null, proj);
                var ret = (CyPhy.DesignContainer)importer.ImportDesign(design, CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_DS);

                Xunit.Assert.Equal(3, ret.Children.PropertyCollection.Count());
            }
            finally
            {
                proj.CommitTransaction();
                if (Debugger.IsAttached)
                {
                    proj.Save(proj.ProjectConnStr + admFilename + ".mga", true);
                }
            }
        }

        private IMgaProject proj { get { return fixture.proj; } }

        private RollingWheelFixture fixture;
        public void SetFixture(RollingWheelFixture data)
        {
            fixture = data;
        }
    }

}


text:
package org.apache.jackrabbit.vault.fs.api;

/**
 * {@code ImportMode} is used to define how importing content is applied
 * to the existing content in the repository.
 *
 *

 *
"Import Mode Effects"

 *
Import Mode	Property/Node (at a specific path)

 *
In Package	In Repository Before Installation	In Repository After Installation

 *
{@link #REPLACE}	non-existing	existing	removed

 *
existing	existing	replaced

 *
existing	non-existing	created

 *
{@link #MERGE_PROPERTIES}	non-existing	existing	not touched

 *
existing	existing	not touched

 *
existing	non-existing	created

 *
{@link #UPDATE_PROPERTIES}	non-existing	existing	not touched

 *
existing	existing	replaced

 *
existing	non-existing	created

 *

 */
public enum ImportMode {

    /**
     * Normal behavior. Existing content is replaced completely by the imported
     * content, i.e. is overridden or deleted accordingly.
     */
    REPLACE,

    /**
     * Existing content is not modified, i.e. only new content is added and
     * none is deleted or modified.
     *

     * Only considered for
     *

     *
Binaries: they will never be imported if the parent node has this import mode.

     *
Authorizable nodes: only {@code rep:members} of existing authorizables is updated, no other property on those node types is added/modified.

     *
Simple files: i.e. they will never be imported in case the repo has this file already.
     *
Other docview files: It will ignore them in case the docview's root node does already exist in the repo (both full coverage and .content.xml). It skips non-existing child nodes/properties in the docview as well.

     *

     *
     * @deprecated As this behaves inconsistently for the different serialization formats, rather use {@link #MERGE_PROPERTIES}.
     */
    @Deprecated()
    MERGE,

    /**
     * Existing properties are replaced (except for {@code jcr:primaryType}), new properties and nodes are added and no existing properties or nodes are deleted.
     * Only affects authorizable nodes (not their child nodes). Other nodes are imported in mode {@link #REPLACE}.
     * @deprecated As this behaves inconsistently for the different serialization formats, rather use {@link #UPDATE_PROPERTIES}
     */
    @Deprecated()
    UPDATE,

    /**
     * Existing properties are not touched, new nodes/properties are added, no existing nodes/properties are deleted.
     * The only existing property potentially touched is the multi-value property {@code jcr:mixinType} which is extended with the values from the imported content.
     * As the primary type is never changed
     * import will skip new properties/nodes which are not allowed by the node type definition of primary + mixin types.
     * Authorizable nodes: only {@code rep:members} of existing authorizables is updated, no other property on those node types is added/modified.
     */
    MERGE_PROPERTIES,

    /**
     * Existing properties are replaced, new nodes/properties are added, no existing nodes/properties are deleted.
     * Existing multi-value properties are replaced completely and not extended except for {@code jcr:mixinType} which is extended with the values from the imported content.
     * As the primary type is never changed
     * import will skip new properties/child nodes which are not allowed by the node type definition of primary + mixin types.
     */
    UPDATE_PROPERTIES
}


text:
from .base import *

DEBUG = False

ALLOWED_HOSTS = [
    'making-a-list.com', 'www.making-a-list.com',
    'hes-making-a-list.com', 'www.hes-making-a-list.com',
    'the-north-pole.christmas', 'www.the-north-pole.christmas',
]

ADMINS = (('David Downes', 'github@theukdave.com'),)


text:
package godot

import (
	"github.com/shadowapex/godot-go/gdnative"
)

/*------------------------------------------------------------------------------
//   This code was generated by a tool.
//
//   Changes to this file may cause incorrect behavior and will be lost if
//   the code is regenerated. Any updates should be done in
//   "class.go.tmpl" so they can be included in the generated
//   code.
//----------------------------------------------------------------------------*/

// TabContainerTabAlign is an enum for TabAlign values.
type TabContainerTabAlign int

const (
	TabContainerAlignCenter TabContainerTabAlign = 1
	TabContainerAlignLeft   TabContainerTabAlign = 0
	TabContainerAlignRight  TabContainerTabAlign = 2
)

//func NewTabContainerFromPointer(ptr gdnative.Pointer) TabContainer {
func newTabContainerFromPointer(ptr gdnative.Pointer) TabContainer {
	owner := gdnative.NewObjectFromPointer(ptr)
	obj := TabContainer{}
	obj.SetBaseObject(owner)

	return obj
}

/*
Sets the active tab's [code]visible[/code] property to the value [code]true[/code]. Sets all other children's to [code]false[/code]. Ignores non-[Control] children. Individual tabs are always visible unless you use [method set_tab_disabled] and [method set_tab_title] to hide it. To hide only a tab's content, nest the content inside a child [Control], so it receives the [code]TabContainer[/code]'s visibility setting instead.
*/
type TabContainer struct {
	Control
	owner gdnative.Object
}

func (o *TabContainer) BaseClass() string {
	return "TabContainer"
}

/*
        Undocumented
	Args: [], Returns: void
*/
func (o *TabContainer) X_ChildRenamedCallback() {
	//log.Println("Calling TabContainer.X_ChildRenamedCallback()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "_child_renamed_callback")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*
        Undocumented
	Args: [{ false arg0 InputEvent}], Returns: void
*/
func (o *TabContainer) X_GuiInput(arg0 InputEventImplementer) {
	//log.Println("Calling TabContainer.X_GuiInput()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromObject(arg0.GetBaseObject())

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "_gui_input")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*
        Undocumented
	Args: [], Returns: void
*/
func (o *TabContainer) X_OnThemeChanged() {
	//log.Println("Calling TabContainer.X_OnThemeChanged()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "_on_theme_changed")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*
        Undocumented
	Args: [], Returns: void
*/
func (o *TabContainer) X_UpdateCurrentTab() {
	//log.Println("Calling TabContainer.X_UpdateCurrentTab()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "_update_current_tab")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*
        Undocumented
	Args: [], Returns: bool
*/
func (o *TabContainer) AreTabsVisible() gdnative.Bool {
	//log.Println("Calling TabContainer.AreTabsVisible()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "are_tabs_visible")

	// Call the parent method.
	// bool
	retPtr := gdnative.NewEmptyBool()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := gdnative.NewBoolFromPointer(retPtr)
	return ret
}

/*
        Undocumented
	Args: [], Returns: int
*/
func (o *TabContainer) GetCurrentTab() gdnative.Int {
	//log.Println("Calling TabContainer.GetCurrentTab()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "get_current_tab")

	// Call the parent method.
	// int
	retPtr := gdnative.NewEmptyInt()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := gdnative.NewIntFromPointer(retPtr)
	return ret
}

/*
        Returns the child [Control] node located at the active tab index.
	Args: [], Returns: Control
*/
func (o *TabContainer) GetCurrentTabControl() ControlImplementer {
	//log.Println("Calling TabContainer.GetCurrentTabControl()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "get_current_tab_control")

	// Call the parent method.
	// Control
	retPtr := gdnative.NewEmptyObject()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := newControlFromPointer(retPtr)

	// Check to see if we already have an instance of this object in our Go instance registry.
	if instance, ok := InstanceRegistry.Get(ret.GetBaseObject().ID()); ok {
		return instance.(ControlImplementer)
	}

	// Check to see what kind of class this is and create it. This is generally used with
	// GetNode().
	className := ret.GetClass()
	if className != "Control" {
		actualRet := getActualClass(className, ret.GetBaseObject())
		return actualRet.(ControlImplementer)
	}

	return &ret
}

/*
        Returns the [Popup] node instance if one has been set already with [method set_popup].
	Args: [], Returns: Popup
*/
func (o *TabContainer) GetPopup() PopupImplementer {
	//log.Println("Calling TabContainer.GetPopup()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "get_popup")

	// Call the parent method.
	// Popup
	retPtr := gdnative.NewEmptyObject()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := newPopupFromPointer(retPtr)

	// Check to see if we already have an instance of this object in our Go instance registry.
	if instance, ok := InstanceRegistry.Get(ret.GetBaseObject().ID()); ok {
		return instance.(PopupImplementer)
	}

	// Check to see what kind of class this is and create it. This is generally used with
	// GetNode().
	className := ret.GetClass()
	if className != "Popup" {
		actualRet := getActualClass(className, ret.GetBaseObject())
		return actualRet.(PopupImplementer)
	}

	return &ret
}

/*
        Returns the previously active tab index.
	Args: [], Returns: int
*/
func (o *TabContainer) GetPreviousTab() gdnative.Int {
	//log.Println("Calling TabContainer.GetPreviousTab()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "get_previous_tab")

	// Call the parent method.
	// int
	retPtr := gdnative.NewEmptyInt()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := gdnative.NewIntFromPointer(retPtr)
	return ret
}

/*
        Undocumented
	Args: [], Returns: enum.TabContainer::TabAlign
*/
func (o *TabContainer) GetTabAlign() TabContainerTabAlign {
	//log.Println("Calling TabContainer.GetTabAlign()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "get_tab_align")

	// Call the parent method.
	// enum.TabContainer::TabAlign
	retPtr := gdnative.NewEmptyInt()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := gdnative.NewIntFromPointer(retPtr)
	return TabContainerTabAlign(ret)
}

/*
        Returns the currently visible tab's [Control] node.
	Args: [{ false idx int}], Returns: Control
*/
func (o *TabContainer) GetTabControl(idx gdnative.Int) ControlImplementer {
	//log.Println("Calling TabContainer.GetTabControl()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromInt(idx)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "get_tab_control")

	// Call the parent method.
	// Control
	retPtr := gdnative.NewEmptyObject()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := newControlFromPointer(retPtr)

	// Check to see if we already have an instance of this object in our Go instance registry.
	if instance, ok := InstanceRegistry.Get(ret.GetBaseObject().ID()); ok {
		return instance.(ControlImplementer)
	}

	// Check to see what kind of class this is and create it. This is generally used with
	// GetNode().
	className := ret.GetClass()
	if className != "Control" {
		actualRet := getActualClass(className, ret.GetBaseObject())
		return actualRet.(ControlImplementer)
	}

	return &ret
}

/*
        Returns the number of tabs.
	Args: [], Returns: int
*/
func (o *TabContainer) GetTabCount() gdnative.Int {
	//log.Println("Calling TabContainer.GetTabCount()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 0, 0)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "get_tab_count")

	// Call the parent method.
	// int
	retPtr := gdnative.NewEmptyInt()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := gdnative.NewIntFromPointer(retPtr)
	return ret
}

/*
        Returns [code]true[/code] if the tab at index [code]tab_idx[/code] is disabled.
	Args: [{ false tab_idx int}], Returns: bool
*/
func (o *TabContainer) GetTabDisabled(tabIdx gdnative.Int) gdnative.Bool {
	//log.Println("Calling TabContainer.GetTabDisabled()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromInt(tabIdx)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "get_tab_disabled")

	// Call the parent method.
	// bool
	retPtr := gdnative.NewEmptyBool()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := gdnative.NewBoolFromPointer(retPtr)
	return ret
}

/*
        Returns the [Texture] for the tab at index [code]tab_idx[/code] or null if the tab has no [Texture].
	Args: [{ false tab_idx int}], Returns: Texture
*/
func (o *TabContainer) GetTabIcon(tabIdx gdnative.Int) TextureImplementer {
	//log.Println("Calling TabContainer.GetTabIcon()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromInt(tabIdx)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "get_tab_icon")

	// Call the parent method.
	// Texture
	retPtr := gdnative.NewEmptyObject()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := newTextureFromPointer(retPtr)

	// Check to see if we already have an instance of this object in our Go instance registry.
	if instance, ok := InstanceRegistry.Get(ret.GetBaseObject().ID()); ok {
		return instance.(TextureImplementer)
	}

	// Check to see what kind of class this is and create it. This is generally used with
	// GetNode().
	className := ret.GetClass()
	if className != "Texture" {
		actualRet := getActualClass(className, ret.GetBaseObject())
		return actualRet.(TextureImplementer)
	}

	return &ret
}

/*
        Returns the title of the tab at index [code]tab_idx[/code]. Tab titles default to the name of the indexed child node, but this can be overridden with [method set_tab_title].
	Args: [{ false tab_idx int}], Returns: String
*/
func (o *TabContainer) GetTabTitle(tabIdx gdnative.Int) gdnative.String {
	//log.Println("Calling TabContainer.GetTabTitle()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromInt(tabIdx)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "get_tab_title")

	// Call the parent method.
	// String
	retPtr := gdnative.NewEmptyString()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

	// If we have a return type, convert it from a pointer into its actual object.
	ret := gdnative.NewStringFromPointer(retPtr)
	return ret
}

/*
        Undocumented
	Args: [{ false tab_idx int}], Returns: void
*/
func (o *TabContainer) SetCurrentTab(tabIdx gdnative.Int) {
	//log.Println("Calling TabContainer.SetCurrentTab()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromInt(tabIdx)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "set_current_tab")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*
        If set on a [Popup] node instance, a popup menu icon appears in the top-right corner of the [code]TabContainer[/code]. Clicking it will expand the [Popup] node.
	Args: [{ false popup Object}], Returns: void
*/
func (o *TabContainer) SetPopup(popup ObjectImplementer) {
	//log.Println("Calling TabContainer.SetPopup()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromObject(popup.GetBaseObject())

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "set_popup")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*
        Undocumented
	Args: [{ false align int}], Returns: void
*/
func (o *TabContainer) SetTabAlign(align gdnative.Int) {
	//log.Println("Calling TabContainer.SetTabAlign()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromInt(align)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "set_tab_align")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*
        If [code]disabled[/code] is false, hides the tab at index [code]tab_idx[/code]. Note that its title text will remain, unless also removed with [method set_tab_title].
	Args: [{ false tab_idx int} { false disabled bool}], Returns: void
*/
func (o *TabContainer) SetTabDisabled(tabIdx gdnative.Int, disabled gdnative.Bool) {
	//log.Println("Calling TabContainer.SetTabDisabled()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 2, 2)
	ptrArguments[0] = gdnative.NewPointerFromInt(tabIdx)
	ptrArguments[1] = gdnative.NewPointerFromBool(disabled)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "set_tab_disabled")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*
        Sets an icon for the tab at index [code]tab_idx[/code].
	Args: [{ false tab_idx int} { false icon Texture}], Returns: void
*/
func (o *TabContainer) SetTabIcon(tabIdx gdnative.Int, icon TextureImplementer) {
	//log.Println("Calling TabContainer.SetTabIcon()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 2, 2)
	ptrArguments[0] = gdnative.NewPointerFromInt(tabIdx)
	ptrArguments[1] = gdnative.NewPointerFromObject(icon.GetBaseObject())

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "set_tab_icon")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*
        Sets a title for the tab at index [code]tab_idx[/code]. Tab titles default to the name of the indexed child node, but this can be overridden with [method set_tab_title].
	Args: [{ false tab_idx int} { false title String}], Returns: void
*/
func (o *TabContainer) SetTabTitle(tabIdx gdnative.Int, title gdnative.String) {
	//log.Println("Calling TabContainer.SetTabTitle()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 2, 2)
	ptrArguments[0] = gdnative.NewPointerFromInt(tabIdx)
	ptrArguments[1] = gdnative.NewPointerFromString(title)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "set_tab_title")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

/*
        Undocumented
	Args: [{ false visible bool}], Returns: void
*/
func (o *TabContainer) SetTabsVisible(visible gdnative.Bool) {
	//log.Println("Calling TabContainer.SetTabsVisible()")

	// Build out the method's arguments
	ptrArguments := make([]gdnative.Pointer, 1, 1)
	ptrArguments[0] = gdnative.NewPointerFromBool(visible)

	// Get the method bind
	methodBind := gdnative.NewMethodBind("TabContainer", "set_tabs_visible")

	// Call the parent method.
	// void
	retPtr := gdnative.NewEmptyVoid()
	gdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)

}

// TabContainerImplementer is an interface that implements the methods
// of the TabContainer class.
type TabContainerImplementer interface {
	ControlImplementer
	X_ChildRenamedCallback()
	X_OnThemeChanged()
	X_UpdateCurrentTab()
	AreTabsVisible() gdnative.Bool
	GetCurrentTab() gdnative.Int
	GetCurrentTabControl() ControlImplementer
	GetPopup() PopupImplementer
	GetPreviousTab() gdnative.Int
	GetTabControl(idx gdnative.Int) ControlImplementer
	GetTabCount() gdnative.Int
	GetTabDisabled(tabIdx gdnative.Int) gdnative.Bool
	GetTabIcon(tabIdx gdnative.Int) TextureImplementer
	GetTabTitle(tabIdx gdnative.Int) gdnative.String
	SetCurrentTab(tabIdx gdnative.Int)
	SetPopup(popup ObjectImplementer)
	SetTabAlign(align gdnative.Int)
	SetTabDisabled(tabIdx gdnative.Int, disabled gdnative.Bool)
	SetTabIcon(tabIdx gdnative.Int, icon TextureImplementer)
	SetTabTitle(tabIdx gdnative.Int, title gdnative.String)
	SetTabsVisible(visible gdnative.Bool)
}


text:
<?php
/**
 * Routes File
 *
 * PHP version 5.6
 *
 * @category Route
 * @package  SetList\Http
 * @author   Taylor Otwell <taylorotwell@gmail.com>
 * @license  http://opensource.org/licenses/MIT MIT License
 * @link     https://laravel.com/docs/5.2 Laravel Documentation
 */
/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get(
    '/', function () {
        return view('welcome');
    }
);

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/

Route::group(
    ['middleware' => ['web']], function () {
    }
);

// Authentication
Route::group(
    ['prefix' => 'api/v1/auth', 'namespace' => 'Auth'], function () {
        Route::post('authenticate', 'AuthController@authenticate');
        Route::post('register', 'AuthController@register');
    }
);

// API Endpoints
Route::group(
    ['prefix' => 'api/v1', 'middleware' => ['jwt.auth']], function () {

        // Set list resource
        Route::resource('setlist', 'SetListController', ['except' => ['create', 'edit']]);

        // Song resource
        Route::resource('song', 'SongController', ['except' => ['create', 'edit']]);

        // User resource
        Route::get('user', 'UserController@index');
        Route::patch('user', 'UserController@update');
        Route::delete('user', 'UserController@destroy');
    }
);


text:
var when = require('a').when;
var c = {};

when(c)
    .it('should set resolved on context').assertDeepEqual([c.arg, c.arg2], c.context.resolved)
    .it('should set completed on context').assertOk(c.context.completed)
    .it('should return promise').assertDeepEqual(c.promise, c.returned)


text:
def plot_logistic_regression_graph():
    import graphviz
    lr_graph = graphviz.Digraph(node_attr={'shape': 'circle', 'fixedsize': 'True'},
                                graph_attr={'rankdir': 'LR', 'splines': 'line'})
    inputs = graphviz.Digraph(node_attr={'shape': 'circle'}, name="cluster_0")
    output = graphviz.Digraph(node_attr={'shape': 'circle'}, name="cluster_2")

    for i in range(4):
        inputs.node("x[%d]" % i, labelloc="c")
    inputs.body.append('label = "inputs"')
    inputs.body.append('color = "white"')

    lr_graph.subgraph(inputs)

    output.body.append('label = "output"')
    output.body.append('color = "white"')
    output.node("y")

    lr_graph.subgraph(output)

    for i in range(4):
        lr_graph.edge("x[%d]" % i, "y", label="w[%d]" % i)
    return lr_graph

def plot_single_hidden_layer_graph():
    import graphviz
    nn_graph = graphviz.Digraph(node_attr={'shape': 'circle', 'fixedsize': 'True'},
                                graph_attr={'rankdir': 'LR', 'splines': 'line'})

    inputs = graphviz.Digraph(node_attr={'shape': 'circle'}, name="cluster_0")
    hidden = graphviz.Digraph(node_attr={'shape': 'circle'}, name="cluster_1")
    output = graphviz.Digraph(node_attr={'shape': 'circle'}, name="cluster_2")

    for i in range(4):
        inputs.node("x[%d]" % i)

    inputs.body.append('label = "inputs"')
    inputs.body.append('color = "white"')

    hidden.body.append('label = "hidden layer"')
    hidden.body.append('color = "white"')

    for i in range(3):
        hidden.node("h%d" % i, label="h[%d]" % i)

    output.node("y")
    output.body.append('label = "output"')
    output.body.append('color = "white"')

    nn_graph.subgraph(inputs)
    nn_graph.subgraph(hidden)
    nn_graph.subgraph(output)

    for i in range(4):
        for j in range(3):
            nn_graph.edge("x[%d]" % i, "h%d" % j)

    for i in range(3):
        nn_graph.edge("h%d" % i, "y")
    return nn_graph

def plot_two_hidden_layer_graph():
    import graphviz
    nn_graph = graphviz.Digraph(node_attr={'shape': 'circle', 'fixedsize': 'True'},
                                graph_attr={'rankdir': 'LR', 'splines': 'line'})

    inputs = graphviz.Digraph(node_attr={'shape': 'circle'}, name="cluster_0")
    hidden = graphviz.Digraph(node_attr={'shape': 'circle'}, name="cluster_1")
    hidden2 = graphviz.Digraph(node_attr={'shape': 'circle'}, name="cluster_2")

    output = graphviz.Digraph(node_attr={'shape': 'circle'}, name="cluster_3")

    for i in range(4):
        inputs.node("x[%d]" % i)

    inputs.body.append('label = "inputs"')
    inputs.body.append('color = "white"')

    for i in range(3):
        hidden.node("h1[%d]" % i)

    for i in range(3):
        hidden2.node("h2[%d]" % i)

    hidden.body.append('label = "hidden layer 1"')
    hidden.body.append('color = "white"')

    hidden2.body.append('label = "hidden layer 2"')
    hidden2.body.append('color = "white"')

    output.node("y")
    output.body.append('label = "output"')
    output.body.append('color = "white"')

    nn_graph.subgraph(inputs)
    nn_graph.subgraph(hidden)
    nn_graph.subgraph(hidden2)

    nn_graph.subgraph(output)

    for i in range(4):
        for j in range(3):
            nn_graph.edge("x[%d]" % i, "h1[%d]" % j, label="")

    for i in range(3):
        for j in range(3):
            nn_graph.edge("h1[%d]" % i, "h2[%d]" % j, label="")

    for i in range(3):
        nn_graph.edge("h2[%d]" % i, "y", label="")

    return nn_graph


text:
@implementation HSChooserRootView

- (BOOL)allowsVibrancy {
    return YES;
}

@end


text:
%
% Plot a motor trajectory on top of the image
%
% Input
%   I [105 x 105] image (double or binary) (large numbers are BLACK)
%   drawings: [ns x 1 cell] of strokes in motor space
%   bool_start: [logical] (default=true) show start position?
%   lw: [scalar] (default=4) line width
%
function plot_motor_on_image(I,drawing,bool_start,lw)

    if ~exist('bool_start','var')
       bool_start = true; % show start position?
    end
    if ~exist('lw','var')
       lw = 4; % line width
    end

    % conversion of coordinates
    drawing = space_motor_to_img(drawing);

    % plot image
    hold on
    plot_image_only(I);

    % plot each stroke
    ns = length(drawing);
    for i=1:ns
        stroke = drawing{i};
        color = get_color(i);
        plot_traj(stroke,color,lw);
    end

    % Plot starting locations and stroke order
    if bool_start
        for i=1:ns
            stroke = drawing{i};
            plot_start_loc(stroke(1,:),i);
        end
    end

    set(gca,'YDir','reverse','XTick',[],'YTick',[]);
    xlim([1 105]);
    ylim([1 105]);
end

function plot_traj(stk,color,lw)
    ystk = stk(:,2);
    stk(:,2) = stk(:,1);
    stk(:,1) = ystk;
    plot(stk(:,1),stk(:,2),color,'LineWidth',lw);
end

% Plot the starting location of a stroke
%
% Input
%  start: [1 x 2]
%  num: number that denotes stroke order
function plot_start_loc(start,num)
    mysize = 18;
    plot(start(2),start(1),'o','MarkerEdgeColor','k','MarkerFaceColor','w',...
        'MarkerSize',mysize);
    text(start(2),start(1),num2str(num),...
        'BackgroundColor','none','EdgeColor','none',...
        'FontSize',mysize,'FontWeight','normal','HorizontalAlignment','center');
end

% Color map for the stroke of index k
function out = get_color(k)
    scol = {'r','g','b','m','c'};
    ncol = length(scol);
    if k <=ncol
       out = scol{k};
    else
       out = scol{end};
    end
end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Adelocaryum erythraeum Brand

### Remarks
null


text:
{template '_header'}

        {ifp 'exchange.balance.creat'}
            $id));}" data-toggle="ajaxModal"> 生成兑换券
        {/if}
        返回列表

{$res['title']}
            兑换率: {$res['use']}/{$res['total']}

        搜索结果({$count})

        $id));}">未兑换 ({$dno})

        $id));}">已兑换 ({$dyet})

        $id));}">已过期 ({$dend})

                <button class="btn btn-default btn-sm" type="button" data-toggle="refresh">

                </button>
                {ifp 'exchange.balance.destory'}
                <button class="btn btn-default btn-sm" type="button" data-toggle="batch-remove"
                        data-confirm="确认要删除选中的商品吗?" data-href="{php echo webUrl('exchange/balance/destroy');}"
                        disabled="disabled">
                     删除
                </button>
                {/if}

                {php echo tpl_form_field_daterange('date',array('start'=>20161001,'end'=>20161001));}

                    <input type="text" class="input-sm form-control" name="keyword" value="" placeholder="请输入兑换码" id="keyword">

                        <input type="hidden" name="id" value="{$id}">
                    <button class="btn btn-sm btn-primary" type="submit" id="so">搜索</button>

        <input type="checkbox">
        排序
        兑换编号

        过期时间

        类型
        状态
        绑定
        操作

        {loop $list $key $value}

            <input type="checkbox" name="checkbox[]" value="{$value['id']}">
            {php echo $key+($page-1)*$psize+1;}
            $value['key'],'status'=>$value['status'],'id'=>$value['id']),1);}">{$value['serial']}

                {if $value['type']!=1}{$value['endtime']}{/if}
                {if $value['type']==1}永不过期{/if}

                {if $value['type']==0}临时{/if}
                {if $value['type']==1}永久{/if}
                {if $value['type']==2}普通{/if}
                {if $value['type']==3}号码{/if}

            {if $value['status']==0}

                      {if strtotime($value['endtime'])<time()}已过期{else}未发放{/if}
            {/if}
            {if $value['status']==1}

                      {if strtotime($value['endtime'])<time()}已过期{else}未兑换{/if}
            {/if}
            {if $value['status']==2}

                      已兑换
            {/if}

                {if !empty($value['openid']) && !empty($res['binding'])}已绑定{else}未绑定{/if}

                {if $value['type']!=3}
                $value['key'],'type'=>$value['type']));}" title="编辑"> 二维码
                {else}
                 复制
                {/if}
                $value['key']));}"> 状态
                {if $value['type']<2}
                $value['key']));}"> 下载
                {/if}
                {if $value['type'] == 2} 下载
                {/if}
                {ifp 'exchange.balance.destroy'}
                $value['id']));}" data-confirm="确认删除兑换码 {$value['key']} 吗?"> 删除
                {/if}

        {/loop}

{$pager}
{template '_footer'}


text:
package com.ruesga.rview.gerrit.model;

import com.google.gson.annotations.Since;

public enum ChangeOptions {
    LABELS, DETAILED_LABELS, CURRENT_REVISION, ALL_REVISIONS, DOWNLOAD_COMMANDS, CURRENT_COMMIT,
    ALL_COMMITS, CURRENT_FILES, ALL_FILES, DETAILED_ACCOUNTS, @Since(2.13) REVIEWER_UPDATES,
    MESSAGES, CURRENT_ACTIONS, CHANGE_ACTIONS, REVIEWED, @Since(2.16) SKIP_MERGEABLE,
    @Since(3.1) SKIP_DIFFSTAT, WEB_LINKS, CHECK, @Since(2.12) COMMIT_FOOTERS,
    @Since(2.12) PUSH_CERTIFICATES, @Since(2.15) TRACKING_IDS, @Since(3.0) NO_LIMIT("NO-LIMIT");

    public final String name;
    ChangeOptions() {
        this.name = null;
    }

    ChangeOptions(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name != null ? name : super.toString();
    }
}


text:
using System;

/// <summary>
/// TicksPerSecond
/// </summary>
public class TimeSpanTicksPerSecond
{
    #region Private Fields
    private const long c_DESIRED_TICKSPERSECOND = 10000000;
    #endregion

    #region Public Methods
    public bool RunTests()
    {
        bool retVal = true;

        TestLibrary.TestFramework.LogInformation("[Positive]");
        retVal = PosTest1() && retVal;

        return retVal;
    }

    #region Positive Test Cases
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: The value of TicksPerSecond should be 10000000");

        try
        {
            long actual = TimeSpan.TicksPerSecond;

            if (actual != c_DESIRED_TICKSPERSECOND)
            {
                TestLibrary.TestFramework.LogError("001.1", "The value of TicksPerSecond is not 10000000");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", c_DESIRED_TICKSPERSECOND = " + c_DESIRED_TICKSPERSECOND);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    #endregion
    #endregion

    public static int Main()
    {
        TimeSpanTicksPerSecond test = new TimeSpanTicksPerSecond();

        TestLibrary.TestFramework.BeginTestCase("TimeSpanTicksPerSecond");

        if (test.RunTests())
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("PASS");
            return 100;
        }
        else
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("FAIL");
            return 0;
        }
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.sumu.mobliesafe.fragment.UnLockFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/tv_app_number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="15sp"
        android:textColor="@color/black"/>

    <include
        android:id="@+id/list_view"
        layout="@layout/list_view" />
</LinearLayout>


text:
case node.platform
when "ubuntu","debian"
  package "postgresql-client"
when "fedora","suse"
  package "postgresql-devel"
when "redhat","centos"
  package "postgresql#{node.postgresql.version.split('.').join}-devel"
end