text:
<?php

namespace MicrosoftAzure\Storage\Tests\Functional\Blob;

use MicrosoftAzure\Storage\Tests\Framework\TestResources;
use MicrosoftAzure\Storage\Blob\Models\AccessCondition;
use MicrosoftAzure\Storage\Blob\Models\ContainerACL;
use MicrosoftAzure\Storage\Blob\Models\CopyBlobOptions;
use MicrosoftAzure\Storage\Blob\Models\BlobServiceOptions;
use MicrosoftAzure\Storage\Blob\Models\CreateBlobOptions;
use MicrosoftAzure\Storage\Blob\Models\CreateBlobSnapshotOptions;
use MicrosoftAzure\Storage\Blob\Models\CreateContainerOptions;
use MicrosoftAzure\Storage\Blob\Models\AppendBlockOptions;
use MicrosoftAzure\Storage\Blob\Models\DeleteBlobOptions;
use MicrosoftAzure\Storage\Blob\Models\GetBlobOptions;
use MicrosoftAzure\Storage\Blob\Models\GetBlobPropertiesOptions;
use MicrosoftAzure\Storage\Blob\Models\ListBlobsOptions;
use MicrosoftAzure\Storage\Blob\Models\ListContainersOptions;
use MicrosoftAzure\Storage\Blob\Models\PublicAccessType;
use MicrosoftAzure\Storage\Blob\Models\SetBlobPropertiesOptions;
use MicrosoftAzure\Storage\Common\Internal\Resources;
use MicrosoftAzure\Storage\Common\Internal\Utilities;
use MicrosoftAzure\Storage\Common\Models\Range;
use MicrosoftAzure\Storage\Common\Models\RangeDiff;
use MicrosoftAzure\Storage\Common\Models\Logging;
use MicrosoftAzure\Storage\Common\Models\Metrics;
use MicrosoftAzure\Storage\Common\Models\CORS;
use MicrosoftAzure\Storage\Common\Models\RetentionPolicy;
use MicrosoftAzure\Storage\Common\Models\ServiceProperties;

class BlobServiceFunctionalTestData
{
    public static $testUniqueId;
    public static $tempBlobCounter = 1;
    public static $nonExistContainerPrefix;
    public static $nonExistBlobPrefix;
    public static $testContainerNames;
    public static $testBlobNames;
    private static $blockIdCount;
    private static $accountName;
    private static $badETag = '0x123456789ABCDEF';

    public static function setupData($accountName)
    {
        $rint = mt_rand(0, 1000000);
        self::$accountName = $accountName;
        self::$testUniqueId = 'qa-' . $rint . '-';
        self::$nonExistContainerPrefix = 'qa-' . ($rint . 1) . '-';
        self::$nonExistBlobPrefix = 'qa-' . ($rint . 2) . '-';
        self::$testContainerNames = array( self::$testUniqueId . 'a1', self::$testUniqueId . 'a2', self::$testUniqueId . 'b1' );
        self::$testBlobNames = array( 'b' . self::$testUniqueId . 'a1', 'b' . self::$testUniqueId . 'a2', 'b' . self::$testUniqueId . 'b1' );
        self::$blockIdCount = 0;
    }

    public static function getInterestingContainerName()
    {
        // http://msdn.microsoft.com/en-us/library/windowsazure/dd135715.aspx
        // 1. Container names must start with a letter or number, and can
        //    contain only letters, numbers, and the dash (-) character.
        // 2. Consecutive dashes are not permitted in container names.
        // 3. All letters in a container name must be lowercase.
        // 4. Container names must be from 3 through 63 characters long.
        // 5. Container names cannot contain control characters: 0x00 to 0x1F

        return self::$testUniqueId . 'con-' . (self::$tempBlobCounter++);
    }

    public static function getInterestingBlobName($container)
    {
        // http://msdn.microsoft.com/en-us/library/windowsazure/dd135715.aspx
        // 1. A blob name cannot contain control characters: 0x00 to 0x1F
        // 2. A blob name can contain any combination of characters, but
        //    reserved URL characters must be properly escaped.
        // 3. A blob name must be at least one character long and cannot be
        //    more than 1,024 characters long.
        // 4. Blob names are case-sensitive.
        // 5. Avoid blob names that end with a dot (.) or a forward slash (/);
        //    they are removed by the server
        // 6. Avoid blob names containing a dot-slash sequence (./);
        //    the dot is removed by the server.

        $uB2E4 = chr(0xEB) . chr(0x8B) . chr(0xA4); // UTF8 encoding of \uB2E4
        $blobname = self::$testUniqueId . '/*\"\'&.({[<+ ' . chr(0x7D) . $uB2E4 . '_' . (self::$tempBlobCounter++);
        if (empty($container) || $container == '$root') {
            $blobname = str_replace('/', 'X', $blobname);
            $blobname = str_replace('\\', 'X', $blobname);
        }
        return $blobname;
    }

    public static function getInterestingBlockId()
    {
        //Block ID must be base64 encoded.
        return base64_encode(
            str_pad(self::$blockIdCount++, 6, '0', STR_PAD_LEFT)
        );
    }

    public static function getSimpleMessageText()
    {
        return 'simple message text #' . (self::$tempBlobCounter++);
    }

    public static function getInterestingTimeoutValues()
    {
        $ret = array();
        array_push($ret, null);
        array_push($ret, -1);
        array_push($ret, 0);
        array_push($ret, 1);
        array_push($ret, -2147483648);
        array_push($ret, 2147483647);
        return $ret;
    }

    public static function diffInTotalSeconds($date1, $date2)
    {
        $diff = $date1->diff($date2);
        $sec = $diff->s
                + 60 * ($diff->i
                + 60 * ($diff->h
                + 24 * ($diff->d
                + 30 * ($diff->m
                + 12 * ($diff->y)))));
        return abs($sec);
    }

    public static function passTemporalAccessCondition($ac)
    {
        if (is_null($ac) ||  empty($ac)) {
            return true;
        }

        $now = new \DateTime();

        if ($ac[0]->getHeader() == Resources::IF_UNMODIFIED_SINCE) {
            return $ac[0]->getValue() > $now;
        } elseif ($ac[0]->getHeader() == Resources::IF_MODIFIED_SINCE) {
            return $ac[0]->getValue() < $now;
        } else {
            return true;
        }
    }

    public static function passETagAccessCondition($ac)
    {
        if (is_null($ac) || empty($ac)) {
            return true;
        } elseif ($ac[0]->getHeader() == Resources::IF_MATCH) {
            return self::$badETag != $ac[0]->getValue();
        } elseif ($ac[0]->getHeader() == Resources::IF_NONE_MATCH) {
            return self::$badETag == $ac[0]->getValue();
        } else {
            return true;
        }
    }

    public static function fixETagAccessCondition($ac, $etag)
    {
        if (!is_null($ac) && !empty($ac)) {
            if ($ac[0]->getHeader() == Resources::IF_MATCH || $ac[0]->getHeader() == Resources::IF_NONE_MATCH) {
                if (is_null($ac[0]->getValue()) || self::$badETag != $ac[0]->getValue()) {
                    $ac[0]->setValue($etag);
                }
            }
        }
    }

    private static function getTemporalAccessConditions()
    {
        $ret = array();

        $past = new \DateTime("01/01/2010");
        $future = new \DateTime("01/01/2020");

        array_push($ret, AccessCondition::ifModifiedSince($past));
        array_push($ret, AccessCondition::ifNotModifiedSince($past));
        array_push($ret, AccessCondition::ifModifiedSince($future));
        array_push($ret, AccessCondition::ifNotModifiedSince($future));

        return $ret;
    }

    private static function getAllAccessConditions()
    {
        $ret = self::getTemporalAccessConditions();

        array_push($ret, AccessCondition::ifMatch(null));
        array_push($ret, AccessCondition::ifMatch(self::$badETag));
        array_push($ret, AccessCondition::ifNoneMatch(null));
        array_push($ret, AccessCondition::ifNoneMatch(self::$badETag));

        return $ret;
    }

    public static function getDefaultServiceProperties()
    {
        // This is the default that comes from the server.
        $rp = new RetentionPolicy();
        $l = new Logging();
        $l->setRetentionPolicy($rp);
        $l->setVersion('1.0');
        $l->setDelete(false);
        $l->setRead(false);
        $l->setWrite(false);

        $m = new Metrics();
        $m->setRetentionPolicy($rp);
        $m->setVersion('1.0');
        $m->setEnabled(false);
        $m->setIncludeAPIs(null);

        $sp = new ServiceProperties();
        $sp->setLogging($l);
        $sp->setHourMetrics($m);

        return $sp;
    }

    public static function getContainerName()
    {
        return self::$testContainerNames[0];
    }

    public static function getInterestingServiceProperties()
    {
        $ret = array();

        {
            // This is the default that comes from the server.
            array_push($ret, self::getDefaultServiceProperties());
        }

        {
            $rp = new RetentionPolicy();
            $rp->setEnabled(true);
            $rp->setDays(10);

            $l = new Logging();
            $l->setRetentionPolicy($rp);
            // Note: looks like only v1.0 is available now.
            // http://msdn.microsoft.com/en-us/library/windowsazure/hh360996.aspx
            $l->setVersion('1.0');
            $l->setDelete(true);
            $l->setRead(true);
            $l->setWrite(true);

            $m = new Metrics();
            $m->setRetentionPolicy($rp);
            $m->setVersion('1.0');
            $m->setEnabled(true);
            $m->setIncludeAPIs(true);

            $c = CORS::create(TestResources::getCORSSingle());

            $sp = new ServiceProperties();
            $sp->setLogging($l);
            $sp->setHourMetrics($m);
            $sp->setCorses(array($c));

            array_push($ret, $sp);
        }

        {
            $rp = new RetentionPolicy();
            // The service does not accept setting days when enabled is false.
            $rp->setEnabled(false);
            $rp->setDays(null);

            $l = new Logging();
            $l->setRetentionPolicy($rp);
            // Note: looks like only v1.0 is available now.
            // http://msdn.microsoft.com/en-us/library/windowsazure/hh360996.aspx
            $l->setVersion('1.0');
            $l->setDelete(false);
            $l->setRead(false);
            $l->setWrite(false);

            $m = new Metrics();
            $m->setRetentionPolicy($rp);
            $m->setVersion('1.0');
            $m->setEnabled(true);
            $m->setIncludeAPIs(true);

            $csArray =
                TestResources::getServicePropertiesSample()[Resources::XTAG_CORS];
            $c0 = CORS::create($csArray[Resources::XTAG_CORS_RULE][0]);
            $c1 = CORS::create($csArray[Resources::XTAG_CORS_RULE][1]);

            $sp = new ServiceProperties();
            $sp->setLogging($l);
            $sp->setHourMetrics($m);
            $sp->setCorses(array($c0, $c1));

            array_push($ret, $sp);
        }

        {
            $rp = new RetentionPolicy();
            $rp->setEnabled(true);
            // Days has to be 0 < days <= 365
            $rp->setDays(364);

            $l = new Logging();
            $l->setRetentionPolicy($rp);
            // Note: looks like only v1.0 is available now.
            // http://msdn.microsoft.com/en-us/library/windowsazure/hh360996.aspx
            $l->setVersion('1.0');
            $l->setDelete(false);
            $l->setRead(false);
            $l->setWrite(false);

            $m = new Metrics();
            $m->setVersion('1.0');
            $m->setEnabled(false);
            $m->setIncludeAPIs(null);
            $m->setRetentionPolicy($rp);

            $csArray =
                TestResources::getServicePropertiesSample()[Resources::XTAG_CORS];
            $c0 = CORS::create($csArray[Resources::XTAG_CORS_RULE][0]);
            $c1 = CORS::create($csArray[Resources::XTAG_CORS_RULE][1]);

            $sp = new ServiceProperties();
            $sp->setLogging($l);
            $sp->setHourMetrics($m);
            $sp->setCorses(array($c0, $c1));

            array_push($ret, $sp);
        }

        return $ret;
    }

