text:
(function() {
    var app = angular.module("app-i18n",
        [
            "pascalprecht.translate",
            "angularMoment"
        ]
    );

    app.run(
        function(amMoment) {
            amMoment.changeLocale("en");
        }
    );

    app.constant("APP_LOCALE",
        {
            EN_US: "en_US",
            PT_BR: "pt_BR"
        }
    );

    app.config(
        [
            "$translateProvider",
            "APP_LOCALE",
            function($translateProvider, APP_LOCALE) {
                $translateProvider.translations(APP_LOCALE.EN_US, {
                    PAGE_TITLE: 'Apt. Complex Manager',

                    MENU_SUMMARY: 'Summary',
                    MENU_STATEMENT: 'Statement',
                    MENU_BALANCE: 'Balance',
                    MENU_INCOMES: 'Incomes',
                    MENU_FEES: 'Fees',
                    MENU_BANKS: 'Banks',
                    MENU_EXPENSES: 'Expenses',
                    MENU_PERSONNEL: 'Personnel',

                    MENU_ABOUT: 'About...',

                    MENU_ENGLISH: 'English (US)',
                    MENU_PORTUGUESE: 'Portuguese (BR)',

                    SUMMARY_TITLE: "Summary",
                    SUMMARY_TITLE_INCOMES: "Incomes",
                    SUMMARY_TITLE_EXPENSES: 'Expenses',
                    SUMMARY_TITLE_APARTMENTS: 'Apartments',
                    SUMMARY_DETAIL_CONDOMINIUM_FEE: 'Fee',
                    SUMMARY_DETAIL_CONDOMINIUM_SURCHARGE: 'Surcharge',
                    SUMMARY_DETAIL_CONDOMINIUM_DISCOUNT: 'Discount',
                    SUMMARY_DETAIL_OTHERS: 'Others',
                    SUMMARY_DETAIL_PAYMENT: 'Payment',
                    SUMMARY_TOTAL_NORMAL_FEE: "Normal fee",
                    SUMMARY_TOTAL_SURCHARGE: "Surcharge",
                    SUMMARY_TOTAL_DISCOUNT: 'Discount',
                    SUMMARY_TOTAL_OTHERS: "Others",
                    SUMMARY_TOTAL_FEE: "Total cond. fee",
                    SUMMARY_TOTAL_PAYMENT: "Total payment",

                    APARTMENT_LIST_TITLE: "Apartments",

                    ABOUT_TITLE: 'Welcome...',
                    ABOUT_SUBTITLE: '... To Apartment Complex Manager',
                    ABOUT_PARAGRAPH_1: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec aliquam elit sit amet risus tempus condimentum. Nam id aliquam ligula, non tincidunt erat. Vivamus nec luctus lorem, sed elementum tortor. Cras accumsan ligula magna, sed cursus quam pellentesque tempus. Donec consequat lorem ac mauris pellentesque viverra. Suspendisse ultricies est in libero sagittis, sed lacinia mauris malesuada. Integer accumsan malesuada mattis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae.',
                    ABOUT_PARAGRAPH_2: 'Aliquam bibendum enim odio, ornare egestas velit placerat at. Fusce fermentum egestas metus non posuere. Morbi porta pharetra neque, ut eleifend dui. In nisl nunc, lobortis quis placerat at, vehicula sit amet leo. Proin scelerisque, mi fermentum varius tempus, nulla lorem porttitor felis, non suscipit tortor tellus id neque. Aenean eu imperdiet mauris. Cras eu fringilla nisl. In malesuada fringilla rhoncus. Sed in mauris nec enim lacinia tristique. Nam id lacus est. Praesent ipsum arcu, tempor vitae posuere in, tincidunt eu quam. In interdum sapien hendrerit aliquet bibendum. Donec id felis eget ex eleifend tempus. Nullam eget arcu orci.',
                    ABOUT_LEARN_MORE: 'Learn more',

                    REMOTE_API_BALANCE_SUMMARY_RETRIEVING: 'Retrieving summary balance for ',
                    REMOTE_API_BALANCE_SUMMARY_RETRIEVED: 'Summary balance retrieved',
                    REMOTE_API_BALANCE_SUMMARY_ERROR_RETRIEVING: 'Error retrieving summary balance',

                    REMOTE_API_STATEMENT_SUMMARY_RETRIEVING: 'Retrieving summary statement for ',
                    REMOTE_API_STATEMENT_SUMMARY_RETRIEVED: 'Summary statement retrieved',
                    REMOTE_API_STATEMENT_SUMMARY_ERROR_RETRIEVING: 'Error retrieving summary statement',

                    REMOTE_API_STATEMENT_SUMMARY_SAVING: 'Saving summary statement for ',
                    REMOTE_API_STATEMENT_SUMMARY_SAVED: 'Summary statement saved',
                    REMOTE_API_STATEMENT_SUMMARY_ERROR_SAVING: 'Error saving summary statement',

                    GENERAL_NO_DATA_TITLE: "Uh oh!",
                    GENERAL_NO_DATA_MESSAGE: "Seems that there is no data registered for this period. No problem... Just create a new monthly balance or try another period."
                });
                $translateProvider.translations(APP_LOCALE.PT_BR, {
                    PAGE_TITLE: 'Gerenciador de Condomínio',
                    MENU_SUMMARY: 'Resumo',
                    MENU_STATEMENT: 'Declaração',
                    MENU_BALANCE: 'Balancete',
                    MENU_INCOMES: 'Créditos',
                    MENU_FEES: 'Taxas',
                    MENU_BANKS: 'Bancos',
                    MENU_EXPENSES: 'Gastos',
                    MENU_PERSONNEL: 'Pessoal',

                    MENU_ABOUT: 'Sobre...',

                    MENU_ENGLISH: 'Inglês (EUA)',
                    MENU_PORTUGUESE: 'Português (BR)',

                    SUMMARY_TITLE: "Resumo",
                    SUMMARY_TITLE_INCOMES: "Créditos",
                    SUMMARY_TITLE_EXPENSES: 'Gastos',
                    SUMMARY_TITLE_APARTMENTS: 'Apartamentos',
                    SUMMARY_DETAIL_CONDOMINIUM_FEE: 'Taxa cond.',
                    SUMMARY_DETAIL_CONDOMINIUM_SURCHARGE: 'Taxa extra',
                    SUMMARY_DETAIL_CONDOMINIUM_DISCOUNT: 'Desconto',
                    SUMMARY_DETAIL_OTHERS: 'Outras taxas',
                    SUMMARY_DETAIL_PAYMENT: 'Pagamento',
                    SUMMARY_TOTAL_NORMAL_FEE: "Taxa ordinária",
                    SUMMARY_TOTAL_SURCHARGE: "Taxa extra",
                    SUMMARY_TOTAL_DISCOUNT: 'Desconto',
                    SUMMARY_TOTAL_OTHERS: "Outras taxas",
                    SUMMARY_TOTAL_FEE: "Taxa cond. total",
                    SUMMARY_TOTAL_PAYMENT: "Pagamento total",

                    APARTMENT_LIST_TITLE: "Apartmentos",

                    ABOUT_TITLE: 'Bem vindo...',
                    ABOUT_SUBTITLE: '... Ao gerenciador de Condomínio',
                    ABOUT_PARAGRAPH_1: 'Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras laoreet sem fermentum libero interdum, placerat mollis est suscipit. Proin mollis finibus porttitor. Fusce feugiat nibh non massa vehicula, id pharetra arcu imperdiet. Cras vitae urna vel odio faucibus tristique non quis nisl. Nullam eget nunc et elit venenatis porta vitae et eros. Nullam metus enim, pretium ut vulputate eu, maximus nec urna. Nunc elementum magna arcu, vel blandit tellus vehicula rutrum. Nullam nec lacinia nulla.',
                    ABOUT_PARAGRAPH_2: 'Donec a efficitur ipsum. Praesent nec sodales purus. Curabitur justo quam, luctus non malesuada et, dapibus tristique libero. Nunc tristique justo eu sapien fermentum bibendum. Maecenas scelerisque vitae orci id semper. Aenean ultrices dui et elementum tincidunt. Phasellus lacinia arcu erat, eu tempor orci dapibus eget. Nunc elementum quam et odio porttitor, varius ultrices eros blandit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam diam lacus, ornare vitae risus vitae, tempor ultrices enim.',
                    ABOUT_LEARN_MORE: 'Veja mais',

                    REMOTE_API_BALANCE_SUMMARY_RETRIEVING: 'Recebendo o resumo do balancete de ',
                    REMOTE_API_BALANCE_SUMMARY_RETRIEVED: 'Resumo do balancete recebido',
                    REMOTE_API_BALANCE_SUMMARY_ERROR_RETRIEVING: 'Erro ao receber o resumo do balancete',

                    REMOTE_API_STATEMENT_SUMMARY_RETRIEVING: 'Recebendo o resumo da declaração de ',
                    REMOTE_API_STATEMENT_SUMMARY_RETRIEVED: 'Resumo da declaração recebido',
                    REMOTE_API_STATEMENT_SUMMARY_ERROR_RETRIEVING: 'Erro ao receber o resumo da declaração',

                    REMOTE_API_STATEMENT_SUMMARY_SAVING: 'Gravando o resumo da declaração de ',
                    REMOTE_API_STATEMENT_SUMMARY_SAVED: 'Resumo da declaração gravado',
                    REMOTE_API_STATEMENT_SUMMARY_ERROR_SAVING: 'Erro ao gravar o resumo da declaração',

                    GENERAL_NO_DATA_TITLE: "Oh oh!",
                    GENERAL_NO_DATA_MESSAGE: "Parece que não há registros para este período. Sem problemas... Apenas registre um novo balancete mensal ou escolha um outro período."
                });

                $translateProvider.preferredLanguage(APP_LOCALE.EN_US);
            }
        ]
    );
})();


text:
import React from "react";
import Rx from "rx";

import AbstractContainer from "zero/component/container";
import List from "zero/component/list/list";

export default class Container extends AbstractContainer {
    constructor( props ) {
        super(props);

        this.state = {
            children: []
        };
    }

    subscribe(props) {
        var children = props.children;
        this.subscription = children.subscribeOnNext(this.setChildren, this);
    }

    setChildren( children ) {
        this.setState({ children });
    }

    render() {
        var children = this.state.children;

        return React.createElement(
            List,
            this.props,
            children
        );
    }
}

Container.propTypes = {
    children: React.PropTypes.instanceOf(Rx.Observable)
};

Container.defaultProps = {
};

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Класс Curl - ООП обвертка стандартной curl-lib
 *
 * @author almazko <a.s.suslov@gmail.com>
 */
require_once CORE_PATH . 'Lib/ConstCurl.php';
require_once CORE_PATH . 'Lib/Mimetypes.php';

class Curl {

    public
        $_referer = 'http://www.google.com',
        $_cookie;

    protected
        // ссылка на текущий курл
        $_ch,
        //массив опций для курла
        $_opt = array(),
        //массив информации о последнем выполненном запросе
        $_info = array(),
        //хранит сырой результат запроса, пока его не распарсят
        $_responseRaw,
        // "Тело" ответа, без заголовков
        $_responseBody,
        // массив заголовоков ответа
        $_aResponseHeaders,
        // кодировка ответа, если не указана - будет браться из заголовков ответа
        $_responseCharset = 'cp1251',
        // кодировка тела, после всех манипуляций
        $_responseBodyCharset = ENCODING_CODE,
        $_responseMimeType = 'text/html',
        // Массив get-параметров для запроса
        $_aGet = array(),
        // Массив post-параметров для запроса
        $_aPost = array(),
        // Массив заголовков для запроса
        $_aRequestHeaders = array(),
        // Массив файлов для запроса
        $_aRequestFiles,
        //ошибки
        $_errors = array(),
        // массив Cookies отсылаемых сервером
        $_aResponseCookies = array(),
        // location, отсылаемый сервером. Т.е. куда хотят нас послать
        $_responseLocation,
        // способ отправки формы серверу
        $_formEnctype = ConstCurl::FORM_ENCTYPE_APP,
        //URL-encodes
        $_prepare = false,
        $_responseMyCharset,
        $_responseMyCharsetForcibly;

