text:
<?php

namespace OpenCloud;

require_once __DIR__ . '/Globals.php';

use OpenCloud\Common\Base;
use OpenCloud\Common\Lang;
use OpenCloud\Common\Exceptions;
use OpenCloud\Common\ServiceCatalogItem;

/**
 * The OpenStack class represents a relationship (or "connection")
 * between a user and a service.
 *
 * This is the primary entry point into an OpenStack system, and the only one
 * where the developer is required to know and provide the endpoint URL (in
 * all other cases, the endpoint is derived from the Service Catalog provided
 * by the authentication system).
 *
 * Since various providers have different mechanisms for authentication, users
 * will often use a subclass of OpenStack. For example, the Rackspace
 * class is provided for users of Rackspace's cloud services, and other cloud
 * providers are welcome to add their own subclasses as well.
 *
 * General usage example:
 *
 *  $username = 'My Username';
 *  $secret = 'My Secret';
 *  $connection = new OpenCloud\OpenStack($username, $secret);
 *  // having established the connection, we can set some defaults
 *  // this sets the default name and region of the Compute service
 *  $connection->SetDefaults('Compute', 'cloudServersOpenStack', 'ORD');
 *  // access a Compute service
 *  $chicago = $connection->Compute();
 *  // if we want to access a different service, we can:
 *  $dallas = $connection->Compute('cloudServersOpenStack', 'DFW');
 *
 */
class OpenStack extends Base
{

    /**
     * This holds the HTTP User-Agent: used for all requests to the services. It
     * is public so that, if necessary, it can be entirely overridden by the
     * developer. However, it's strongly recomended that you use the
     * appendUserAgent() method to APPEND your own User Agent identifier to the
     * end of this string; the user agent information can be very valuable to
     * service providers to track who is using their service.
     *
     * @var string
     */
    public $useragent = RAXSDK_USER_AGENT;

    protected $url;
    protected $secret = array();
    protected $token;
    protected $expiration = 0;
    protected $tenant;
    protected $catalog;
    protected $connectTimeout = RAXSDK_CONNECTTIMEOUT;
    protected $httpTimeout = RAXSDK_TIMEOUT;
    protected $overlimitTimeout = RAXSDK_OVERLIMIT_TIMEOUT;

    /**
     * This associative array holds default values used to identify each
     * service (and to select it from the Service Catalog). Use the
     * Compute::SetDefaults() method to change the default values, or
     * define the global constants (for example, RAXSDK_COMPUTE_NAME)
     * BEFORE loading the OpenCloud library:
     *
     *
     * define('RAXSDK_COMPUTE_NAME', 'cloudServersOpenStack');
     * include('openstack.php');
     *
     */
    protected $defaults = array(
        'Compute' => array(
            'name'      => RAXSDK_COMPUTE_NAME,
            'region'    => RAXSDK_COMPUTE_REGION,
            'urltype'   => RAXSDK_COMPUTE_URLTYPE
        ),
        'ObjectStore' => array(
            'name'      => RAXSDK_OBJSTORE_NAME,
            'region'    => RAXSDK_OBJSTORE_REGION,
            'urltype'   => RAXSDK_OBJSTORE_URLTYPE
        ),
        'Database' => array(
            'name'      => RAXSDK_DATABASE_NAME,
            'region'    => RAXSDK_DATABASE_REGION,
            'urltype'   => RAXSDK_DATABASE_URLTYPE
        ),
        'Volume' => array(
            'name'      => RAXSDK_VOLUME_NAME,
            'region'    => RAXSDK_VOLUME_REGION,
            'urltype'   => RAXSDK_VOLUME_URLTYPE
        ),
        'LoadBalancer' => array(
            'name'      => RAXSDK_LBSERVICE_NAME,
            'region'    => RAXSDK_LBSERVICE_REGION,
            'urltype'   => RAXSDK_LBSERVICE_URLTYPE
        ),
        'DNS' => array(
            'name'      => RAXSDK_DNS_NAME,
            'region'    => RAXSDK_DNS_REGION,
            'urltype'   => RAXSDK_DNS_URLTYPE
        ),
        'Orchestration' => array(
            'name'      => RAXSDK_ORCHESTRATION_NAME,
            'region'    => RAXSDK_ORCHESTRATION_REGION,
            'urltype'   => RAXSDK_ORCHESTRATION_URLTYPE
        ),
        'CloudMonitoring' => array(
            'name'      => RAXSDK_MONITORING_NAME,
            'region'    => RAXSDK_MONITORING_REGION,
            'urltype'   => RAXSDK_MONITORING_URLTYPE
        ),
        'Autoscale' => array(
        	'name'		=> RAXSDK_AUTOSCALE_NAME,
        	'region'	=> RAXSDK_AUTOSCALE_REGION,
        	'urltype'	=> RAXSDK_AUTOSCALE_URLTYPE
        )
    );

    private $_user_write_progress_callback_func;
    private $_user_read_progress_callback_func;

    /**
     * Tracks file descriptors used by streaming downloads
     *
     * This will permit multiple simultaneous streaming downloads; the
     * key is the URL of the object, and the value is its file descriptor.
     *
     * To prevent memory overflows, each array element is deleted when
     * the end of the file is reached.
     */
    private $fileDescriptors = array();

    /**
     * array of options to pass to the CURL request object
     */
    private $curlOptions = array();

    /**
     * list of attributes to export/import
     */
    private $exportItems = array(
        'token',
        'expiration',
        'tenant',
        'catalog'
    );

    /**
     * Creates a new OpenStack object
     *
     * The OpenStack object needs two bits of information: the URL to
     * authenticate against, and a "secret", which is an associative array
     * of name/value pairs. Usually, the secret will be a username and a
     * password, but other values may be required by different authentication
     * systems. For example, OpenStack Keystone requires a username and
     * password, but Rackspace uses a username, tenant ID, and API key.
     * (See OpenCloud\Rackspace for that.)
     *
     * @param string $url - the authentication endpoint URL
     * @param array $secret - an associative array of auth information:
     * * username
     * * password
     * @param array $options - CURL options to pass to the HttpRequest object
     */
    public function __construct($url, array $secret, array $options = array())
    {
    	// check for supported version
        // @codeCoverageIgnoreStart
        $version = phpversion();
    	if ($version < '5.3.1') {
    		throw new Exceptions\UnsupportedVersionError(sprintf(
                Lang::translate('PHP version [%s] is not supported'),
                $version
            ));
        }
        // @codeCoverageIgnoreEnd

    	// Start processing
        $this->getLogger()->info(Lang::translate('Initializing OpenStack client'));

        // Set properties
        $this->setUrl($url);
        $this->setSecret($secret);
        $this->setCurlOptions($options);
    }

    /**
     * Set user agent.
     *
     * @param  string $useragent
     * @return OpenCloud\OpenStack
     */
    public function setUserAgent($useragent)
    {
        $this->useragent = $useragent;

        return $this;
    }

    /**
     * Allows the user to append a user agent string
     *
     * Programs that are using these bindings are encouraged to add their
     * user agent to the one supplied by this SDK. This will permit cloud
     * providers to track users so that they can provide better service.
     *
     * @param string $agent an arbitrary user-agent string; e.g. "My Cloud App"
     * @return OpenCloud\OpenStack
     */
    public function appendUserAgent($useragent)
    {
        $this->useragent .= ';' . $useragent;

        return $this;
    }

    /**
     * Get user agent.
     *
     * @return string
     */
    public function getUserAgent()
    {
        return $this->useragent;
    }

    /**
     * Sets the URL which the client will access.
     *
     * @param string $url
     * @return OpenCloud\OpenStack
     */
    public function setUrl($url)
    {
        $this->url = $url;

        return $this;
    }

    /**
     * Get the URL.
     *
     * @return string
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * Set the secret for the client.
     *
     * @param  array $secret
     * @return OpenCloud\OpenStack
     */
    public function setSecret(array $secret = array())
    {
        $this->secret = $secret;

        return $this;
    }

    /**
     * Get the secret.
     *
     * @return array
     */
    public function getSecret()
    {
        return $this->secret;
    }

    /**
     * Set the token for this client.
     *
     * @param  string $token
     * @return OpenCloud\OpenStack
     */
    public function setToken($token)
    {
        $this->token = $token;

        return $this;
    }

    /**
     * Get the token for this client.
     *
     * @return string
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * Set the expiration for this token.
     *
     * @param  int $expiration
     * @return OpenCloud\OpenStack
     */
    public function setExpiration($expiration)
    {
        $this->expiration = $expiration;

        return $this;
    }

    /**
     * Get the expiration time.
     *
     * @return int
     */
    public function getExpiration()
    {
        return $this->expiration;
    }

    /**
     * Set the tenant for this client.
     *
     * @param  string $tenant
     * @return OpenCloud\OpenStack
     */
    public function setTenant($tenant)
    {
        $this->tenant = $tenant;

        return $this;
    }

    /**
     * Get the tenant for this client.
     *
     * @return string
     */
    public function getTenant()
    {
        return $this->tenant;
    }

    /**
     * Set the service catalog.
     *
     * @param  mixed $catalog
     * @return OpenCloud\OpenStack
     */
    public function setCatalog($catalog)
    {
        $this->catalog = $catalog;

        return $this;
    }

    /**
     * Get the service catalog.
     *
     * @return array
     */
    public function getCatalog()
    {
        return $this->catalog;
    }

    /**
     * Set (all) the cURL options.
     *
     * @param  array $options
     * @return OpenCloud\OpenStack
     */
    public function setCurlOptions(array $options)
    {
        $this->curlOptions = $options;

        return $this;
    }

    /**
     * Get the cURL options.
     *
     * @return array
     */
    public function getCurlOptions()
    {
        return $this->curlOptions;
    }

    /**
     * Set a specific file descriptor (associated with a URL)
     *
     * @param  string $key
     * @param  resource $value
     * @return OpenCloud\OpenStack
     */
    public function setFileDescriptor($key, $value)
    {
        $this->descriptors[$key] = $value;

        return $this;
    }

    /**
     * Get a specific file descriptor (associated with a URL)
     *
     * @param  string $key
     * @return resource|false
     */
    public function getFileDescriptor($key)
    {
        return (!isset($this->descriptors[$key])) ? false : $this->descriptors[$key];
    }

    /**
     * Get the items to be exported.
     *
     * @return array
     */
    public function getExportItems()
    {
        return $this->exportItems;
    }

    /**
     * Sets the connect timeout.
     *
     * @param  int $timeout
     * @return OpenCloud\OpenStack
     */
    public function setConnectTimeout($timeout)
    {
        $this->connectTimeout = $timeout;

        return $this;
    }

    /**
     * Get the connect timeout.
     *
     * @return int
     */
    public function getConnectTimeout()
    {
        return $this->connectTimeout;
    }

    /**
     * Set the HTTP timeout.
     *
     * @param  int $timeout
     * @return OpenCloud\OpenStack
     */
    public function setHttpTimeout($timeout)
    {
        $this->httpTimeout = $timeout;

        return $this;
    }

    /**
     * Get the HTTP timeout.
     *
     * @return int
     */
    public function getHttpTimeout()
    {
        return $this->httpTimeout;
    }

    /**
     * Set the overlimit timeout.
     *
     * @param  int $timeout
     * @return OpenCloud\OpenStack
     */
    public function setOverlimitTimeout($timeout)
    {
        $this->overlimitTimeout = $timeout;

        return $this;
    }