    public static function getInterestingListContainersOptions()
    {
        $ret = array();

        $options = new ListContainersOptions();
        array_push($ret, $options);

        $options = new ListContainersOptions();
        $marker = '/' . self::$accountName . '/' . self::$testContainerNames[1];
        $options->setMarker($marker);
        array_push($ret, $options);

        $options = new ListContainersOptions();
        $marker = '/' . self::$accountName . '/' . self::$nonExistContainerPrefix;
        $options->setMarker($marker);
        array_push($ret, $options);

        $options = new ListContainersOptions();
        $maxResults = 2;
        $options->setMaxResults($maxResults);
        array_push($ret, $options);

        $options = new ListContainersOptions();
        $prefix = self::$testUniqueId;
        $options->setPrefix($prefix);
        array_push($ret, $options);

        $options = new ListContainersOptions();
        $prefix = self::$nonExistContainerPrefix;
        $options->setPrefix($prefix);
        array_push($ret, $options);

        $options = new ListContainersOptions();
        $prefix = self::$testContainerNames[1];
        $options->setPrefix($prefix);
        array_push($ret, $options);

        $options = new ListContainersOptions();
        $timeout = -1;
        $options->setTimeout($timeout);
        array_push($ret, $options);

        $options = new ListContainersOptions();
        $timeout = 60;
        $options->setTimeout($timeout);
        array_push($ret, $options);

        $options = new ListContainersOptions();
        $includeMetadata = true;
        $options->setIncludeMetadata($includeMetadata);
        array_push($ret, $options);

        $options = new ListContainersOptions();
        $marker = '/' . self::$accountName . '/' . self::$testContainerNames[1];
        $maxResults = 2;
        $prefix = self::$testUniqueId;
        $timeout = 60;
        $includeMetadata = true;
        $options->setMarker($marker);
        $options->setMaxResults($maxResults);
        $options->setPrefix($prefix);
        $options->setTimeout($timeout);
        $options->setIncludeMetadata($includeMetadata);
        array_push($ret, $options);

        return $ret;
    }

    public static function getInterestingMetadata()
    {
        $ret = array();

        $metadata = array();
        array_push($ret, $metadata);

        array_push($ret, self::getNiceMetadata());

        // Some metadata that HTTP will not like.
        $metadata = array('<>000' => '::::value');
        array_push($ret, $metadata);

        return $ret;
    }

    public static function getNiceMetadata()
    {
        return array(
            'key' => 'value',
            'foo' => 'bar',
            'baz' => 'boo');
    }

    public static function getInterestingCreateBlobOptions()
    {
        $ret = array();

        $options = new CreateBlobOptions();
        array_push($ret, $options);

        $options = new CreateBlobOptions();
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new CreateBlobOptions();
        $options->setTimeout(-10);
        array_push($ret, $options);

        $options = new CreateBlobOptions();
        $metadata = array(
            'foo' => 'bar',
            'foo2' => 'bar2',
            'foo3' => 'bar3');
        $options->setMetadata($metadata);
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new CreateBlobOptions();
        $metadata = array('foo' => 'bar');
        $options->setMetadata($metadata);
        $options->setTimeout(-10);
        array_push($ret, $options);

        return $ret;
    }

    public static function getInterestingListBlobsOptions()
    {
        $ret = array();

        $options = new ListBlobsOptions();
        array_push($ret, $options);

        $options = new ListBlobsOptions();
        $options->setMaxResults(2);
        array_push($ret, $options);

        $options = new ListBlobsOptions();
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new ListBlobsOptions();
        $options->setTimeout(-10);
        array_push($ret, $options);

        $options = new ListBlobsOptions();
        $options->setPrefix(self::$nonExistBlobPrefix);
        array_push($ret, $options);

        $options = new ListBlobsOptions();
        $options->setPrefix(self::$testUniqueId);
        array_push($ret, $options);

        $options = new ListBlobsOptions();
        // Cannot set Marker to arbitrary values. Must only use if the previous request returns a NextMarker.
        //            $options->setMarker('abc');
        // So, add logic in listBlobsWorker to loop and setMarker if there is a NextMarker.
        $options->setMaxResults(2);
        $options->setPrefix(self::$testUniqueId);
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new ListBlobsOptions();
        $options->setMaxResults(3);
        $options->setPrefix(self::$testUniqueId);
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new ListBlobsOptions();
        $options->setMaxResults(4);
        $options->setPrefix(self::$testUniqueId);
        $options->setTimeout(10);
        array_push($ret, $options);

        return $ret;
    }

    public static function getInterestingCreateContainerOptions()
    {
        $ret = array();

        $options = new CreateContainerOptions();
        array_push($ret, $options);

        $options = new CreateContainerOptions();
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new CreateContainerOptions();
        $options->setTimeout(-10);
        array_push($ret, $options);

        $options = new CreateContainerOptions();
        $options->setPublicAccess('container');
        array_push($ret, $options);

        $options = new CreateContainerOptions();
        $options->setPublicAccess('blob');
        array_push($ret, $options);

        $options = new CreateContainerOptions();
        $metadata = array(
            'foo' => 'bar',
            'boo' => 'baz',
        );
        $options->setMetadata($metadata);
        array_push($ret, $options);

        return $ret;
    }

    public static function getInterestingDeleteContainerOptions()
    {
        $ret = array();

        $past = new \DateTime("01/01/2010");
        $future = new \DateTime("01/01/2020");

        $options = new BlobServiceOptions();
        array_push($ret, $options);

        $options = new BlobServiceOptions();
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new BlobServiceOptions();
        $options->setTimeout(-10);
        array_push($ret, $options);

        $options = new BlobServiceOptions();
        $options->setAccessConditions(AccessCondition::ifModifiedSince($past));
        array_push($ret, $options);

        $options = new BlobServiceOptions();
        $options->setAccessConditions(AccessCondition::ifNotModifiedSince($past));
        array_push($ret, $options);

        $options = new BlobServiceOptions();
        $options->setAccessConditions(AccessCondition::ifModifiedSince($future));
        array_push($ret, $options);

        $options = new BlobServiceOptions();
        $options->setAccessConditions(AccessCondition::ifNotModifiedSince($future));
        array_push($ret, $options);

        return $ret;
    }

    public static function getSetContainerMetadataOptions()
    {
        $ret = array();

        $options = new BlobServiceOptions();
        array_push($ret, $options);

        $options = new BlobServiceOptions();
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new BlobServiceOptions();
        $options->setTimeout(-10);
        array_push($ret, $options);

        // Set Container Metadata only supports the If-Modified-Since access condition.
        // But easier to special-case If-Unmodified-Since in the test.
        foreach (self::getTemporalAccessConditions() as $ac) {
            $options = new BlobServiceOptions();
            $options->setAccessConditions($ac);
            array_push($ret, $options);
        }

        return $ret;
    }

    public static function getSetBlobMetadataOptions()
    {
        $ret = array();

        $options = new BlobServiceOptions();
        array_push($ret, $options);

        $options = new BlobServiceOptions();
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new BlobServiceOptions();
        $options->setTimeout(-10);
        array_push($ret, $options);

        foreach (self::getAllAccessConditions() as $ac) {
            $options = new BlobServiceOptions();
            $options->setAccessConditions($ac);
            array_push($ret, $options);
        }

        // TODO: Make sure the lease id part is tested in the leasing part.
        //        $options = new BlobServiceOptions();
        //        $options->setLeaseId(leaseId)
        //        array_push($ret, $options);

        return $ret;
    }

    public static function getGetBlobPropertiesOptions()
    {
        $ret = array();

        $options = new GetBlobPropertiesOptions();
        array_push($ret, $options);

        $options = new GetBlobPropertiesOptions();
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new GetBlobPropertiesOptions();
        $options->setTimeout(-10);
        array_push($ret, $options);

        // Get Blob Properties only supports the temporal access conditions.
        foreach (self::getTemporalAccessConditions() as $ac) {
            $options = new GetBlobPropertiesOptions();
            $options->setAccessConditions($ac);
            array_push($ret, $options);
        }

        return $ret;
    }

    public static function getSetBlobPropertiesOptions()
    {
        $ret = array();

        $options = new SetBlobPropertiesOptions();
        array_push($ret, $options);

        $options = new SetBlobPropertiesOptions();
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new SetBlobPropertiesOptions();
        $options->setTimeout(-10);
        array_push($ret, $options);

        // Get Blob Properties only supports the temporal access conditions.
        foreach (self::getTemporalAccessConditions() as $ac) {
            $options = new SetBlobPropertiesOptions();
            $options->setAccessConditions($ac);
            array_push($ret, $options);
        }

        $options = new SetBlobPropertiesOptions();
        $options->setCacheControl('setCacheControl');
        array_push($ret, $options);

        $options = new SetBlobPropertiesOptions();
        $options->setContentEncoding('setContentEncoding');
        array_push($ret, $options);

        $options = new SetBlobPropertiesOptions();
        $options->setContentLanguage('setContentLanguage');
        array_push($ret, $options);

        // Note: This is not allowed on block blobs
        $options = new SetBlobPropertiesOptions();
        $options->setContentLength(2048);
        array_push($ret, $options);

        $options = new SetBlobPropertiesOptions();
        $options->setContentMD5('d41d8cd98f00b204e9800998ecf8427e');
        array_push($ret, $options);

        $options = new SetBlobPropertiesOptions();
        $options->setContentType('setContentType');
        array_push($ret, $options);

        // TODO: Handle Lease ID
        //        $options = new SetBlobPropertiesOptions();
        //        $options->setLeaseId('setLeaseId');
        //        array_push($ret, $options);

        // Note: This is not allowed on block blobs
        $options = new SetBlobPropertiesOptions();
        $options->setSequenceNumber(0);
        $options->setSequenceNumberAction('update');
        array_push($ret, $options);

        return $ret;
    }