    public function __construct() {
        $session = RegistrySession::instance();
        if ($session->is('curl_referer')) {
            $this->_referer = $session->get('curl_referer');
        }
        if ($session->is('curl_cookie')) {
            $this->_cookie = $session->get('curl_cookie');
        }
        $this->_ch = curl_init();
    }

    public function __destruct() {
        $session = RegistrySession::instance();
        $session->set('curl_cookie', $this->_cookie);
        $session->set('curl_referer', $this->_referer);
    }

    /**
     * Задать прокси
     * @param string $address
     * @param int $port
     * @param string $login
     * @param string $password
     */
    public function setProxy($address, $port, $login, $password) {
     //   $this->setOpt(CURLOPT_INTERFACE, null);
        $this->setOpt(CURLOPT_PROXY, $address);
        $this->setOpt(CURLOPT_PROXYPORT, $port);
        $this->setOpt(CURLOPT_PROXYUSERPWD, $login . ':' . $password);
    }

    function disableProxy() {
        $this->setOpt(CURLOPT_PROXY, null);
     }
    /**
     * Скачать файл с сервера
     * NO STABLE
     * @param string $url - адрес картинки
     * @param string $path - куда сохранять
     * @return bool
     */
    public function downloadFile($url, $path) {
        $this->_clean();
        $this->_preparePost();
        $this->setOpt(CURLOPT_URL, $url);
        if ($this->_exec()) {
            $this->_parseResponse(false);
            $file = $this->_responseBody;
        } else {
            return false;
        }
        @unlink($path);
        $fd = fopen($path, "a");
        fwrite($fd, $file);
        fclose($fd);
        return true;
    }

    /**
     * Выполняет запрос и все необходимые действия
     * @return Curl
     */
    public function request($url) {
        $this->_clean();
        $aGet = $this->_preparedGet();

        if ($aGet) {
            $url = $url . '?' . $aGet;
        }
         //TODO сделать по нормальному и всунуть в демона
         echo "\nCurl GET: " . $url;
        if ($this->getOpt(CURLOPT_POST)) {
            $this->_preparePost();
        }
        $this->setOpt(CURLOPT_URL, $url);

        if ($this->_exec()) {
            $this->_referer = $this->getinfo("url");
            $this->_parseResponse();
        }
        return $this;
    }

    /**
     * Выполнить Get запрос
     * @param string $url - url, без get-параметров
     */
    public function requestGet($url) {
        $this->setOpt(CURLOPT_CUSTOMREQUEST, 'GET');
        $this->setOpt(CURLOPT_POST, false);
        return $this->request($url);
    }

    /**
     * Выполнить Post запрос
     * @param string $url - url, без get-параметров
     */
    public function requestPost($url) {
        $this->setOpt(CURLOPT_CUSTOMREQUEST, 'POST');
        $this->setOpt(CURLOPT_POST, true);
        return $this->request($url);
    }

    /**
     * Добавить файл к запросу
     * @param string $key
     * @param string $pathToFile
     */
    function setFile($key, $pathToFile) {

    }

    /**
     * Получить файл
     * @param string $key
     * @return string path to file
     */
    function getFile($key) {
        return path;
    }

    /**
     * Задать массив Post
     * @param array $array
     */
    function setPost (array $array) {
        $this->_aPost = array_replace($this->_aPost, $array);
    }

    /**
     * Получить массив Post
     * @return array
     */
    function getPost () {
        return $this->_aPost;
    }

    /**
     * Задать массив Get
     * @param array $array
     */
    function setGet(array $array) {
        $this->_aGet = array_replace($this->_aGet, $array);
    }

    /**
     * Получить массив Get
     * @return array
     */
    function getGet() {
        return $this->_aGet;
    }

    /**
     * Получить url, который будет использоваться в запросе.
     * Собирается из get-параметров
     * @param string $url url, к которому присоденится  результат
     * @return string
     */
    function getUrl($url = '') {
        $strGet = $this->_preparedGet();

        if ($strGet) {
            $url = (string) $url . '?' . $strGet;
        } else {
            $url = (string) $url;
        }
        return $url;
    }
    /**
     * Задать заголовки запроса
     */
    function setHeaders(array $aHeaders) {
        $this->_aRequestHeaders = array_replace($this->_aRequestHeaders, $aHeaders);
    }

    /**
     * Получить заголовки запроса
     */
    function getHeaders() {
        return $this->_aRequestHeaders;
    }

    function reset() {
        $this->resetCookies();
        $this->resetReferer();
    }

    function resetReferer() {
        $this->setReferer();
    }

    /**
     * Задать рефер
     */
    function setReferer($referer = null) {
        $session = RegistrySession::instance();
        if ($referer) {
            $session->del('curl_referer');
        } else {
            $session->set('curl_referer', $referer);
        }
        $this->_referer = $referer;
    }
    /**
     * Сбросить куки и другую информацию которую хранит курл для себя между вызовами.
     */
    public function resetCookies() {
        $session = RegistrySession::instance();
        $session->del('curl_cookie');
        $this->_cookie = '';
    }

    /**
     * Указать способ отправки данных формой
     * @param string $encType
     */
    public function setFormEnctype($encType = ConstCurl::FORM_ENCTYPE_APP) {
        if (ConstCurl::FORM_ENCTYPE_MULTIPART != $encType) {
            $encType = ConstCurl::FORM_ENCTYPE_APP;
        }
        $this->_formEnctype = $encType;
    }

    /**
     * Производить конвертирование запроса в urlencode()
     * @param string $encType
     */
    public function setPrepared($value = true) {
        $this->_prepare = (bool) $value;
    }
    /**
     * Формирует строку из get-параметров
     * Применяет к параметрам urldecode
     * например key1=123&key2=a%20b&key2
     * @return string
     */
    protected function _preparedGet($prepare = true) {
        $get = array();
        foreach ($this->_aGet as $key => $value) {
            if ($this->_prepare) {
                $get[] = urlencode($key) . (($value === '') ? '=' : '=' . urlencode($value));
            } else {
                $get[] = $key . (($value === '') ? '=' : '=' . $value);
            }
        }
        return implode('&' , $get);
    }

    /**
     * Формирует тело Post запроса
     */
    protected function _preparePost($prepare = true) {
        if ($this->getOpt(CURLOPT_POST)) {
            $post = array();
            if (ConstCurl::FORM_ENCTYPE_APP == $this->_formEnctype) {
                foreach ($this->_aPost as $key => $value) {
                    if ($this->_prepare) {
                        $post[] = urlencode($key) . (($value === '') ? '=' : '=' . urlencode($value));
                    } else {
                        $post[] = $key . (($value === '') ? '=' : '=' . $value);
                    }
                }
                $this->setOpt(CURLOPT_POSTFIELDS, implode('&' , $post));
            } else {
                foreach ($this->_aPost as $key => $value) {
                    $post[$key] = @iconv(ENCODING_CODE, $this->_responseCharset, $value);
                }
                $this->setOpt(CURLOPT_POSTFIELDS, $post);
            }
        } else {
            $this->delOpt(CURLOPT_POSTFIELDS);
        }
    }

    /**
     * Формирует строку заголовков
     */
    protected function _preparedHeaders() {
        $this->setHeaders(array(
            'Accept'	 => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'User-Agent' => 'Mozilla/5.0 (X11; U; Linux i686; ru; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.10 (maverick) Firefox/3.6.12',
            'Accept-Language' => 'ru,en-us;q=0.7,en;q=0.3',
            'Accept-Charset' =>	'windows-1251,utf-8;q=0.7,*;q=0.7',
            'Connection' => 'keep-alive',
            'Keep-Alive' => '115',
            ));

         if ($this->_referer) {
             $this->setHeaders(array('Referer' => $this->_referer));
         }

         if ($this->_cookie) {
             $this->setOpt(CURLOPT_COOKIE, $this->_cookie);
         //    $this->setHeaders(array('Cookie' => $this->_cookie));
         }

        if ($this->_aRequestHeaders) {
            $this->setOpt(CURLOPT_HTTPHEADER, $this->_aRequestHeaders);
        }
    }

    /**
     * Выполнить как ajax-запрос
     */
    function asAjax() {
        $this->setHeaders(array('X-Requested-With' => 'XMLHttpRequest',
                                'Content-Type'     => 'application/x-www-form-urlencoded; charset=UTF-8;'));
    }

    /**
     * Возвращает тело ответа
     * @return string Utf-8
     */
    public function getResponseBody() {
        return $this->_responseBody;
    }

    /**
     * Возвращает массив заголовков
     * @return array
     */
    public function getResponseHeaders() {
        return $this->_aResponseHeaders;
    }

    /**
     * Задать настройки курла из массива
     * @param array $opt массив настроек для curl
     */
    public function setOptArray(array $opt = array()) {
         $this->_opt = $this->_opt + $opt;
    }

    /**
     * Задать настройку для курла
     * @param int $key
     * @param mixed $value
     */
    public function setOpt($key, $value) {
         $this->_opt[$key] = $value;
    }

    public function delOpt($key) {
        if ($this->isOpt($key)) {
            unset($this->_opt[$key]);
        }
    }

    /**
     * Получить информацию о последнем действии
     * @param string $key
     * @return mixed
     */
    public function getinfo($key = null) {
        $this->_info = curl_getinfo($this->_ch);
        if($key) {
            return $this->_info[$key];
        } else {
            return $this->_info;
        }
    }

    /**
     * получить ошибки
     * @return array
     */
    public function getErrors() {
        return $this->_errors;
    }

    public function getCharsetBody() {
        return $this->_responseBodyCharset;
    }
    /**
     * Узнать если такое с-во в опциях курла
     * @param string $name название опции
     * @return mixed
     */
    public function isOpt($name) {
        return isset($this->_opt[$name]) ? true : false;
    }

    public function getOpt($name) {
        return $this->isOpt($name) ? $this->_opt[$name] : null;
    }

    /**
     * Возвращает массив всех настроек курла
     *
     * @param bool $analogView - вывести в человекопонятном виде
     * @return array
     */
    public function getOpts($analogView = false) {
        if ($analogView) {
            $analogOpt = array();
            foreach($this->_opt as $key => $val) {
                if (isset(ConstCurl::$opts[$key])) {
                    $analogOpt[ConstCurl::$opts[$key]] = $val;
                } else {
                    $analogOpt[$key] = $val;
                }
            }
            return $analogOpt;
        } else {
            return $this->_opt;
        }
    }