    /**
     * Get the overlimit timeout.
     *
     * @return int
     */
    public function getOverlimitTimeout()
    {
        return $this->overlimitTimeout;
    }

    /**
     * Sets default values (an array) for a service. Each array must contain a
     * "name", "region" and "urltype" key.
     *
     * @param string $service
     * @param array $value
     * @return OpenCloud\OpenStack
     */
    public function setDefault($service, array $value = array())
    {
        if (isset($value['name']) && isset($value['region']) && isset($value['urltype'])) {
            $this->defaults[$service] = $value;
        }

        return $this;
    }

    /**
     * Get a specific default value for a service. If none exist, return FALSE.
     *
     * @param  string $service
     * @return array|false
     */
    public function getDefault($service)
    {
        return (!isset($this->defaults[$service])) ? false : $this->defaults[$service];
    }

/**
     * Sets the timeouts for the current connection
     *
     * @api
     * @param integer $t_http the HTTP timeout value (the max period that
     *      the OpenStack object will wait for any HTTP request to complete).
     *      Value is in seconds.
     * @param integer $t_conn the Connect timeout value (the max period
     *      that the OpenStack object will wait to establish an HTTP
     *      connection). Value is in seconds.
     * @param integer $t_overlimit the overlimit timeout value (the max period
     *      that the OpenStack object will wait to retry on an overlimit
     *      condition). Value is in seconds.
     * @return void
     */
    public function setTimeouts($httpTimeout, $connectTimeout = null, $overlimitTimeout = null)
    {
        $this->setHttpTimeout($httpTimeout);

        if (isset($connectTimeout)) {
            $this->setConnectTimeout($connectTimeout);
        }

        if (isset($overlimitTimeout)) {
            $this->setOverlimitTimeout($overlimitTimeout);
        }
    }

    /**
     * Returns the URL of this object
     *
     * @api
     * @param string $subresource specified subresource
     * @return string
     */
    public function url($subresource='tokens')
    {
        return Lang::noslash($this->url) . '/' . $subresource;
    }

    /**
     * Returns the stored secret
     *
     * @return array
     */
    public function secret()
    {
        return $this->getSecret();
    }

    /**
     * Re-authenticates session if expired.
     */
    public function checkExpiration()
    {
        if ($this->hasExpired()) {
            $this->authenticate();
        }
    }

    /**
     * Checks whether token has expired.
     *
     * @return bool
     */
    public function hasExpired()
    {
        return time() > ($this->getExpiration() - RAXSDK_FUDGE);
    }

    /**
     * Returns the cached token; if it has expired, then it re-authenticates
     *
     * @api
     * @return string
     */
    public function token()
    {
        $this->checkExpiration();

        return $this->getToken();
    }

    /**
     * Returns the cached expiration time;
     * if it has expired, then it re-authenticates
     *
     * @api
     * @return string
     */
    public function expiration()
    {
        $this->checkExpiration();

        return $this->getExpiration();
    }

    /**
     * Returns the tenant ID, re-authenticating if necessary
     *
     * @api
     * @return string
     */
    public function tenant()
    {
        $this->checkExpiration();

        return $this->getTenant();
    }

    /**
     * Returns the service catalog object from the auth service
     *
     * @return \stdClass
     */
    public function serviceCatalog()
    {
        $this->checkExpiration();

        return $this->getCatalog();
    }

    /**
     * Returns a Collection of objects with information on services
     *
     * Note that these are informational (read-only) and are not actually
     * 'Service'-class objects.
     */
    public function serviceList()
    {
        return new Common\Collection($this, 'ServiceCatalogItem', $this->serviceCatalog());
    }

    /**
     * Creates and returns the formatted credentials to POST to the auth
     * service.
     *
     * @return string
     */
    public function credentials()
    {
        if (isset($this->secret['username']) && isset($this->secret['password'])) {

            $credentials = array(
                'auth' => array(
                    'passwordCredentials' => array(
                        'username' => $this->secret['username'],
                        'password' => $this->secret['password']
                    )
                )
            );

            if (isset($this->secret['tenantName'])) {
                $credentials['auth']['tenantName'] = $this->secret['tenantName'];
            }

            return json_encode($credentials);

        } else {
            throw new Exceptions\CredentialError(
               Lang::translate('Unrecognized credential secret')
            );
        }
    }

    /**
     * Authenticates using the supplied credentials
     *
     * @api
     * @return void
     * @throws AuthenticationError
     */
    public function authenticate()
    {
        // try to auth
        $response = $this->request(
            $this->url(),
            'POST',
            array('Content-Type'=>'application/json'),
            $this->credentials()
        );

        $json = $response->httpBody();

        // check for errors
        if ($response->HttpStatus() >= 400) {
            throw new Exceptions\AuthenticationError(sprintf(
                Lang::translate('Authentication failure, status [%d], response [%s]'),
                $response->httpStatus(),
                $json
            ));
        }

        // Decode and check
        $object = json_decode($json);
        $this->checkJsonError();

        // Save the token information as well as the ServiceCatalog
        $this->setToken($object->access->token->id);
        $this->setExpiration(strtotime($object->access->token->expires));
        $this->setCatalog($object->access->serviceCatalog);

        /**
         * In some cases, the tenant name/id is not returned
         * as part of the auth token, so we check for it before
         * we set it. This occurs with pure Keystone, but not
         * with the Rackspace auth.
         */
        if (isset($object->access->token->tenant)) {
            $this->setTenant($object->access->token->tenant->id);
        }
    }

    /**
     * Performs a single HTTP request
     *
     * The request() method is one of the most frequently-used in the entire
     * library. It performs an HTTP request using the specified URL, method,
     * and with the supplied headers and body. It handles error and
     * exceptions for the request.
     *
     * @api
     * @param string url - the URL of the request
     * @param string method - the HTTP method (defaults to GET)
     * @param array headers - an associative array of headers
     * @param string data - either a string or a resource (file pointer) to
     *      use as the request body (for PUT or POST)
     * @return HttpResponse object
     * @throws HttpOverLimitError, HttpUnauthorizedError, HttpForbiddenError
     */
    public function request($url, $method = 'GET', $headers = array(), $data = null)
    {
        $this->getLogger()->info('Resource [{url}] method [{method}] body [{body}]', array(
            'url'    => $url,
            'method' => $method,
            'data'   => $data
        ));

        // get the request object
        $http = $this->getHttpRequestObject($url, $method, $this->getCurlOptions());

        // set various options
        $this->getLogger()->info('Headers: [{headers}]', array(
            'headers' => print_r($headers, true)
        ));

        $http->setheaders($headers);
        $http->setHttpTimeout($this->getHttpTimeout());
        $http->setConnectTimeout($this->getConnectTimeout());
        $http->setOption(CURLOPT_USERAGENT, $this->getUserAgent());

        // data can be either a resource or a string
        if (is_resource($data)) {
            // loading from or writing to a file
            // set the appropriate callback functions
            switch($method) {
                // @codeCoverageIgnoreStart
                case 'GET':
                    // need to save the file descriptor
                    $this->setFileDescriptor($url, $data);
                    // set the CURL options
                    $http->setOption(CURLOPT_FILE, $data);
                    $http->setOption(CURLOPT_WRITEFUNCTION, array($this, '_write_cb'));
                    break;
                // @codeCoverageIgnoreEnd
                case 'PUT':
                case 'POST':
                    // need to save the file descriptor
                    $this->setFileDescriptor($url, $data);
                    if (!isset($headers['Content-Length'])) {
                        throw new Exceptions\HttpError(
                            Lang::translate('The Content-Length: header must be specified for file uploads')
                        );
                    }
                    $http->setOption(CURLOPT_UPLOAD, TRUE);
                    $http->setOption(CURLOPT_INFILE, $data);
                    $http->setOption(CURLOPT_INFILESIZE, $headers['Content-Length']);
                    $http->setOption(CURLOPT_READFUNCTION, array($this, '_read_cb'));
                    break;
                default:
                    // do nothing
                    break;
            }
        } elseif (is_string($data)) {
            $http->setOption(CURLOPT_POSTFIELDS, $data);
        } elseif (isset($data)) {
            throw new Exceptions\HttpError(
                Lang::translate('Unrecognized data type for PUT/POST body, must be string or resource')
            );
        }

        // perform the HTTP request; returns an HttpResult object
        $response = $http->execute();

        // handle and retry on overlimit errors
        if ($response->httpStatus() == 413) {

            $object = json_decode($response->httpBody());
            $this->checkJsonError();

            // @codeCoverageIgnoreStart
            if (isset($object->overLimit)) {
                /**
                 * @TODO(glen) - The documentation says "retryAt", but
                 * the field returned is "retryAfter". If the doc changes,
                 * then there's no problem, but we'll need to fix this if
                 * they change the code to match the docs.
                 */
                $retryAfter    = $object->overLimit->retryAfter;
                $sleepInterval = strtotime($retryAfter) - time();

                if ($sleepInterval && $sleepInterval <= $this->getOverlimitTimeout()) {
                    sleep($sleepInterval);
                    $response = $http->Execute();
                } else {
                    throw new Exceptions\HttpOverLimitError(sprintf(
                        Lang::translate('Over limit; next available request [%s][%s] is not for [%d] seconds at [%s]'),
                        $method,
                        $url,
                        $sleepInterval,
                        $retryAfter
                    ));
                }
            }
            // @codeCoverageIgnoreEnd
        }

        // do some common error checking
        switch ($response->httpStatus()) {
            case 401:
                throw new Exceptions\HttpUnauthorizedError(sprintf(
                    Lang::translate('401 Unauthorized for [%s] [%s]'),
                    $url,
                    $response->HttpBody()
                ));
                break;
            case 403:
                throw new Exceptions\HttpForbiddenError(sprintf(
                    Lang::translate('403 Forbidden for [%s] [%s]'),
                    $url,
                    $response->HttpBody()
                ));
                break;
            case 413:   // limit
                throw new Exceptions\HttpOverLimitError(sprintf(
                    Lang::translate('413 Over limit for [%s] [%s]'),
                    $url,
                    $response->HttpBody()
                ));
                break;
            default:
                // everything is fine here, we're fine, how are you?
                break;
        }

        // free the handle
        $http->close();

        // return the HttpResponse object
        $this->getLogger()->info('HTTP STATUS [{code}]', array(
            'code' => $response->httpStatus()
        ));

        return $response;
    }

    /**
     * Sets default values for name, region, URL type for a service
     *
     * Once these are set (and they can also be set by defining global
     * constants), then you do not need to specify these values when
     * creating new service objects.
     *
     * @api
     * @param string $service the name of a supported service; e.g. 'Compute'
     * @param string $name the service name; e.g., 'cloudServersOpenStack'
     * @param string $region the region name; e.g., 'LON'
     * @param string $urltype the type of URL to use; e.g., 'internalURL'
     * @return void
     * @throws UnrecognizedServiceError
     */
    public function setDefaults(
        $service,
        $name = null,
        $region = null,
        $urltype = null
    ) {

        if (!isset($this->defaults[$service])) {
            throw new Exceptions\UnrecognizedServiceError(sprintf(
                Lang::translate('Service [%s] is not recognized'), $service
            ));
        }

        if (isset($name)) {
            $this->defaults[$service]['name'] = $name;
        }

        if (isset($region)) {
            $this->defaults[$service]['region'] = $region;
        }

        if (isset($urltype)) {
            $this->defaults[$service]['urltype'] = $urltype;
        }
    }