    public static function getInterestingACL()
    {
        $ret = array();

        $past = new \DateTime("01/01/2010");
        $future = new \DateTime("01/01/2020");

        $acl = new ContainerACL();
        array_push($ret, $acl);

        $acl = new ContainerACL();
        $acl->setPublicAccess(PublicAccessType::NONE);
        array_push($ret, $acl);

        $acl = new ContainerACL();
        $acl->setPublicAccess(PublicAccessType::BLOBS_ONLY);
        array_push($ret, $acl);

        $acl = new ContainerACL();
        $acl->setPublicAccess(PublicAccessType::CONTAINER_AND_BLOBS);
        array_push($ret, $acl);

        $acl = new ContainerACL();
        $acl->addSignedIdentifier('123', $past, $future, 'rw');
        array_push($ret, $acl);

        return $ret;
    }

    public static function getGetBlobOptions()
    {
        $ret = array();

        $options = new GetBlobOptions();
        array_push($ret, $options);

        $options = new GetBlobOptions();
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new GetBlobOptions();
        $options->setTimeout(-10);
        array_push($ret, $options);

        // Get Blob only supports the temporal access conditions.
        foreach (self::getTemporalAccessConditions() as $ac) {
            $options = new GetBlobOptions();
            $options->setAccessConditions($ac);
            array_push($ret, $options);
        }

        $options = new GetBlobOptions();
        $options->setRange(new Range(50, 200));
        array_push($ret, $options);

        $options = new GetBlobOptions();
        $options->setRange(new Range(50, 200));
        $options->setRangeGetContentMD5(true);
        array_push($ret, $options);

        $options = new GetBlobOptions();
        $options->setRange(new Range(50));
        array_push($ret, $options);

        $options = new GetBlobOptions();
        $options->setRangeGetContentMD5(true);
        array_push($ret, $options);

        $options = new GetBlobOptions();
        $options->setRange(new Range(null, 200));
        $options->setRangeGetContentMD5(true);
        array_push($ret, $options);

        $options = new GetBlobOptions();
        $options->setRange(new Range(null, 200));
        array_push($ret, $options);

        $options = new GetBlobOptions();
        $options->setSnapshot('placeholder');
        array_push($ret, $options);

        return $ret;
    }

    public static function getDeleteBlobOptions()
    {
        $ret = array();

        $options = new DeleteBlobOptions();
        array_push($ret, $options);

        $options = new DeleteBlobOptions();
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new DeleteBlobOptions();
        $options->setTimeout(-10);
        array_push($ret, $options);

        foreach (self::getAllAccessConditions() as $ac) {
            $options = new DeleteBlobOptions();
            $options->setAccessConditions($ac);
            array_push($ret, $options);
        }

        $options = new DeleteBlobOptions();
        $options->setDeleteSnaphotsOnly(true);
        array_push($ret, $options);

        $options = new DeleteBlobOptions();
        $options->setDeleteSnaphotsOnly(false);
        array_push($ret, $options);

        $options = new DeleteBlobOptions();
        $options->setSnapshot('placeholder');
        array_push($ret, $options);

        return $ret;
    }

    public static function getCreateBlobSnapshotOptions()
    {
        $ret = array();

        $options = new CreateBlobSnapshotOptions();
        array_push($ret, $options);

        $options = new CreateBlobSnapshotOptions();
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new CreateBlobSnapshotOptions();
        $options->setTimeout(-10);
        array_push($ret, $options);

        foreach (self::getAllAccessConditions() as $ac) {
            $options = new CreateBlobSnapshotOptions();
            $options->setAccessConditions($ac);
            array_push($ret, $options);
        }

        $options = new CreateBlobSnapshotOptions();
        $options->setMetadata(self::getNiceMetadata());
        array_push($ret, $options);

        return $ret;
    }

    public static function getCopyBlobOptions()
    {
        $ret = array();

        $options = new CopyBlobOptions();
        array_push($ret, $options);

        $options = new CopyBlobOptions();
        $options->setTimeout(10);
        array_push($ret, $options);

        $options = new CopyBlobOptions();
        $options->setTimeout(-10);
        array_push($ret, $options);

        foreach (self::getAllAccessConditions() as $ac) {
            $options = new CopyBlobOptions();
            $options->setSourceAccessConditions($ac);
            array_push($ret, $options);
        }

        foreach (self::getAllAccessConditions() as $ac) {
            $options = new CopyBlobOptions();
            $options->setAccessConditions($ac);
            array_push($ret, $options);
        }

        $options = new CopyBlobOptions();
        $metadata = array(
            'Xkey' => 'Avalue',
            'Yfoo' => 'Bbar',
            'Zbaz' => 'Cboo');
        $options->setMetadata($metadata);
        array_push($ret, $options);

        $options = new CopyBlobOptions();
        $options->setSourceSnapshot('placeholder');
        array_push($ret, $options);

        return $ret;
    }

    public static function getCreateBlockBlobAttributes()
    {
        $ret = array();
        $ret[] = ['size' => Resources::MB_IN_BYTES_4];
        $ret[] = ['size' => Resources::MB_IN_BYTES_32];
        $ret[] = ['size' => Resources::MB_IN_BYTES_32 + Resources::MB_IN_BYTES_1];
        $ret[] = ['size' => Resources::MB_IN_BYTES_128];
        $ret[] = ['size' => Resources::MB_IN_BYTES_256];
        $ret[] = [
            'threshold' => Resources::MB_IN_BYTES_4,
            'size' => Resources::MB_IN_BYTES_4 * 2
        ];
        $ret[] = [
            'threshold' => Resources::MB_IN_BYTES_64,
            'size' => Resources::MB_IN_BYTES_64
        ];
        $ret[] = [
            'threshold' => Resources::MB_IN_BYTES_64,
            'size' => Resources::MB_IN_BYTES_64 + Resources::MB_IN_BYTES_1
        ];

        return $ret;
    }

    public static function getRangesArray()
    {
        $ret = array();

        $ret[] = [
            'putRange' => new Range(0, 511),
            'clearRange' => null,
            'listRange' => null,
            'resultListRange' => [new Range(0, 511)]
        ];

        $ret[] = [
            'putRange' => new Range(1024, 1535),
            'clearRange' => null,
            'listRange' => null,
            'resultListRange' => [new Range(0, 511), new Range(1024, 1535)]
        ];

        $ret[] = [
            'putRange' => new Range(512, 1023),
            'clearRange' => null,
            'listRange' => null,
            'resultListRange' => [new Range(0, 1535)]
        ];

        $ret[] = [
            'putRange' => null,
            'clearRange' => new Range(1024, 1535),
            'listRange' => null,
            'resultListRange' => [new Range(0, 1023)]
        ];

        $ret[] = [
            'putRange' => null,
            'clearRange' => null,
            'listRange' => new Range(0, 511),
            'resultListRange' => [new Range(0, 511)]
        ];

        $ret[] = [
            'putRange' => new Range(1024, 2047),
            'clearRange' => new Range(512, 1023),
            'listRange' => null,
            'resultListRange' => [new Range(0, 511), new Range(1024, 2047)]
        ];

        $ret[] = [
            'putRange' => null,
            'clearRange' => new Range(0, 2047),
            'listRange' => null,
            'resultListRange' => array()
        ];

        return $ret;
    }

    public static function getRangesDiffArray()
    {
        $ret = array();

        $ret[] = [
            'putRange' => null,
            'clearRange' => null,
            'listRange' => null,
            'resultListRange' => []
        ];

        $ret[] = [
            'putRange' => new Range(0, 511),
            'clearRange' => null,
            'listRange' => null,
            'resultListRange' => [new RangeDiff(0, 511)]
        ];

        $ret[] = [
            'putRange' => new Range(1024, 1535),
            'clearRange' => null,
            'listRange' => null,
            'resultListRange' => [new RangeDiff(1024, 1535)]
        ];

        $ret[] = [
            'putRange' => null,
            'clearRange' => new Range(1024, 1535),
            'listRange' => null,
            'resultListRange' => [new RangeDiff(1024, 1535, true)]
        ];

        $ret[] = [
            'putRange' => new Range(0, 1023),
            'clearRange' => new Range(0, 511),
            'listRange' => null,
            'resultListRange' => [
                new RangeDiff(512, 1023),
                new RangeDiff(0, 511, true)
            ]
        ];

        $ret[] = [
            'putRange' => new Range(0, 2047),
            'clearRange' => null,
            'listRange' => new Range(0, 511),
            'resultListRange' => [new RangeDiff(0, 511)]
        ];

        $ret[] = [
            'putRange' => new Range(0, 2047),
            'clearRange' => new Range(512, 1023),
            'listRange' => new Range(512, 1535),
            'resultListRange' => [
                new RangeDiff(1024, 1535),
                new RangeDiff(512, 1023, true)
            ]
        ];

        $ret[] = [
            'putRange' => null,
            'clearRange' => new Range(0, 2047),
            'listRange' => null,
            'resultListRange' => [new RangeDiff(0, 2047, true)]
        ];

        return $ret;
    }

    public static function getAppendBlockSetup()
    {
        $ret = array();

        $size = Resources::MB_IN_BYTES_4;
        $options = new AppendBlockOptions();
        $errorMsg = '';
        $ret[] = ['size' => $size, 'options' => $options, 'error' => $errorMsg];

        $size = Resources::MB_IN_BYTES_1;
        $options = new AppendBlockOptions();
        $options->setContentMD5(Utilities::calculateContentMD5(''));
        $errorMsg = 'The MD5 value specified in the request did not match with the MD5 value calculated by the server.';
        $ret[] = ['size' => $size, 'options' => $options, 'error' => $errorMsg];

        $size = Resources::MB_IN_BYTES_1;
        $options = new AppendBlockOptions();
        $options->setMaxBlobSize(Resources::MB_IN_BYTES_4);
        $errorMsg = 'The max blob size condition specified was not met';
        $ret[] = ['size' => $size, 'options' => $options, 'error' => $errorMsg];

        $size = Resources::MB_IN_BYTES_1;
        $options = new AppendBlockOptions();
        $options->setAppendPosition(Resources::MB_IN_BYTES_1);
        $errorMsg = 'The append position condition specified was not met.';
        $ret[] = ['size' => $size, 'options' => $options, 'error' => $errorMsg];

        $size = Resources::MB_IN_BYTES_1 + Resources::MB_IN_BYTES_4;
        $options = new AppendBlockOptions();
        $errorMsg = 'The request body is too large and exceeds the maximum permissible limit.';
        $ret[] = ['size' => $size, 'options' => $options, 'error' => $errorMsg];

        return $ret;
    }
}

redpajama_set_name: RedPajamaGithub


text:
class CreateArticles < ActiveRecord::Migration
  def change
    create_table :articles do |t|
      t.string :link
      t.integer :status, default: 0
      t.belongs_to :category, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end


text:
using System;
using System.Linq;
namespace PowerArgs
{
    /// <summary>
    /// A hook that can be put on an argument so that if a user specifies the argument with no value they will get prompted for that value with a rich prompt
    /// that supports tab completion and syntax highlighting.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)]
    public class PromptIfEmpty : ArgHook, ICommandLineArgumentMetadata
    {
        /// <summary>
        /// Gets or sets the type to be used for global tab completion.  The type must implement ITabCompletionHandler
        /// </summary>
        public Type TabCompletionHandlerType { get; set; }