    /**
     * Выполнить курл с текущими настройками
     * @return bool удачно или нет
     */
    protected function _exec() {
        echo "\nCOOKIE: " . $this->_cookie . "\n\n";
        $this->_preparedHeaders();
        curl_setopt_array($this->_ch, $this->_opt);
       // Log::dump($this->getOpts(true));

        $this->_responseRaw = curl_exec($this->_ch);
        $this->_responseLocation = null;
        //FIXME: сделать нормальное логирование ошибок. общее и для текущией итерации
        $this->_errors = array();
        $this->getinfo();
//Log::dump($this->getinfo());
//Log::dump($this->_responseRaw);

        //сохраняем рефер

        if (!$this->getinfo('http_code')) {
            $this->_errors[] = 'Не удалось выполнить операцию';
            return;
        }

        if (preg_match('/[45][0-9][0-9]/', $this->getinfo('http_code'))) {
            $this->_errors[] = 'Сервер ответил с ошибкой '. $this->getinfo('http_code');
        }

     //   RunTimer::endPoint('Curl');

        return $this->_responseRaw ? true : false;
    }

    /**
     * Парсит строку хидеров.
     * Также пытается получить кодировку, mime-type, cookies и location
     * @param string $response
     * @return array хидеры в виде массива
     * @todo отрефакторить цикл
     */
    protected function _parseHeaders() {
        $this->_aResponseCookies = array();
        $aHeaders = array();
        $sHeaders = substr($this->_responseRaw, 0, $this->_info['header_size']);
        $sHeaders = TFormat::winTextToLinux($sHeaders);
        $sHeaders = preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $sHeaders);
        $rows = explode("\n", $sHeaders);
        foreach ($rows as $row) {
            if (preg_match('/([a-zA-Z-]+): (.+)/', $row, $matches)) {
                $headerName = strtolower($matches[1]);
                $headerValues = preg_split("/;\s*/", $matches[2]);
                foreach($headerValues as $subValue) {
                    switch ($headerName) {
                        case ConstCurl::HEADER_CONTENT_TYPE:
                            if (preg_match('/charset=(.+)/i', $subValue, $subMatch)) {
                                $this->_responseCharset = $subMatch[1];
                            } else if (Mimetypes::is($subValue)){
                                $this->_responseMimeType = $subValue;
                            }
                            break;
                        case ConstCurl::HEADER_SET_COOKIE:
                            $this->_aResponseCookies[] = $subValue;

                            break;
                        case ConstCurl::HEADER_LOCATION:
                            $this->_responseLocation = $subValue;
                    }
                 }
                 $aHeaders[$matches[1]] = $matches[2];
             }
         }
        if (isset($this->_aResponseCookies[0])) {
            $this->_cookie = implode('; ', $this->_aResponseCookies);
        }
//Log::dump($aHeaders);
        return $this->_aResponseHeaders = $aHeaders;
    }

    /**
     * Парсит ответ
     * Получает массив заголовков и строку тела в UTF-8 кодировке
     */
    protected function _parseResponse($convert = true) {
        // если в конфигурации стоит получение заголовков
        if ($this->isOpt(CURLOPT_HEADER)) {
            $this->_aResponseHeaders = $this->_parseHeaders();
        }
        if ($this->_responseLocation || preg_match('/30[0-9]/', $this->getinfo('http_code'))) {

            if (@parse_url($this->_responseLocation, PHP_URL_HOST)) {
                $urlRedirect = $this->_responseLocation;
                return $this->requestGet($urlRedirect);
            } else {
                $url = $this->getinfo('url');
                $parseUrl = @parse_url($url);
                $urlRedirect = $parseUrl['scheme'] . '://' . $parseUrl['host'] . $this->_responseLocation;
            }

            /*
             * http://ru.wikipedia.org/wiki/Список_кодов_состояния_HTTP
             */
            $this->_clean();
            if ('302' == $this->getinfo('http_code') || '303' == $this->getinfo('http_code')) {
                $this->_aPost = array();
                $this->_aGet = array();
                $this->delOpt(CURLOPT_POSTFIELDS);
                $this->requestGet($urlRedirect);
            } else {
                $this->request($url);
            }
            return;
        }
        if (!$this->isOpt(CURLOPT_NOBODY)) {
            $this->_responseBody = substr($this->_responseRaw, $this->_info['header_size']);
            if ($this->_responseMyCharsetForcibly) {
                $charset = $this->_responseMyCharset;
            } else if (!$this->_responseCharset && $this->_responseMyCharset) {
                $charset = $this->_responseMyCharset;
            } else {
                $charset = $this->_responseCharset;
            }
            $this->_responseBodyCharset = $charset;
            if ($convert && $charset && ENCODING_CODE != $charset) {
                $this->_responseBody = @iconv($charset, ENCODING_CODE, $this->_responseBody);
            }
        }
        $this->_responseRaw = null;
    }

    /**
     * Очищает данные, полученные из прошлого запроса
     */
    protected function _clean() {
        $this->_responseBody = null;
        $this->_aResponseHeaders = null;
        $this->_info = null;
    }

    /**
     * Закрывает соединение
     * @return bool
     */
    public function close() {
        if ($this->_ch) {
            curl_close($this->_ch);
            return true;
        } else {
            return false;
        }
    }

    /**
     * Задать кодировку сайта
     * @param string $charset
     * @param bool $forcibly - применять ее принудительно или только если не смогли получить ее от сайта
     */

    public function setResponseCharset($charset, $forcibly = false) {
        $this->_responseMyCharset = $charset;
        $this->_responseMyCharsetForcibly = $forcibly;
    }

    /**
     * Задать кодировку сайта
     */
    public function getResponseMimeType($charset) {
        $this->_responseMimeType;
    }

    public function ping($host) {

    }
}