    /**
     * Allows the user to define a function for tracking uploads
     *
     * This can be used to implement a progress bar or similar function. The
     * callback function is called with a single parameter, the length of the
     * data that is being uploaded on this call.
     *
     * @param callable $callback the name of a global callback function, or an
     *      array($object, $functionname)
     * @return void
     */
    public function setUploadProgressCallback($callback)
    {
        $this->_user_write_progress_callback_func = $callback;
    }

    /**
     * Allows the user to define a function for tracking downloads
     *
     * This can be used to implement a progress bar or similar function. The
     * callback function is called with a single parameter, the length of the
     * data that is being downloaded on this call.
     *
     * @param callable $callback the name of a global callback function, or an
     *      array($object, $functionname)
     * @return void
     */
    public function setDownloadProgressCallback($callback)
    {
        $this->_user_read_progress_callback_func = $callback;
    }

    /**
     * Callback function to handle reads for file uploads
     *
     * Internal function for handling file uploads. Note that, although this
     * function's visibility is public, this is only because it must be called
     * from the HttpRequest interface. This should NOT be called by users
     * directly.
     *
     * @param resource $ch a CURL handle
     * @param resource $fd a file descriptor
     * @param integer $length the amount of data to read
     * @return string the data read
     * @codeCoverageIgnore
     */
    public function _read_cb($ch, $fd, $length)
    {
        $data = fread($fd, $length);
        $len = strlen($data);
        if (isset($this->_user_write_progress_callback_func)) {
            call_user_func($this->_user_write_progress_callback_func, $len);
        }
        return $data;
    }

    /**
     * Callback function to handle writes for file downloads
     *
     * Internal function for handling file downloads. Note that, although this
     * function's visibility is public, this is only because it must be called
     * via the HttpRequest interface. This should NOT be called by users
     * directly.
     *
     * @param resource $ch a CURL handle
     * @param string $data the data to be written to a file
     * @return integer the number of bytes written
     * @codeCoverageIgnore
     */
    public function _write_cb($ch, $data)
    {
        $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

        if (false === ($fp = $this->getFileDescriptor($url))) {
            throw new Exceptions\HttpUrlError(sprintf(
                Lang::translate('Cannot find file descriptor for URL [%s]'), $url)
            );
        }

        $dlen = strlen($data);
        fwrite($fp, $data, $dlen);

        // call used callback function
        if (isset($this->_user_read_progress_callback_func)) {
            call_user_func($this->_user_read_progress_callback_func, $dlen);
        }

        // MUST return the length to CURL
        return $dlen;
    }

    /**
     * exports saved token, expiration, tenant, and service catalog as an array
     *
     * This could be stored in a cache (APC or disk file) and reloaded using
     * ImportCredentials()
     *
     * @return array
     */
    public function exportCredentials()
    {
    	$this->authenticate();

        $array = array();

        foreach ($this->getExportItems() as $key) {
            $array[$key] = $this->$key;
        }

        return $array;
    }

    /**
     * imports credentials from an array
     *
     * Takes the same values as ExportCredentials() and reuses them.
     *
     * @return void
     */
    public function importCredentials(array $values)
    {
        foreach ($this->getExportItems() as $item) {
            $this->$item = $values[$item];
        }
    }

    /********** FACTORY METHODS **********
     *
     * These methods are provided to permit easy creation of services
     * (for example, Nova or Swift) from a connection object. As new
     * services are supported, factory methods should be provided here.
     */

    /**
     * Creates a new ObjectStore object (Swift/Cloud Files)
     *
     * @api
     * @param string $name the name of the Object Storage service to attach to
     * @param string $region the name of the region to use
     * @param string $urltype the URL type (normally "publicURL")
     * @return ObjectStore
     */
    public function objectStore($name = null, $region = null, $urltype = null)
    {
        return $this->service('ObjectStore', $name, $region, $urltype);
    }

    /**
     * Creates a new Compute object (Nova/Cloud Servers)
     *
     * @api
     * @param string $name the name of the Compute service to attach to
     * @param string $region the name of the region to use
     * @param string $urltype the URL type (normally "publicURL")
     * @return Compute
     */
    public function compute($name = null, $region = null, $urltype = null)
    {
        return $this->service('Compute', $name, $region, $urltype);
    }

    /**
     * Creates a new Orchestration (heat) service object
     *
     * @api
     * @param string $name the name of the Compute service to attach to
     * @param string $region the name of the region to use
     * @param string $urltype the URL type (normally "publicURL")
     * @return Orchestration\Service
     * @codeCoverageIgnore
     */
    public function orchestration($name = null, $region = null, $urltype = null)
    {
        return $this->service('Orchestration', $name, $region, $urltype);
    }

    /**
     * Creates a new VolumeService (cinder) service object
     *
     * This is a factory method that is Rackspace-only (NOT part of OpenStack).
     *
     * @param string $name the name of the service (e.g., 'cloudBlockStorage')
     * @param string $region the region (e.g., 'DFW')
     * @param string $urltype the type of URL (e.g., 'publicURL');
     */
    public function volumeService($name = null, $region = null, $urltype = null)
    {
        return $this->service('Volume', $name, $region, $urltype);
    }

    /**
     * Generic Service factory method
     *
     * Contains code reused by the other service factory methods.
     *
     * @param string $class the name of the Service class to produce
     * @param string $name the name of the Compute service to attach to
     * @param string $region the name of the region to use
     * @param string $urltype the URL type (normally "publicURL")
     * @return Service (or subclass such as Compute, ObjectStore)
     * @throws ServiceValueError
     */
    public function service($class, $name = null, $region = null, $urltype = null)
    {
        // debug message
        $this->getLogger()->info('Factory for class [{class}] [{name}/{region}/{urlType}]', array(
            'class'   => $class,
            'name'    => $name,
            'region'  => $region,
            'urlType' => $urltype
        ));

        // Strips off base namespace
        $class = preg_replace('#\\\?OpenCloud\\\#', '', $class);

        // check for defaults
        $default = $this->getDefault($class);

        // report errors
        if (!$name = $name ?: $default['name']) {
            throw new Exceptions\ServiceValueError(sprintf(
                Lang::translate('No value for %s name'),
                $class
            ));
        }

        if (!$region = $region ?: $default['region']) {
            throw new Exceptions\ServiceValueError(sprintf(
                Lang::translate('No value for %s region'),
                $class
            ));
        }

        if (!$urltype = $urltype ?: $default['urltype']) {
            throw new Exceptions\ServiceValueError(sprintf(
                Lang::translate('No value for %s URL type'),
                $class
            ));
        }

        // return the object
        $fullclass = 'OpenCloud\\' . $class . '\\Service';

        return new $fullclass($this, $name, $region, $urltype);
    }

    /**
     * returns a service catalog item
     *
     * This is a helper function used to list service catalog items easily
     */
    public function serviceCatalogItem($info = array())
    {
        return new ServiceCatalogItem($info);
    }

}


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

namespace Piranha.Manager.Models.Post
{
	/// <summary>
	/// View model for the post list.
	/// </summary>
	public class ListModel
	{
		#region Inner classes
		/// <summary>
		/// An item in the post list.
		/// </summary>
		public class PostListItem
		{
			/// <summary>
			/// Gets/sets the unique id.
			/// </summary>
			public Guid Id { get; set; }

			/// <summary>
			/// Gets/sets the title.
			/// </summary>
			public string Title { get; set; }

			/// <summary>
			/// Gets/sets the name of the post type.
			/// </summary>
			public string Type { get; set; }

			/// <summary>
			/// Gets/sets the date the post was initially created.
			/// </summary>
			public DateTime Created { get; set; }

			/// <summary>
			/// Gets/sets the date the post was last updated.
			/// </summary>
			public DateTime Updated { get; set; }

			/// <summary>
			/// Gets/sets the published date.
			/// </summary>
			public DateTime? Published { get; set; }
		}

		/// <summary>
		/// An item in the post type list.
		/// </summary>
		public class PostTypeListItem
		{
			/// <summary>
			/// Gets/sets the display name.
			/// </summary>
			public string Name { get; set; }

			/// <summary>
			/// Gets/sets the unique slug.
			/// </summary>
			public string Slug { get; set; }

			/// <summary>
			/// Gets/sets if this is the currently selected post type.
			/// </summary>
			public bool IsActive { get; set; }
		}
		#endregion

		#region Properties
		/// <summary>
		/// Gets/sets the available items.
		/// </summary>
		public IList<PostListItem> Items { get; set; }

		/// <summary>
		/// Gets/sets the available post types.
		/// </summary>
		public IList<PostTypeListItem> PostTypes { get; set; }

		/// <summary>
		/// Gets/sets if no specific post type has been selected.
		/// </summary>
		public bool IsDefaultSelection { get; set; }
		#endregion

		/// <summary>
		/// Default constructor.
		/// </summary>
		public ListModel() {
			Items = new List<PostListItem>();
			PostTypes = new List<PostTypeListItem>();
			IsDefaultSelection = true;
		}