        /// <summary>
        /// Gets or sets the type to use inject custom syntax highlighting to the command prompt.  The type must implement IHighlighterConfigurator
        /// </summary>
        public Type HighlighterConfiguratorType { get; set; }

        /// <summary>
        /// If set to true the prompt will only run once on empty.  Program execution will continue if the value given to the prompt is empty
        /// </summary>
        public bool KeepAsking { get; set; }

        /// <summary>
        /// Prompts the user to enter a value for the given property in the case that the option was specified with no value
        /// </summary>
        /// <param name="context">the parser context</param>
        public override void BeforePopulateProperty(ArgHook.HookContext context)
        {
            if (string.IsNullOrEmpty(context.ArgumentValue))
            {
                do
                {
                    var cli = new CliHelper();

                    ITabCompletionHandler tabHandler;
                    IHighlighterConfigurator highlighterConfigurator;

                    if (TabCompletionHandlerType.TryCreate<ITabCompletionHandler>(out tabHandler))
                    {
                        cli.Reader.TabHandler.TabCompletionHandlers.Add(tabHandler);
                    }

                    if (HighlighterConfiguratorType.TryCreate<IHighlighterConfigurator>(out highlighterConfigurator))
                    {
                        cli.Reader.Highlighter = new SimpleSyntaxHighlighter();
                        highlighterConfigurator.Configure(cli.Reader.Highlighter);
                    }

                    var result = cli.PromptForLine("Enter value for " + context.CurrentArgument.DefaultAlias);
                    result = result == "" ? null : result;
                    context.ArgumentValue = result;
                } while (KeepAsking && context.ArgumentValue == null);
            }
        }
    }
}


text:
namespace Microsoft.Azure.CognitiveServices.Search.ImageSearch.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// The top-level object that the response includes when an image insights
    /// request succeeds. For information about requesting image insights, see
    /// the
    /// [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)
    /// query parameter. The modules query parameter affects the fields that
    /// Bing includes in the response. If you set
    /// [modules](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#modulesrequested)
    /// to only Caption, then this object includes only the imageCaption field.
    /// </summary>
    public partial class ImageInsights : Response
    {
        /// <summary>
        /// Initializes a new instance of the ImageInsights class.
        /// </summary>
        public ImageInsights()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ImageInsights class.
        /// </summary>
        /// <param name="id">A String identifier.</param>
        /// <param name="readLink">The URL that returns this resource.</param>
        /// <param name="webSearchUrl">The URL To Bing's search result for this
        /// item.</param>
        /// <param name="imageInsightsToken">A token that you use in a
        /// subsequent call to the Image Search API to get more information
        /// about the image. For information about using this token, see the
        /// insightsToken query parameter. This token has the same usage as the
        /// token in the Image object.</param>
        /// <param name="bestRepresentativeQuery">The query term that best
        /// represents the image. Clicking the link in the Query object, takes
        /// the user to a webpage with more pictures of the image.</param>
        /// <param name="imageCaption">The caption to use for the
        /// image.</param>
        /// <param name="relatedCollections">A list of links to webpages that
        /// contain related images.</param>
        /// <param name="pagesIncluding">A list of webpages that contain the
        /// image. To access the webpage, use the URL in the image's
        /// hostPageUrl field.</param>
        /// <param name="shoppingSources">A list of merchants that offer items
        /// related to the image. For example, if the image is of an apple pie,
        /// the list contains merchants that are selling apple pies.</param>
        /// <param name="relatedSearches">A list of related queries made by
        /// others.</param>
        /// <param name="recipes">A list of recipes related to the image. For
        /// example, if the image is of an apple pie, the list contains recipes
        /// for making an apple pie.</param>
        /// <param name="visuallySimilarImages">A list of images that are
        /// visually similar to the original image. For example, if the
        /// specified image is of a sunset over a body of water, the list of
        /// similar images are of a sunset over a body of water. If the
        /// specified image is of a person, similar images might be of the same
        /// person or they might be of persons dressed similarly or in a
        /// similar setting. The criteria for similarity continues to
        /// evolve.</param>
        /// <param name="visuallySimilarProducts">A list of images that contain
        /// products that are visually similar to products found in the
        /// original image. For example, if the specified image contains a
        /// dress, the list of similar images contain a dress. The image
        /// provides summary information about offers that Bing found online
        /// for the product.</param>
        /// <param name="recognizedEntityGroups">A list of groups that contain
        /// images of entities that match the entity found in the specified
        /// image. For example, the response might include images from the
        /// general celebrity group if the entity was recognized in that
        /// group.</param>
        /// <param name="imageTags">A list of characteristics of the content
        /// found in the image. For example, if the image is of a person, the
        /// tags might indicate the person's gender and the type of clothes
        /// they're wearing.</param>
        public ImageInsights(string id = default(string), string readLink = default(string), string webSearchUrl = default(string), string imageInsightsToken = default(string), Query bestRepresentativeQuery = default(Query), ImageInsightsImageCaption imageCaption = default(ImageInsightsImageCaption), RelatedCollectionsModule relatedCollections = default(RelatedCollectionsModule), ImagesModule pagesIncluding = default(ImagesModule), AggregateOffer shoppingSources = default(AggregateOffer), RelatedSearchesModule relatedSearches = default(RelatedSearchesModule), RecipesModule recipes = default(RecipesModule), ImagesModule visuallySimilarImages = default(ImagesModule), ImagesModule visuallySimilarProducts = default(ImagesModule), RecognizedEntitiesModule recognizedEntityGroups = default(RecognizedEntitiesModule), ImageTagsModule imageTags = default(ImageTagsModule))
            : base(id, readLink, webSearchUrl)
        {
            ImageInsightsToken = imageInsightsToken;
            BestRepresentativeQuery = bestRepresentativeQuery;
            ImageCaption = imageCaption;
            RelatedCollections = relatedCollections;
            PagesIncluding = pagesIncluding;
            ShoppingSources = shoppingSources;
            RelatedSearches = relatedSearches;
            Recipes = recipes;
            VisuallySimilarImages = visuallySimilarImages;
            VisuallySimilarProducts = visuallySimilarProducts;
            RecognizedEntityGroups = recognizedEntityGroups;
            ImageTags = imageTags;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets a token that you use in a subsequent call to the Image Search
        /// API to get more information about the image. For information about
        /// using this token, see the insightsToken query parameter. This token
        /// has the same usage as the token in the Image object.
        /// </summary>
        [JsonProperty(PropertyName = "imageInsightsToken")]
        public string ImageInsightsToken { get; private set; }

        /// <summary>
        /// Gets the query term that best represents the image. Clicking the
        /// link in the Query object, takes the user to a webpage with more
        /// pictures of the image.
        /// </summary>
        [JsonProperty(PropertyName = "bestRepresentativeQuery")]
        public Query BestRepresentativeQuery { get; private set; }

        /// <summary>
        /// Gets the caption to use for the image.
        /// </summary>
        [JsonProperty(PropertyName = "imageCaption")]
        public ImageInsightsImageCaption ImageCaption { get; private set; }

        /// <summary>
        /// Gets a list of links to webpages that contain related images.
        /// </summary>
        [JsonProperty(PropertyName = "relatedCollections")]
        public RelatedCollectionsModule RelatedCollections { get; private set; }

        /// <summary>
        /// Gets a list of webpages that contain the image. To access the
        /// webpage, use the URL in the image's hostPageUrl field.
        /// </summary>
        [JsonProperty(PropertyName = "pagesIncluding")]
        public ImagesModule PagesIncluding { get; private set; }

        /// <summary>
        /// Gets a list of merchants that offer items related to the image. For
        /// example, if the image is of an apple pie, the list contains
        /// merchants that are selling apple pies.
        /// </summary>
        [JsonProperty(PropertyName = "shoppingSources")]
        public AggregateOffer ShoppingSources { get; private set; }

        /// <summary>
        /// Gets a list of related queries made by others.
        /// </summary>
        [JsonProperty(PropertyName = "relatedSearches")]
        public RelatedSearchesModule RelatedSearches { get; private set; }

        /// <summary>
        /// Gets a list of recipes related to the image. For example, if the
        /// image is of an apple pie, the list contains recipes for making an
        /// apple pie.
        /// </summary>
        [JsonProperty(PropertyName = "recipes")]
        public RecipesModule Recipes { get; private set; }

        /// <summary>
        /// Gets a list of images that are visually similar to the original
        /// image. For example, if the specified image is of a sunset over a
        /// body of water, the list of similar images are of a sunset over a
        /// body of water. If the specified image is of a person, similar
        /// images might be of the same person or they might be of persons
        /// dressed similarly or in a similar setting. The criteria for
        /// similarity continues to evolve.
        /// </summary>
        [JsonProperty(PropertyName = "visuallySimilarImages")]
        public ImagesModule VisuallySimilarImages { get; private set; }

        /// <summary>
        /// Gets a list of images that contain products that are visually
        /// similar to products found in the original image. For example, if
        /// the specified image contains a dress, the list of similar images
        /// contain a dress. The image provides summary information about
        /// offers that Bing found online for the product.
        /// </summary>
        [JsonProperty(PropertyName = "visuallySimilarProducts")]
        public ImagesModule VisuallySimilarProducts { get; private set; }

        /// <summary>
        /// Gets a list of groups that contain images of entities that match
        /// the entity found in the specified image. For example, the response
        /// might include images from the general celebrity group if the entity
        /// was recognized in that group.
        /// </summary>
        [JsonProperty(PropertyName = "recognizedEntityGroups")]
        public RecognizedEntitiesModule RecognizedEntityGroups { get; private set; }

        /// <summary>
        /// Gets a list of characteristics of the content found in the image.
        /// For example, if the image is of a person, the tags might indicate
        /// the person's gender and the type of clothes they're wearing.
        /// </summary>
        [JsonProperty(PropertyName = "imageTags")]
        public ImageTagsModule ImageTags { get; private set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="Rest.ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (BestRepresentativeQuery != null)
            {
                BestRepresentativeQuery.Validate();
            }
            if (ImageCaption != null)
            {
                ImageCaption.Validate();
            }
            if (ImageTags != null)
            {
                ImageTags.Validate();
            }
        }
    }
}


text:
import os

from django.conf import settings
from django.contrib.staticfiles.finders import BaseFinder
from django.core.files.storage import FileSystemStorage

logo_paths = {
    'header_logo': settings.HEADER_LOGO,
    'favicon': settings.FAVICON,
}

logofinder_results = {
    os.path.join(prefix, os.path.basename(path)): path
    for prefix, path in logo_paths.items()
    if path
}

favicon_package_files = {
    'android-chrome-192x192.png',
    'android-chrome-512x512.png',
    'apple-touch-icon.png',
    'browserconfig.xml',
    'mstile-150x150.png',
    'mstile-310x310.png',
    'safari-pinned-tab.svg',
    'site.webmanifest',
}

if settings.FAVICON_PACKAGE and os.path.isdir(settings.FAVICON_PACKAGE):
    logofinder_results.update({
        os.path.join('favicon_package', file): os.path.join(settings.FAVICON_PACKAGE, file)
        for file in favicon_package_files
    })