text:
function Invoke-DbaDatabaseUpgrade {
    <#
    .SYNOPSIS
    Take a database and upgrades it to compatibility of the SQL Instance its hosted on. Based on https://thomaslarock.com/2014/06/upgrading-to-sql-server-2014-a-dozen-things-to-check/

    .DESCRIPTION
    Updates compatibility level, then runs CHECKDB with data_purity, DBCC updateusage, sp_updatestats and finally sp_refreshview against all user views.

    .PARAMETER SqlInstance
    The SQL Server that you're connecting to.

    .PARAMETER SqlCredential
    SqlCredential object used to connect to the SQL Server as a different user.

    .PARAMETER Database
    The database(s) to process - this list is autopopulated from the server. If unspecified, all databases will be processed.

    .PARAMETER ExcludeDatabase
    The database(s) to exclude - this list is autopopulated from the server

    .PARAMETER AllUserDatabases
    Run command against all user databases

    .PARAMETER Force
    Don't skip over databases that are already at the same level the instance is

    .PARAMETER NoCheckDb
    Skip checkdb

    .PARAMETER NoUpdateUsage
    Skip usage update

    .PARAMETER NoUpdateStats
    Skip stats update

    .PARAMETER NoRefreshView
    Skip view update

    .PARAMETER InputObject
    A collection of databases (such as returned by Get-DbaDatabase)

    .PARAMETER WhatIf
    Shows what would happen if the command were to run

    .PARAMETER Confirm
    Prompts for confirmation of every step. For example:

    Are you sure you want to perform this action?
    Performing the operation "Update database" on target "pubs on SQL2016\VNEXT".
    [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

    .PARAMETER EnableException
    By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
    This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
    Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Author: Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/
        Tags: Shrink, Databases

        Website: https://dbatools.io
        Copyright: (C) Chrissy LeMaire, clemaire@gmail.com
        License: MIT https://opensource.org/licenses/MIT

    .LINK
        https://dbatools.io/Invoke-DbaDatabaseUpgrade

    .EXAMPLE
        Invoke-DbaDatabaseUpgrade -SqlInstance PRD-SQL-MSD01 -Database Test

        Runs the below processes against the databases
        -- Puts compatibility of database to level of SQL Instance
        -- Runs CHECKDB DATA_PURITY
        -- Runs DBCC UPDATESUSAGE
        -- Updates all users statistics
        -- Runs sp_refreshview against every view in the database

    .EXAMPLE
        Invoke-DbaDatabaseUpgrade -SqlInstance PRD-SQL-INT01 -Database Test -NoRefreshView

        Runs the upgrade command skipping the sp_refreshview update on all views

    .EXAMPLE
        Invoke-DbaDatabaseUpgrade -SqlInstance PRD-SQL-INT01 -Database Test -Force

        If database Test is already at the correct compatibility, runs every necessary step

    .EXAMPLE
        Get-DbaDatabase -SqlInstance sql2016 | Out-GridView -Passthru | Invoke-DbaDatabaseUpgrade

        Get only specific databases using GridView and pass those to Invoke-DbaDatabaseUpgrade
#>
    [CmdletBinding(SupportsShouldProcess)]
    Param (
        [parameter(Position = 0)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [System.Management.Automation.PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$NoCheckDb,
        [switch]$NoUpdateUsage,
        [switch]$NoUpdateStats,
        [switch]$NoRefreshView,
        [switch]$AllUserDatabases,
        [switch]$Force,
        [parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [Alias('Silent')]
        [switch]$EnableException
    )
    process {

        if (Test-Bound -not 'SqlInstance', 'InputObject') {
            Write-Message -Level Warning -Message "You must specify either a SQL instance or pipe a database collection"
            continue
        }

        if (Test-Bound -not 'Database', 'InputObject', 'ExcludeDatabase', 'AllUserDatabases') {
            Write-Message -Level Warning -Message "You must explicitly specify a database. Use -Database, -ExcludeDatabase, -AllUserDatabases or pipe a database collection"
            continue
        }

        foreach ($instance in $SqlInstance) {
            try {
                Write-Message -Level VeryVerbose -Message "Connecting to <c='green'>$instance</c>" -Target $instance
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
                $server.ConnectionContext.StatementTimeout = [Int32]::MaxValue
            }
            catch {
                Stop-Function -Message "Failed to process Instance $Instance" -ErrorRecord $_ -Target $instance -Continue
            }
            $InputObject += $server.Databases | Where-Object IsAccessible
        }

        $InputObject = $InputObject | Where-Object { $_.IsSystemObject -eq $false }
        if ($Database) {
            $InputObject = $InputObject | Where-Object { $_.Name -contains $Database }
        }
        if ($ExcludeDatabase) {
            $InputObject = $InputObject | Where-Object { $_.Name -notcontains $ExcludeDatabase }
        }

        foreach ($db in $InputObject) {
            # create objects to use in updates
            $server = $db.Parent
            $ServerVersion = $server.VersionMajor
            Write-Message -Level Verbose -Message "SQL Server is using Version: $ServerVersion"

            $ogcompat = $db.CompatibilityLevel
            $dbname = $db.Name
            $dbversion = switch ($db.CompatibilityLevel) {
                "Version100" { 10 } # SQL Server 2008
                "Version110" { 11 } # SQL Server 2012
                "Version120" { 12 } # SQL Server 2014
                "Version130" { 13 } # SQL Server 2016
                "Version140" { 14 } # SQL Server 2017
                default { 9 } # SQL Server 2005
            }
            if (-not $Force) {
                # skip over databases at the correct level, unless -Force
                if ($dbversion -ge $ServerVersion) {
                    Write-Message -Level VeryVerbose -Message "Skipping $db because compatibility is at the correct level. Use -Force if you want to run all the additional steps"
                    continue
                }
            }
            Write-Message -Level Verbose -Message "Updating $db compatibility to SQL Instance level"
            if ($dbversion -lt $ServerVersion) {
                If ($Pscmdlet.ShouldProcess($server, "Updating $db version on $server from $dbversion to $ServerVersion")) {
                    $Comp = $ServerVersion * 10
                    $tsqlComp = "ALTER DATABASE $db SET COMPATIBILITY_LEVEL = $Comp"
                    try {
                        $db.ExecuteNonQuery($tsqlComp)
                        $comResult = $Comp
                    }
                    catch {
                        Write-Message -Level Warning -Message "Failed run Compatibility Upgrade" -ErrorRecord $_ -Target $instance
                        $comResult = "Fail"
                    }
                }
            }
            else {
                $comResult = "No change"
            }

            if (!($NoCheckDb)) {
                Write-Message -Level Verbose -Message "Updating $db with DBCC CHECKDB DATA_PURITY"
                If ($Pscmdlet.ShouldProcess($server, "Updating $db with DBCC CHECKDB DATA_PURITY")) {
                    $tsqlCheckDB = "DBCC CHECKDB ('$dbname') WITH DATA_PURITY, NO_INFOMSGS"
                    try {
                        $db.ExecuteNonQuery($tsqlCheckDB)
                        $DataPurityResult = "Success"
                    }
                    catch {
                        Write-Message -Level Warning -Message "Failed run DBCC CHECKDB with DATA_PURITY on $db" -ErrorRecord $_ -Target $instance
                        $DataPurityResult = "Fail"
                    }
                }
            }
            else {
                Write-Message -Level Verbose -Message "Ignoring CHECKDB DATA_PURITY"
            }

            if (!($NoUpdateUsage)) {
                Write-Message -Level Verbose -Message "Updating $db with DBCC UPDATEUSAGE"
                If ($Pscmdlet.ShouldProcess($server, "Updating $db with DBCC UPDATEUSAGE")) {
                    $tsqlUpdateUsage = "DBCC UPDATEUSAGE ($db) WITH NO_INFOMSGS;"
                    try {
                        $db.ExecuteNonQuery($tsqlUpdateUsage)
                        $UpdateUsageResult = "Success"
                    }
                    catch {
                        Write-Message -Level Warning -Message "Failed to run DBCC UPDATEUSAGE on $db" -ErrorRecord $_ -Target $instance
                        $UpdateUsageResult = "Fail"
                    }
                }
            }
            else {
                Write-Message -Level Verbose -Message "Ignore DBCC UPDATEUSAGE"
                $UpdateUsageResult = "Skipped"
            }

            if (!($NoUpdatestats)) {
                Write-Message -Level Verbose -Message "Updating $db statistics"
                If ($Pscmdlet.ShouldProcess($server, "Updating $db statistics")) {
                    $tsqlStats = "EXEC sp_updatestats;"
                    try {
                        $db.ExecuteNonQuery($tsqlStats)
                        $UpdateStatsResult = "Success"
                    }
                    catch {
                        Write-Message -Level Warning -Message "Failed to run sp_updatestats on $db" -ErrorRecord $_ -Target $instance
                        $UpdateStatsResult = "Fail"
                    }
                }
            }
            else {
                Write-Message -Level Verbose -Message "Ignoring sp_updatestats"
                $UpdateStatsResult = "Skipped"
            }

            if (!($NoRefreshView)) {
                Write-Message -Level Verbose -Message "Refreshing $db Views"
                $dbViews = $db.Views | Where-Object IsSystemObject -eq $false
                $RefreshViewResult = "Success"
                foreach ($dbview in $dbviews) {
                    $viewName = $dbView.Name
                    $viewSchema = $dbView.Schema
                    $fullName = $viewSchema + "." + $viewName

                    $tsqlupdateView = "EXECUTE sp_refreshview N'$fullName';  "

                    If ($Pscmdlet.ShouldProcess($server, "Refreshing view $fullName on $db")) {
                        try {
                            $db.ExecuteNonQuery($tsqlupdateView)
                        }
                        catch {
                            Write-Message -Level Warning -Message "Failed update view $fullName on $db" -ErrorRecord $_ -Target $instance
                            $RefreshViewResult = "Fail"
                        }
                    }
                }
            }
            else {
                Write-Message -Level Verbose -Message "Ignore View Refreshes"
                $RefreshViewResult = "Skipped"
            }

            If ($Pscmdlet.ShouldProcess("console", "Outputting object")) {
                $db.Refresh()

                [PSCustomObject]@{
                    ComputerName          = $server.NetName
                    InstanceName          = $server.ServiceName
                    SqlInstance           = $server.DomainInstanceName
                    Database              = $db.name
                    OriginalCompatibility = $ogcompat.ToString().Replace('Version', '')
                    CurrentCompatibility  = $db.CompatibilityLevel.ToString().Replace('Version', '')
                    Compatibility         = $comResult
                    DataPurity            = $DataPurityResult
                    UpdateUsage           = $UpdateUsageResult
                    UpdateStats           = $UpdateStatsResult
                    RefreshViews          = $RefreshViewResult
                }
            }
        }
    }
}


text:
#ifndef _paintown_cat_h
#define _paintown_cat_h

#include <map>
#include <string>
#include <vector>
#include "object_nonattack.h"
#include <r-tech1/sound/sound.h>
#include <r-tech1/network/network.h>
#include <r-tech1/file-system.h>

namespace Graphics{
class Bitmap;
}

namespace Paintown{

class Animation;

class Cat: public ObjectNonAttack {
public:
	Cat(const Filesystem::AbsolutePath & filename );
	Cat( const Cat & cat );

	virtual void act( std::vector< Object * > * others, World * world, std::vector< Object * > * add );
	virtual void draw( Graphics::Bitmap * work, int rel_x, int rel_y );
	virtual bool isCollidable( Object * obj );
	virtual bool isGettable();
	virtual int getWidth() const;
	virtual int getHeight() const;
	virtual Network::Message getCreateMessage();

	virtual Object * copy();

	virtual int getRX() const;

	virtual ~Cat();

protected:
    std::map< std::string, Animation * > animations;
	Animation * current_animation;

    /* meow meow! */
	Sound meow;

        Filesystem::AbsolutePath path;

	enum State{
		IDLE1,
		IDLE2,
		YAWN,
		WALK,
		TURN,
		RUN,
		SIT,
	};

	State state;
};

}

#endif


text:
	color: black;
	font-family: monospace;
	font-size: 11px;
	line-height: 14px;
	box-sizing: initial;
	-webkit-box-sizing: initial;
	-moz-box-sizing: initial;
}

#BAOBAB * {
	box-sizing: initial;
	-webkit-box-sizing: initial;
	-moz-box-sizing: initial;
}

#BAOBAB .BAOBAB_LABEL {
	border: 1px solid #333333;
	cursor: pointer;
	background-color: white;
	z-index: 1;
}

#BAOBAB .BAOBAB_LABEL.BAOBAB_hasFocus {
	background-color: #afa;
}
#BAOBAB .BAOBAB_LABEL.BAOBAB_collapsed {
	background-color: #888;
}
#BAOBAB .BAOBAB_LABEL.BAOBAB_hasFocus.BAOBAB_collapsed {
	background-color: #8c8;
}

#BAOBAB li {
	list-style: none;
	color: black;
}

#BAOBAB ul {
	padding-left: 0px;
}

#BAOBAB input, button, select, textarea {
	font-family: inherit;
	font-size: inherit;
	line-height: inherit;
	outline: none;
	cursor: pointer;
}
#BAOBAB input, textarea:focus {
	cursor: text;
}

#BAOBAB textarea {
	background: transparent;
	resize: none;
	border: none;
	overflow: hidden;
	padding: 0;
	top: 0;
	left: 0;
}


text:
import sys,os
import piconv_handler

class PIconvHandlerTool(object):
    """
        Application behaviour for 'piconv' program
    """
    running = False
    def __init__(self, argv):
        """ Set up a new instance """
        self.parse_commandline(argv)

    def parse_commandline(self, argv):
        """
            Parse command-line arguments
        """
        from optparse import OptionParser
        usage = "usage: %prog [options] arg"
        parser = OptionParser(usage)
        #parser.add_option("-f", "--file", dest="filename",help="read data from FILENAME")
        #parser.add_option("-v", "--verbose",action="store_true", dest="verbose")
        #parser.add_option("-q", "--quiet",action="store_false", dest="verbose")
        (options, args) = parser.parse_args(argv[1:])
        if len(args)==2:
            self.name = args[0]
            self.encoding = args[1]
            self.is_file = os.path.isfile(args[0])
            self.is_dir = os.path.isdir(args[0])
            if self.is_file or self.is_dir:
                self.running = True

            self.check_commandline(args)

        elif len(args) ==1 or len(args)>2:
            print('You must input 2 params')
            sys.exit()

    def check_commandline(self,args):
        from support_encodings import SupportEncodings
        supports = SupportEncodings().get_support_encodings()
        encoding_illegal = str.upper(args[1]) in supports
        if encoding_illegal is False:
            print('The encoding format is illegal, please choose the encoding to convert below:')
            print("[ %s ]" % ','.join(supports))
            sys.exit()

        if not self.is_file and not self.is_dir:
            print('path is illegal, input again')
            sys.exit()

    def run(self):
        if self.running:
            print('Start to iconv files......')

            if self.is_file:
                from piconv_handler import FIconv
                print('[file_name] = `%s`, [encoding] = `%s`' % (self.name,self.encoding))
                ficonv = FIconv(self.name,self.encoding)
                sys.exit()
            if self.is_dir:
                from piconv_handler import DIconv
                print('[dir_path] = `%s`, [encoding] = `%s`' % (self.name,self.encoding))
                diconv = DIconv(self.name,self.encoding)
                diconv.codecs_iconv_iterator()
                sys.exit
        pass
    def help(self):
        print('Usage')
        pass

def main(argv=None):
    from sys import argv as sys_argv
    #print(argv)
    if argv is None:
        argv = sys_argv

    piconv = PIconvHandlerTool(argv)
    exitcode = None
    try:
        piconv.run()
    except SystemExit as e:
        exitcode = e.code
    return exitcode

if __name__ == '__main__':
    exitcode = main(argv=sys.argv)
    sys.exit(exitcode)


text:
//===- CoroElide.cpp - Coroutine Frame Allocation Elision Pass ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This pass replaces dynamic allocation of coroutine frame with alloca and
// replaces calls to llvm.coro.resume and llvm.coro.destroy with direct calls
// to coroutine sub-functions.
//===----------------------------------------------------------------------===//

#include "CoroInternal.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/Pass.h"
#include "llvm/Support/ErrorHandling.h"

using namespace llvm;

#define DEBUG_TYPE "coro-elide"

namespace {
// Created on demand if CoroElide pass has work to do.
struct Lowerer : coro::LowererBase {
  SmallVector<CoroIdInst *, 4> CoroIds;
  SmallVector<CoroBeginInst *, 1> CoroBegins;
  SmallVector<CoroAllocInst *, 1> CoroAllocs;
  SmallVector<CoroSubFnInst *, 4> ResumeAddr;
  SmallVector<CoroSubFnInst *, 4> DestroyAddr;
  SmallVector<CoroFreeInst *, 1> CoroFrees;

  Lowerer(Module &M) : LowererBase(M) {}

  void elideHeapAllocations(Function *F, Type *FrameTy, AAResults &AA);
  bool shouldElide() const;
  bool processCoroId(CoroIdInst *, AAResults &AA);
};
} // end anonymous namespace

// Go through the list of coro.subfn.addr intrinsics and replace them with the
// provided constant.
static void replaceWithConstant(Constant *Value,
                                SmallVectorImpl<CoroSubFnInst *> &Users) {
  if (Users.empty())
    return;

  // See if we need to bitcast the constant to match the type of the intrinsic
  // being replaced. Note: All coro.subfn.addr intrinsics return the same type,
  // so we only need to examine the type of the first one in the list.
  Type *IntrTy = Users.front()->getType();
  Type *ValueTy = Value->getType();
  if (ValueTy != IntrTy) {
    // May need to tweak the function type to match the type expected at the
    // use site.
    assert(ValueTy->isPointerTy() && IntrTy->isPointerTy());
    Value = ConstantExpr::getBitCast(Value, IntrTy);
  }

  // Now the value type matches the type of the intrinsic. Replace them all!
  for (CoroSubFnInst *I : Users)
    replaceAndRecursivelySimplify(I, Value);
}