		/// <summary>
		/// Gets the post list model.
		/// </summary>
		/// <param name="slug">Optional post type slug</param>
		/// <returns>The model</returns>
		public static ListModel Get(string slug = null) {
			using (var api = new Api()) {
				var m = new ListModel();

				if (!String.IsNullOrWhiteSpace(slug)) {
					m.Items = api.Posts.Get(where: p => p.Type.Slug == slug).Select(p => new PostListItem() {
						Id = p.Id,
						Title = p.Title,
						Type = p.Type.Name,
						Created = p.Created,
						Updated = p.Updated,
						Published = p.Published
					}).ToList();
					m.IsDefaultSelection = false;
				} else {
					m.Items = api.Posts.Get().Select(p => new PostListItem() {
						Id = p.Id,
						Title = p.Title,
						Type = p.Type.Name,
						Created = p.Created,
						Updated = p.Updated,
						Published = p.Published
					}).ToList();
				}
				m.PostTypes = api.PostTypes.Get().Select(t => new PostTypeListItem() {
					Name = t.Name,
					Slug = t.Slug,
					IsActive = t.Slug == slug
				}).ToList();
				return m;
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
The current major version of Benthos continually receives security updates. We recommend that users maintain a reasonable upgrade plan that follows current releases of Benthos.

| Version | Supported          |
| ------- | ------------------ |
| 3.x   | :white_check_mark: |
| < 3.0   | :x:                |

## Reporting a Vulnerability

If you have found or suspect to have found a vulnerability in Benthos then please proceed to report it to security@benthos.dev.

Please note, we do not operate a bug bounty program. However, we deeply appreciate any contributions that guide us towards building a better and safer project.


text:
package main

import (
	"bufio"
	"errors"
	"io/ioutil"
	"os"
	"strings"
	"time"

	"github.com/tarm/serial"
)

const (
	ArduinoSerialBaud int = 115200
)

type ArduinoSerial struct {
	Serial *serial.Port
}

func NewArduinoSerial() (*ArduinoSerial, error) {
	a := &ArduinoSerial{}
	if err := a.initArduinoSerial(); err != nil {
		return nil, err
	}
	return a, nil
}

func (a *ArduinoSerial) initArduinoSerial() error {
	device, err := a.findArduino()
	if err != nil {
		return err
	}
	ser, err := serial.OpenPort(&serial.Config{
		Name: device,
		Baud: ArduinoSerialBaud,
	})
	if err != nil {
		return err
	}
	time.Sleep(time.Second * 1)
	a.Serial = ser
	return nil
}

func (a *ArduinoSerial) findArduino() (string, error) {
	devices, _ := ioutil.ReadDir("/dev")
	for _, d := range devices {
		if a.isArduino(d.Name()) {
			return "/dev/" + d.Name(), nil
		}
	}
	return "", errors.New("Cannot find Arduino device.")
}

func (a *ArduinoSerial) isArduino(device string) bool {
	return strings.Contains(device, "ttyACM") ||
		strings.Contains(device, "tty.usbmodem") ||
		strings.Contains(device, "tty.usbserial") ||
		strings.Contains(device, "ttyUSB")
}

func (a *ArduinoSerial) Listen() <-chan string {
	output := make(chan string)
	go func() {
		scanner := bufio.NewScanner(a.Serial)
		for scanner.Scan() {
			output <- scanner.Text()
		}
	}()
	return output
}

func (a *ArduinoSerial) Send(data string) error {
	_, err := a.Serial.Write([]byte(data + "\n"))
	if err != nil {
		return err
	}
	return nil
}

func (a *ArduinoSerial) WaitForStdin() <-chan error {
	serErr := make(chan error)
	go func() {
		scanner := bufio.NewScanner(os.Stdin)
		for scanner.Scan() {
			if err := a.Send(scanner.Text()); err != nil {
				serErr <- err
			}
		}
	}()
	return serErr
}


text:
package com.jeequan.jeepay.components.mq.vender.rabbitmq.receive;

import com.jeequan.jeepay.components.mq.constant.MQVenderCS;
import com.jeequan.jeepay.components.mq.model.ResetIsvMchAppInfoConfigMQ;
import com.jeequan.jeepay.components.mq.vender.IMQMsgReceiver;
import com.jeequan.jeepay.components.mq.vender.rabbitmq.RabbitMQConfig;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
* rabbitMQ消息接收器:仅在vender=rabbitMQ时 && 项目实现IMQReceiver接口时 进行实例化
* 业务:  更新服务商/商户/商户应用配置信息
*
* @author terrfly
* @site https://www.jeequan.com
* @date 2021/7/22 17:06
*/
@Component
@ConditionalOnProperty(name = MQVenderCS.YML_VENDER_KEY, havingValue = MQVenderCS.RABBIT_MQ)
@ConditionalOnBean(ResetIsvMchAppInfoConfigMQ.IMQReceiver.class)
public class ResetIsvMchAppInfoRabbitMQReceiver implements IMQMsgReceiver {

    @Autowired
    private ResetIsvMchAppInfoConfigMQ.IMQReceiver mqReceiver;

    /** 接收 【 MQSendTypeEnum.BROADCAST  】 广播类型的消息
     *
     * 注意:
     *   RabbitMQ的广播模式(fanout)交换机 --》全部的Queue
     *   如果queue包含多个消费者, 【例如,manager和payment的监听器是名称相同的queue下的消费者(Consumers) 】, 两个消费者是工作模式且存在竞争关系, 导致只能一个来消费。
     * 解决:
     *   每个topic的QUEUE都声明一个FANOUT交换机, 消费者声明一个系统产生的【随机队列】绑定到这个交换机上,然后往交换机发消息,只要绑定到这个交换机上都能收到消息。
     *   参考: https://bbs.csdn.net/topics/392509262?list=70088931
     *
     * **/
    @Override
    @RabbitListener(
            bindings = {@QueueBinding(value = @Queue(), // 注意这里不要定义队列名称,系统会随机产生
            exchange = @Exchange(name = RabbitMQConfig.FANOUT_EXCHANGE_NAME_PREFIX + ResetIsvMchAppInfoConfigMQ.MQ_NAME,
            type = ExchangeTypes.FANOUT ))} )
    public void receiveMsg(String msg){
        mqReceiver.receive(ResetIsvMchAppInfoConfigMQ.parse(msg));
    }

}


text:
<?php

namespace Cop\DataStoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * BlacklistCategories
 *
 * @ORM\Table(name="blacklist_categories" , indexes={@ORM\Index(name="tamerelagrosse_idx", columns={"pending"})}  )
 * @ORM\Entity(repositoryClass="Cop\DataStoreBundle\Entity\BlacklistCategoriesRepository")
 */
class BlacklistCategories
{

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

    /**
     * @param string $createdAt
     * @return Categories
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
        return $this;
    }

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

    /**
     * @param string $updateAt
     * @return Categories
     */
    public function setUpdateAt($updateAt)
    {
        $this->updateAt = $updateAt;
        return $this;
    }

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     *
     */
    private $id;

    /**
     * @var string
     * @ORM\OneToOne(targetEntity="Pending")
     * @ORM\JoinColumn(name="pending" , referencedColumnName="id",  nullable=false)
     */
    private $pending;

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

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

    /**
     * @var string
     *
     * @ORM\Column(name="createdAt", type="datetime")
     */
    private $createdAt;

    /**
     * @var string
     *
     * @ORM\Column(name="updateAt", type="datetime")
     */
    private $updateAt;

}


text:
package com.cloud.api.doc;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

public class DotNetFileWriter implements AutoCloseable {

    private IndentWriter _writer;
    private boolean _namespaceOpen = false;
    private boolean _openDefinition = false;

    public DotNetFileWriter(File file) throws IOException {
        if (!file.createNewFile()) {
            throw new java.io.IOException(String.format("File %s already exists", file.getPath()));
        }

        _writer = new IndentWriter(new PrintWriter(file), "    ");
    }

    public DotNetFileWriter(File file, String namespace, String[] imports) throws IOException {
        this(file);

        println("using System;");
        if (imports != null) {
            for (String importLine : imports) {
                println("using %s;", importLine);
            }
        }
        println();

        println("namespace %s", namespace);
        println("{");
        incrementIndent();
        _namespaceOpen = true;
    }

    public DotNetFileWriter(String baseDirectory, String namespace, String[] imports, String typeName, String type) throws IOException {
        this(new File(baseDirectory, typeName + ".cs"), namespace, imports);

        addType(typeName, type);
    }

    public DotNetFileWriter(String fileName, String namespace, String[] imports) throws IOException {
        this(new File(fileName), namespace, imports);
    }

    public DotNetFileWriter(String baseDirectory, String namespace, String[] imports, String typeName) throws IOException {
        this(baseDirectory, namespace, imports, typeName, "class");
    }

    public void addType(String typeName, String type) {
        println("public %s %s", type, typeName);
        println("{");
        incrementIndent();
        _openDefinition = true;
    }

    public void addType(String typeName) {
        addType(typeName, "class");
    }

    public void closeTypeDef() {
        if (_openDefinition) {
            decrementIndent();
            println("}");
            _openDefinition = false;
        }
    }

    public void incrementIndent() {
        _writer.incrementIndent();
    }

    public void decrementIndent() {
        _writer.decrementIndent();
    }

    public void println() {
        _writer.println();
    }

    public void println(String format, Object... args) {
        _writer.println(format, args);
    }

    @Override
    public void close() throws Exception {
        if (_openDefinition) {
            closeTypeDef();
        }

        if (_namespaceOpen) {
            decrementIndent();
            println("}");
        }

        if (_writer.getIndentLevel() > 0) {
            throw new Exception("Indent level was non-zero at close - mismatched incrementIndent");
        }

        _writer.flush();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/cardSnapshotGraph"
        card_view:cardBackgroundColor="@android:color/white"
        card_view:cardElevation="2sp"
        card_view:cardUseCompatPadding="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="16dp">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/graph1"
                android:src="@drawable/preview"/>

            <TextView
                android:id="@+id/title1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/graph1"
                android:layout_toLeftOf="@+id/imgSource1"
                android:maxLines="3"
                android:layout_marginTop="8dp"
                android:text="Snapshot and share"
                android:textColor="#222"
                android:textStyle="bold"
                android:textSize="22dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/title1"
                android:maxLines="3"
                android:text="Programmatically snapshot and share the graph"
                android:textColor="#666"
                android:textSize="14dp" />

            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@drawable/fullscreen"
                android:id="@+id/imgFullscreen1"
                android:layout_margin="5dp"
                android:layout_alignParentRight="true"
                android:layout_alignTop="@id/title1"/>

            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@drawable/source"
                android:id="@id/imgSource1"
                android:layout_margin="5dp"
                android:layout_toLeftOf="@id/imgFullscreen1"
                android:layout_alignTop="@id/title1"/>

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:interpolator="@android:anim/bounce_interpolator"
        android:fromXDelta="100%"
        android:toXDelta="0"
        android:duration="300"
        android:fillAfter="true"
        android:fillEnabled="true"/>

    <alpha
        android:interpolator="@android:anim/decelerate_interpolator"
        android:fromAlpha="0"
        android:toAlpha="1"
        android:duration="200"
        android:fillAfter="true"
        android:fillEnabled="true"/>
</set>


text: <!DOCTYPE html>


text:
from __future__ import division
import os.path
import numpy as np
import sys, getopt, argparse
import gzip
import cPickle as pickle
import skimage.morphology
import time
import re
import glob
import datetime
from random import shuffle
from random import randint
import unicodecsv

from keras.layers.core import Reshape, Lambda
from keras.models import Sequential,load_model,Model
from keras.layers import Dense, MaxPooling2D, Input, merge, UpSampling2D
from keras.layers.advanced_activations import LeakyReLU
from keras.callbacks import EarlyStopping,ModelCheckpoint,TensorBoard
from keras.layers.convolutional import Convolution2D, SeparableConvolution2D, AtrousConvolution2D
from keras.layers.local import LocallyConnected2D
from keras.layers.core import Dense, Dropout, Activation, Flatten, SpatialDropout2D
from keras.optimizers import SGD , Adam, RMSprop
from keras.callbacks import Callback
from keras.layers.normalization import BatchNormalization
from keras import backend as K

from dsb_image import *
from unet_model import *
from voxel_extract import *

def read_labels(filename):
    labels = {}
    csvFile = open(filename)
    reader = unicodecsv.DictReader(csvFile,encoding='utf-8')
    for j in reader:
        #if not j['id'] == 'b8bb02d229361a623a4dc57aa0e5c485':
        labels[j['id']] = int(j['cancer'])
    return labels

def touch(fname, times=None):
    with open(fname, 'a'):
        os.utime(fname, times)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(prog='create_replay')
    parser.add_argument('--input-folder', help='train folder', required=True)
    parser.add_argument('--output-folder', help='output folder', required=True)
    parser.add_argument('--labels', help='labels file', default='../stage1_labels.csv')
    parser.add_argument('--model', help='model', required=True)
    parser.add_argument('--augment', help='augment images',dest='deterministic', action='store_false')
    parser.set_defaults(deterministic=True)

    args = parser.parse_args()
    opts = vars(args)

    lmap = read_labels(args.labels)

    model = unet_model(True,False)
    print "loading existing weights into model from ",args.model
    model.load_weights(args.model)

    patients = os.listdir(args.input_folder)
    patients.sort()

    print "deterministic -> ",args.deterministic

    t1 = int(round(time.time() * 1000))
    fnum = 0
    for filename in patients:
        fnum += 1
        print "processing file ",filename,fnum,"/",len(patients)

        key = filename.split(".")[0]

        file_glob = args.output_folder + key+"*"
        ofiles = glob.glob(file_glob)
        if len(ofiles)>0:
            print "skipping existing file ",filename
            continue

        (l,p) = predict_unet(model,args.input_folder,filename,args.deterministic,0.95)

        print l.shape,p.shape
        p = p.reshape(p.shape[0],512,512)
        l = l.reshape(l.shape[0],512,512)

        voxels = extract_voxels(l,p)
        print "Saving ",len(voxels)," voxel files"
        sys.stdout.flush()

        label = "ukn"
        if key in lmap:
            label = str(lmap[key])

        key = filename.split(".")[0]
        idx = 0
        if len(voxels) > 0:
            for (voxel,_,bbox) in voxels:
                file = gzip.open(args.output_folder+key+"_"+label+"_"+str(idx)+".pkl.gz",'wb')
                pickle.dump(voxel,file,protocol=-1)
                pickle.dump(bbox,file,protocol=-1)
                pickle.dump(label,file,protocol=-1)
                file.close()
                idx += 1
        else:
            print "creating empty touch file"
            touch(args.output_folder + key+".touch" )
        sys.stdout.flush()


text:
<?php

namespace ws\loewe\Woody\Components\Controls;

use \ws\loewe\Woody\App\TestApplication;
use \ws\loewe\Woody\Components\Timer\Timer;
use \ws\loewe\Utils\Geom\Point;
use \ws\loewe\Utils\Geom\Dimension;

/**
 * Test class for EditArea.
 * Generated by PHPUnit on 2011-11-15 at 23:23:15.
 */
class CheckboxTest extends \PHPUnit_Framework_TestCase {
  /**
   * the checkbox to test
   *
   * @var \ws\loewe\Woody\Components\Controls\Checkbox
   */
  private $checkbox = null;

  /**
   * the test application
   *
   * @var \ws\loewe\Woody\App\TestApplication
   */
  private $application = null;

  /**
   * the timer for the test application
   *
   * @var \ws\loewe\Woody\Components\Timer\Timer
   */
  private $timer = null;

  /**
   * Sets up the fixture, for example, opens a network connection.
   * This method is called before a test is executed.
   */
  protected function setUp() {
    $this->application = new TestApplication();

    $this->checkbox = new Checkbox(FALSE, Point::createInstance(20, 20), Dimension::createInstance(20, 20));

    $this->application->getWindow()->getRootPane()->add($this->checkbox);
  }

  /**
   * Tears down the fixture, for example, closes a network connection.
   * This method is called after a test is executed.
   */
  protected function tearDown() {
  }

  /**
   * This method tests resizing the checkbox.
   *
   * @covers \ws\loewe\Woody\Components\Controls\Checkbox::resizeTo
   */
  public function testResizeTo() {
    $callback = function() {
      $expected = Dimension::createInstance(15, 15);
      $this->checkbox->resizeTo($expected);

      $actual = $this->checkbox->getDimension();
      $this->assertEquals($expected->width, $actual->width);
      $this->assertEquals($expected->height, $actual->height);

      $this->checkbox->resizeTo(Dimension::createInstance(150, 150));

      $actual = $this->checkbox->getDimension();
      $this->assertEquals(Checkbox::MAX_WIDTH, $actual->width);
      $this->assertEquals(Checkbox::MAX_HEIGHT, $actual->height);

      $this->timer->destroy();
      $this->application->stop();
    };

    $this->timer = new Timer($callback, $this->application->getWindow(), Timer::TEST_TIMEOUT);

    $this->timer->start();

    $this->application->start();
  }

  /**
   * This method tests retrieving the value of the checkbox.
   *
   * @covers \ws\loewe\Woody\Components\Controls\Checkbox::isChecked
   */
  public function testIsChecked() {
    $this->timer = new Timer(function() {
                              $this->assertEquals(FALSE, $this->checkbox->isChecked());

                              $this->checkbox->setChecked(TRUE);
                              $this->assertEquals(TRUE, $this->checkbox->isChecked());

                              $this->checkbox->setChecked(FALSE);
                              $this->assertEquals(FALSE, $this->checkbox->isChecked());

                              $this->timer->destroy();

                              $this->application->stop();
                            }, $this->application->getWindow(), Timer::TEST_TIMEOUT);

    $this->timer->start();

    $this->application->start();
  }

  /**
   * This method tests setting the value of the checkbox.
   *
   * @covers \ws\loewe\Woody\Components\Controls\Checkbox::setChecked
   */
  public function testSetChecked() {
    $this->timer = new Timer(function() {
                              $this->assertEquals(FALSE, $this->checkbox->isChecked());

                              $this->checkbox->setChecked(TRUE);
                              $this->assertEquals(TRUE, $this->checkbox->isChecked());

                              $this->checkbox->setChecked(FALSE);
                              $this->assertEquals(FALSE, $this->checkbox->isChecked());

                              $this->checkbox->setChecked(TRUE);
                              $this->assertEquals(TRUE, $this->checkbox->isChecked());

                              $this->timer->destroy();

                              $this->application->stop();
                            }, $this->application->getWindow(), Timer::TEST_TIMEOUT);

    $this->timer->start();

    $this->application->start();
  }
}


text:
#include "trace_impl.h"

#include <cassert>
#include <string.h> // memset

#ifdef _WIN32
#include "trace_windows.h"
#include "fix_interlocked_exchange_pointer_windows.h"
#else
#include <stdio.h>
#include <time.h>
#include <stdarg.h>
#include "trace_linux.h"
#endif // _WIN32

#define KEY_LEN_CHARS 31

#ifdef _WIN32
    #pragma warning(disable:4355)
// VS 2005: Disable warnings for default initialized arrays.
    #pragma warning(disable:4351)
#endif // _WIN32

namespace webrtc {
static WebRtc_UWord32 levelFilter = kTraceDefault;

// Construct On First Use idiom. Avoids "static initialization order fiasco".
Trace* TraceImpl::StaticInstance(TraceCount inc, const TraceLevel level)
{
    // TODO (hellner): use atomic wrapper instead.
    static volatile long theTraceCount = 0;
    static Trace* volatile theTrace = NULL;

    TraceCreate state = WEBRTC_TRACE_EXIST;

    // Sanitys to avoid taking lock unless absolutely necessary (for
    // performance reasons). inc == WEBRTC_TRACE_INC_NO_CREATE) implies that
    // a message will be written to file.
    if(level != kTraceAll && inc == WEBRTC_TRACE_INC_NO_CREATE)
    {
        if(!(level & levelFilter))
        {
            return NULL;
        }
    }

#ifndef _WIN32
    // TODO (pwestin): crtiSect is never reclaimed. Fix memory leak.
    static CriticalSectionWrapper* crtiSect(
        CriticalSectionWrapper::CreateCriticalSection());
    CriticalSectionScoped lock(*crtiSect);

    if(inc == WEBRTC_TRACE_INC_NO_CREATE && theTraceCount == 0)
    {
        return NULL;
    }

    if(inc == WEBRTC_TRACE_INC || inc == WEBRTC_TRACE_INC_NO_CREATE)
    {
        theTraceCount++;
        if(theTraceCount == 1)
        {
            state = WEBRTC_TRACE_CREATE;
        }
    } else {
        theTraceCount--;
        if(theTraceCount == 0)
        {
            state = WEBRTC_TRACE_DESTROY;
        }
    }
    if(state == WEBRTC_TRACE_CREATE)
    {
        theTrace = TraceImpl::CreateTrace();

    } else if(state == WEBRTC_TRACE_DESTROY) {
        Trace* oldValue = theTrace;
        theTrace = NULL;
        // The lock is held by the scoped critical section. Release the lock
        // temporarily so that the trace can be safely deleted. If the lock
        // was kept during the delete, e.g. creating and destroying the trace
        // too quickly may lead to a deadlock.
        // This is due to the fact that starting and stopping a ThreadWrapper
        // thread will trigger writing of trace messages.
        // TODO (hellner): remove the tight coupling with the thread
        //                 implementation.
        crtiSect->Leave();
        if(oldValue)
        {
            delete static_cast<TraceImpl*>(oldValue);
        }
        // Re-aqcuire the lock.
        crtiSect->Enter();
        return NULL;
    }
#else  // _WIN32
    if(inc == WEBRTC_TRACE_INC_NO_CREATE && theTraceCount == 0)
    {
        return NULL;
    }
    if(inc == WEBRTC_TRACE_INC_NO_CREATE)
    {
        if(1 == InterlockedIncrement(&theTraceCount))
        {
            // The trace has been destroyed by some other thread. Rollback.
            InterlockedDecrement(&theTraceCount);
            assert(false);
            return NULL;
        }
        // Sanity to catch corrupt state.
        if(theTrace == NULL)
        {
            assert(false);
            InterlockedDecrement(&theTraceCount);
            return NULL;
        }
    } else if(inc == WEBRTC_TRACE_INC) {
        if(theTraceCount == 0)
        {
            state = WEBRTC_TRACE_CREATE;
        } else {
            if(1 == InterlockedIncrement(&theTraceCount))
            {
                // InterlockedDecrement because reference count should not be
                // updated just yet (that's done when the trace is created).
                InterlockedDecrement(&theTraceCount);
                state = WEBRTC_TRACE_CREATE;
            }
        }
    } else {
        int newValue = InterlockedDecrement(&theTraceCount);
        if(newValue == 0)
        {
            state = WEBRTC_TRACE_DESTROY;
        }
    }

    if(state == WEBRTC_TRACE_CREATE)
    {
        // Create trace and let whichever thread finishes first assign its local
        // copy to the global instance. All other threads reclaim their local
        // copy.
        Trace* newTrace = TraceImpl::CreateTrace();
        if(1 == InterlockedIncrement(&theTraceCount))
        {
            Trace* oldValue = (Trace*)InterlockedExchangePointer(
                reinterpret_cast<void* volatile*>(&theTrace), newTrace);
            assert(oldValue == NULL);
            assert(theTrace);
        } else {
            InterlockedDecrement(&theTraceCount);
            if(newTrace)
            {
                delete static_cast<TraceImpl*>(newTrace);
            }
        }
        return NULL;
    } else if(state == WEBRTC_TRACE_DESTROY)
    {
        Trace* oldValue = (Trace*)InterlockedExchangePointer(
            reinterpret_cast<void* volatile*>(&theTrace), NULL);
        if(oldValue)
        {
            delete static_cast<TraceImpl*>(oldValue);
        }
        return NULL;
    }
#endif // #ifndef _WIN32
    return theTrace;
}

void Trace::CreateTrace()
{
    TraceImpl::StaticInstance(WEBRTC_TRACE_INC);
}

void Trace::ReturnTrace()
{
    TraceImpl::StaticInstance(WEBRTC_TRACE_DEC);
}

TraceImpl* TraceImpl::GetTrace(const TraceLevel level)
{
    return (TraceImpl*)StaticInstance(WEBRTC_TRACE_INC_NO_CREATE, level);
}

Trace* TraceImpl::CreateTrace()
{
#if defined(_WIN32)
    return new TraceWindows();
#else
    return new TraceLinux();
#endif
}

TraceImpl::TraceImpl()
    : _critsectInterface(*CriticalSectionWrapper::CreateCriticalSection()),
      _callback(NULL),
      _rowCountText(0),
      _fileCountText(0),
      _traceFile(*FileWrapper::Create()),
      _thread(*ThreadWrapper::CreateThread(TraceImpl::Run, this,
                                           kHighestPriority, "Trace")),
      _event(*EventWrapper::Create()),
      _critsectArray(*CriticalSectionWrapper::CreateCriticalSection()),
      _nextFreeIdx(),
      _level(),
      _length(),
      _messageQueue(),
      _activeQueue(0)
{
    _nextFreeIdx[0] = 0;
    _nextFreeIdx[1] = 0;

    unsigned int tid = 0;
    _thread.Start(tid);

    for(int m = 0; m < WEBRTC_TRACE_NUM_ARRAY; m++)
    {
        for(int n = 0; n < WEBRTC_TRACE_MAX_QUEUE; n++)
        {
            _messageQueue[m][n] = new
                WebRtc_Word8[WEBRTC_TRACE_MAX_MESSAGE_SIZE];
        }
    }
}

bool TraceImpl::StopThread()
{
    // Release the worker thread so that it can flush any lingering messages.
    _event.Set();

    // Allow 10 ms for pending messages to be flushed out.
    // TODO (hellner): why not use condition variables to do this? Or let the
    //                 worker thread die and let this thread flush remaining
    //                 messages?
#ifdef _WIN32
    Sleep(10);
#else
    timespec t;
    t.tv_sec = 0;
    t.tv_nsec = 10*1000000;
    nanosleep(&t,NULL);
#endif

    _thread.SetNotAlive();
    // Make sure the thread finishes as quickly as possible (instead of having
    // to wait for the timeout).
    _event.Set();
    bool stopped = _thread.Stop();

    CriticalSectionScoped lock(_critsectInterface);
    _traceFile.Flush();
    _traceFile.CloseFile();
    return stopped;
}

TraceImpl::~TraceImpl()
{
    StopThread();
    delete &_event;
    delete &_traceFile;
    delete &_thread;
    delete &_critsectInterface;
    delete &_critsectArray;

    for(int m = 0; m < WEBRTC_TRACE_NUM_ARRAY; m++)
    {
        for(int n = 0; n < WEBRTC_TRACE_MAX_QUEUE; n++)
        {
            delete [] _messageQueue[m][n];
        }
    }
}

WebRtc_Word32 TraceImpl::AddLevel(char* szMessage, const TraceLevel level) const
{
    switch (level)
    {
        case kTraceStateInfo:
            sprintf (szMessage, "STATEINFO ; ");
            break;
        case kTraceWarning:
            sprintf (szMessage, "WARNING   ; ");
            break;
        case kTraceError:
            sprintf (szMessage, "ERROR     ; ");
            break;
        case kTraceCritical:
            sprintf (szMessage, "CRITICAL  ; ");
            break;
        case kTraceInfo:
            sprintf (szMessage, "DEBUGINFO ; ");
            break;
        case kTraceModuleCall:
            sprintf (szMessage, "MODULECALL; ");
            break;
        case kTraceMemory:
            sprintf (szMessage, "MEMORY    ; ");
            break;
        case kTraceTimer:
            sprintf (szMessage, "TIMER     ; ");
            break;
        case kTraceStream:
            sprintf (szMessage, "STREAM    ; ");
            break;
        case kTraceApiCall:
            sprintf (szMessage, "APICALL   ; ");
            break;
        case kTraceDebug:
            sprintf (szMessage, "DEBUG     ; ");
            break;
        default:
            assert(false);
            return 0;
    }
    // All messages are 12 characters.
    return 12;
}

WebRtc_Word32 TraceImpl::AddModuleAndId(char* traceMessage,
                                        const TraceModule module,
                                        const WebRtc_Word32 id) const
{
    // Use long int to prevent problems with different definitions of
    // WebRtc_Word32.
    // TODO (hellner): is this actually a problem? If so, it should be better to
    //                 clean up WebRtc_Word32
    const long int idl = id;
    if(idl != -1)
    {
        const unsigned long int idEngine = id>>16;
        const unsigned long int idChannel = id & 0xffff;

        switch (module)
        {
            case kTraceVoice:
                sprintf(traceMessage, "       VOICE:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceVideo:
                sprintf(traceMessage, "       VIDEO:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceUtility:
                sprintf(traceMessage, "     UTILITY:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceRtpRtcp:
                sprintf(traceMessage, "    RTP/RTCP:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceTransport:
                sprintf(traceMessage, "   TRANSPORT:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceAudioCoding:
                sprintf(traceMessage, "AUDIO CODING:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceSrtp:
                sprintf(traceMessage, "        SRTP:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceAudioMixerServer:
                sprintf(traceMessage, " AUDIO MIX/S:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceAudioMixerClient:
                sprintf(traceMessage, " AUDIO MIX/C:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceVideoCoding:
                sprintf(traceMessage, "VIDEO CODING:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceVideoMixer:
                // Print sleep time and API call
                sprintf(traceMessage, "   VIDEO MIX:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceFile:
                sprintf(traceMessage, "        FILE:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceAudioProcessing:
                sprintf(traceMessage, "  AUDIO PROC:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceAudioDevice:
                sprintf(traceMessage, "AUDIO DEVICE:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceVideoRenderer:
                sprintf(traceMessage, "VIDEO RENDER:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceVideoCapture:
                sprintf(traceMessage, "VIDEO CAPTUR:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            case kTraceVideoPreocessing:
                sprintf(traceMessage, "  VIDEO PROC:%5ld %5ld;", idEngine,
                        idChannel);
                break;
            default:
                assert(false);
                return 0;
        }
    } else {
        switch (module)
        {
            case kTraceVoice:
                sprintf (traceMessage, "       VOICE:%11ld;", idl);
                break;
            case kTraceVideo:
                sprintf (traceMessage, "       VIDEO:%11ld;", idl);
                break;
            case kTraceUtility:
                sprintf (traceMessage, "     UTILITY:%11ld;", idl);
                break;
            case kTraceRtpRtcp:
                sprintf (traceMessage, "    RTP/RTCP:%11ld;", idl);
                break;
            case kTraceTransport:
                sprintf (traceMessage, "   TRANSPORT:%11ld;", idl);
                break;
            case kTraceAudioCoding:
                sprintf (traceMessage, "AUDIO CODING:%11ld;", idl);
                break;
            case kTraceSrtp:
                sprintf (traceMessage, "        SRTP:%11ld;", idl);
                break;
            case kTraceAudioMixerServer:
                sprintf (traceMessage, " AUDIO MIX/S:%11ld;", idl);
                break;
            case kTraceAudioMixerClient:
                sprintf (traceMessage, " AUDIO MIX/C:%11ld;", idl);
                break;
            case kTraceVideoCoding:
                sprintf (traceMessage, "VIDEO CODING:%11ld;", idl);
                break;
            case kTraceVideoMixer:
                sprintf (traceMessage, "   VIDEO MIX:%11ld;", idl);
                break;
            case kTraceFile:
                sprintf (traceMessage, "        FILE:%11ld;", idl);
                break;
            case kTraceAudioProcessing:
                sprintf (traceMessage, "  AUDIO PROC:%11ld;", idl);
                break;
            case kTraceAudioDevice:
                sprintf (traceMessage, "AUDIO DEVICE:%11ld;", idl);
                break;
            case kTraceVideoRenderer:
                sprintf (traceMessage, "VIDEO RENDER:%11ld;", idl);
                break;
            case kTraceVideoCapture:
                sprintf (traceMessage, "VIDEO CAPTUR:%11ld;", idl);
                break;
            case kTraceVideoPreocessing:
                sprintf (traceMessage, "  VIDEO PROC:%11ld;", idl);
                break;
            default:
                assert(false);
                return 0;
        }
    }
    // All messages are 25 characters.
    return 25;
}

WebRtc_Word32 TraceImpl::SetTraceFileImpl(const WebRtc_Word8* fileNameUTF8,
                                          const bool addFileCounter)
{
    CriticalSectionScoped lock(_critsectInterface);

    _traceFile.Flush();
    _traceFile.CloseFile();

    if(fileNameUTF8)
    {
        if(addFileCounter)
        {
            _fileCountText = 1;

            WebRtc_Word8 fileNameWithCounterUTF8[FileWrapper::kMaxFileNameSize];
            CreateFileName(fileNameUTF8, fileNameWithCounterUTF8,
                           _fileCountText);
            if(_traceFile.OpenFile(fileNameWithCounterUTF8, false, false,
                                   true) == -1)
            {
                return -1;
            }
        }else {
            _fileCountText = 0;
            if(_traceFile.OpenFile(fileNameUTF8, false, false, true) == -1)
            {
                return -1;
            }
        }
    }
    _rowCountText = 0;
    return 0;
}

WebRtc_Word32 TraceImpl::TraceFileImpl(
    WebRtc_Word8 fileNameUTF8[FileWrapper::kMaxFileNameSize])
{
    CriticalSectionScoped lock(_critsectInterface);
    return _traceFile.FileName(fileNameUTF8, FileWrapper::kMaxFileNameSize);
}

WebRtc_Word32 TraceImpl::SetTraceCallbackImpl(TraceCallback* callback)
{
    CriticalSectionScoped lock(_critsectInterface);
    _callback = callback;
    return 0;
}

WebRtc_Word32 TraceImpl::AddMessage(
    char* traceMessage,
    const char msg[WEBRTC_TRACE_MAX_MESSAGE_SIZE],
    const WebRtc_UWord16 writtenSoFar) const

{
    int length = 0;
    if(writtenSoFar >= WEBRTC_TRACE_MAX_MESSAGE_SIZE)
    {
        return -1;
    }
    // - 2 to leave room for newline and NULL termination
#ifdef _WIN32
    length = _snprintf(traceMessage,
                       WEBRTC_TRACE_MAX_MESSAGE_SIZE - writtenSoFar - 2,
                       "%s",msg);
    if(length < 0)
    {
        length = WEBRTC_TRACE_MAX_MESSAGE_SIZE - writtenSoFar - 2;
        traceMessage[length] = 0;
    }
#else
    length = snprintf(traceMessage,
                      WEBRTC_TRACE_MAX_MESSAGE_SIZE-writtenSoFar-2, "%s",msg);
    if(length < 0 || length > WEBRTC_TRACE_MAX_MESSAGE_SIZE-writtenSoFar - 2)
    {
        length = WEBRTC_TRACE_MAX_MESSAGE_SIZE - writtenSoFar - 2;
        traceMessage[length] = 0;
    }
#endif
    // Length with NULL termination.
    return length+1;
}

void TraceImpl::AddMessageToList(
    const char traceMessage[WEBRTC_TRACE_MAX_MESSAGE_SIZE],
    const WebRtc_UWord16 length,
    const TraceLevel level)
{
    CriticalSectionScoped lock(_critsectArray);

    if(_nextFreeIdx[_activeQueue] >= WEBRTC_TRACE_MAX_QUEUE)
    {
        if( ! _traceFile.Open() &&
            !_callback)
        {
            // Keep at least the last 1/4 of old messages when not logging.
            // TODO (hellner): isn't this redundant. The user will make it known
            //                 when to start logging. Why keep messages before
            //                 that?
            for(int n = 0; n < WEBRTC_TRACE_MAX_QUEUE/4; n++)
            {
                const int lastQuarterOffset = (3*WEBRTC_TRACE_MAX_QUEUE/4);
                memcpy(_messageQueue[_activeQueue][n],
                       _messageQueue[_activeQueue][n + lastQuarterOffset],
                       WEBRTC_TRACE_MAX_MESSAGE_SIZE);
            }
            _nextFreeIdx[_activeQueue] = WEBRTC_TRACE_MAX_QUEUE/4;
        } else {
            // More messages are being written than there is room for in the
            // buffer. Drop any new messages.
            // TODO (hellner): its probably better to drop old messages instead
            //                 of new ones. One step further: if this happens
            //                 it's due to writing faster than what can be
            //                 processed. Maybe modify the filter at this point.
            //                 E.g. turn of STREAM.
            return;
        }
    }

    WebRtc_UWord16 idx = _nextFreeIdx[_activeQueue];
    _nextFreeIdx[_activeQueue]++;

    _level[_activeQueue][idx] = level;
    _length[_activeQueue][idx] = length;
    memcpy(_messageQueue[_activeQueue][idx], traceMessage, length);

    if(_nextFreeIdx[_activeQueue] == WEBRTC_TRACE_MAX_QUEUE-1)
    {
        // Loggin more messages than can be worked off. Log a warning.
        memcpy(_messageQueue[_activeQueue][_nextFreeIdx[_activeQueue]],
               "WARNING MISSING TRACE MESSAGES\n", 32);
        _nextFreeIdx[_activeQueue]++;
    }
}

bool TraceImpl::Run(void* obj)
{
    return static_cast<TraceImpl*>(obj)->Process();
}

bool TraceImpl::Process()
{
    if(_event.Wait(1000) == kEventSignaled)
    {
        if(_traceFile.Open() || _callback)
        {
            // File mode (not calback mode).
            WriteToFile();
        }
    } else {
        _traceFile.Flush();
    }
    return true;
}

void TraceImpl::WriteToFile()
{
    WebRtc_UWord8 localQueueActive = 0;
    WebRtc_UWord16 localNextFreeIdx = 0;

    // There are two buffer. One for reading (for writing to file) and one for
    // writing (for storing new messages). Let new messages be posted to the
    // unused buffer so that the current buffer can be flushed safely.
    {
        CriticalSectionScoped lock(_critsectArray);
        localNextFreeIdx = _nextFreeIdx[_activeQueue];
        _nextFreeIdx[_activeQueue] = 0;
        localQueueActive = _activeQueue;
        if(_activeQueue == 0)
        {
            _activeQueue = 1;
        } else
        {
            _activeQueue = 0;
        }
    }
    if(localNextFreeIdx == 0)
    {
        return;
    }

    CriticalSectionScoped lock(_critsectInterface);

    for(WebRtc_UWord16 idx = 0; idx <localNextFreeIdx; idx++)
    {
        TraceLevel localLevel = _level[localQueueActive][idx];
        if(_callback)
        {
            _callback->Print(localLevel, _messageQueue[localQueueActive][idx],
                             _length[localQueueActive][idx]);
        }
        if(_traceFile.Open())
        {
            if(_rowCountText > WEBRTC_TRACE_MAX_FILE_SIZE)
            {
                // wrap file
                _rowCountText = 0;
                _traceFile.Flush();

                if(_fileCountText == 0)
                {
                    _traceFile.Rewind();
                } else
                {
                    WebRtc_Word8 oldFileName[FileWrapper::kMaxFileNameSize];
                    WebRtc_Word8 newFileName[FileWrapper::kMaxFileNameSize];

                    // get current name
                    _traceFile.FileName(oldFileName,
                                        FileWrapper::kMaxFileNameSize);
                    _traceFile.CloseFile();

                    _fileCountText++;

                    UpdateFileName(oldFileName, newFileName, _fileCountText);

                    if(_traceFile.OpenFile(newFileName, false, false,
                                           true) == -1)
                    {
                        return;
                    }
                }
            }
            if(_rowCountText ==  0)
            {
                WebRtc_Word8 message[WEBRTC_TRACE_MAX_MESSAGE_SIZE + 1];
                WebRtc_Word32 length = AddDateTimeInfo(message);
                if(length != -1)
                {
                    message[length] = 0;
                    message[length-1] = '\n';
                    _traceFile.Write(message, length);
                    _rowCountText++;
                }
                length = AddBuildInfo(message);
                if(length != -1)
                {
                    message[length+1] = 0;
                    message[length] = '\n';
                    message[length-1] = '\n';
                    _traceFile.Write(message, length+1);
                    _rowCountText++;
                    _rowCountText++;
                }
            }
            WebRtc_UWord16 length = _length[localQueueActive][idx];
            _messageQueue[localQueueActive][idx][length] = 0;
            _messageQueue[localQueueActive][idx][length-1] = '\n';
            _traceFile.Write(_messageQueue[localQueueActive][idx], length);
            _rowCountText++;
        }
    }
}

void TraceImpl::AddImpl(const TraceLevel level, const TraceModule module,
                        const WebRtc_Word32 id,
                        const char msg[WEBRTC_TRACE_MAX_MESSAGE_SIZE])
{
    if (TraceCheck(level))
    {
        char traceMessage[WEBRTC_TRACE_MAX_MESSAGE_SIZE];
        char* meassagePtr = traceMessage;

        WebRtc_Word32 len = 0;
        WebRtc_Word32 ackLen = 0;

        len = AddLevel(meassagePtr, level);
        if(len == -1)
        {
            return;
        }
        meassagePtr += len;
        ackLen += len;

        len = AddTime(meassagePtr, level);
        if(len == -1)
        {
            return;
        }
        meassagePtr += len;
        ackLen += len;

        len = AddModuleAndId(meassagePtr, module, id);
        if(len == -1)
        {
            return;
        }
        meassagePtr += len;
        ackLen += len;

        len = AddThreadId(meassagePtr);
        if(len == -1)
        {
            return;
        }
        meassagePtr += len;
        ackLen += len;

        len = AddMessage(meassagePtr, msg, (WebRtc_UWord16)ackLen);
        if(len == -1)
        {
            return;
        }
        ackLen += len;
        AddMessageToList(traceMessage,(WebRtc_UWord16)ackLen, level);

        // Make sure that messages are written as soon as possible.
        _event.Set();
    }
}

bool TraceImpl::TraceCheck(const TraceLevel level) const
{
    return (level & levelFilter)? true:false;
}

bool TraceImpl::UpdateFileName(
    const WebRtc_Word8 fileNameUTF8[FileWrapper::kMaxFileNameSize],
    WebRtc_Word8 fileNameWithCounterUTF8[FileWrapper::kMaxFileNameSize],
    const WebRtc_UWord32 newCount) const
{
    WebRtc_Word32 length = (WebRtc_Word32)strlen(fileNameUTF8);
    if(length < 0)
    {
        return false;
    }

    WebRtc_Word32 lengthWithoutFileEnding = length-1;
    while(lengthWithoutFileEnding > 0)
    {
        if(fileNameUTF8[lengthWithoutFileEnding] == '.')
        {
            break;
        } else {
            lengthWithoutFileEnding--;
        }
    }
    if(lengthWithoutFileEnding == 0)
    {
        lengthWithoutFileEnding = length;
    }
    WebRtc_Word32 lengthTo_ = lengthWithoutFileEnding - 1;
    while(lengthTo_ > 0)
    {
        if(fileNameUTF8[lengthTo_] == '_')
        {
            break;
        } else {
            lengthTo_--;
        }
    }

    memcpy(fileNameWithCounterUTF8, fileNameUTF8, lengthTo_);
    sprintf(fileNameWithCounterUTF8+lengthTo_, "_%lu%s", newCount,
            fileNameUTF8+lengthWithoutFileEnding);
    return true;
}

bool TraceImpl::CreateFileName(
    const WebRtc_Word8 fileNameUTF8[FileWrapper::kMaxFileNameSize],
    WebRtc_Word8 fileNameWithCounterUTF8[FileWrapper::kMaxFileNameSize],
    const WebRtc_UWord32 newCount) const
{
    WebRtc_Word32 length = (WebRtc_Word32)strlen(fileNameUTF8);
    if(length < 0)
    {
        return false;
    }

    WebRtc_Word32 lengthWithoutFileEnding = length-1;
    while(lengthWithoutFileEnding > 0)
    {
        if(fileNameUTF8[lengthWithoutFileEnding] == '.')
        {
            break;
        }else
        {
            lengthWithoutFileEnding--;
        }
    }
    if(lengthWithoutFileEnding == 0)
    {
        lengthWithoutFileEnding = length;
    }
    memcpy(fileNameWithCounterUTF8, fileNameUTF8, lengthWithoutFileEnding);
    sprintf(fileNameWithCounterUTF8+lengthWithoutFileEnding, "_%lu%s",
            newCount, fileNameUTF8+lengthWithoutFileEnding);
    return true;
}

WebRtc_Word32 Trace::SetLevelFilter(WebRtc_UWord32 filter)
{
    levelFilter = filter;
    return 0;
};

WebRtc_Word32 Trace::LevelFilter(WebRtc_UWord32& filter)
{
    filter = levelFilter;
    return 0;
};

WebRtc_Word32 Trace::TraceFile(WebRtc_Word8 fileName[FileWrapper::kMaxFileNameSize])
{
    TraceImpl* trace = TraceImpl::GetTrace();
    if(trace)
    {
        int retVal = trace->TraceFileImpl(fileName);
        ReturnTrace();
        return retVal;
    }
    return -1;
}

WebRtc_Word32 Trace::SetTraceFile(const WebRtc_Word8* fileName,
                                  const bool addFileCounter)
{
    TraceImpl* trace = TraceImpl::GetTrace();
    if(trace)
    {
        int retVal = trace->SetTraceFileImpl(fileName, addFileCounter);
        ReturnTrace();
        return retVal;
    }
    return -1;
}

WebRtc_Word32 Trace::SetTraceCallback(TraceCallback* callback)
{
    TraceImpl* trace = TraceImpl::GetTrace();
    if(trace)
    {
        int retVal = trace->SetTraceCallbackImpl(callback);
        ReturnTrace();
        return retVal;
    }
    return -1;
}

void Trace::Add(const TraceLevel level, const TraceModule module,
                const WebRtc_Word32 id, const char* msg, ...)

{
    TraceImpl* trace = TraceImpl::GetTrace(level);
    if(trace)
    {
        if(trace->TraceCheck(level))
        {
            char tempBuff[WEBRTC_TRACE_MAX_MESSAGE_SIZE];
            char* buff = 0;
            if(msg)
            {
                va_list args;
                va_start(args, msg);
#ifdef _WIN32
                _vsnprintf(tempBuff,WEBRTC_TRACE_MAX_MESSAGE_SIZE-1,msg,args);
#else
                vsnprintf(tempBuff,WEBRTC_TRACE_MAX_MESSAGE_SIZE-1,msg,args);
#endif
                va_end(args);
                buff = tempBuff;
            }
            trace->AddImpl(level, module, id, buff);
        }
        ReturnTrace();
    }
}
} // namespace webrtc


text:
<?php

namespace App\Http\Api\V1\Controllers;

use App\Http\Api\V1\ResourceDefinitions\UserResourceDefinition;
use App\Models\User;
use CatLab\Charon\Collections\RouteCollection;
use Gatekeeper;

/**
 * Class UserController
 * @package App\Http\Api\V1\Controllers
 */
class UserController extends Base\ResourceController
{
    const USER_ME = 'me';

    /**
     * Set all routes for this controller
     * @param RouteCollection $routes
     */
    public static function setRoutes(RouteCollection $routes)
    {
        $routes->group(function(RouteCollection $routes)
        {
            $routes->tag('users');

            $routes
                ->get('users/{id}', 'UserController@show')
                ->parameters()->path('id')->required()
                ->returns()->one(UserResourceDefinition::class)
                ->summary('Return a user object');

            $routes
                ->get('users', 'UserController@index')
                ->returns()->many(UserResourceDefinition::class)
                ->summary('Return all users');
        });
    }

    /**
     * UserController constructor.
     */
    public function __construct()
    {
        parent::__construct(UserResourceDefinition::class);
    }

    /**
     * @param string $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        $user = $this->getUser($id);
        if (!$user) {
            return $this->notFound($id, User::class);
        }

        $this->authorize('show', $user);
        return $this->output($user);
    }

    /**
     * @TODO This method only exists as an example. You do NOT want this in your production app.
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $this->authorize('index');
        return $this->output(User::all());
    }

    /**
     * @param string $id
     * @return mixed
     */
    private function getUser($id)
    {
        if ($id === self::USER_ME) {
            return Gatekeeper::getIdentity()->getUser();
        } else {
            return User::find($id);
        }
    }
}


text:
import json

import pytest

from telegram import (InlineKeyboardButton, InputTextMessageContent, InlineQueryResultCachedVoice,
                      InlineKeyboardMarkup, InlineQueryResultCachedGif)

@pytest.fixture(scope='class')
def inline_query_result_cached_gif():
    return InlineQueryResultCachedGif(TestInlineQueryResultCachedGif.id,
                                      TestInlineQueryResultCachedGif.gif_file_id,
                                      title=TestInlineQueryResultCachedGif.title,
                                      caption=TestInlineQueryResultCachedGif.caption,
                                      input_message_content=TestInlineQueryResultCachedGif.input_message_content,
                                      reply_markup=TestInlineQueryResultCachedGif.reply_markup)

class TestInlineQueryResultCachedGif:
    id = 'id'
    type = 'gif'
    gif_file_id = 'gif file id'
    title = 'title'
    caption = 'caption'
    input_message_content = InputTextMessageContent('input_message_content')
    reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])

    def test_expected_values(self, inline_query_result_cached_gif):
        assert inline_query_result_cached_gif.type == self.type
        assert inline_query_result_cached_gif.id == self.id
        assert inline_query_result_cached_gif.gif_file_id == self.gif_file_id
        assert inline_query_result_cached_gif.title == self.title
        assert inline_query_result_cached_gif.caption == self.caption
        assert inline_query_result_cached_gif.input_message_content.to_dict() == \
               self.input_message_content.to_dict()
        assert inline_query_result_cached_gif.reply_markup.to_dict() == self.reply_markup.to_dict()

    def test_to_json(self, inline_query_result_cached_gif):
        json.loads(inline_query_result_cached_gif.to_json())

    def test_to_dict(self, inline_query_result_cached_gif):
        inline_query_result_cached_gif_dict = inline_query_result_cached_gif.to_dict()

        assert isinstance(inline_query_result_cached_gif_dict, dict)
        assert inline_query_result_cached_gif_dict['type'] == inline_query_result_cached_gif.type
        assert inline_query_result_cached_gif_dict['id'] == inline_query_result_cached_gif.id
        assert inline_query_result_cached_gif_dict['gif_file_id'] == \
               inline_query_result_cached_gif.gif_file_id
        assert inline_query_result_cached_gif_dict['title'] == inline_query_result_cached_gif.title
        assert inline_query_result_cached_gif_dict['caption'] == \
               inline_query_result_cached_gif.caption
        assert inline_query_result_cached_gif_dict['input_message_content'] == \
               inline_query_result_cached_gif.input_message_content.to_dict()
        assert inline_query_result_cached_gif_dict['reply_markup'] == \
               inline_query_result_cached_gif.reply_markup.to_dict()

    def test_equality(self):
        a = InlineQueryResultCachedGif(self.id, self.gif_file_id)
        b = InlineQueryResultCachedGif(self.id, self.gif_file_id)
        c = InlineQueryResultCachedGif(self.id, "")
        d = InlineQueryResultCachedGif("", self.gif_file_id)
        e = InlineQueryResultCachedVoice(self.id, "", "")

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)


text:
Comparisons
===========

The following are a few comparisons of the **Cake Markup Language** versus standard code in *CakePHP*.

Output
------

Output an escaped string of text.

```html
<cake:out value="Hello World" />
```

```php
<?php echo h('Hello World'); ?>
```

Output a View variable.

```html
%{example}
```

```php
<?php echo $example; ?>
```

Output a translation literal.

```html
#{Hello World}
```

```php
<?php echo __('Hello World'); ?>
```

Output a domain specific translation literal.

```html
#{example^Hello World}
```

```php
<?php echo __d('example', 'Hello World'); ?>
```

Links
-----

Create a link to a Controller and action.

```html
<cake:link url="['controller' => 'example', 'action' => 'test', 123]" value="#{Click here}" />
```

```php
<?php echo $this->Html->link(__('Click here'), array('controller' => 'example', 'action' => 'test', 123)); ?>
```

Create a link with an image.

```html
<cake:link url="['controller' => 'example', 'action' => 'test', 123]">
	<cake:image path="example.jpg" options="['alt' => #{Click here}]" />
</cake:link>
```

```php
<?php echo $this->Html->link($this->Html->image('example.jpg', array('alt' => __('Click here'))), array('controller' => 'example', 'action' => 'test', 123)); ?>
```

Forms
-----

Create a form with a custom submit button.

```html
<cake:form model="Example" submit="['label' => 'Update', 'div' => ['class' => 'glass-pill']]">
	<cake:input field="Example.field" options="['type' => 'text']" />
</cake:form>
```

```php
<?php
$this->Form->create('Example');
$this->Form->input('Example.field', array('type' => 'text'));
$this->Form->end(array('label' => 'Update', 'div' => array('class' => 'glass-pill')));
?>
```

View Blocks
-----------

Create a new View block.

```html
<cake:block name="example">
	Hello World
</cake:block>
```

```php
<?php $this->start('example'); ?>
	Hello World
<?php $this->end(); ?>
```

Append to an existing View block.

```html
<cake:append name="example">
	Hello World
</cake:append>
```

```php
<?php $this->append('example'); ?>
	Hello World
<?php $this->end(); ?>
```

Fetching a View block.

```html
<cake:fetch name="example" />
```

```php
<?php echo $this->fetch('example'); ?>
```

Elements
--------

Include an element.

```html
<cake:element name="example" vars="['something' => %{example}]" />
```

```php
<?php echo $this->element('example', array('something' => $example)); ?>
```

Logic
-----

Simple condition checking.

```html
<php:if expr="%{example} > 0">
	#{You won a prize!}
</php:if>
```

```php
<?php
if ($example > 0) {
	echo __('You won a prize!');
}
?>
```

```php
<?php if ($example > 0): ?>
	<?php echo __('You won a prize!'); ?>
<?php endif; ?>
```

Iterating over an array of values.

```html
<php:for var="items" default="#{No items available}">
	#{Item} %{COUNT}: <cake:out value="%{VALUE}" />
</php:for>
```

```php
<?php
if (count($items) > 0) {
	for ($i = 0; $i < count($items); $i++) {
		echo __('Item') . ' ' . ($i+1) . ': ' . h($items[$i]);
	}
} else {
	echo __('No items available');
}
?>
```

```php
<?php if (count($items) > 0): ?>
	<?php for ($i = 0; $i < count($items); $i++): ?>
		<?php echo __('Item') . ' ' . ($i+1) . ': ' . h($items[$i]); ?>
	<?php endfor; ?>
<?php else: ?>
	<?php echo __('No items available'); ?>
<?php endif; ?>
```


text:
import { Editor } from '@ckeditor/ckeditor5-core';
import { Element } from '@ckeditor/ckeditor5-engine';
import Writer from '@ckeditor/ckeditor5-engine/src/model/writer';
import CKTable from '@ckeditor/ckeditor5-table';

class MyEditor extends Editor {}
const editor = new MyEditor();

new CKTable.Table(editor);
CKTable.Table.requires.map(Plugin => new Plugin(editor).init());

new CKTable.TableUI(editor).init();

new CKTable.TableMouse(editor).init();
CKTable.TableMouse.requires.map(Plugin => new Plugin(editor).init());

new CKTable.TableUtils(editor).init();
new CKTable.TableUtils(editor).getCellLocation(new Element('div')).row > 0;
new CKTable.TableUtils(editor).getCellLocation(new Element('div')).column > 0;
new CKTable.TableUtils(editor)
    .createTable(new Writer(), { rows: 4, columns: 0, headingRows: 4, headingColumns: 4 })
    .getChildren();
let table = new CKTable.TableUtils(editor).createTable(new Writer());
new CKTable.TableUtils(editor).insertRows(table, { at: 0, rows: 3 });
new CKTable.TableUtils(editor).insertColumns(table, { at: 0, columns: 3 });
new CKTable.TableUtils(editor).removeRows(table, { at: 0, rows: 3 });
new CKTable.TableUtils(editor).removeColumns(table, { at: 0, columns: 3 });
new CKTable.TableUtils(editor).splitCellVertically(table, 0);
new CKTable.TableUtils(editor).splitCellHorizontally(table, 0);
new CKTable.TableUtils(editor).getColumns(table) > 0;
new CKTable.TableUtils(editor).getRows(table) > 0;

CKTable.TableEditing.requires.map(Plugin => new Plugin(editor).init());
new CKTable.TableEditing(editor);

CKTable.TableToolbar.requires.map(Plugin => new Plugin(editor).init());
new CKTable.TableToolbar(editor).afterInit();

CKTable.TableClipboard.requires.map(Plugin => new Plugin(editor).init());
new CKTable.TableClipboard(editor).init();

CKTable.TableKeyboard.requires.map(Plugin => new Plugin(editor).init());
new CKTable.TableKeyboard(editor).init();

CKTable.TableSelection.requires.map(Plugin => new Plugin(editor).init());
new CKTable.TableSelection(editor).init();
const cells = new CKTable.TableSelection(editor).getSelectedTableCells();
if (Array.isArray(cells)) {
    table = cells[0];
}
new CKTable.TableSelection(editor).getSelectionAsFragment()?.getChildren();
new CKTable.TableSelection(editor).setCellSelection(table, table);
table = new CKTable.TableSelection(editor).getFocusCell();
table = new CKTable.TableSelection(editor).getAnchorCell();

CKTable.TableProperties.requires.map(Plugin => new Plugin(editor).init());
new CKTable.TableProperties(editor);

CKTable.TablePropertiesEditing.requires.map(Plugin => new Plugin(editor).init());
new CKTable.TablePropertiesEditing(editor).init();

CKTable.TablePropertiesUI.requires.map(Plugin => new Plugin(editor).stopListening());
new CKTable.TablePropertiesUI(editor).init();
new CKTable.TablePropertiesUI(editor).destroy();

CKTable.TableCellPropertiesUI.requires.map(Plugin => new Plugin(editor).stopListening());
new CKTable.TableCellPropertiesUI(editor).init();
new CKTable.TableCellPropertiesUI(editor).destroy();

CKTable.TableCellPropertiesEditing.requires.map(Plugin => new Plugin(editor).init());
new CKTable.TableCellPropertiesEditing(editor).init();