class LogoFinder(BaseFinder):
    def find(self, path, all=False):
        result = logofinder_results.get(path)
        if not result:
            return []
        if all:
            return [result]
        return result

    def list(self, ignore_patterns):
        result = []
        for prefix, path in logo_paths.items():
            if not path:
                continue
            basedir, filename = os.path.split(path)
            storage = FileSystemStorage(location=basedir)
            storage.prefix = prefix
            result.append((filename, storage))
        if settings.FAVICON_PACKAGE and os.path.isdir(settings.FAVICON_PACKAGE):
            storage = FileSystemStorage(location=settings.FAVICON_PACKAGE)
            storage.prefix = 'favicon_package'
            result += [(filename, storage) for filename in favicon_package_files]
        return result


text:
package org.jboss.hal.dmr;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;

/**
 * @author David M. Lloyd
 */
class BytesModelValue extends ModelValue {

    /** JSON Key used to identify BytesModelValue. */
    private static final String TYPE_KEY = "BYTES_VALUE";

    private final byte[] bytes;

    BytesModelValue(byte[] bytes) {
        super(ModelType.BYTES);
        this.bytes = bytes;
    }

    @Override
    void writeExternal(DataOutput out) {
        out.writeInt(bytes.length);
        out.write(bytes);
    }

    @Override
    long asLong() {
        byte[] bytes = this.bytes;
        int length = bytes.length;
        int cnt = Math.min(8, length);
        long v = 0L;
        for (int i = 0; i < cnt; i++) {
            v <<= 8;
            v |= bytes[length - cnt + i] & 0xff;
        }
        return v;
    }

    @Override
    long asLong(long defVal) {
        return asLong();
    }

    @Override
    int asInt() {
        byte[] bytes = this.bytes;
        int length = bytes.length;
        int cnt = Math.min(4, length);
        int v = 0;
        for (int i = 0; i < cnt; i++) {
            v <<= 8;
            v |= bytes[length - cnt + i] & 0xff;
        }
        return v;
    }

    @Override
    int asInt(int defVal) {
        return asInt();
    }

    @Override
    double asDouble() {
        throw new IllegalArgumentException();
        //return Double.longBitsToDouble(asLong());
    }

    @Override
    double asDouble(double defVal) {
        throw new IllegalArgumentException();
        //return Double.longBitsToDouble(asLong());
    }

    @Override
    BigDecimal asBigDecimal() {
        return new BigDecimal(new BigInteger(bytes));
    }

    @Override
    BigInteger asBigInteger() {
        return new BigInteger(bytes);
    }

    @Override
    byte[] asBytes() {
        byte[] clone = new byte[bytes.length];
        for (int i = 0; i < bytes.length; i++) {
            clone[i] = bytes[i];
        }
        return clone;
    }

    @Override
    String asString() {
        StringBuilder builder = new StringBuilder(bytes.length * 4 + 4);
        format(builder, 0, false);
        return builder.toString();
    }

    @Override
    public String toJSONString(boolean compact) {
        StringBuilder builder = new StringBuilder(bytes.length * 4 + 4);
        formatAsJSON(builder, 0, !compact);
        return builder.toString();
    }

    @Override
    void formatAsJSON(StringBuilder builder, int indent, boolean multiLine) {
        builder.append('{');
        if (multiLine) {
            indent(builder.append('\n'), indent + 1);
        } else {
            builder.append(' ');
        }
        builder.append(jsonEscape(TYPE_KEY));
        builder.append(" : ");
        //builder.append(jsonEscape(Base64.encodeBytes(bytes)));
        if (multiLine) {
            indent(builder.append('\n'), indent);
        } else {
            builder.append(' ');
        }
        builder.append('}');
    }

    @Override
    @SuppressWarnings("HardCodedStringLiteral")
    void format(StringBuilder builder, int indent, boolean multiLine) {
        builder.append("bytes {");
        if (multiLine) {
            builder.append('\n');
            indent(builder, indent + 1);
        } else {
            builder.append(' ');
        }
        for (int i = 0, length = bytes.length; i < length; i++) {
            byte b = bytes[i];
            if (b >= 0 && b < 0x10) {
                builder.append("0x0").append(Integer.toHexString(b & 0xff));
            } else {
                builder.append("0x").append(Integer.toHexString(b & 0xff));
            }
            if (i != length - 1) {
                if (multiLine && (i & 7) == 7) {
                    indent(builder.append(",\n"), indent + 1);
                } else {
                    builder.append(", ");
                }
            }
        }
        if (multiLine) {
            indent(builder.append('\n'), indent);
        } else {
            builder.append(' ');
        }
        builder.append('}');
    }

    void formatMultiLine(StringBuilder target, int indent) {
        int length = bytes.length;
        format(target, indent, length > 8);
    }

    /**
     * Determine whether this object is equal to another.
     *
     * @param other the other object
     *
     * @return {@code true} if they are equal, {@code false} otherwise
     */
    @Override
    public boolean equals(Object other) {
        return other instanceof BytesModelValue && equals((BytesModelValue) other);
    }

    /**
     * Determine whether this object is equal to another.
     *
     * @param other the other object
     *
     * @return {@code true} if they are equal, {@code false} otherwise
     */
    public boolean equals(BytesModelValue other) {
        return this == other || other != null && Arrays.equals(bytes, other.bytes);
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(bytes) + 71;
    }
}


text:
from .aws import Action as BaseAction
from .aws import BaseARN

service_name = "AWS Performance Insights"
prefix = "pi"

class Action(BaseAction):
    def __init__(self, action: str = None) -> None:
        super().__init__(prefix, action)

class ARN(BaseARN):
    def __init__(self, resource: str = "", region: str = "", account: str = "") -> None:
        super().__init__(
            service=prefix, resource=resource, region=region, account=account
        )

DescribeDimensionKeys = Action("DescribeDimensionKeys")
GetDimensionKeyDetails = Action("GetDimensionKeyDetails")
GetResourceMetadata = Action("GetResourceMetadata")
GetResourceMetrics = Action("GetResourceMetrics")
ListAvailableResourceDimensions = Action("ListAvailableResourceDimensions")
ListAvailableResourceMetrics = Action("ListAvailableResourceMetrics")


text:
#ifndef SkFontMgr_DEFINED
#define SkFontMgr_DEFINED

#include "SkFontStyle.h"
#include "SkRefCnt.h"
#include "SkScalar.h"
#include "SkTypes.h"

class SkData;
class SkFontData;
class SkStreamAsset;
class SkString;
class SkTypeface;

class SK_API SkFontStyleSet : public SkRefCnt {
public:
    virtual int count() = 0;
    virtual void getStyle(int index, SkFontStyle*, SkString* style) = 0;
    virtual SkTypeface* createTypeface(int index) = 0;
    virtual SkTypeface* matchStyle(const SkFontStyle& pattern) = 0;

    static SkFontStyleSet* CreateEmpty();

protected:
    SkTypeface* matchStyleCSS3(const SkFontStyle& pattern);

private:
    typedef SkRefCnt INHERITED;
};

class SK_API SkFontMgr : public SkRefCnt {
public:
    int countFamilies() const;
    void getFamilyName(int index, SkString* familyName) const;
    SkFontStyleSet* createStyleSet(int index) const;

    /**
     *  The caller must call unref() on the returned object.
     *  Never returns NULL; will return an empty set if the name is not found.
     *
     *  Passing |nullptr| as the parameter will return the default system font.
     *
     *  It is possible that this will return a style set not accessible from
     *  createStyleSet(int) due to hidden or auto-activated fonts.
     */
    SkFontStyleSet* matchFamily(const char familyName[]) const;

    /**
     *  Find the closest matching typeface to the specified familyName and style
     *  and return a ref to it. The caller must call unref() on the returned
     *  object. Will never return NULL, as it will return the default font if
     *  no matching font is found.
     *
     *  Passing |nullptr| as the parameter for |familyName| will return the
     *  default system font.
     *
     *  It is possible that this will return a style set not accessible from
     *  createStyleSet(int) or matchFamily(const char[]) due to hidden or
     *  auto-activated fonts.
     */
    SkTypeface* matchFamilyStyle(const char familyName[], const SkFontStyle&) const;

    /**
     *  Use the system fallback to find a typeface for the given character.
     *  Note that bcp47 is a combination of ISO 639, 15924, and 3166-1 codes,
     *  so it is fine to just pass a ISO 639 here.
     *
     *  Will return NULL if no family can be found for the character
     *  in the system fallback.
     *
     *  Passing |nullptr| as the parameter for |familyName| will return the
     *  default system font.
     *
     *  bcp47[0] is the least significant fallback, bcp47[bcp47Count-1] is the
     *  most significant. If no specified bcp47 codes match, any font with the
     *  requested character will be matched.
     */
    SkTypeface* matchFamilyStyleCharacter(const char familyName[], const SkFontStyle&,
                                          const char* bcp47[], int bcp47Count,
                                          SkUnichar character) const;

    SkTypeface* matchFaceStyle(const SkTypeface*, const SkFontStyle&) const;

    /**
     *  Create a typeface for the specified data and TTC index (pass 0 for none)
     *  or NULL if the data is not recognized. The caller must call unref() on
     *  the returned object if it is not null.
     */
    SkTypeface* createFromData(SkData*, int ttcIndex = 0) const;

    /**
     *  Create a typeface for the specified stream and TTC index
     *  (pass 0 for none) or NULL if the stream is not recognized. The caller
     *  must call unref() on the returned object if it is not null.
     */
    SkTypeface* createFromStream(SkStreamAsset*, int ttcIndex = 0) const;

    struct FontParameters {
        struct Axis {
            SkFourByteTag fTag;
            SkScalar fStyleValue;
        };

        FontParameters() : fCollectionIndex(0), fAxisCount(0), fAxes(nullptr) {}

        /** Specify the index of the desired font.
         *
         *  Font formats like ttc, dfont, cff, cid, pfr, t42, t1, and fon may actually be indexed
         *  collections of fonts.
         */
        FontParameters& setCollectionIndex(int collectionIndex) {
            fCollectionIndex = collectionIndex;
            return *this;
        }

        /** Specify the GX variation axis values.
         *
         *  Any axes not specified will use the default value. Specified axes not present in the
         *  font will be ignored.
         *
         *  @param axes not copied. This pointer must remain valid for life of FontParameters.
         */
        FontParameters& setAxes(const Axis* axes, int axisCount) {
            fAxisCount = axisCount;
            fAxes = axes;
            return *this;
        }

        int getCollectionIndex() const {
            return fCollectionIndex;
        }
        const Axis* getAxes(int* axisCount) const {
            *axisCount = fAxisCount;
            return fAxes;
        }
    private:
        int fCollectionIndex;
        int fAxisCount;
        const Axis* fAxes;
    };
    /* Experimental, API subject to change. */
    SkTypeface* createFromStream(SkStreamAsset*, const FontParameters&) const;