// See if any operand of the call instruction references the coroutine frame.
static bool operandReferences(CallInst *CI, AllocaInst *Frame, AAResults &AA) {
  for (Value *Op : CI->operand_values())
    if (AA.alias(Op, Frame) != NoAlias)
      return true;
  return false;
}

// Look for any tail calls referencing the coroutine frame and remove tail
// attribute from them, since now coroutine frame resides on the stack and tail
// call implies that the function does not references anything on the stack.
static void removeTailCallAttribute(AllocaInst *Frame, AAResults &AA) {
  Function &F = *Frame->getFunction();
  MemoryLocation Mem(Frame);
  for (Instruction &I : instructions(F))
    if (auto *Call = dyn_cast<CallInst>(&I))
      if (Call->isTailCall() && operandReferences(Call, Frame, AA)) {
        // FIXME: If we ever hit this check. Evaluate whether it is more
        // appropriate to retain musttail and allow the code to compile.
        if (Call->isMustTailCall())
          report_fatal_error("Call referring to the coroutine frame cannot be "
                             "marked as musttail");
        Call->setTailCall(false);
      }
}

// Given a resume function @f.resume(%f.frame* %frame), returns %f.frame type.
static Type *getFrameType(Function *Resume) {
  auto *ArgType = Resume->getArgumentList().front().getType();
  return cast<PointerType>(ArgType)->getElementType();
}

// Finds first non alloca instruction in the entry block of a function.
static Instruction *getFirstNonAllocaInTheEntryBlock(Function *F) {
  for (Instruction &I : F->getEntryBlock())
    if (!isa<AllocaInst>(&I))
      return &I;
  llvm_unreachable("no terminator in the entry block");
}

// To elide heap allocations we need to suppress code blocks guarded by
// llvm.coro.alloc and llvm.coro.free instructions.
void Lowerer::elideHeapAllocations(Function *F, Type *FrameTy, AAResults &AA) {
  LLVMContext &C = FrameTy->getContext();
  auto *InsertPt =
      getFirstNonAllocaInTheEntryBlock(CoroIds.front()->getFunction());

  // Replacing llvm.coro.alloc with false will suppress dynamic
  // allocation as it is expected for the frontend to generate the code that
  // looks like:
  //   id = coro.id(...)
  //   mem = coro.alloc(id) ? malloc(coro.size()) : 0;
  //   coro.begin(id, mem)
  auto *False = ConstantInt::getFalse(C);
  for (auto *CA : CoroAllocs) {
    CA->replaceAllUsesWith(False);
    CA->eraseFromParent();
  }

  // FIXME: Design how to transmit alignment information for every alloca that
  // is spilled into the coroutine frame and recreate the alignment information
  // here. Possibly we will need to do a mini SROA here and break the coroutine
  // frame into individual AllocaInst recreating the original alignment.
  auto *Frame = new AllocaInst(FrameTy, "", InsertPt);
  auto *FrameVoidPtr =
      new BitCastInst(Frame, Type::getInt8PtrTy(C), "vFrame", InsertPt);

  for (auto *CB : CoroBegins) {
    CB->replaceAllUsesWith(FrameVoidPtr);
    CB->eraseFromParent();
  }

  // Since now coroutine frame lives on the stack we need to make sure that
  // any tail call referencing it, must be made non-tail call.
  removeTailCallAttribute(Frame, AA);
}

bool Lowerer::shouldElide() const {
  // If no CoroAllocs, we cannot suppress allocation, so elision is not
  // possible.
  if (CoroAllocs.empty())
    return false;

  // Check that for every coro.begin there is a coro.destroy directly
  // referencing the SSA value of that coro.begin. If the value escaped, then
  // coro.destroy would have been referencing a memory location storing that
  // value and not the virtual register.

  SmallPtrSet<CoroBeginInst *, 8> ReferencedCoroBegins;

  for (CoroSubFnInst *DA : DestroyAddr) {
    if (auto *CB = dyn_cast<CoroBeginInst>(DA->getFrame()))
      ReferencedCoroBegins.insert(CB);
    else
      return false;
  }

  // If size of the set is the same as total number of CoroBegins, means we
  // found a coro.free or coro.destroy mentioning a coro.begin and we can
  // perform heap elision.
  return ReferencedCoroBegins.size() == CoroBegins.size();
}

bool Lowerer::processCoroId(CoroIdInst *CoroId, AAResults &AA) {
  CoroBegins.clear();
  CoroAllocs.clear();
  CoroFrees.clear();
  ResumeAddr.clear();
  DestroyAddr.clear();

  // Collect all coro.begin and coro.allocs associated with this coro.id.
  for (User *U : CoroId->users()) {
    if (auto *CB = dyn_cast<CoroBeginInst>(U))
      CoroBegins.push_back(CB);
    else if (auto *CA = dyn_cast<CoroAllocInst>(U))
      CoroAllocs.push_back(CA);
    else if (auto *CF = dyn_cast<CoroFreeInst>(U))
      CoroFrees.push_back(CF);
  }

  // Collect all coro.subfn.addrs associated with coro.begin.
  // Note, we only devirtualize the calls if their coro.subfn.addr refers to
  // coro.begin directly. If we run into cases where this check is too
  // conservative, we can consider relaxing the check.
  for (CoroBeginInst *CB : CoroBegins) {
    for (User *U : CB->users())
      if (auto *II = dyn_cast<CoroSubFnInst>(U))
        switch (II->getIndex()) {
        case CoroSubFnInst::ResumeIndex:
          ResumeAddr.push_back(II);
          break;
        case CoroSubFnInst::DestroyIndex:
          DestroyAddr.push_back(II);
          break;
        default:
          llvm_unreachable("unexpected coro.subfn.addr constant");
        }
  }

  // PostSplit coro.id refers to an array of subfunctions in its Info
  // argument.
  ConstantArray *Resumers = CoroId->getInfo().Resumers;
  assert(Resumers && "PostSplit coro.id Info argument must refer to an array"
                     "of coroutine subfunctions");
  auto *ResumeAddrConstant =
      ConstantExpr::getExtractValue(Resumers, CoroSubFnInst::ResumeIndex);

  replaceWithConstant(ResumeAddrConstant, ResumeAddr);

  bool ShouldElide = shouldElide();

  auto *DestroyAddrConstant = ConstantExpr::getExtractValue(
      Resumers,
      ShouldElide ? CoroSubFnInst::CleanupIndex : CoroSubFnInst::DestroyIndex);

  replaceWithConstant(DestroyAddrConstant, DestroyAddr);

  if (ShouldElide) {
    auto *FrameTy = getFrameType(cast<Function>(ResumeAddrConstant));
    elideHeapAllocations(CoroId->getFunction(), FrameTy, AA);
    coro::replaceCoroFree(CoroId, /*Elide=*/true);
  }

  return true;
}

// See if there are any coro.subfn.addr instructions referring to coro.devirt
// trigger, if so, replace them with a direct call to devirt trigger function.
static bool replaceDevirtTrigger(Function &F) {
  SmallVector<CoroSubFnInst *, 1> DevirtAddr;
  for (auto &I : instructions(F))
    if (auto *SubFn = dyn_cast<CoroSubFnInst>(&I))
      if (SubFn->getIndex() == CoroSubFnInst::RestartTrigger)
        DevirtAddr.push_back(SubFn);

  if (DevirtAddr.empty())
    return false;

  Module &M = *F.getParent();
  Function *DevirtFn = M.getFunction(CORO_DEVIRT_TRIGGER_FN);
  assert(DevirtFn && "coro.devirt.fn not found");
  replaceWithConstant(DevirtFn, DevirtAddr);

  return true;
}

//===----------------------------------------------------------------------===//
//                              Top Level Driver
//===----------------------------------------------------------------------===//

namespace {
struct CoroElide : FunctionPass {
  static char ID;
  CoroElide() : FunctionPass(ID) {}

  std::unique_ptr<Lowerer> L;

  bool doInitialization(Module &M) override {
    if (coro::declaresIntrinsics(M, {"llvm.coro.id"}))
      L = llvm::make_unique<Lowerer>(M);
    return false;
  }

  bool runOnFunction(Function &F) override {
    if (!L)
      return false;

    bool Changed = false;

    if (F.hasFnAttribute(CORO_PRESPLIT_ATTR))
      Changed = replaceDevirtTrigger(F);

    L->CoroIds.clear();

    // Collect all PostSplit coro.ids.
    for (auto &I : instructions(F))
      if (auto *CII = dyn_cast<CoroIdInst>(&I))
        if (CII->getInfo().isPostSplit())
          // If it is the coroutine itself, don't touch it.
          if (CII->getCoroutine() != CII->getFunction())
            L->CoroIds.push_back(CII);

    // If we did not find any coro.id, there is nothing to do.
    if (L->CoroIds.empty())
      return Changed;

    AAResults &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();

    for (auto *CII : L->CoroIds)
      Changed |= L->processCoroId(CII, AA);

    return Changed;
  }
  void getAnalysisUsage(AnalysisUsage &AU) const override {
    AU.addRequired<AAResultsWrapperPass>();
  }
};
}

char CoroElide::ID = 0;
INITIALIZE_PASS_BEGIN(
    CoroElide, "coro-elide",
    "Coroutine frame allocation elision and indirect calls replacement", false,
    false)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_END(
    CoroElide, "coro-elide",
    "Coroutine frame allocation elision and indirect calls replacement", false,
    false)

Pass *llvm::createCoroElidePass() { return new CoroElide(); }


text:
PDF Theory of Operation
=======================