    /**
     *  Create a typeface from the specified font data.
     *  Takes ownership of the font data, so the caller should not reference it again.
     *  Will return NULL if the typeface could not be created.
     *  The caller must call unref() on the returned object if it is not null.
     */
    SkTypeface* createFromFontData(SkFontData*) const;

    /**
     *  Create a typeface for the specified fileName and TTC index
     *  (pass 0 for none) or NULL if the file is not found, or its contents are
     *  not recognized. The caller must call unref() on the returned object
     *  if it is not null.
     */
    SkTypeface* createFromFile(const char path[], int ttcIndex = 0) const;

    SkTypeface* legacyCreateTypeface(const char familyName[], SkFontStyle style) const;

    /**
     *  Return a ref to the default fontmgr. The caller must call unref() on
     *  the returned object.
     */
    static SkFontMgr* RefDefault();

protected:
    virtual int onCountFamilies() const = 0;
    virtual void onGetFamilyName(int index, SkString* familyName) const = 0;
    virtual SkFontStyleSet* onCreateStyleSet(int index)const  = 0;

    /** May return NULL if the name is not found. */
    virtual SkFontStyleSet* onMatchFamily(const char familyName[]) const = 0;

    virtual SkTypeface* onMatchFamilyStyle(const char familyName[],
                                           const SkFontStyle&) const = 0;
    virtual SkTypeface* onMatchFamilyStyleCharacter(const char familyName[], const SkFontStyle&,
                                                    const char* bcp47[], int bcp47Count,
                                                    SkUnichar character) const = 0;
    virtual SkTypeface* onMatchFaceStyle(const SkTypeface*,
                                         const SkFontStyle&) const = 0;

    virtual SkTypeface* onCreateFromData(SkData*, int ttcIndex) const = 0;
    virtual SkTypeface* onCreateFromStream(SkStreamAsset*, int ttcIndex) const = 0;
    // TODO: make pure virtual.
    virtual SkTypeface* onCreateFromStream(SkStreamAsset*, const FontParameters&) const;
    virtual SkTypeface* onCreateFromFontData(SkFontData*) const;
    virtual SkTypeface* onCreateFromFile(const char path[], int ttcIndex) const = 0;

    virtual SkTypeface* onLegacyCreateTypeface(const char familyName[], SkFontStyle) const = 0;

private:
    static SkFontMgr* Factory();    // implemented by porting layer
    friend SkFontMgr* sk_fontmgr_create_default();

    typedef SkRefCnt INHERITED;
};

#endif


text:
package lecho.lib.hellocharts.renderer;

import lecho.lib.hellocharts.ChartComputator;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.AxisAutoValues;
import lecho.lib.hellocharts.util.Utils;
import lecho.lib.hellocharts.view.Chart;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.text.TextUtils;

/**
 * Default axes renderer. Can draw maximum four axes - two horizontal(top/bottom) and two vertical(left/right).
 *
 */
public class AxesRenderer {
	private static final int DEFAULT_AXIS_MARGIN_DP = 2;

	/** Axis positions indexes, used for indexing tabs that holds axes parameters, see below. */
	private static final int TOP = 0;
	private static final int LEFT = 1;
	private static final int RIGHT = 2;
	private static final int BOTTOM = 3;

	/**
	 * Used to measure label width. If label has mas 5 characters only 5 first characters of this array are used to
	 * measure text width.
	 **/
	private static final char[] labelWidthChars = new char[] { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
			'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' };

	private Chart chart;
	private int axisMargin;

	/** 4 text paints for every axis, not all have to be used, indexed with TOP, LEFT, RIGHT, BOTTOM. */
	private Paint[] textPaintTab = new Paint[] { new Paint(), new Paint(), new Paint(), new Paint() };
	private Paint linePaint;

	/** Holds number of values that should be drown for each axis. */
	private int[] axisValuesToDrawNumTab = new int[4];

	/** Holds raw values to draw for each axis. */
	private float[][] axisRawValuesTab = new float[4][0];

	/**
	 * Holds auto-generated values that should be drawn, i.e if axis is inside not all auto-generated values should be
	 * drawn to avoid overdrawing. Used only for auto axes.
	 **/
	private float[][] axisAutoValuesToDrawTab = new float[4][0];

	/** Holds custom values that should be drawn, used only for custom axes. */
	private AxisValue[][] axisValuesToDrawTab = new AxisValue[4][0];

	/** Buffers for axes lines coordinates(to draw grid in the background). */
	private float[][] axisLinesDrawBufferTab = new float[4][0];

	/** Buffers for auto-generated values for each axis, used only if there are auto axes. */
	private AxisAutoValues[] axisAutoValuesBufferTab = new AxisAutoValues[] { new AxisAutoValues(),
			new AxisAutoValues(), new AxisAutoValues(), new AxisAutoValues() };

	/** Holds fixed coordinates for each axis, for horizontal axes Y value is fixed, for vertical axes X value is fixed. */
	private float[] axisFixedCoordinateTab = new float[4];

	/** Holds baselines for axes names. */
	private float[] axisNameBaselineTab = new float[4];

	/** Holds fixed coordinate for axes separations lines, used only for horizontal axes where fixed value is Y. */
	private float[] axisSeparationLineTab = new float[4];

	/** Label max width for each axis. */
	private int[] axisLabelWidthTab = new int[4];

	/** Label height for each axis. */
	private int[] axisLabelTextAscentTab = new int[4];

	/** Label descent for each axis. **/
	private int[] axisLabelTextDescentTab = new int[4];

	/** Font metrics for each axis. */
	private FontMetricsInt[] fontMetricsTab = new FontMetricsInt[] { new FontMetricsInt(), new FontMetricsInt(),
			new FontMetricsInt(), new FontMetricsInt() };

	/** Buffer used to pass axis value to ValueFormatter implementation. */
	private float[] valuesBuff = new float[1];

	/** Holds formated axis value label. */
	private char[] labelBuffer = new char[32];

	private float density;
	private float scaledDensity;

	public AxesRenderer(Context context, Chart chart) {
		this.chart = chart;

		density = context.getResources().getDisplayMetrics().density;
		scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
		axisMargin = Utils.dp2px(density, DEFAULT_AXIS_MARGIN_DP);

		linePaint = new Paint();
		linePaint.setAntiAlias(true);
		linePaint.setStyle(Paint.Style.STROKE);
		linePaint.setStrokeWidth(1);

		for (Paint paint : textPaintTab) {
			paint.setAntiAlias(true);
		}
	}

	public void initAxesAttributes() {

		int axisXTopHeight = initAxisAttributes(chart.getChartData().getAxisXTop(), TOP);
		int axisXBottomHeight = initAxisAttributes(chart.getChartData().getAxisXBottom(), BOTTOM);

		int axisYLeftWidth = initAxisAttributes(chart.getChartData().getAxisYLeft(), LEFT);
		int axisYRightWidth = initAxisAttributes(chart.getChartData().getAxisYRight(), RIGHT);

		chart.getChartComputator().setAxesMargin(axisYLeftWidth, axisXTopHeight, axisYRightWidth, axisXBottomHeight);
	}

	/**
	 * Prepare axes coordinates and draw axes lines(if enabled) in the background.
	 *
	 * @param canvas
	 */
	public void drawInBackground(Canvas canvas) {
		Axis axis = chart.getChartData().getAxisYLeft();
		if (null != axis) {
			prepareAxis(axis, LEFT);
			drawAxisVerticalLines(canvas, axis, LEFT);
		}

		axis = chart.getChartData().getAxisYRight();
		if (null != axis) {
			prepareAxis(axis, RIGHT);
			drawAxisVerticalLines(canvas, axis, RIGHT);
		}

		axis = chart.getChartData().getAxisXBottom();
		if (null != axis) {
			prepareAxis(axis, BOTTOM);
			drawAxisHorizontalLines(canvas, axis, BOTTOM);
		}

		axis = chart.getChartData().getAxisXTop();
		if (null != axis) {
			prepareAxis(axis, TOP);
			drawAxisHorizontalLines(canvas, axis, TOP);
		}
	}

	/**
	 * Draw axes labels and names in the foreground.
	 *
	 * @param canvas
	 */
	public void drawInForeground(Canvas canvas) {
		Axis axis = chart.getChartData().getAxisYLeft();
		if (null != axis) {
			drawAxisVerticalLabels(canvas, axis, LEFT);
		}

		axis = chart.getChartData().getAxisYRight();
		if (null != axis) {
			drawAxisVerticalLabels(canvas, axis, RIGHT);
		}

		axis = chart.getChartData().getAxisXBottom();
		if (null != axis) {
			drawAxisHorizontalLabels(canvas, axis, BOTTOM);
		}

		axis = chart.getChartData().getAxisXTop();
		if (null != axis) {
			drawAxisHorizontalLabels(canvas, axis, TOP);
		}
	}

	/**
	 * Initialize attributes and measurement for axes(left, right, top, bottom); Returns axis measured width( for left
	 * and right) or height(for top and bottom).
	 */
	private int initAxisAttributes(Axis axis, int position) {
		if (null == axis) {
			return 0;
		}

		Typeface typeface = axis.getTypeface();
		if (null != typeface) {
			textPaintTab[position].setTypeface(typeface);
		}

		textPaintTab[position].setColor(axis.getTextColor());
		textPaintTab[position].setTextSize(Utils.sp2px(scaledDensity, axis.getTextSize()));
		textPaintTab[position].getFontMetricsInt(fontMetricsTab[position]);

		axisLabelTextAscentTab[position] = Math.abs(fontMetricsTab[position].ascent);
		axisLabelTextDescentTab[position] = Math.abs(fontMetricsTab[position].descent);
		axisLabelWidthTab[position] = (int) textPaintTab[position].measureText(labelWidthChars, 0,
				axis.getMaxLabelChars());

		int result = 0;

		if (LEFT == position || RIGHT == position) {

			int width = 0;

			// If auto-generated or has manual values add height for value labels.
			if ((axis.isAutoGenerated() || !axis.getValues().isEmpty()) && !axis.isInside()) {
				width += axisLabelWidthTab[position];
				width += axisMargin;
			}

			// If has name add height for axis name text.
			if (!TextUtils.isEmpty(axis.getName())) {
				width += axisLabelTextAscentTab[position];
				width += axisLabelTextDescentTab[position];
				width += axisMargin;
			}

			result = width;

		} else if (TOP == position || BOTTOM == position) {

			int height = 0;

			// If auto-generated or has manual values add height for value labels.
			if ((axis.isAutoGenerated() || !axis.getValues().isEmpty()) && !axis.isInside()) {
				height += axisLabelTextAscentTab[position];
				height += axisLabelTextDescentTab[position];
				height += axisMargin;
			}

			// If has name add height for axis name text.
			if (!TextUtils.isEmpty(axis.getName())) {
				height += axisLabelTextAscentTab[position];
				height += axisLabelTextDescentTab[position];
				height += axisMargin;
			}

			result = height;

		} else {
			throw new IllegalArgumentException("Invalid axis position: " + position);
		}

		return result;
	}

	private void prepareAxis(Axis axis, int position) {
		final ChartComputator computator = chart.getChartComputator();

		if (BOTTOM == position) {
			textPaintTab[position].setTextAlign(Align.CENTER);

			if (axis.isInside()) {
				axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().bottom - axisMargin
						- axisLabelTextDescentTab[position];
				axisNameBaselineTab[position] = computator.getContentRectWithMargins().bottom
						+ axisLabelTextAscentTab[position] + axisMargin;
			} else {
				axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().bottom
						+ axisLabelTextAscentTab[position] + axisMargin;
				axisNameBaselineTab[position] = axisFixedCoordinateTab[position] + axisMargin
						+ axisLabelTextAscentTab[position] + axisLabelTextDescentTab[position];
			}

			axisSeparationLineTab[position] = computator.getContentRect().bottom;

		} else if (TOP == position) {
			textPaintTab[position].setTextAlign(Align.CENTER);

			if (axis.isInside()) {
				axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().top + axisMargin
						+ axisLabelTextAscentTab[position];
				axisNameBaselineTab[position] = computator.getContentRectWithMargins().top - axisMargin
						- axisLabelTextDescentTab[position];
			} else {
				axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().top - axisMargin
						- axisLabelTextDescentTab[position];
				axisNameBaselineTab[position] = axisFixedCoordinateTab[position] - axisMargin
						- axisLabelTextAscentTab[position] - axisLabelTextDescentTab[position];
			}

			axisSeparationLineTab[position] = computator.getContentRect().top;

		} else if (LEFT == position) {

			if (axis.isInside()) {
				textPaintTab[position].setTextAlign(Align.LEFT);
				axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().left + axisMargin;
				axisNameBaselineTab[position] = computator.getContentRectWithMargins().left - axisMargin
						- axisLabelTextDescentTab[position];
			} else {
				textPaintTab[position].setTextAlign(Align.RIGHT);
				axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().left - axisMargin;
				axisNameBaselineTab[position] = axisFixedCoordinateTab[position] - axisLabelWidthTab[position]
						- axisMargin - axisLabelTextDescentTab[position];
			}

			axisSeparationLineTab[position] = computator.getContentRect().left;

		} else if (RIGHT == position) {

			if (axis.isInside()) {
				textPaintTab[position].setTextAlign(Align.RIGHT);
				axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().right - axisMargin;
				axisNameBaselineTab[position] = computator.getContentRectWithMargins().right + axisMargin
						+ axisLabelTextAscentTab[position];
			} else {
				textPaintTab[position].setTextAlign(Align.LEFT);
				axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().right + axisMargin;
				axisNameBaselineTab[position] = axisFixedCoordinateTab[position] + axisLabelWidthTab[position]
						+ axisMargin + axisLabelTextAscentTab[position];
			}

			axisSeparationLineTab[position] = computator.getContentRect().right;

		} else {
			throw new IllegalArgumentException("Invalid position for horizontal axis: " + position);
		}

		if (TOP == position || BOTTOM == position) {
			if (axis.isAutoGenerated()) {
				prepareAxisHorizontalAuto(axis, position);
			} else {
				prepareAxisHorizontalCustom(axis, position);
			}
		} else if (LEFT == position || RIGHT == position) {
			if (axis.isAutoGenerated()) {
				prepareAxisVerticalAuto(axis, position);
			} else {
				prepareAxisVerticalCustom(axis, position);
			}
		}

	}

	// ********** HORIZONTAL X AXES ****************

	private void prepareAxisHorizontalCustom(Axis axis, int position) {
		final ChartComputator computator = chart.getChartComputator();
		final Viewport maxViewport = computator.getMaximumViewport();
		final Viewport visibleViewport = computator.getVisibleViewport();
		final Rect contentRect = computator.getContentRect();
		float scale = maxViewport.width() / visibleViewport.width();

		int module = (int) Math.ceil((axis.getValues().size() * axisLabelWidthTab[position])
				/ (contentRect.width() * scale));

		if (module < 1) {
			module = 1;
		}

		if (axis.hasLines() && axisLinesDrawBufferTab[position].length < axis.getValues().size() * 4) {
			axisLinesDrawBufferTab[position] = new float[axis.getValues().size() * 4];
		}

		if (axisRawValuesTab[position].length < axis.getValues().size()) {
			axisRawValuesTab[position] = new float[axis.getValues().size()];
			axisValuesToDrawTab[position] = new AxisValue[axis.getValues().size()];
		}

		int valueIndex = 0;
		int valueToDrawIndex = 0;

		for (AxisValue axisValue : axis.getValues()) {
			final float value = axisValue.getValue();

			// Draw axis values that area within visible viewport.
			if (value >= visibleViewport.left && value <= visibleViewport.right) {

				// Draw axis values that have 0 module value, this will hide some labels if there is no place for them.
				if (0 == valueIndex % module) {

					final float rawX = computator.computeRawX(axisValue.getValue());

					if (checkRawX(contentRect, rawX, axis.isInside(), position)) {

						axisRawValuesTab[position][valueToDrawIndex] = rawX;
						axisValuesToDrawTab[position][valueToDrawIndex] = axisValue;

						++valueToDrawIndex;

					}
				}
				// If within viewport - increment valueIndex;
				++valueIndex;
			}
		}

		axisValuesToDrawNumTab[position] = valueToDrawIndex;

	}

	private void prepareAxisHorizontalAuto(Axis axis, int position) {
		final ChartComputator computator = chart.getChartComputator();
		final Viewport visibleViewport = computator.getVisibleViewport();
		final Rect contentRect = computator.getContentRect();

		Utils.computeAxisAutoValues(visibleViewport.left, visibleViewport.right, contentRect.width()
				/ axisLabelWidthTab[position] / 2, axisAutoValuesBufferTab[position]);

		if (axis.hasLines()
				&& axisLinesDrawBufferTab[position].length < axisAutoValuesBufferTab[position].valuesNumber * 4) {
			axisLinesDrawBufferTab[position] = new float[axisAutoValuesBufferTab[position].valuesNumber * 4];
		}

		if (axisRawValuesTab[position].length < axisAutoValuesBufferTab[position].valuesNumber) {
			axisRawValuesTab[position] = new float[axisAutoValuesBufferTab[position].valuesNumber];
			axisAutoValuesToDrawTab[position] = new float[axisAutoValuesBufferTab[position].valuesNumber];
		}

		int valueToDrawIndex = 0;

		for (int i = 0; i < axisAutoValuesBufferTab[position].valuesNumber; ++i) {

			final float rawX = computator.computeRawX(axisAutoValuesBufferTab[position].values[i]);

			if (checkRawX(contentRect, rawX, axis.isInside(), position)) {

				axisRawValuesTab[position][valueToDrawIndex] = rawX;
				axisAutoValuesToDrawTab[position][valueToDrawIndex] = axisAutoValuesBufferTab[position].values[i];

				++valueToDrawIndex;
			}
		}

		axisValuesToDrawNumTab[position] = valueToDrawIndex;

	}

	private void drawAxisHorizontalLines(Canvas canvas, Axis axis, int position) {
		final Rect contentRectMargins = chart.getChartComputator().getContentRectWithMargins();

		// Draw separation line with the same color as axis text.
		if (axis.hasSeparationLine()) {
			canvas.drawLine(contentRectMargins.left, axisSeparationLineTab[position], contentRectMargins.right,
					axisSeparationLineTab[position], textPaintTab[position]);
		}

		if (!axis.hasLines()) {
			return;
		}

		int valueToDrawIndex = 0;

		for (; valueToDrawIndex < axisValuesToDrawNumTab[position]; ++valueToDrawIndex) {

			axisLinesDrawBufferTab[position][valueToDrawIndex * 4 + 0] = axisRawValuesTab[position][valueToDrawIndex];
			axisLinesDrawBufferTab[position][valueToDrawIndex * 4 + 1] = contentRectMargins.top;
			axisLinesDrawBufferTab[position][valueToDrawIndex * 4 + 2] = axisRawValuesTab[position][valueToDrawIndex];
			axisLinesDrawBufferTab[position][valueToDrawIndex * 4 + 3] = contentRectMargins.bottom;
		}

		linePaint.setColor(axis.getLineColor());
		canvas.drawLines(axisLinesDrawBufferTab[position], 0, valueToDrawIndex * 4, linePaint);
	}

	private void drawAxisHorizontalLabels(Canvas canvas, Axis axis, int position) {
		final Rect contentRectMargins = chart.getChartComputator().getContentRectWithMargins();

		int valueToDrawIndex = 0;

		for (; valueToDrawIndex < axisValuesToDrawNumTab[position]; ++valueToDrawIndex) {

			final int numChars;

			if (axis.isAutoGenerated()) {
				valuesBuff[0] = axisAutoValuesToDrawTab[position][valueToDrawIndex];

				numChars = axis.getFormatter().formatAutoValue(labelBuffer, valuesBuff,
						axisAutoValuesBufferTab[position].decimals);
			} else {
				valuesBuff[0] = axisValuesToDrawTab[position][valueToDrawIndex].getValue();

				numChars = axis.getFormatter().formatValue(labelBuffer, valuesBuff,
						axisValuesToDrawTab[position][valueToDrawIndex].getLabel());
			}

			canvas.drawText(labelBuffer, labelBuffer.length - numChars, numChars,
					axisRawValuesTab[position][valueToDrawIndex], axisFixedCoordinateTab[position],
					textPaintTab[position]);

		}

		// Drawing axis name
		if (!TextUtils.isEmpty(axis.getName())) {
			textPaintTab[position].setTextAlign(Align.CENTER);
			canvas.drawText(axis.getName(), contentRectMargins.centerX(), axisNameBaselineTab[position],
					textPaintTab[position]);
		}
	}

	/**
	 * For axis inside chart area this method checks if there is place to draw axis label. If yes returns true,
	 * otherwise false.
	 */
	private boolean checkRawX(Rect rect, float rawX, boolean axisInside, int position) {
		if (axisInside) {
			float margin = axisLabelWidthTab[position] / 2;
			if (rawX >= rect.left + margin && rawX <= rect.right - margin) {
				return true;
			} else {
				return false;
			}
		}

		return true;

	}

	// ********** VERTICAL Y AXES ****************

	private void prepareAxisVerticalCustom(Axis axis, int position) {
		final ChartComputator computator = chart.getChartComputator();
		final Viewport maxViewport = computator.getMaximumViewport();
		final Viewport visibleViewport = computator.getVisibleViewport();
		final Rect contentRect = computator.getContentRect();
		float scale = maxViewport.height() / visibleViewport.height();

		int module = (int) Math.ceil((axis.getValues().size() * axisLabelTextAscentTab[position] * 2)
				/ (contentRect.height() * scale));

		if (module < 1) {
			module = 1;
		}

		if (axis.hasLines() && axisLinesDrawBufferTab[position].length < axis.getValues().size() * 4) {
			axisLinesDrawBufferTab[position] = new float[axis.getValues().size() * 4];
		}

		if (axisRawValuesTab[position].length < axis.getValues().size()) {
			axisRawValuesTab[position] = new float[axis.getValues().size()];
			axisValuesToDrawTab[position] = new AxisValue[axis.getValues().size()];
		}

		int valueIndex = 0;
		int valueToDrawIndex = 0;

		for (AxisValue axisValue : axis.getValues()) {
			final float value = axisValue.getValue();

			// Draw axis values that area within visible viewport.
			if (value >= visibleViewport.bottom && value <= visibleViewport.top) {

				// Draw axis values that have 0 module value, this will hide some labels if there is no place for them.
				if (0 == valueIndex % module) {

					final float rawY = computator.computeRawY(value);

					if (checkRawY(contentRect, rawY, axis.isInside(), position)) {

						axisRawValuesTab[position][valueToDrawIndex] = rawY;
						axisValuesToDrawTab[position][valueToDrawIndex] = axisValue;

						++valueToDrawIndex;
					}
				}
				// If within viewport - increment valueIndex;
				++valueIndex;
			}
		}

		axisValuesToDrawNumTab[position] = valueToDrawIndex;
	}