To make use of Skia's PDF backend, see
[Using Skia's PDF Backend](../../user/sample/pdf).

Internally, Skia uses SkPDFDocument and SkPDFDevice to represent PDF
documents and pages.  This document describes how the backend
operates, but **these interfaces are not part of the public API and
are subject to perpetual change.**

* * *

### Contents ###

*   [Typical usage of the PDF backend](#Typical_usage_of_the_PDF_backend)
*   [PDF Objects and Document Structure](#PDF_Objects_and_Document_Structure)
*   [PDF drawing](#PDF_drawing)
*   [Interned objects](#Interned_objects)
*   [Graphic States](#Graphic_States)
*   [Clip and Transform](#Clip_and_Transform)
*   [Generating a content stream](#Generating_a_content_stream)
*   [Margins and content area](#Margins_and_content_area)
*   [Drawing details](#Drawing_details)
    +   [Layers](#Layers)
    +   [Fonts](#Fonts)
    +   [Shaders](#Shaders)
    +   [Xfer modes](#Xfer_modes)
*   [Known issues](#Known_issues)

Typical usage of the PDF backend
--------------------------------

SkPDFDevice is the main interface to the PDF backend. This child of
SkDevice can be set on an SkCanvas and drawn to. It requires no more
care and feeding than SkDevice. Once drawing is complete, the device
should be added to an SkPDFDocument as a page of the desired PDF. A
new SkPDFDevice should be created for each page desired in the
document. After all the pages have been added to the document,
`SkPDFDocument::emitPDF()` can be called to get a PDF file. One of the
special features of the PDF backend is that the same device can be
added to multiple documents. This for example, would let you generate
a PDF with the single page you just drew as well as adding it to a
longer document with a bunch of other pages.

    SkPDFCanon canon;
    SkAutoUnref<SkPDFDevice> pdfDevice(
        SkPDFDevice::Create(SkISize::Make(width, height), 72.0f, &canon));

    SkCanvas canvas(pdfDevice);
    draw_content(&canvas);

    SkPDFDocument doc;
    doc.appendPage(dev);
    doc.emitPDF(&pdf_stream);

PDF Objects and Document Structure
----------------------------------

![PDF Logical Document Structure](PdfLogicalDocumentStructure.png)

**Background**: The PDF file format has a header, a set of objects and
then a footer that contains a table of contents for all of the objects
in the document (the cross-reference table). The table of contents
lists the specific byte position for each object. The objects may have
references to other objects and the ASCII size of those references is
dependent on the object number assigned to the referenced object;
therefore we can't calculate the table of contents until the size of
objects is known, which requires assignment of object
numbers.

Furthermore, PDF files can support a *linearized* mode, where objects
are in a specific order so that pdf-viewers can more easily retrieve
just the objects they need to display a specific page, i.e. by
byte-range requests over the web. Linearization also requires that all
objects used or referenced on the first page of the PDF have object
numbers before the rest of the objects. Consequently, before
generating a linearized PDF, all objects, their sizes, and object
references must be known.  Skia has no plans to implement linearized
PDFs.

    %PDF-1.4
    …objects...
    xref
    0 31  % Total number of entries in the table of contents.
    0000000000 65535 f
    0000210343 00000 n
    …
    0000117055 00000 n
    trailer
    <</Size 31 /Root 1 0 R>>
    startxref
    210399  % Byte offset to the start of the table of contents.
    %%EOF

The class SkPDFCatalog and the virtual class SkPDFObject are used to
manage the needs of the file format. Any object that will represent a
PDF object must inherit from SkPDFObject and implement the methods to
generate the binary representation and report any other SkPDFObjects
used as resources. SkPDFTypes.h defines most of the basic PDF objects
types: bool, int, scalar, string, name, array, dictionary, and object
reference. The stream type is defined in SkPDFStream.h. A stream is a
dictionary containing at least a Length entry followed by the data of
the stream. All of these types except the stream type can be used in
both a direct and an indirect fashion, i.e. an array can have an int
or a dictionary as an inline entry, which does not require an object
number. The stream type, cannot be inlined and must be referred to
with an object reference. Most of the time, other objects types can be
referred to with an object reference, but there are specific rules in
the PDF specification that requires an inline reference in some place
or an indirect reference in other places. All indirect objects must
have an object number assigned.

*   **bools**: `true` `false`
*   **ints**: `42` `0` `-1`
*   **scalars**: `0.001`
*   **strings**: `(strings are in parentheses or byte encoded)` `<74657374>`
*   **name**: `/Name` `/Name#20with#20spaces`
*   **array**: `[/Foo 42 (arrays can contain multiple types)]`
*   **dictionary**: `<</Key1 (value1) /key2 42>>`
*   **indirect object**:
    `5 0 obj
    (An indirect string. Indirect objects have an object number and a
    generation number, Skia always uses generation 0 objects)
    endobj`
*   **object reference**: `5 0 R`
*   **stream**: `<</Length 56>>
    stream
    ...stream contents can be arbitrary, including binary...
    endstream`

The PDF backend requires all indirect objects used in a PDF to be
added to the SkPDFCatalog of the SkPDFDocument. The catalog is
responsible for assigning object numbers and generating the table of
contents required at the end of PDF files. In some sense, generating a
PDF is a three step process. In the first step all the objects and
references among them are created (mostly done by SkPDFDevice). In the
second step, object numbers are assigned and SkPDFCatalog is informed
of the file offset of each indirect object. Finally, in the third
step, the header is printed, each object is printed, and then the
table of contents and trailer are printed. SkPDFDocument takes care of
collecting all the objects from the various SkPDFDevice instances,
adding them to an SkPDFCatalog, iterating through the objects once to
set their file positions, and iterating again to generate the final
PDF.

    %PDF-1.4
    2 0 obj <<
      /Type /Catalog
      /Pages 1 0 R
    >>
    endobj
    3 0 obj <<
      /Type /Page
      /Parent 1 0 R
      /Resources <>
      /MediaBox [0 0 612 792]
      /Contents 4 0 R
    >>
    endobj
    4 0 obj <> stream
    endstream
    endobj
    1 0 obj <<
      /Type /Pages
      /Kids [3 0 R]
      /Count 1
    >>
    endobj
    xref
    0 5
    0000000000 65535 f
    0000000236 00000 n
    0000000009 00000 n
    0000000062 00000 n
    0000000190 00000 n
    trailer
    <</Size 5 /Root 2 0 R>>
    startxref
    299
    %%EOF

PDF drawing
-----------

Most drawing in PDF is specified by the text of a stream, referred to
as a content stream. The syntax of the content stream is different
than the syntax of the file format described above and is much closer
to PostScript in nature. The commands in the content stream tell the
PDF interpreter to draw things, like a rectangle (`x y w h re`), an
image, or text, or to do meta operations like set the drawing color,
apply a transform to the drawing coordinates, or clip future drawing
operations. The page object that references a content stream has a
list of resources that can be used in the content stream using the
dictionary name to reference the resources. Resources are things like
font objects, images objects, graphic state objects (a set of meta
operations like miter limit, line width, etc). Because of a mismatch
between Skia and PDF's support for transparency (which will be
explained later), SkPDFDevice records each drawing operation into an
internal structure (ContentEntry) and only when the content stream is
needed does it flatten that list of structures into the final content
stream.

    4 0 obj <<
      /Type /Page
      /Resources <<
        /Font <</F1 9 0 R>>
        /XObject <</Image1 22 0 R /Image2 73 0 R>>
      >>
      /Content 5 0 R
    >> endobj

    5 0 obj <</Length 227>> stream
    % In the font specified in object 9 and a height
    % of 12 points, at (72, 96) draw 'Hello World.'
    BT
      /F1 12 Tf
      72 96 Td
      (Hello World) Tj
    ET
    % Draw a filled rectange.
    200 96 72 72 re B
    ...
    endstream
    endobj

Interned objects
----------------

There are a number of high level PDF objects (like fonts, graphic
states, etc) that are likely to be referenced multiple times in a
single PDF. To ensure that there is only one copy of each object
instance these objects an implemented with an
[interning pattern](http://en.wikipedia.org/wiki/String_interning).
As such, the classes representing these objects (like
SkPDFGraphicState) have private constructors and static methods to
retrieve an instance of the class. Internally, the class has a list of
unique instances that it consults before returning a new instance of
the class. If the requested instance already exists, the existing one
is returned. For obvious reasons, the returned instance should not be
modified. A mechanism to ensure that interned classes are immutable is
needed.  See [issue 2683](https://bug.skia.org/2683).

Graphic States
--------------

PDF has a number of parameters that affect how things are drawn. The
ones that correspond to drawing options in Skia are: color, alpha,
line cap, line join type, line width, miter limit, and xfer/blend mode
(see later section for xfer modes). With the exception of color, these
can all be specified in a single pdf object, represented by the
SkPDFGraphicState class. A simple command in the content stream can
then set the drawing parameters to the values specified in that
graphic state object. PDF does not allow specifying color in the
graphic state object, instead it must be specified directly in the
content stream. Similarly the current font and font size are set
directly in the content stream.

    6 0 obj <<
      /Type /ExtGState
      /CA 1  % Opaque - alpha = 1
      /LC 0  % Butt linecap
      /LJ 0  % Miter line-join
      /LW 2  % Line width of 2
      /ML 6  % Miter limit of 6
      /BM /Normal  % Blend mode is normal i.e. source over
    >>
    endobj

Clip and Transform
------------------

Similar to Skia, PDF allows drawing to be clipped or
transformed. However, there are a few caveats that affect the design
of the PDF backend. PDF does not support perspective transforms
(perspective transform are treated as identity transforms). Clips,
however, have more issues to cotend with. PDF clips cannot be directly
unapplied or expanded. i.e. once an area has been clipped off, there
is no way to draw to it. However, PDF provides a limited depth stack
for the PDF graphic state (which includes the drawing parameters
mentioned above in the Graphic States section as well as the clip and
transform). Therefore to undo a clip, the PDF graphic state must be
pushed before the clip is applied, then popped to revert to the state
of the graphic state before the clip was applied.

As the canvas makes drawing calls into SkPDFDevice, the active
transform, clip region, and clip stack are stored in a ContentEntry
structure. Later, when the ContentEntry structures are flattened into
a valid PDF content stream, the transforms and clips are compared to
decide on an efficient set of operations to transition between the
states needed. Currently, a local optimization is used, to figure out
the best transition from one state to the next. A global optimization
could improve things by more effectively using the graphics state
stack provided in the PDF format.

Generating a content stream
---------------------------

For each draw call on an SkPDFDevice, a new ContentEntry is created,
which stores the matrix, clip region, and clip stack as well as the
paint parameters. Most of the paint parameters are bundled into an
SkPDFGraphicState (interned) with the rest (color, font size, etc)
explicitly stored in the ContentEntry. After populating the
ContentEntry with all the relevant context, it is compared to the the
most recently used ContentEntry. If the context matches, then the
previous one is appended to instead of using the new one. In either
case, with the context populated into the ContentEntry, the
appropriate draw call is allowed to append to the content stream
snippet in the ContentEntry to affect the core of the drawing call,
i.e. drawing a shape, an image, text, etc.

When all drawing is complete, SkPDFDocument::emitPDF() will call
SkPDFDevice::content() to request the complete content stream for the
page. The first thing done is to apply the initial transform specified
in part in the constructor, this transform takes care of changing the
coordinate space from an origin in the lower left (PDF default) to the
upper left (Skia default) as well as any translation or scaling
requested by the user (i.e. to achieve a margin or scale the
canvas). Next (well almost next, see the next section), a clip is
applied to restrict drawing to the content area (the part of the page
inside the margins) of the page. Then, each ContentEntry is applied to
the content stream with the help of a helper class, GraphicStackState,
which tracks the state of the PDF graphics stack and optimizes the
output. For each ContentEntry, commands are emitted to the final
content entry to update the clip from its current state to the state
specified in the ContentEntry, similarly the Matrix and drawing state
(color, line joins, etc) are updated, then the content entry fragment
(the actual drawing operation) is appended.

Margins and content area
------------------------

The above procedure does not permit drawing in the margins. This is
done in order to contain any rendering problems in WebKit. In order to
support headers and footers, which are drawn in the margin, a second
set of ContentEntry's are maintained. The
methodSkPDFDevice::setDrawingArea() selects which set of
ContentEntry's are drawn into. Then, in the SkPDFDevice::content()
method, just before the clip to the content area is applied the margin
ContentEntry's are played back.

Drawing details
---------------

Certain objects have specific properties that need to be dealt
with. Images, layers (see below), and fonts assume the standard PDF
coordinate system, so we have to undo any flip to the Skia coordinate
system before drawing these entities. We don't currently support
inverted paths, so filling an inverted path will give the wrong result
([issue 241](https://bug.skia.org/241)). PDF doesn't draw zero length
lines that have butt of square caps, so that is emulated.

### Layers ###

PDF has a higher level object called a form x-object (form external
object) that is basically a PDF page, with resources and a content
stream, but can be transformed and drawn on an existing page. This is
used to implement layers. SkDevice has a method,
createFormXObjectFromDevice, which uses the SkPDFDevice::content()
method to construct a form x-object from the the
device. SkPDFDevice::drawDevice() works by creating a form x-object of
the passed device and then drawing that form x-object in the root
device. There are a couple things to be aware of in this process. As
noted previously, we have to be aware of any flip to the coordinate
system - flipping it an even number of times will lead to the wrong
result unless it is corrected for. The SkClipStack passed to drawing
commands includes the entire clip stack, including the clipping
operations done on the base layer. Since the form x-object will be
drawn as a single operation onto the base layer, we can assume that
all of those clips are in effect and need not apply them within the
layer.

### Fonts ###

There are many details for dealing with fonts, so this document will
only talk about some of the more important ones. A couple short
details:

*   We can't assume that an arbitrary font will be available at PDF view
    time, so we embed all fonts in accordance with modern PDF
    guidelines.
*   Most fonts these days are TrueType fonts, so this is where most of
    the effort has been concentrated.
*   Because Skia may only be given a glyph-id encoding of the text to
    render and there is no perfect way to reverse the encoding, the
    PDF backend always uses the glyph-id encoding of the text.

#### *Type1/Type3 fonts* ####

Linux supports Type1 fonts, but Windows and Mac seem to lack the
functionality required to extract the required information from the
font without parsing the font file. When a non TrueType font is used
any any platform (except for Type1 on Linux), it is encoded as a Type3
font. In this context, a Type3 font is an array of form x-objects
(content streams) that draw each glyph of the font. No hinting or
kerning information is included in a Type3 font, just the shape of
each glyph. Any font that has the do-not embed copy protection bit set
will also get embedded as a Type3 font. From what I understand, shapes
are not copyrightable, but programs are, so by stripping all the
programmatic information and only embedding the shape of the glyphs we
are honoring the do-not embed bit as much as required by law.

PDF only supports an 8-bit encoding for Type1 or Type3 fonts. However,
they can contain more than 256 glyphs. The PDF backend handles this by
segmenting the glyphs into groups of 255 (glyph id 0 is always the
unknown glyph) and presenting the font as multiple fonts, each with up
to 255 glyphs.

#### *Font subsetting* ####

Many fonts, especially fonts with CJK support are fairly large, so it
is desirable to subset them. Chrome uses the SFNTLY package to provide
subsetting support to Skia for TrueType fonts. However, there is a
conflict between font subsetting and interned objects. If the object
is immutable, how can it be subsetted? This conflict is resolved by
using a substitution mechanism in SkPDFCatalog. Font objects are still
interned, but the interned objects aren't internally
populated. Subsetting starts while drawing text to an SkPDFDevice; a
bit set indicating which glyphs have been used is maintained. Later,
when SkPDFDocument::emitPDF() is rendering the PDF, it queries each
device (each page) for the set of fonts used and the glyphs used from
each font and combines the information. It then asks the interned
(unpopulated) font objects to create a populated instance with the
calculated subset of the font - this instance is not interned. The
subsetted instance is then set as a substitute for the interned font
object in the SkPDFCatalog. All future references to those fonts
within that document will refer to the subsetted instances, resulting
in a final PDF with exactly one instance of each used font that
includes only the glyphs used.

The substitution mechanism is a little complicated, but is needed to
support the use case of an SkPDFDevice being added to multiple
documents. If fonts were subsetted in-situ, concurrent PDF generation
would have to be explicitly handled. Instead, by giving each document
its own subsetted instance, there is no need to worry about concurrent
PDF generation. The substitution method is also used to support
optional stream compression. A stream can used by different documents
in both a compressed and uncompressed form, leading to the same
potential difficulties faced by the concurrent font use case.

### Shaders ###

Skia has two types of predefined shaders, image shaders and gradient
shaders. In both cases, shaders are effectively positioned absolutely,
so the initial position and bounds of where they are visible is part
of the immutable state of the shader object. Each of the Skia's tile
modes needs to be considered and handled explicitly. The image shader
we generate will be tiled, so tiling is handled by default. To support
mirroring, we draw the image, reversed, on the appropriate axis, or on
both axes plus a fourth in the vacant quadrant. For clamp mode, we
extract the pixels along the appropriate edge and stretch the single
pixel wide/long image to fill the bounds. For both x and y in clamp
mode, we fill the corners with a rectangle of the appropriate
color. The composed shader is then rotated or scaled as appropriate
for the request.

Gradient shaders are handled purely mathematically. First, the matrix
is transformed so that specific points in the requested gradient are
at pre-defined locations, for example, the linear distance of the
gradient is always normalized to one. Then, a type 4 PDF function is
created that achieves the desired gradient. A type 4 function is a
function defined by a resticted postscript language. The generated
functions clamp at the edges so if the desired tiling mode is tile or
mirror, we hav to add a bit more postscript code to map any input
parameter into the 0-1 range appropriately. The code to generate the
postscript code is somewhat obtuse, since it is trying to generate
optimized (for space) postscript code, but there is a significant
number of comments to explain the intent.

### Xfer modes ###

PDF supports some of the xfer modes used in Skia directly. For those,
it is simply a matter of setting the blend mode in the graphic state
to the appropriate value (Normal/SrcOver, Multiply, Screen, Overlay,
Darken, Lighten, !ColorDOdge, ColorBurn, HardLight, SoftLight,
Difference, Exclusion). Aside from the standard SrcOver mode, PDF does
not directly support the porter-duff xfer modes though. Most of them
(Clear, SrcMode, DstMode, DstOver, SrcIn, DstIn, SrcOut, DstOut) can
be emulated by various means, mostly by creating form x-objects out of
part of the content and drawing it with a another form x-object as a
mask. I have not figured out how to emulate the following modes:
SrcATop, DstATop, Xor, Plus.

At the time of writing [2012-06-25], I have a [CL outstanding to fix a
misunderstanding I had about the meaning of some of the emulated
modes](https://codereview.appspot.com/4631078/).
I will describe the system with this change applied.

First, a bit of terminology and definition. When drawing something
with an emulated xfer mode, what's already drawn to the device is
called the destination or Dst, and what's about to be drawn is the
source or Src. Src (and Dst) can have regions where it is transparent
(alpha equals zero), but it also has an inherent shape. For most kinds
of drawn objects, the shape is the same as where alpha is not
zero. However, for things like images and layers, the shape is the
bounds of the item, not where the alpha is non-zero. For example, a
10x10 image, that is transparent except for a 1x1 dot in the center
has a shape that is 10x10. The xfermodes gm test demonstrates the
interaction between shape and alpha in combination with the port-duff
xfer modes.

The clear xfer mode removes any part of Dst that is within Src's
shape. This is accomplished by bundling the current content of the
device (Dst) into a single entity and then drawing that with the
inverse of Src's shape used as a mask (we want Dst where Src
isn't). The implementation of that takes a couple more steps. You may
have to refer back to [the content stream section](#Generating_a_content_stream). For any draw call, a
ContentEntry is created through a method called
SkPDFDevice::setUpContentEntry(). This method examines the xfer modes
in effect for that drawing operation and if it is an xfer mode that
needs emulation, it creates a form x-object from the device,
i.e. creates Dst, and stores it away for later use. This also clears
all of that existing ContentEntry's on that device. The drawing
operation is then allowed to proceed as normal (in most cases, see
note about shape below), but into the now empty device. Then, when the
drawing operation in done, a complementary method is
called,SkPDFDevice::finishContentEntry(), which takes action if the
current xfer mode is emulated. In the case of Clear, it packages what
was just drawn into another form x-object, and then uses the Src form
x-object, an invert function, and the Dst form x-object to draw Dst
with the inverse shape of Src as a mask. This works well when the
shape of Src is the same as the opaque part of the drawing, since PDF
uses the alpha channel of the mask form x-object to do masking. When
shape doesn't match the alpha channel, additional action is
required. The drawing routines where shape and alpha don't match, set
state to indicate the shape (always rectangular), which
finishContentEntry uses. The clear xfer mode is a special case; if
shape is needed, then Src isn't used, so there is code to not bother
drawing Src if shape is required and the xfer mode is clear.

SrcMode is clear plus Src being drawn afterward. DstMode simply omits
drawing Src. DstOver is the same as SrcOver with Src and Dst swapped -
this is accomplished by inserting the new ContentEntry at the
beginning of the list of ContentEntry's in setUpContentEntry instead
of at the end. SrcIn, SrcOut, DstIn, DstOut are similar to each, the
difference being an inverted or non-inverted mask and swapping Src and
Dst (or not). SrcIn is SrcMode with Src drawn with Dst as a
mask. SrcOut is like SrcMode, but with Src drawn with an inverted Dst
as a mask. DstIn is SrcMode with Dst drawn with Src as a
mask. Finally, DstOut is SrcMode with Dst draw with an inverted Src as
a mask.

Known issues
------------

*   [issue 241](https://bug.skia.org/241)
    As previously noted, a boolean geometry library
    would improve clip fidelity in some places, add supported for
    inverted fill types, as well as simplify code.
    This is fixed, but behind a flag until path ops is production ready.
*   [issue 237](https://bug.skia.org/237)
    SkMaskFilter is not supported.
*   [issue 238](https://bug.skia.org/238)
    SkColorFilter is not supported.
*   [issue 249](https://bug.skia.org/249)
    SrcAtop Xor, and Plus xfer modes are not supported.
*   [issue 240](https://bug.skia.org/240)
    drawVerticies is not implemented.
*   [issue 244](https://bug.skia.org/244)
    Mostly, only TTF fonts are directly supported.  (User metrics
    show that almost all fonts are truetype.
*   [issue 260](https://bug.skia.org/260)
    Page rotation is accomplished by specifying a different
    size page instead of including the appropriate rotation
    annotation.

* * *


text:
deps:
	git submodule init
	git submodule update
	npm install -d

build:
	mkdir -p build/js
	mkdir -p build/css
	./node_modules/.bin/uglifyjs --comments \
		-o build/js/bootstrap-datetimepicker.min.js \
	       	src/js/bootstrap-datetimepicker.js
	./node_modules/.bin/lessc \
	       	src/less/build.less \
	       	build/css/bootstrap-datetimepicker.css
	./node_modules/.bin/lessc -x \
	       	src/less/build.less \
	       	build/css/bootstrap-datetimepicker.min.css

clean:
	rm -rf build

.PHONY: deps build clean test


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

    <title>GradleProject (Gradle API 2.1)</title>
    <meta name="date" content="2014-09-08">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
    <link href="../../../../groovy.ico" type="image/x-icon" rel="icon">
    <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Summary:

            Nested   Field
Method

 | Detail:

            Field
Method

Package: org.gradle.tooling.model

[Java] Interface GradleProject

org.gradle.tooling.model.Model

All Superinterfaces:

BuildableElement, Element, HierarchicalElement, Model

 Represents a Gradle project.

Since:

1.0-milestone-5

Methods Summary

Methods

                            Type
                            Name and description

                            GradleProject
                            findByPath(String path)
Searches all descendants (children, grand-children, etc.), including self, by given path.

                            File
                            getBuildDirectory()
Returns the build directory for this project.

                            GradleScript
                            getBuildScript()
Returns the build script for this project.

                            DomainObjectSet<? extends GradleProject>
                            getChildren()
{@inheritDoc}

                            GradleProject
                            getParent()
{@inheritDoc}

                            String
                            getPath()
Returns the path of this project.

                            DomainObjectSet<? extends GradleTask>
                            getTasks()
{@inheritDoc}

Inherited Methods Summary

Inherited Methods

                            Methods inherited from class
                            Name

                            interface BuildableElement
                            getTasks

                            interface HierarchicalElement
                            getChildren, getParent

Method Detail

@Nullable
public GradleProject findByPath(String path)

 Searches all descendants (children, grand-children, etc.), including self, by given path.

Returns:

Gradle project with matching path or null if not found.

@Incubating
public File getBuildDirectory()

 Returns the build directory for this project.

Returns:

The build directory.

Since:

2.0

@Incubating
public GradleScript getBuildScript()

 Returns the build script for this project.

Returns:

The build script.

Since:

1.8

public DomainObjectSet<? extends GradleProject> getChildren()

 {@inheritDoc}

public GradleProject getParent()

 {@inheritDoc}

public String getPath()

 Returns the path of this project. This is a unique identifier for this project.

Returns:

The path.

public DomainObjectSet<? extends GradleTask> getTasks()

 {@inheritDoc}

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Summary:

            Nested   Field
Method

 | Detail:

            Field
Method

Gradle API 2.1


text: munging and loading of external datasets for system augmentation


text:
package gwt.material.design.demo.client.application.addins.timepickers;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Widget;
import com.gwtplatform.mvp.client.ViewImpl;
import gwt.material.design.addins.client.timepicker.MaterialTimePicker;
import gwt.material.design.client.ui.MaterialToast;

import javax.inject.Inject;
import java.util.Date;

public class TimePickersView extends ViewImpl implements TimePickersPresenter.MyView {
    interface Binder extends UiBinder<Widget, TimePickersView> {
    }

    @UiField
    MaterialTimePicker tpEvents, tpClear, tpOpenClose, tpValue  ;

    @Inject
    TimePickersView(Binder uiBinder) {
        initWidget(uiBinder.createAndBindUi(this));

        tpEvents.addOpenHandler(event -> MaterialToast.fireToast("Opened Time Picker"));
        tpEvents.addCloseHandler(event -> MaterialToast.fireToast("Closed Time Picker"));
        tpEvents.addValueChangeHandler(event -> {
            DateTimeFormat dtf = DateTimeFormat.getFormat("hh:mm a");
            Date time = event.getValue();
            MaterialToast.fireToast("MaterialTimePicker value changed to: " + dtf.format(time));
        });

        tpOpenClose.addOpenHandler(event -> MaterialToast.fireToast("Opened Time Picker"));
        tpOpenClose.addCloseHandler(event -> MaterialToast.fireToast("Closed Time Picker"));
        tpOpenClose.addValueChangeHandler(event -> {
            DateTimeFormat dtf = DateTimeFormat.getFormat("hh:mm a");
            Date time = event.getValue();
            MaterialToast.fireToast("MaterialTimePicker value changed to: " + dtf.format(time));
        });
    }

    @UiHandler("tpValue")
    void onTimePickerValue(ValueChangeEvent<Date> e) {
        DateTimeFormat dtf = DateTimeFormat.getFormat("hh:mm a");
        Date time = e.getValue();
        MaterialToast.fireToast("Value : " + dtf.format(time));
    }

    @UiHandler("btnTpValue")
    void btnTpValue(ClickEvent e) {
        tpValue.setValue(new Date());
    }

    @UiHandler("btnTpValueEvent")
    void btnTpValueEvent(ClickEvent e) {
        tpValue.setValue(new Date(), true);
    }

    @UiHandler("btnClear")
    void onClear(ClickEvent e){
        tpClear.clear();
    }

    @UiHandler("btnGetValue")
    void onGetValue(ClickEvent e) {
        MaterialToast.fireToast(tpClear.getValue() + "");
    }

    @UiHandler("btnOpen")
    void onOpen(ClickEvent e) {
        tpOpenClose.open();
    }
}


text:
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;

namespace Fungus
{
    /// <summary>
    /// Detects drag and drop interactions on a Game Object, and sends events to all Flowchart event handlers in the scene.
    /// The Game Object must have Collider2D & RigidBody components attached.
    /// The Collider2D must have the Is Trigger property set to true.
    /// The RigidBody would typically have the Is Kinematic property set to true, unless you want the object to move around using physics.
    /// Use in conjunction with the Drag Started, Drag Completed, Drag Cancelled, Drag Entered & Drag Exited event handlers.
    /// </summary>
    public class Draggable2D : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerEnterHandler, IPointerExitHandler
    {
        [Tooltip("Is object dragging enabled")]
        [SerializeField] protected bool dragEnabled = true;

        [Tooltip("Move object back to its starting position when drag is cancelled")]
        [FormerlySerializedAs("returnToStartPos")]
        [SerializeField] protected bool returnOnCancelled = true;

        [Tooltip("Move object back to its starting position when drag is completed")]
        [SerializeField] protected bool returnOnCompleted = true;

        [Tooltip("Time object takes to return to its starting position")]
        [SerializeField] protected float returnDuration = 1f;

        [Tooltip("Mouse texture to use when hovering mouse over object")]
        [SerializeField] protected Texture2D hoverCursor;

        [Tooltip("Use the UI Event System to check for drag events. Clicks that hit an overlapping UI object will be ignored. Camera must have a PhysicsRaycaster component, or a Physics2DRaycaster for 2D colliders.")]
        [SerializeField] protected bool useEventSystem;

        protected Vector3 startingPosition;
        protected bool updatePosition = false;
        protected Vector3 newPosition;
        protected Vector3 delta = Vector3.zero;

        protected virtual void LateUpdate()
        {
            // iTween will sometimes override the object position even if it should only be affecting the scale, rotation, etc.
            // To make sure this doesn't happen, we force the position change to happen in LateUpdate.
            if (updatePosition)
            {
                transform.position = newPosition;
                updatePosition = false;
            }
        }

        protected virtual void OnTriggerEnter2D(Collider2D other)
        {
            if (!dragEnabled)
            {
                return;
            }

            var dragEnteredHandlers = GetHandlers<DragEntered>();
            for (int i = 0; i < dragEnteredHandlers.Length; i++)
            {
                var handler = dragEnteredHandlers[i];
                handler.OnDragEntered(this, other);
            }

            var dragCompletedHandlers = GetHandlers<DragCompleted>();
            for (int i = 0; i < dragCompletedHandlers.Length; i++)
            {
                var handler = dragCompletedHandlers[i];
                handler.OnDragEntered(this, other);
            }
        }

        protected virtual void OnTriggerExit2D(Collider2D other)
        {
            if (!dragEnabled)
            {
                return;
            }

            var dragExitedHandlers = GetHandlers<DragExited>();
            for (int i = 0; i < dragExitedHandlers.Length; i++)
            {
                var handler = dragExitedHandlers[i];
                handler.OnDragExited(this, other);
            }

            var dragCompletedHandlers = GetHandlers<DragCompleted>();
            for (int i = 0; i < dragCompletedHandlers.Length; i++)
            {
                var handler = dragCompletedHandlers[i];
                handler.OnDragExited(this, other);
            }
        }

        protected virtual T[] GetHandlers<T>() where T : EventHandler
        {
            // TODO: Cache these object for faster lookup
            return GameObject.FindObjectsOfType<T>();
        }

        protected virtual void DoBeginDrag()
        {
            // Offset the object so that the drag is anchored to the exact point where the user clicked it
            float x = Input.mousePosition.x;
            float y = Input.mousePosition.y;
            delta = Camera.main.ScreenToWorldPoint(new Vector3(x, y, 10f)) - transform.position;
            delta.z = 0f;

            startingPosition = transform.position;

            var dragStartedHandlers = GetHandlers<DragStarted>();
            for (int i = 0; i < dragStartedHandlers.Length; i++)
            {
                var handler = dragStartedHandlers[i];
                handler.OnDragStarted(this);
            }
        }

        protected virtual void DoDrag()
        {
            if (!dragEnabled)
            {
                return;
            }

            float x = Input.mousePosition.x;
            float y = Input.mousePosition.y;
            float z = transform.position.z;

            newPosition = Camera.main.ScreenToWorldPoint(new Vector3(x, y, 10f)) - delta;
            newPosition.z = z;
            updatePosition = true;
        }

        protected virtual void DoEndDrag()
        {
            if (!dragEnabled)
            {
                return;
            }

            bool dragCompleted = false;

            var handlers = GetHandlers<DragCompleted>();
            for (int i = 0; i < handlers.Length; i++)
            {
                var handler = handlers[i];
                if (handler.DraggableObject == this)
                {
                    if (handler.IsOverTarget())
                    {
                        handler.OnDragCompleted(this);
                        dragCompleted = true;
                        if (returnOnCompleted)
                        {
                            LeanTween.move(gameObject, startingPosition, returnDuration).setEase(LeanTweenType.easeOutExpo);
                        }
                    }
                }
            }

            if (!dragCompleted)
            {
                var dragCancelledHandlers = GetHandlers<DragCancelled>();
                for (int i = 0; i < dragCancelledHandlers.Length; i++)
                {
                    var handler = dragCancelledHandlers[i];
                    handler.OnDragCancelled(this);
                }

                if (returnOnCancelled)
                {
                    LeanTween.move(gameObject, startingPosition, returnDuration).setEase(LeanTweenType.easeOutExpo);
                }
            }
        }

        protected virtual void DoPointerEnter()
        {
            ChangeCursor(hoverCursor);
        }

        protected virtual void DoPointerExit()
        {
            SetMouseCursor.ResetMouseCursor();
        }

        protected virtual void ChangeCursor(Texture2D cursorTexture)
        {
            if (!dragEnabled)
            {
                return;
            }

            Cursor.SetCursor(cursorTexture, Vector2.zero, CursorMode.Auto);
        }

        #region Legacy OnMouseX methods

        protected virtual void OnMouseDown()
        {
            if (!useEventSystem)
            {
                DoBeginDrag();
            }
        }

        protected virtual void OnMouseDrag()
        {
            if (!useEventSystem)
            {
                DoDrag();
            }
        }

        protected virtual void OnMouseUp()
        {
            if (!useEventSystem)
            {
                DoEndDrag();
            }
        }

        protected virtual void OnMouseEnter()
        {
            if (!useEventSystem)
            {
                DoPointerEnter();
            }
        }

        protected virtual void OnMouseExit()
        {
            if (!useEventSystem)
            {
                DoPointerExit();
            }
        }

        #endregion

        #region Public members

        /// <summary>
        /// Is object drag and drop enabled.
        /// </summary>
        /// <value><c>true</c> if drag enabled; otherwise, <c>false</c>.</value>
        public virtual bool DragEnabled { get { return dragEnabled; } set { dragEnabled = value; } }

        #endregion

        #region IBeginDragHandler implementation

        public void OnBeginDrag(PointerEventData eventData)
        {
            if (useEventSystem)
            {
                DoBeginDrag();
            }
        }

        #endregion

        #region IDragHandler implementation

        public void OnDrag(PointerEventData eventData)
        {
            if (useEventSystem)
            {
                DoDrag();
            }
        }

        #endregion

        #region IEndDragHandler implementation

        public void OnEndDrag(PointerEventData eventData)
        {
            if (useEventSystem)
            {
                DoEndDrag();
            }
        }

        #endregion

        #region IPointerEnterHandler implementation

        public void OnPointerEnter(PointerEventData eventData)
        {
            if (useEventSystem)
            {
                DoPointerEnter();
            }
        }

        #endregion

        #region IPointerExitHandler implementation

        public void OnPointerExit(PointerEventData eventData)
        {
            if (useEventSystem)
            {
                DoPointerExit();
            }
        }

        #endregion
    }
}