	private void prepareAxisVerticalAuto(Axis axis, int position) {
		final ChartComputator computator = chart.getChartComputator();
		final Viewport visibleViewport = computator.getVisibleViewport();
		final Rect contentRect = computator.getContentRect();

		Utils.computeAxisAutoValues(visibleViewport.bottom, visibleViewport.top, contentRect.height()
				/ axisLabelTextAscentTab[position] / 2, axisAutoValuesBufferTab[position]);

		if (axis.hasLines()
				&& axisLinesDrawBufferTab[position].length < axisAutoValuesBufferTab[position].valuesNumber * 4) {
			axisLinesDrawBufferTab[position] = new float[axisAutoValuesBufferTab[position].valuesNumber * 4];
		}

		if (axisRawValuesTab[position].length < axisAutoValuesBufferTab[position].valuesNumber) {
			axisRawValuesTab[position] = new float[axisAutoValuesBufferTab[position].valuesNumber];
			axisAutoValuesToDrawTab[position] = new float[axisAutoValuesBufferTab[position].valuesNumber];
		}

		int stopsToDrawIndex = 0;

		for (int i = 0; i < axisAutoValuesBufferTab[position].valuesNumber; i++) {
			final float rawY = computator.computeRawY(axisAutoValuesBufferTab[position].values[i]);

			if (checkRawY(contentRect, rawY, axis.isInside(), position)) {

				axisRawValuesTab[position][stopsToDrawIndex] = rawY;
				axisAutoValuesToDrawTab[position][stopsToDrawIndex] = axisAutoValuesBufferTab[position].values[i];

				++stopsToDrawIndex;
			}
		}

		axisValuesToDrawNumTab[position] = stopsToDrawIndex;
	}

	private void drawAxisVerticalLines(Canvas canvas, Axis axis, int position) {
		final Rect contentRectMargins = chart.getChartComputator().getContentRectWithMargins();

		// Draw separation line with the same color as axis text.
		if (axis.hasSeparationLine()) {
			canvas.drawLine(axisSeparationLineTab[position], contentRectMargins.bottom,
					axisSeparationLineTab[position], contentRectMargins.top, textPaintTab[position]);
		}

		if (!axis.hasLines()) {
			return;
		}

		int stopsToDrawIndex = 0;

		for (; stopsToDrawIndex < axisValuesToDrawNumTab[position]; ++stopsToDrawIndex) {

			axisLinesDrawBufferTab[position][stopsToDrawIndex * 4 + 0] = contentRectMargins.left;
			axisLinesDrawBufferTab[position][stopsToDrawIndex * 4 + 1] = axisRawValuesTab[position][stopsToDrawIndex];
			axisLinesDrawBufferTab[position][stopsToDrawIndex * 4 + 2] = contentRectMargins.right;
			axisLinesDrawBufferTab[position][stopsToDrawIndex * 4 + 3] = axisRawValuesTab[position][stopsToDrawIndex];
		}

		linePaint.setColor(axis.getLineColor());
		canvas.drawLines(axisLinesDrawBufferTab[position], 0, stopsToDrawIndex * 4, linePaint);
	}

	private void drawAxisVerticalLabels(Canvas canvas, Axis axis, int position) {
		final Rect contentRectMargins = chart.getChartComputator().getContentRectWithMargins();

		int stopsToDrawIndex = 0;

		for (; stopsToDrawIndex < axisValuesToDrawNumTab[position]; ++stopsToDrawIndex) {

			final int numChars;

			if (axis.isAutoGenerated()) {
				valuesBuff[0] = axisAutoValuesToDrawTab[position][stopsToDrawIndex];

				numChars = axis.getFormatter().formatAutoValue(labelBuffer, valuesBuff,
						axisAutoValuesBufferTab[position].decimals);
			} else {
				valuesBuff[0] = axisValuesToDrawTab[position][stopsToDrawIndex].getValue();

				numChars = axis.getFormatter().formatValue(labelBuffer, valuesBuff,
						axisValuesToDrawTab[position][stopsToDrawIndex].getLabel());
			}

			canvas.drawText(labelBuffer, labelBuffer.length - numChars, numChars, axisFixedCoordinateTab[position],
					axisRawValuesTab[position][stopsToDrawIndex], textPaintTab[position]);

		}

		// drawing axis name
		if (!TextUtils.isEmpty(axis.getName())) {
			textPaintTab[position].setTextAlign(Align.CENTER);
			canvas.save();
			canvas.rotate(-90, contentRectMargins.centerY(), contentRectMargins.centerY());
			canvas.drawText(axis.getName(), contentRectMargins.centerY(), axisNameBaselineTab[position],
					textPaintTab[position]);
			canvas.restore();
		}

	}

	/**
	 * For axis inside chart area this method checks if there is place to draw axis label. If yes returns true,
	 * otherwise false.
	 */
	private boolean checkRawY(Rect rect, float rawY, boolean axisInside, int position) {
		if (axisInside) {
			float marginBottom = axisLabelTextAscentTab[BOTTOM] + axisMargin;
			float marginTop = axisLabelTextAscentTab[TOP] + axisMargin;
			if (rawY <= rect.bottom - marginBottom && rawY >= rect.top + marginTop) {
				return true;
			} else {
				return false;
			}
		}

		return true;

	}
}


text:
import thunk from 'redux-thunk';
import axios from 'axios';
import jwtDecode from 'jwt-decode';
import configureMockStore from 'redux-mock-store';

import * as types from '../../src/actions/actionTypes';
import { signupAction, setCurrentUser }
from '../../src/actions/auth/signupAction';

jest.mock('react-router');
jwtDecode.mockImplementation(() => ({}));
const mockStore = configureMockStore([thunk]);

describe('Signup Action', () => {
  it('should return appropriate action when user signs up', () => {
    const action = setCurrentUser({
      username: 'enodi',
      fullname: 'Enodi Audu',
      email: 'enodiaudu5@gmail.com',
      password: 'password'
    });
    expect(action).toEqual({
      type: 'SIGNUP_SUCCESSFUL',
      user: {
        username: 'enodi',
        fullname: 'Enodi Audu',
        email: 'enodiaudu5@gmail.com',
        password: 'password'
      }
    });
  });

  it('should dispatch appropriate action on successful signup', () => {
    axios.post = jest.fn(() => Promise.resolve({
      data: { token: 'token' }
    }));

    const expectedActions = [
      {
        type: types.SIGNUP_SUCCESSFUL,
        user: {}
      }
    ];
    const store = mockStore();
    return store.dispatch(signupAction({
      username: 'enodi',
      fullname: 'Enodi Audu',
      email: 'enodiaudu5@gmail.com',
      password: 'password'
    }))
    .then(() => {
      expect(store.getActions()).toEqual(expectedActions);
    });
  });
});


text:
separate_arguments
------------------

Parse command-line arguments into a semicolon-separated list.

.. code-block:: cmake

  separate_arguments(<variable> <mode> <args>)

Parses a space-separated string ``<args>`` into a list of items,
and stores this list in semicolon-separated standard form in ``<variable>``.

This function is intended for parsing command-line arguments.
The entire command line must be passed as one string in the
argument ``<args>``.

The exact parsing rules depend on the operating system.
They are specified by the ``<mode>`` argument which must
be one of the following keywords:

``UNIX_COMMAND``
  Arguments are separated by by unquoted whitespace.
  Both single-quote and double-quote pairs are respected.
  A backslash escapes the next literal character (``\"`` is ``"``);
  there are no special escapes (``\n`` is just ``n``).

``WINDOWS_COMMAND``
  A Windows command-line is parsed using the same
  syntax the runtime library uses to construct argv at startup.  It
  separates arguments by whitespace that is not double-quoted.
  Backslashes are literal unless they precede double-quotes.  See the
  MSDN article `Parsing C Command-Line Arguments`_ for details.

``NATIVE_COMMAND``
  Proceeds as in ``WINDOWS_COMMAND`` mode if the host system is Windows.
  Otherwise proceeds as in ``UNIX_COMMAND`` mode.

.. _`Parsing C Command-Line Arguments`: https://msdn.microsoft.com/library/a1y7w461.aspx

.. code-block:: cmake

  separate_arguments(<var>)

Convert the value of ``<var>`` to a semi-colon separated list.  All
spaces are replaced with ';'.  This helps with generating command
lines.


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        android:orientation="vertical">

        <Switch
            android:id="@+id/value"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="16dp" />

    </LinearLayout>
</layout>


text:
package figglewatts.SEGment;

public abstract class BaseObject {
	public ComponentDock components = new ComponentDock();
	public String name;
	private long ID;

	public long getID() {
		return this.ID;
	}

	public boolean hasComponent(String name) {
		if (components.get(name) != null) {
			return true;
		} else {
			return false;
		}
	}

	public Component getComponent(String name) {
		return components.get(name);
	}

	public BaseObject() {
		this.ID = java.util.UUID.randomUUID().getMostSignificantBits();
	}
}


text:
/*
 * Do not modify this file. This file is generated from the elastictranscoder-2012-09-25.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.ElasticTranscoder.Model
{
    ///
    /// The ListPresetsResponse structure.
    ///
    public partial class ListPresetsResponse : AmazonWebServiceResponse
    {
        private string _nextPageToken;
        private List<Preset> _presets = new List<Preset>();

        ///
        /// Gets and sets the property NextPageToken.
        /// <para>
        /// A value that you use to access the second and subsequent pages of results, if any.
        /// When the presets fit on one page or when you've reached the last page of results,
        /// the value of NextPageToken is null.
        /// </para>
        ///
        public string NextPageToken
        {
            get { return this._nextPageToken; }
            set { this._nextPageToken = value; }
        }

        // Check to see if NextPageToken property is set
        internal bool IsSetNextPageToken()
        {
            return this._nextPageToken != null;
        }

        ///
        /// Gets and sets the property Presets.
        /// <para>
        /// An array of Preset objects.
        /// </para>
        ///
        public List<Preset> Presets
        {
            get { return this._presets; }
            set { this._presets = value; }
        }

        // Check to see if Presets property is set
        internal bool IsSetPresets()
        {
            return this._presets != null && this._presets.Count > 0;
        }

    }
}