text:
<?php

/*
 * GENERATED CODE WARNING
 * This file was automatically generated - do not edit!
 */

namespace Google\Cloud\Firestore\Admin\Tests\Unit\V1;

use Google\ApiCore\ApiException;

use Google\ApiCore\CredentialsWrapper;
use Google\ApiCore\LongRunning\OperationsClient;
use Google\ApiCore\Testing\GeneratedTest;

use Google\ApiCore\Testing\MockTransport;
use Google\Cloud\Firestore\Admin\V1\Database;
use Google\Cloud\Firestore\Admin\V1\ExportDocumentsResponse;

use Google\Cloud\Firestore\Admin\V1\Field;
use Google\Cloud\Firestore\Admin\V1\FirestoreAdminClient;
use Google\Cloud\Firestore\Admin\V1\Index;
use Google\Cloud\Firestore\Admin\V1\ListDatabasesResponse;
use Google\Cloud\Firestore\Admin\V1\ListFieldsResponse;
use Google\Cloud\Firestore\Admin\V1\ListIndexesResponse;
use Google\LongRunning\GetOperationRequest;
use Google\LongRunning\Operation;
use Google\Protobuf\Any;
use Google\Protobuf\GPBEmpty;
use Google\Rpc\Code;
use stdClass;

/**
 * @group firestore-admin
 *
 * @group gapic
 */
class FirestoreAdminClientTest extends GeneratedTest
{
    /**
     * @return TransportInterface
     */
    private function createTransport($deserialize = null)
    {
        return new MockTransport($deserialize);
    }

    /**
     * @return CredentialsWrapper
     */
    private function createCredentials()
    {
        return $this->getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock();
    }

    /**
     * @return FirestoreAdminClient
     */
    private function createClient(array $options = [])
    {
        $options += [
            'credentials' => $this->createCredentials(),
        ];
        return new FirestoreAdminClient($options);
    }

    /**
     * @test
     */
    public function createIndexTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new OperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('operations/createIndexTest');
        $incompleteOperation->setDone(false);
        $transport->addResponse($incompleteOperation);
        $name = 'name3373707';
        $expectedResponse = new Index();
        $expectedResponse->setName($name);
        $anyResponse = new Any();
        $anyResponse->setValue($expectedResponse->serializeToString());
        $completeOperation = new Operation();
        $completeOperation->setName('operations/createIndexTest');
        $completeOperation->setDone(true);
        $completeOperation->setResponse($anyResponse);
        $operationsTransport->addResponse($completeOperation);
        // Mock request
        $formattedParent = $gapicClient->collectionGroupName('[PROJECT]', '[DATABASE]', '[COLLECTION]');
        $index = new Index();
        $response = $gapicClient->createIndexLRO($formattedParent, $index);
        $this->assertFalse($response->isDone());
        $this->assertNull($response->getResult());
        $apiRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($apiRequests));
        $operationsRequestsEmpty = $operationsTransport->popReceivedCalls();
        $this->assertSame(0, count($operationsRequestsEmpty));
        $actualApiFuncCall = $apiRequests[0]->getFuncCall();
        $actualApiRequestObject = $apiRequests[0]->getRequestObject();
        $this->assertSame('/google.firestore.admin.v1.FirestoreAdmin/CreateIndex', $actualApiFuncCall);
        $actualValue = $actualApiRequestObject->getParent();
        $this->assertProtobufEquals($formattedParent, $actualValue);
        $actualValue = $actualApiRequestObject->getIndex();
        $this->assertProtobufEquals($index, $actualValue);
        $expectedOperationsRequestObject = new GetOperationRequest();
        $expectedOperationsRequestObject->setName('operations/createIndexTest');
        $response->pollUntilComplete([
            'initialPollDelayMillis' => 1,
        ]);
        $this->assertTrue($response->isDone());
        $this->assertEquals($expectedResponse, $response->getResult());
        $apiRequestsEmpty = $transport->popReceivedCalls();
        $this->assertSame(0, count($apiRequestsEmpty));
        $operationsRequests = $operationsTransport->popReceivedCalls();
        $this->assertSame(1, count($operationsRequests));
        $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall();
        $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject();
        $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall);
        $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }

    /**
     * @test
     */
    public function createIndexExceptionTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new OperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('operations/createIndexTest');
        $incompleteOperation->setDone(false);
        $transport->addResponse($incompleteOperation);
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $operationsTransport->addResponse(null, $status);
        // Mock request
        $formattedParent = $gapicClient->collectionGroupName('[PROJECT]', '[DATABASE]', '[COLLECTION]');
        $index = new Index();
        $response = $gapicClient->createIndexLRO($formattedParent, $index);
        $this->assertFalse($response->isDone());
        $this->assertNull($response->getResult());
        $expectedOperationsRequestObject = new GetOperationRequest();
        $expectedOperationsRequestObject->setName('operations/createIndexTest');
        try {
            $response->pollUntilComplete([
                'initialPollDelayMillis' => 1,
            ]);
            // If the pollUntilComplete() method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stubs are exhausted
        $transport->popReceivedCalls();
        $operationsTransport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }

    /**
     * @test
     */
    public function deleteIndexTest()
    {
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        // Mock response
        $expectedResponse = new GPBEmpty();
        $transport->addResponse($expectedResponse);
        // Mock request
        $formattedName = $gapicClient->indexName('[PROJECT]', '[DATABASE]', '[COLLECTION]', '[INDEX]');
        $gapicClient->deleteIndex($formattedName);
        $actualRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($actualRequests));
        $actualFuncCall = $actualRequests[0]->getFuncCall();
        $actualRequestObject = $actualRequests[0]->getRequestObject();
        $this->assertSame('/google.firestore.admin.v1.FirestoreAdmin/DeleteIndex', $actualFuncCall);
        $actualValue = $actualRequestObject->getName();
        $this->assertProtobufEquals($formattedName, $actualValue);
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function deleteIndexExceptionTest()
    {
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage  = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $transport->addResponse(null, $status);
        // Mock request
        $formattedName = $gapicClient->indexName('[PROJECT]', '[DATABASE]', '[COLLECTION]', '[INDEX]');
        try {
            $gapicClient->deleteIndex($formattedName);
            // If the $gapicClient method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stub is exhausted
        $transport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function exportDocumentsTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new OperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('operations/exportDocumentsTest');
        $incompleteOperation->setDone(false);
        $transport->addResponse($incompleteOperation);
        $outputUriPrefix2 = 'outputUriPrefix2-377757258';
        $expectedResponse = new ExportDocumentsResponse();
        $expectedResponse->setOutputUriPrefix($outputUriPrefix2);
        $anyResponse = new Any();
        $anyResponse->setValue($expectedResponse->serializeToString());
        $completeOperation = new Operation();
        $completeOperation->setName('operations/exportDocumentsTest');
        $completeOperation->setDone(true);
        $completeOperation->setResponse($anyResponse);
        $operationsTransport->addResponse($completeOperation);
        // Mock request
        $formattedName = $gapicClient->databaseName('[PROJECT]', '[DATABASE]');
        $response = $gapicClient->exportDocumentsLRO($formattedName);
        $this->assertFalse($response->isDone());
        $this->assertNull($response->getResult());
        $apiRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($apiRequests));
        $operationsRequestsEmpty = $operationsTransport->popReceivedCalls();
        $this->assertSame(0, count($operationsRequestsEmpty));
        $actualApiFuncCall = $apiRequests[0]->getFuncCall();
        $actualApiRequestObject = $apiRequests[0]->getRequestObject();
        $this->assertSame('/google.firestore.admin.v1.FirestoreAdmin/ExportDocuments', $actualApiFuncCall);
        $actualValue = $actualApiRequestObject->getName();
        $this->assertProtobufEquals($formattedName, $actualValue);
        $expectedOperationsRequestObject = new GetOperationRequest();
        $expectedOperationsRequestObject->setName('operations/exportDocumentsTest');
        $response->pollUntilComplete([
            'initialPollDelayMillis' => 1,
        ]);
        $this->assertTrue($response->isDone());
        $this->assertEquals($expectedResponse, $response->getResult());
        $apiRequestsEmpty = $transport->popReceivedCalls();
        $this->assertSame(0, count($apiRequestsEmpty));
        $operationsRequests = $operationsTransport->popReceivedCalls();
        $this->assertSame(1, count($operationsRequests));
        $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall();
        $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject();
        $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall);
        $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }

    /**
     * @test
     */
    public function exportDocumentsExceptionTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new OperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('operations/exportDocumentsTest');
        $incompleteOperation->setDone(false);
        $transport->addResponse($incompleteOperation);
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $operationsTransport->addResponse(null, $status);
        // Mock request
        $formattedName = $gapicClient->databaseName('[PROJECT]', '[DATABASE]');
        $response = $gapicClient->exportDocumentsLRO($formattedName);
        $this->assertFalse($response->isDone());
        $this->assertNull($response->getResult());
        $expectedOperationsRequestObject = new GetOperationRequest();
        $expectedOperationsRequestObject->setName('operations/exportDocumentsTest');
        try {
            $response->pollUntilComplete([
                'initialPollDelayMillis' => 1,
            ]);
            // If the pollUntilComplete() method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stubs are exhausted
        $transport->popReceivedCalls();
        $operationsTransport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }

    /**
     * @test
     */
    public function getDatabaseTest()
    {
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        // Mock response
        $name2 = 'name2-1052831874';
        $locationId = 'locationId552319461';
        $keyPrefix = 'keyPrefix438630514';
        $etag = 'etag3123477';
        $expectedResponse = new Database();
        $expectedResponse->setName($name2);
        $expectedResponse->setLocationId($locationId);
        $expectedResponse->setKeyPrefix($keyPrefix);
        $expectedResponse->setEtag($etag);
        $transport->addResponse($expectedResponse);
        // Mock request
        $formattedName = $gapicClient->databaseName('[PROJECT]', '[DATABASE]');
        $response = $gapicClient->getDatabase($formattedName);
        $this->assertEquals($expectedResponse, $response);
        $actualRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($actualRequests));
        $actualFuncCall = $actualRequests[0]->getFuncCall();
        $actualRequestObject = $actualRequests[0]->getRequestObject();
        $this->assertSame('/google.firestore.admin.v1.FirestoreAdmin/GetDatabase', $actualFuncCall);
        $actualValue = $actualRequestObject->getName();
        $this->assertProtobufEquals($formattedName, $actualValue);
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function getDatabaseExceptionTest()
    {
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage  = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $transport->addResponse(null, $status);
        // Mock request
        $formattedName = $gapicClient->databaseName('[PROJECT]', '[DATABASE]');
        try {
            $gapicClient->getDatabase($formattedName);
            // If the $gapicClient method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stub is exhausted
        $transport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function getFieldTest()
    {
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        // Mock response
        $name2 = 'name2-1052831874';
        $expectedResponse = new Field();
        $expectedResponse->setName($name2);
        $transport->addResponse($expectedResponse);
        // Mock request
        $formattedName = $gapicClient->fieldName('[PROJECT]', '[DATABASE]', '[COLLECTION]', '[FIELD]');
        $response = $gapicClient->getField($formattedName);
        $this->assertEquals($expectedResponse, $response);
        $actualRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($actualRequests));
        $actualFuncCall = $actualRequests[0]->getFuncCall();
        $actualRequestObject = $actualRequests[0]->getRequestObject();
        $this->assertSame('/google.firestore.admin.v1.FirestoreAdmin/GetField', $actualFuncCall);
        $actualValue = $actualRequestObject->getName();
        $this->assertProtobufEquals($formattedName, $actualValue);
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function getFieldExceptionTest()
    {
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage  = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $transport->addResponse(null, $status);
        // Mock request
        $formattedName = $gapicClient->fieldName('[PROJECT]', '[DATABASE]', '[COLLECTION]', '[FIELD]');
        try {
            $gapicClient->getField($formattedName);
            // If the $gapicClient method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stub is exhausted
        $transport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function getIndexTest()
    {
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        // Mock response
        $name2 = 'name2-1052831874';
        $expectedResponse = new Index();
        $expectedResponse->setName($name2);
        $transport->addResponse($expectedResponse);
        // Mock request
        $formattedName = $gapicClient->indexName('[PROJECT]', '[DATABASE]', '[COLLECTION]', '[INDEX]');
        $response = $gapicClient->getIndex($formattedName);
        $this->assertEquals($expectedResponse, $response);
        $actualRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($actualRequests));
        $actualFuncCall = $actualRequests[0]->getFuncCall();
        $actualRequestObject = $actualRequests[0]->getRequestObject();
        $this->assertSame('/google.firestore.admin.v1.FirestoreAdmin/GetIndex', $actualFuncCall);
        $actualValue = $actualRequestObject->getName();
        $this->assertProtobufEquals($formattedName, $actualValue);
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function getIndexExceptionTest()
    {
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage  = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $transport->addResponse(null, $status);
        // Mock request
        $formattedName = $gapicClient->indexName('[PROJECT]', '[DATABASE]', '[COLLECTION]', '[INDEX]');
        try {
            $gapicClient->getIndex($formattedName);
            // If the $gapicClient method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stub is exhausted
        $transport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function importDocumentsTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new OperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('operations/importDocumentsTest');
        $incompleteOperation->setDone(false);
        $transport->addResponse($incompleteOperation);
        $expectedResponse = new GPBEmpty();
        $anyResponse = new Any();
        $anyResponse->setValue($expectedResponse->serializeToString());
        $completeOperation = new Operation();
        $completeOperation->setName('operations/importDocumentsTest');
        $completeOperation->setDone(true);
        $completeOperation->setResponse($anyResponse);
        $operationsTransport->addResponse($completeOperation);
        // Mock request
        $formattedName = $gapicClient->databaseName('[PROJECT]', '[DATABASE]');
        $response = $gapicClient->importDocumentsLRO($formattedName);
        $this->assertFalse($response->isDone());
        $this->assertNull($response->getResult());
        $apiRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($apiRequests));
        $operationsRequestsEmpty = $operationsTransport->popReceivedCalls();
        $this->assertSame(0, count($operationsRequestsEmpty));
        $actualApiFuncCall = $apiRequests[0]->getFuncCall();
        $actualApiRequestObject = $apiRequests[0]->getRequestObject();
        $this->assertSame('/google.firestore.admin.v1.FirestoreAdmin/ImportDocuments', $actualApiFuncCall);
        $actualValue = $actualApiRequestObject->getName();
        $this->assertProtobufEquals($formattedName, $actualValue);
        $expectedOperationsRequestObject = new GetOperationRequest();
        $expectedOperationsRequestObject->setName('operations/importDocumentsTest');
        $response->pollUntilComplete([
            'initialPollDelayMillis' => 1,
        ]);
        $this->assertTrue($response->isDone());
        $this->assertEquals($expectedResponse, $response->getResult());
        $apiRequestsEmpty = $transport->popReceivedCalls();
        $this->assertSame(0, count($apiRequestsEmpty));
        $operationsRequests = $operationsTransport->popReceivedCalls();
        $this->assertSame(1, count($operationsRequests));
        $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall();
        $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject();
        $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall);
        $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }

    /**
     * @test
     */
    public function importDocumentsExceptionTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new OperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('operations/importDocumentsTest');
        $incompleteOperation->setDone(false);
        $transport->addResponse($incompleteOperation);
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $operationsTransport->addResponse(null, $status);
        // Mock request
        $formattedName = $gapicClient->databaseName('[PROJECT]', '[DATABASE]');
        $response = $gapicClient->importDocumentsLRO($formattedName);
        $this->assertFalse($response->isDone());
        $this->assertNull($response->getResult());
        $expectedOperationsRequestObject = new GetOperationRequest();
        $expectedOperationsRequestObject->setName('operations/importDocumentsTest');
        try {
            $response->pollUntilComplete([
                'initialPollDelayMillis' => 1,
            ]);
            // If the pollUntilComplete() method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stubs are exhausted
        $transport->popReceivedCalls();
        $operationsTransport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }

    /**
     * @test
     */
    public function listDatabasesTest()
    {
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        // Mock response
        $expectedResponse = new ListDatabasesResponse();
        $transport->addResponse($expectedResponse);
        // Mock request
        $formattedParent = $gapicClient->projectName('[PROJECT]');
        $response = $gapicClient->listDatabases($formattedParent);
        $this->assertEquals($expectedResponse, $response);
        $actualRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($actualRequests));
        $actualFuncCall = $actualRequests[0]->getFuncCall();
        $actualRequestObject = $actualRequests[0]->getRequestObject();
        $this->assertSame('/google.firestore.admin.v1.FirestoreAdmin/ListDatabases', $actualFuncCall);
        $actualValue = $actualRequestObject->getParent();
        $this->assertProtobufEquals($formattedParent, $actualValue);
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function listDatabasesExceptionTest()
    {
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage  = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $transport->addResponse(null, $status);
        // Mock request
        $formattedParent = $gapicClient->projectName('[PROJECT]');
        try {
            $gapicClient->listDatabases($formattedParent);
            // If the $gapicClient method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stub is exhausted
        $transport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function listFieldsTest()
    {
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        // Mock response
        $nextPageToken = '';
        $fieldsElement = new Field();
        $fields = [
            $fieldsElement,
        ];
        $expectedResponse = new ListFieldsResponse();
        $expectedResponse->setNextPageToken($nextPageToken);
        $expectedResponse->setFields($fields);
        $transport->addResponse($expectedResponse);
        // Mock request
        $formattedParent = $gapicClient->collectionGroupName('[PROJECT]', '[DATABASE]', '[COLLECTION]');
        $response = $gapicClient->listFields($formattedParent);
        $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject());
        $resources = iterator_to_array($response->iterateAllElements());
        $this->assertSame(1, count($resources));
        $this->assertEquals($expectedResponse->getFields()[0], $resources[0]);
        $actualRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($actualRequests));
        $actualFuncCall = $actualRequests[0]->getFuncCall();
        $actualRequestObject = $actualRequests[0]->getRequestObject();
        $this->assertSame('/google.firestore.admin.v1.FirestoreAdmin/ListFields', $actualFuncCall);
        $actualValue = $actualRequestObject->getParent();
        $this->assertProtobufEquals($formattedParent, $actualValue);
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function listFieldsExceptionTest()
    {
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage  = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $transport->addResponse(null, $status);
        // Mock request
        $formattedParent = $gapicClient->collectionGroupName('[PROJECT]', '[DATABASE]', '[COLLECTION]');
        try {
            $gapicClient->listFields($formattedParent);
            // If the $gapicClient method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stub is exhausted
        $transport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function listIndexesTest()
    {
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        // Mock response
        $nextPageToken = '';
        $indexesElement = new Index();
        $indexes = [
            $indexesElement,
        ];
        $expectedResponse = new ListIndexesResponse();
        $expectedResponse->setNextPageToken($nextPageToken);
        $expectedResponse->setIndexes($indexes);
        $transport->addResponse($expectedResponse);
        // Mock request
        $formattedParent = $gapicClient->collectionGroupName('[PROJECT]', '[DATABASE]', '[COLLECTION]');
        $response = $gapicClient->listIndexes($formattedParent);
        $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject());
        $resources = iterator_to_array($response->iterateAllElements());
        $this->assertSame(1, count($resources));
        $this->assertEquals($expectedResponse->getIndexes()[0], $resources[0]);
        $actualRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($actualRequests));
        $actualFuncCall = $actualRequests[0]->getFuncCall();
        $actualRequestObject = $actualRequests[0]->getRequestObject();
        $this->assertSame('/google.firestore.admin.v1.FirestoreAdmin/ListIndexes', $actualFuncCall);
        $actualValue = $actualRequestObject->getParent();
        $this->assertProtobufEquals($formattedParent, $actualValue);
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function listIndexesExceptionTest()
    {
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
        ]);
        $this->assertTrue($transport->isExhausted());
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage  = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $transport->addResponse(null, $status);
        // Mock request
        $formattedParent = $gapicClient->collectionGroupName('[PROJECT]', '[DATABASE]', '[COLLECTION]');
        try {
            $gapicClient->listIndexes($formattedParent);
            // If the $gapicClient method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stub is exhausted
        $transport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
    }

    /**
     * @test
     */
    public function updateDatabaseTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new OperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('operations/updateDatabaseTest');
        $incompleteOperation->setDone(false);
        $transport->addResponse($incompleteOperation);
        $name = 'name3373707';
        $locationId = 'locationId552319461';
        $keyPrefix = 'keyPrefix438630514';
        $etag = 'etag3123477';
        $expectedResponse = new Database();
        $expectedResponse->setName($name);
        $expectedResponse->setLocationId($locationId);
        $expectedResponse->setKeyPrefix($keyPrefix);
        $expectedResponse->setEtag($etag);
        $anyResponse = new Any();
        $anyResponse->setValue($expectedResponse->serializeToString());
        $completeOperation = new Operation();
        $completeOperation->setName('operations/updateDatabaseTest');
        $completeOperation->setDone(true);
        $completeOperation->setResponse($anyResponse);
        $operationsTransport->addResponse($completeOperation);
        // Mock request
        $database = new Database();
        $response = $gapicClient->updateDatabase($database);
        $this->assertFalse($response->isDone());
        $this->assertNull($response->getResult());
        $apiRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($apiRequests));
        $operationsRequestsEmpty = $operationsTransport->popReceivedCalls();
        $this->assertSame(0, count($operationsRequestsEmpty));
        $actualApiFuncCall = $apiRequests[0]->getFuncCall();
        $actualApiRequestObject = $apiRequests[0]->getRequestObject();
        $this->assertSame('/google.firestore.admin.v1.FirestoreAdmin/UpdateDatabase', $actualApiFuncCall);
        $actualValue = $actualApiRequestObject->getDatabase();
        $this->assertProtobufEquals($database, $actualValue);
        $expectedOperationsRequestObject = new GetOperationRequest();
        $expectedOperationsRequestObject->setName('operations/updateDatabaseTest');
        $response->pollUntilComplete([
            'initialPollDelayMillis' => 1,
        ]);
        $this->assertTrue($response->isDone());
        $this->assertEquals($expectedResponse, $response->getResult());
        $apiRequestsEmpty = $transport->popReceivedCalls();
        $this->assertSame(0, count($apiRequestsEmpty));
        $operationsRequests = $operationsTransport->popReceivedCalls();
        $this->assertSame(1, count($operationsRequests));
        $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall();
        $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject();
        $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall);
        $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }

    /**
     * @test
     */
    public function updateDatabaseExceptionTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new OperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('operations/updateDatabaseTest');
        $incompleteOperation->setDone(false);
        $transport->addResponse($incompleteOperation);
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $operationsTransport->addResponse(null, $status);
        // Mock request
        $database = new Database();
        $response = $gapicClient->updateDatabase($database);
        $this->assertFalse($response->isDone());
        $this->assertNull($response->getResult());
        $expectedOperationsRequestObject = new GetOperationRequest();
        $expectedOperationsRequestObject->setName('operations/updateDatabaseTest');
        try {
            $response->pollUntilComplete([
                'initialPollDelayMillis' => 1,
            ]);
            // If the pollUntilComplete() method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stubs are exhausted
        $transport->popReceivedCalls();
        $operationsTransport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }

    /**
     * @test
     */
    public function updateFieldTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new OperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('operations/updateFieldTest');
        $incompleteOperation->setDone(false);
        $transport->addResponse($incompleteOperation);
        $name = 'name3373707';
        $expectedResponse = new Field();
        $expectedResponse->setName($name);
        $anyResponse = new Any();
        $anyResponse->setValue($expectedResponse->serializeToString());
        $completeOperation = new Operation();
        $completeOperation->setName('operations/updateFieldTest');
        $completeOperation->setDone(true);
        $completeOperation->setResponse($anyResponse);
        $operationsTransport->addResponse($completeOperation);
        // Mock request
        $field = new Field();
        $fieldName = 'fieldName1265009317';
        $field->setName($fieldName);
        $response = $gapicClient->updateFieldLRO($field);
        $this->assertFalse($response->isDone());
        $this->assertNull($response->getResult());
        $apiRequests = $transport->popReceivedCalls();
        $this->assertSame(1, count($apiRequests));
        $operationsRequestsEmpty = $operationsTransport->popReceivedCalls();
        $this->assertSame(0, count($operationsRequestsEmpty));
        $actualApiFuncCall = $apiRequests[0]->getFuncCall();
        $actualApiRequestObject = $apiRequests[0]->getRequestObject();
        $this->assertSame('/google.firestore.admin.v1.FirestoreAdmin/UpdateField', $actualApiFuncCall);
        $actualValue = $actualApiRequestObject->getField();
        $this->assertProtobufEquals($field, $actualValue);
        $expectedOperationsRequestObject = new GetOperationRequest();
        $expectedOperationsRequestObject->setName('operations/updateFieldTest');
        $response->pollUntilComplete([
            'initialPollDelayMillis' => 1,
        ]);
        $this->assertTrue($response->isDone());
        $this->assertEquals($expectedResponse, $response->getResult());
        $apiRequestsEmpty = $transport->popReceivedCalls();
        $this->assertSame(0, count($apiRequestsEmpty));
        $operationsRequests = $operationsTransport->popReceivedCalls();
        $this->assertSame(1, count($operationsRequests));
        $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall();
        $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject();
        $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall);
        $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }

    /**
     * @test
     */
    public function updateFieldExceptionTest()
    {
        $operationsTransport = $this->createTransport();
        $operationsClient = new OperationsClient([
            'serviceAddress' => '',
            'transport' => $operationsTransport,
            'credentials' => $this->createCredentials(),
        ]);
        $transport = $this->createTransport();
        $gapicClient = $this->createClient([
            'transport' => $transport,
            'operationsClient' => $operationsClient,
        ]);
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
        // Mock response
        $incompleteOperation = new Operation();
        $incompleteOperation->setName('operations/updateFieldTest');
        $incompleteOperation->setDone(false);
        $transport->addResponse($incompleteOperation);
        $status = new stdClass();
        $status->code = Code::DATA_LOSS;
        $status->details = 'internal error';
        $expectedExceptionMessage = json_encode([
            'message' => 'internal error',
            'code' => Code::DATA_LOSS,
            'status' => 'DATA_LOSS',
            'details' => [],
        ], JSON_PRETTY_PRINT);
        $operationsTransport->addResponse(null, $status);
        // Mock request
        $field = new Field();
        $fieldName = 'fieldName1265009317';
        $field->setName($fieldName);
        $response = $gapicClient->updateFieldLRO($field);
        $this->assertFalse($response->isDone());
        $this->assertNull($response->getResult());
        $expectedOperationsRequestObject = new GetOperationRequest();
        $expectedOperationsRequestObject->setName('operations/updateFieldTest');
        try {
            $response->pollUntilComplete([
                'initialPollDelayMillis' => 1,
            ]);
            // If the pollUntilComplete() method call did not throw, fail the test
            $this->fail('Expected an ApiException, but no exception was thrown.');
        } catch (ApiException $ex) {
            $this->assertEquals($status->code, $ex->getCode());
            $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
        }
        // Call popReceivedCalls to ensure the stubs are exhausted
        $transport->popReceivedCalls();
        $operationsTransport->popReceivedCalls();
        $this->assertTrue($transport->isExhausted());
        $this->assertTrue($operationsTransport->isExhausted());
    }
}


text:
require "thor"

Dir[File.join(File.dirname(__FILE__), "commands", "*.rb")].each do |file|
  require file
end

module Meatshield
  class CLI < Thor
    desc "summary", "Summary of the shit"
    def summary
      puts "This is a summary of all that shit."
    end

    desc "attackers", "Top source ip addresses in the logs"
    def attackers
      puts "These are the fuckers right here"
    end

    desc "hits", "which known bad ips are in the logs"
    def hits
      puts "These are the hits"
    end

    desc "artwork", "displays some artwork"
    def artwork
      Meatshield::Artwork.run
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Imper86\AllegroApi\Soap\Wsdl;

class PostageStruct
{

    /**
     * @var float $postageAmount
     */
    protected $postageAmount = null;

    /**
     * @var float $postageAmountAdd
     */
    protected $postageAmountAdd = null;

    /**
     * @var int $postagePackSize
     */
    protected $postagePackSize = null;

    /**
     * @var int $postageId
     */
    protected $postageId = null;

    /**
     * @var int $postageFreeShipping
     */
    protected $postageFreeShipping = null;

    /**
     * @var int $postageFreeReturn
     */
    protected $postageFreeReturn = null;

    /**
     * @var FulfillmentTimeStruct $postageFulfillmentTime
     */
    protected $postageFulfillmentTime = null;

    /**
     * @param float $postageAmount
     * @param float $postageAmountAdd
     * @param int $postagePackSize
     * @param int $postageId
     * @param int $postageFreeShipping
     * @param FulfillmentTimeStruct $postageFulfillmentTime
     */
    public function __construct($postageAmount = null, $postageAmountAdd = null, $postagePackSize = null, $postageId = null, $postageFreeShipping = null, $postageFulfillmentTime = null)
    {
      $this->postageAmount = $postageAmount;
      $this->postageAmountAdd = $postageAmountAdd;
      $this->postagePackSize = $postagePackSize;
      $this->postageId = $postageId;
      $this->postageFreeShipping = $postageFreeShipping;
      $this->postageFulfillmentTime = $postageFulfillmentTime;
    }

    /**
     * @return float
     */
    public function getPostageAmount()
    {
      return $this->postageAmount;
    }

    /**
     * @param float $postageAmount
     * @return \Imper86\AllegroApi\Soap\Wsdl\PostageStruct
     */
    public function setPostageAmount($postageAmount)
    {
      $this->postageAmount = $postageAmount;
      return $this;
    }

    /**
     * @return float
     */
    public function getPostageAmountAdd()
    {
      return $this->postageAmountAdd;
    }

    /**
     * @param float $postageAmountAdd
     * @return \Imper86\AllegroApi\Soap\Wsdl\PostageStruct
     */
    public function setPostageAmountAdd($postageAmountAdd)
    {
      $this->postageAmountAdd = $postageAmountAdd;
      return $this;
    }

    /**
     * @return int
     */
    public function getPostagePackSize()
    {
      return $this->postagePackSize;
    }

    /**
     * @param int $postagePackSize
     * @return \Imper86\AllegroApi\Soap\Wsdl\PostageStruct
     */
    public function setPostagePackSize($postagePackSize)
    {
      $this->postagePackSize = $postagePackSize;
      return $this;
    }

    /**
     * @return int
     */
    public function getPostageId()
    {
      return $this->postageId;
    }

    /**
     * @param int $postageId
     * @return \Imper86\AllegroApi\Soap\Wsdl\PostageStruct
     */
    public function setPostageId($postageId)
    {
      $this->postageId = $postageId;
      return $this;
    }

    /**
     * @return int
     */
    public function getPostageFreeShipping()
    {
      return $this->postageFreeShipping;
    }

    /**
     * @param int $postageFreeShipping
     * @return \Imper86\AllegroApi\Soap\Wsdl\PostageStruct
     */
    public function setPostageFreeShipping($postageFreeShipping)
    {
      $this->postageFreeShipping = $postageFreeShipping;
      return $this;
    }

    /**
     * @return int
     */
    public function getPostageFreeReturn()
    {
      return $this->postageFreeReturn;
    }

    /**
     * @param int $postageFreeReturn
     * @return \Imper86\AllegroApi\Soap\Wsdl\PostageStruct
     */
    public function setPostageFreeReturn($postageFreeReturn)
    {
      $this->postageFreeReturn = $postageFreeReturn;
      return $this;
    }

    /**
     * @return FulfillmentTimeStruct
     */
    public function getPostageFulfillmentTime()
    {
      return $this->postageFulfillmentTime;
    }

    /**
     * @param FulfillmentTimeStruct $postageFulfillmentTime
     * @return \Imper86\AllegroApi\Soap\Wsdl\PostageStruct
     */
    public function setPostageFulfillmentTime($postageFulfillmentTime)
    {
      $this->postageFulfillmentTime = $postageFulfillmentTime;
      return $this;
    }

}


text:
package org.diorite.impl.inventory;

import org.diorite.impl.inventory.item.ItemStackImplArray;
import org.diorite.inventory.InventoryType;
import org.diorite.inventory.PlayerEqInventory;

public class PlayerEqInventoryImpl extends PlayerInventoryPartImpl implements PlayerEqInventory
{
    public PlayerEqInventoryImpl(final PlayerInventoryImpl playerInventory)
    {
        super(playerInventory, playerInventory.getArray().getSubArray(9, InventoryType.PLAYER_EQ.getSize()));
    }

    public PlayerEqInventoryImpl(final PlayerInventoryImpl playerInventory, final ItemStackImplArray content)
    {
        super(playerInventory, content);
    }
}


text:
#pragma once

#include "RenderPass.h"
#include "ofShader.h"

namespace itg
{
    class ZoomBlurPass : public RenderPass
    {
    public:

        typedef shared_ptr<ZoomBlurPass> Ptr;

        ZoomBlurPass(const ofVec2f& aspect, bool arb, float centerX = 0.5, float centerY = 0.5,
                       float exposure = 0.48, float decay = 0.9, float density = 0.25,
                       float weight = 0.25, float clamp = 1);

        void render(ofFbo& readFbo, ofFbo& writeFbo, ofTexture& depth);

        void setCenterX(float v){ centerX = v; }
        float getCenterX() { return centerX; }

        void setCenterY(float v){ centerY = v; }
        float getCenterY() { return centerY; }

        void setExposure(float v){ exposure = v; }
        float getExposure() { return exposure; }

        void setDecay(float v){ decay = v; }
        float getDecay() { return decay; }

        void setDensity(float v){ density = v; }
        float getDensity() { return density; }

        void setWeight(float v){ weight = v; }
        float getWeight() { return weight; }

        void setClamp(float v){ clamp = v; }
        float getClamp() { return clamp; }
    private:

        ofShader shader;

        float centerX;
        float centerY;
        float exposure;
        float decay;
        float density;
        float weight;
        float clamp;

    };
}


text:
import template from './templates/mentionEditor.hbs';
import dropdown from 'dropdown';
import { keyCode } from 'utils';
import BaseEditorView from './base/BaseEditorView';
import UserService from 'services/UserService';
import TextAreaEditorView from './TextAreaEditorView';
import LocalizationService from '../../services/LocalizationService';
import formRepository from '../formRepository';
import MembersListView from './impl/members/views/MembersListView';
import MembersCollection from './impl/members/collections/MembersCollection';

const defaultOptions = {
    editorOptions: undefined
};

/**
 * @name MentionEditorView
 * @memberof module:core.form.editors
 * @class Текстовый редактор с возможностью упоминания пользователей (mentions). Поддерживаемый тип данных: String
 * (простой многострочный текст). Например, 'Hello, @alex!'. Список доступных пользователей
 * берется из core.services.CacheService.
 * @extends module:core.form.editors.base.BaseEditorView
 * @param {Object} options Options object. All the properties of {@link module:core.form.editors.base.BaseEditorView BaseEditorView} class are also supported.
 * @param {Number} [options.editorOptions=Object] Опции для используемого {@link module:core.form.editors.TextAreaEditorView TextAreaEditorView}.
 * */
export default (formRepository.editors.Mention = BaseEditorView.extend({
    initialize(options = {}) {
        this.__applyOptions(options, defaultOptions);
        this.__createViewModel();
    },

    __createViewModel() {
        this.viewModel = new Backbone.Model();
        const membersCollection = new MembersCollection();
        membersCollection.reset(UserService.listUsers());
        this.viewModel.set('availableMembers', membersCollection);
        this.viewModel.set(
            'membersByUserName',
            membersCollection.reduce((memo, value) => {
                memo[value.get('userName')] = value;
                return memo;
            }, {})
        );
    },

    template: Handlebars.compile(template),

    regions: {
        dropdownRegion: '.js-dropdown-region'
    },

    events: {
        'keydown:captured': '__handleKeydown'
    },

    onRender() {
        if (this.dropdownView) {
            this.stopListening(this.dropdownView);
        }
        this.dropdownView = dropdown.factory.createDropdown({
            buttonView: TextAreaEditorView,
            buttonViewOptions: _.extend({}, this.options.editorOptions || {}, {
                model: this.model,
                readonly: this.getReadonly(),
                enabled: this.getEnabled(),
                key: this.key,
                autocommit: this.options.autocommit,
                emptyPlaceholder: LocalizationService.get('CORE.FORM.EDITORS.MENTIONS.PLACEHOLDER')
            }),
            panelView: MembersListView,
            panelViewOptions: {
                collection: this.viewModel.get('availableMembers')
            },
            autoOpen: false,
            renderAfterClose: false
        });

        this.showChildView('dropdownRegion', this.dropdownView);
        this.listenTo(this.dropdownView, 'change', this.__onTextChange);
        this.listenTo(this.dropdownView, 'focus', this.__onFocus);
        this.listenTo(this.dropdownView, 'blur', this.__onBlur);
        this.listenTo(this.dropdownView, 'input', this.__onInput);
        this.listenTo(this.dropdownView, 'caretChange', this.__onCaretChange);
        this.listenTo(this.dropdownView, 'panel:member:select', this.__onMemberSelect);
        // We discarded it during render phase, so we do it now.
        this.setPermissions(this.enabled, this.readonly);
        this.setValue(this.value);
    },

    __handleKeydown(e) {
        switch (e.keyCode) {
            case keyCode.UP:
                if (!this.dropdownView.isOpen) {
                    return true;
                }
                this.__sendPanelCommand('up');
                this.__updateMentionInText();
                return false;
            case keyCode.DOWN:
                if (!this.dropdownView.isOpen) {
                    return true;
                }
                this.__sendPanelCommand('down');
                this.__updateMentionInText();
                return false;
            case keyCode.ENTER:
            case keyCode.NUMPAD_ENTER:
                if (!this.dropdownView.isOpen) {
                    return true;
                }
                this.__updateMentionInText();
                this.dropdownView.close();
                return false;
            case keyCode.ESCAPE:
                this.dropdownView.close();
                return false;
            default:
                break;
        }
    },

    __value(value): void {
        this.setValue(value);
        this.__triggerChange();
    },

    __onTextChange(): void {
        this.value = this.dropdownView.getValue();
        this.__triggerChange();
    },

    __onFocus(): void {
        this.trigger('focus', this);
    },

    __onBlur(): void {
        this.trigger('blur', this);
    },

    __onInput(text: string, caret: { start: number, end: number }): void {
        // 1. Open dropdown when: @ is immediately before caret, @ is at start or prepended by whitespace
        // 2. Maintain dropdown open (and filter the list) when: text between caret and @ matches username pattern [a-zA-Z0-9_\.]
        // 3. Hide dropdown when: username text doesn't match
        // 4. track caret change and hide dropdown if resulting username patters doesn't match
        // 5. hide dropdown on blur

        const leftFragment = text.substring(0, caret.end);

        const regex = /(?:\s|^)@([a-z0-9_\.]*)$/i;
        const match = leftFragment.match(regex);
        if (match) {
            const userName = match[1];
            this.dropdownView.open();
            const collection = this.viewModel.get('availableMembers');
            collection.applyTextFilter(userName);
            if (collection.length === 0) {
                this.dropdownView.close();
            }
            this.mentionState = {
                start: caret.end - userName.length,
                end: caret.end,
                text
            };
        } else {
            this.dropdownView.close();
        }
    },

    __onCaretChange(text, caret) {
        if (this.dropdownView.isOpen) {
            this.__onInput(text, caret);
        }
    },

    __onMemberSelect(): void {
        this.__updateMentionInText();
        this.dropdownView.close();
    },

    __updateMentionInText(): void {
        const selectedMember = this.viewModel.get('availableMembers').selected;
        if (!selectedMember) {
            return;
        }

        const editor = this.dropdownView;
        const text = this.mentionState.text;

        let mention = selectedMember.get('userName') || '';
        if (mention && !text.substring(this.mentionState.end).match(/^\s/)) {
            mention += ' ';
        }

        const updatedText = text.substring(0, this.mentionState.start) + mention + text.substring(this.mentionState.end);
        editor.setValue(updatedText);
        editor.setCaretPos(this.mentionState.start + mention.length);
        this.value = updatedText;
        this.__triggerChange();
    },

    /**
     * Получить список пользователей, упомянутых в тексте.
     * @return {String[]} Список строковых идентификаторов пользователей, упомянутых в тексте.
     * */
    getMentions(): Array<any> {
        const text = this.getValue();
        const regex = /(?:\s|^)@([a-z0-9_\.]+)/gi;
        const members = this.viewModel.get('membersByUserName');

        const result = [];
        while (true) {
            const matches = regex.exec(text);
            if (!matches) {
                break;
            }
            const userName = matches[1];
            const member = members[userName];
            if (member) {
                result.push(member.id);
            }
        }
        return _.uniq(result);
    },

    setValue(value) {
        if (this.dropdownView) {
            this.dropdownView.setValue(value);
            this.value = this.dropdownView.getValue();
        } else {
            this.value = value;
        }
    },

    __sendPanelCommand(command, options) {
        if (this.dropdownView.isOpen) {
            this.dropdownView.panelView.handleCommand(command, options);
        }
    },

    __setEnabled(enabled: boolean): void {
        BaseEditorView.prototype.__setEnabled.call(this, enabled);
        if (this.dropdownView) {
            this.dropdownView.setEnabled(enabled);
        }
    },

    __setReadonly(readonly: boolean): void {
        BaseEditorView.prototype.__setReadonly.call(this, readonly);
        if (this.dropdownView) {
            this.dropdownView.setReadonly(readonly);
        }
    }
}));


text:
Given(/^a tic\-tac\-toe feature file and a step file$/) do
  cuke = <<CUKE
  	Given I have a started Tic-Tac-Toe game
  		And it is the computer's turn
  		And the computer is playing X
  	Then the computer randomly chooses an open position for its move
  		And the board should have an X on it
CUKE
  @cuke_lines = cuke.split("\n")
  steps = <<STEP
Given /^I have a started Tic\-Tac\-Toe game$/ do
  @game = TicTacToe.new(:player)
  @game.player = "Renee"
end

Given /^it is the computer's turn$/ do
  @game = TicTacToe.new(:computer, :O)
  @game.current_player.should eq "Computer"
end

Given /^the computer is playing X$/ do
  @game.computer_symbol.should eq :X
end

Then /^the computer randomly chooses an open position for its move$/ do
  open_spots = @game.open_spots
  @com_move = @game.computer_move
  open_spots.should include(@com_move)
end

Then /^the board should have an X on it$/ do
  @game.current_state.should include 'X'
end
STEP
  @step_lines = steps.split("\n")
end

When(/^I slice them\.$/) do
  @cs = CucumberSlices.new
  @cs.extract_steps @step_lines
  @output = @cs.splice_features @cuke_lines
end

Then(/^The program should return lines of the cuke followed by the steps$/) do
  @output[0].should == "1 #{@cuke_lines[0]}"
  @output[1].should == "  \t#{@step_lines[1]}"
  @output[2].should == "  \t#{@step_lines[2]}"
  @output[3].should == "2 #{@cuke_lines[1]}"
  @output[4].should == "  \t\t#{@step_lines[6]}"
  @output[5].should == "  \t\t#{@step_lines[7]}"
  @output[6].should == "3 #{@cuke_lines[2]}"
  @output[7].should == "  \t\t#{@step_lines[11]}"
end

When(/^I slice them with a lines=\((\d+)\.\.(\d+)\) arguement$/) do |arg1, arg2|
  @cs = CucumberSlices.new
  @cs.extract_steps @step_lines
  @output = @cs.splice_features @cuke_lines, (arg1.to_i()..arg2.to_i())
end

Then(/^Then it should return lines 2 to 3 of the feature$/) do
  @output[0].should == "2 #{@cuke_lines[1]}"
  @output[1].should == "  \t\t#{@step_lines[6]}"
  @output[2].should == "  \t\t#{@step_lines[7]}"
  @output[3].should == "3 #{@cuke_lines[2]}"
  @output[4].should == "  \t\t#{@step_lines[11]}"
end


text:
package org.apache.flink.streaming.scala.examples.ml

import org.apache.flink.api.java.utils.ParameterTool
import org.apache.flink.api.scala._
import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks
import org.apache.flink.streaming.api.functions.co.CoMapFunction
import org.apache.flink.streaming.api.functions.source.SourceFunction
import org.apache.flink.streaming.api.functions.source.SourceFunction.SourceContext
import org.apache.flink.streaming.api.scala.function.AllWindowFunction
import org.apache.flink.streaming.api.scala.{DataStream, StreamExecutionEnvironment}
import org.apache.flink.streaming.api.watermark.Watermark
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.streaming.api.windowing.windows.TimeWindow
import org.apache.flink.util.Collector

/**
 * Skeleton for incremental machine learning algorithm consisting of a
 * pre-computed model, which gets updated for the new inputs and new input data
 * for which the job provides predictions.
 *
 * This may serve as a base of a number of algorithms, e.g. updating an
 * incremental Alternating Least Squares model while also providing the
 * predictions.
 *
 * This example shows how to use:
 *
 *  - Connected streams
 *  - CoFunctions
 *  - Tuple data types
 *
 */
object IncrementalLearningSkeleton {

  // *************************************************************************
  // PROGRAM
  // *************************************************************************

  def main(args: Array[String]): Unit = {
    // Checking input parameters
    val params = ParameterTool.fromArgs(args)

    // set up the execution environment
    val env = StreamExecutionEnvironment.getExecutionEnvironment

    // build new model on every second of new data
    val trainingData: DataStream[Integer] = env.addSource(new FiniteTrainingDataSource)
    val newData: DataStream[Integer] = env.addSource(new FiniteNewDataSource)

    val model: DataStream[Array[java.lang.Double]] = trainingData
      .assignTimestampsAndWatermarks(new LinearTimestamp)
      .windowAll(TumblingEventTimeWindows.of(Time.milliseconds(5000)))
      .apply(new PartialModelBuilder)

    // use partial model for newData
    val prediction: DataStream[Integer] = newData.connect(model).map(new Predictor)

    // emit result
    if (params.has("output")) {
      prediction.writeAsText(params.get("output"))
    } else {
      println("Printing result to stdout. Use --output to specify output path.")
      prediction.print()
    }

    // execute program
    env.execute("Streaming Incremental Learning")
  }

  // *************************************************************************
  // USER FUNCTIONS
  // *************************************************************************

  /**
   * Feeds new data for newData. By default it is implemented as constantly
   * emitting the Integer 1 in a loop.
   */
  private class FiniteNewDataSource extends SourceFunction[Integer] {
    override def run(ctx: SourceContext[Integer]) = {
      Thread.sleep(15)
      (0 until 50).foreach{ _ =>
        Thread.sleep(5)
        ctx.collect(1)
      }
    }

    override def cancel() = {
      // No cleanup needed
    }
  }

  /**
   * Feeds new training data for the partial model builder. By default it is
   * implemented as constantly emitting the Integer 1 in a loop.
   */
  private class FiniteTrainingDataSource extends SourceFunction[Integer] {
    override def run(ctx: SourceContext[Integer]) =
      (0 until 8200).foreach( _ => ctx.collect(1) )

    override def cancel() = {
      // No cleanup needed
    }
  }

  private class LinearTimestamp extends AssignerWithPunctuatedWatermarks[Integer] {
    var counter = 0L

    override def extractTimestamp(element: Integer, previousElementTimestamp: Long): Long = {
      counter += 10L
      counter
    }

    override def checkAndGetNextWatermark(lastElement: Integer, extractedTimestamp: Long) = {
      new Watermark(counter - 1)
    }
  }

  /**
   * Builds up-to-date partial models on new training data.
   */
  private class PartialModelBuilder
      extends AllWindowFunction[Integer, Array[java.lang.Double], TimeWindow] {

    protected def buildPartialModel(values: Iterable[Integer]): Array[java.lang.Double] =
      Array[java.lang.Double](1)

    override def apply(window: TimeWindow,
                       values: Iterable[Integer],
                       out: Collector[Array[java.lang.Double]]): Unit = {
      out.collect(buildPartialModel(values))
    }
  }

  /**
   * Creates newData using the model produced in batch-processing and the
   * up-to-date partial model.
   *
   * By default emits the Integer 0 for every newData and the Integer 1
   * for every model update.
   *
   */
  private class Predictor extends CoMapFunction[Integer, Array[java.lang.Double], Integer] {

    var batchModel: Array[java.lang.Double] = null
    var partialModel: Array[java.lang.Double] = null

    override def map1(value: Integer): Integer = {
      // Return newData
      predict(value)
    }

    override def map2(value: Array[java.lang.Double]): Integer = {
      // Update model
      partialModel = value
      batchModel = getBatchModel()
      1
    }

    // pulls model built with batch-job on the old training data
    protected def getBatchModel(): Array[java.lang.Double] = Array[java.lang.Double](0)

    // performs newData using the two models
    protected def predict(inTuple: Int): Int = 0
  }

}


text:
package org.mule.transport.domino;

import org.mule.api.MuleContext;
import org.mule.api.transport.MessageTypeNotSupportedException;
import org.mule.transport.AbstractMuleMessageFactory;

/**
 * DominoMuleMessageFactory
 */
public class DominoMuleMessageFactory extends AbstractMuleMessageFactory
{

    public DominoMuleMessageFactory(MuleContext context)
    {
        super(context);
    }

	/** {@inheritDoc}
	 */
    @Override
    protected Object extractPayload(Object transportMessage, String encoding) throws Exception
    {
        if (transportMessage == null)
        {
            throw new MessageTypeNotSupportedException(null, getClass());
        }
        else
        {
            return transportMessage;
        }
    }

	/** {@inheritDoc}
	 */
    @Override
    protected Class<?>[] getSupportedTransportMessageTypes()
    {
        return new Class[]{Object.class};
    }
}


text:
#include "config.h"
#include "CSSToLengthConversionData.h"

#include "RenderStyle.h"
#include "RenderView.h"

namespace WebCore {

float CSSToLengthConversionData::zoom() const
{
    if (m_useEffectiveZoom)
        return m_style ? m_style->effectiveZoom() : 1;
    return m_zoom;
}

double CSSToLengthConversionData::viewportWidthFactor() const
{
    if (m_style && !m_computingFontSize)
        const_cast<RenderStyle*>(m_style)->setHasViewportUnits();

    if (!m_renderView)
        return 0;

    return m_renderView->viewportSizeForCSSViewportUnits().width() / 100.0;
}

double CSSToLengthConversionData::viewportHeightFactor() const
{
    if (m_style && !m_computingFontSize)
        const_cast<RenderStyle*>(m_style)->setHasViewportUnits();

    if (!m_renderView)
        return 0;

    return m_renderView->viewportSizeForCSSViewportUnits().height() / 100.0;
}

double CSSToLengthConversionData::viewportMinFactor() const
{
    if (m_style && !m_computingFontSize)
        const_cast<RenderStyle*>(m_style)->setHasViewportUnits();

    if (!m_renderView)
        return 0;

    IntSize viewportSizeForCSSViewportUnits = m_renderView->viewportSizeForCSSViewportUnits();
    return std::min(viewportSizeForCSSViewportUnits.width(), viewportSizeForCSSViewportUnits.height()) / 100.0;
}

double CSSToLengthConversionData::viewportMaxFactor() const
{
    if (m_style && !m_computingFontSize)
        const_cast<RenderStyle*>(m_style)->setHasViewportUnits();

    if (!m_renderView)
        return 0;

    IntSize viewportSizeForCSSViewportUnits = m_renderView->viewportSizeForCSSViewportUnits();
    return std::max(viewportSizeForCSSViewportUnits.width(), viewportSizeForCSSViewportUnits.height()) / 100.0;
}

} // namespace WebCore


text:
package com.sponberg.fluid.tool;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;

import javax.imageio.ImageIO;

public class MakeImagesFile {

	static final String kImagesFileName = "images.txt";

	static final String kResourcesDirName = "resources";

	static final String kImagesDir = "images";

	static final String kGeneratedDirName = "generated";

	HashMap<String, TreeSet<ImageInfo>> imagesByName = new HashMap<>();

	public MakeImagesFile(String workingDir) throws IOException {

		System.out.println("Runing MakeImagesFile");

		for (File file : getImageFiles(workingDir + "/" + kResourcesDirName + "/" + kImagesDir)) {

			if (file.getName().startsWith("."))
				continue;

			String name = file.getName();
			int i = name.indexOf("@");
			if (i == -1) {
				throw new RuntimeException("Image doesn't contain '@' " + name);
			}
			int i2 = name.indexOf(".", i + 1);

			String base = name.substring(0, i);
			String sizeToken = name.substring(i + 1, i2);

			ImageInfo ii = new ImageInfo();
			ii.sizeToken = sizeToken;
			setImageSize(file, ii);

			TreeSet<ImageInfo> set = imagesByName.get(base);
			if (set == null) {
				set = new TreeSet<ImageInfo>();
				imagesByName.put(base, set);
			}
			set.add(ii);
		}

		FileWriter out = new FileWriter(workingDir + "/" + kResourcesDirName + "/" + kGeneratedDirName + "/" + kImagesFileName);

		TreeSet<String> keysSorted = new TreeSet(imagesByName.keySet());
		for (String key : keysSorted) {
			out.append(key);
			for (ImageInfo ii : imagesByName.get(key)) {
				out.append(":" + ii.sizeToken + ":");
				out.append(ii.width + ",");
				out.append(ii.height + "");
			}
			out.append("\n");
		}

		out.close();

		System.out.println("Done");
	}

	void setImageSize(File file, ImageInfo imageInfo) throws IOException {
		long time = System.currentTimeMillis();
		BufferedImage bimg = ImageIO.read(file);
		imageInfo.width = bimg.getWidth();
		imageInfo.height = bimg.getHeight();
		System.out.println((System.currentTimeMillis() - time));
	}

	public static void main(String[] args) throws IOException {

		String workingDir = (args.length > 0) ? args[0] : ".";

		new MakeImagesFile(workingDir);
	}

	static List<File> getImageFiles(String resourcesDir) {

		ArrayList<File> files = new ArrayList<>();

		File folder = new File(resourcesDir);

		if (!folder.exists()) {
			throw new RuntimeException("Folder doesn't exist " + resourcesDir);
		}

		getImageFilesHelper(folder, files);

		return files;
	}

	static void getImageFilesHelper(File folder, ArrayList<File> files) {
		for (File file : folder.listFiles()) {
			if (file.isFile()) {
				files.add(file);
			} else if (file.isDirectory()) {
				getImageFilesHelper(file, files);
			}
		}
	}

	static class ImageInfo implements Comparable<ImageInfo> {

		String sizeToken;

		int width;

		int height;

		@Override
		public int compareTo(ImageInfo o) {
			return sizeToken.compareTo(o.sizeToken);
		}

		@Override
		public int hashCode() {
			return sizeToken.hashCode();
		}

		@Override
		public boolean equals(Object obj) {
			return sizeToken.equals(((ImageInfo) obj).sizeToken);
		}

	}

}


text:
<?php

namespace yii2mod\rbac\models\search;

use dosamigos\arrayquery\ArrayQuery;
use Yii;
use yii\base\Model;
use yii\data\ArrayDataProvider;

/**
 * Class BizRuleSearch
 *
 * @package yii2mod\rbac\models\search
 */
class BizRuleSearch extends Model
{
    /**
     * @var string name of the rule
     */
    public $name;

    /**
     * @var int the default page size
     */
    public $pageSize = 25;

    /**
     * @inheritdoc
     */
    public function rules(): array
    {
        return [
            ['name', 'trim'],
            ['name', 'safe'],
        ];
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ArrayDataProvider
     */
    public function search(array $params): ArrayDataProvider
    {
        $query = new ArrayQuery(Yii::$app->authManager->getRules());

        if ($this->load($params) && $this->validate()) {
            $query->addCondition('name', $this->name ? "~{$this->name}" : null);
        }

        return new ArrayDataProvider([
            'allModels' => $query->find(),
            'sort' => [
                'attributes' => ['name'],
            ],
            'pagination' => [
                'pageSize' => $this->pageSize,
            ],
        ]);
    }
}


text:
from settings import location

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': location('db.sqlite3'),
    }
}


text:
package com.dataartisans.blogpost.eventtime.java;

import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction;

import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * A sample data generator of sensor readings.
 */
public class SampleDataGenerator extends RichParallelSourceFunction<SensorReading> {

    private static final int numSensors = 1000;

    private static final int numSensorGroups = 80;

    private static final int baseInterval = 5000;

    private static final int maxDelay = 6000;

    private static final double maxRegularReading = 100.0;

    private static final double fractionOfExceedingReadings = 0.0005;

    private volatile boolean running = true;

    @Override
    public void run(final SourceContext<SensorReading> ctx) throws Exception {
        final Random rnd = new Random();
        final ScheduledExecutorService exec = Executors.newScheduledThreadPool(2);
        final int idOffset = getRuntimeContext().getIndexOfThisSubtask() * numSensors;

        try {
            while (running) {
                long baseTimestamp = System.currentTimeMillis();

                // create a variably delayed event from all sensors
                for (int i = 0; i < numSensors; i++) {
                    long shiftInInterval = rnd.nextInt(baseInterval) - baseInterval;

                    double reading = rnd.nextDouble() < fractionOfExceedingReadings ?
                            maxRegularReading + rnd.nextDouble() * maxRegularReading :
                            rnd.nextDouble() * maxRegularReading;

                    String sensorName = String.format("sensor-%04d", i + idOffset);
                    String groupName = String.format("group-%03d", i % numSensorGroups);

                    long delay = rnd.nextInt(maxDelay);

                    final SensorReading event = new SensorReading(groupName, sensorName,
                            baseTimestamp + shiftInInterval, reading);

                    exec.schedule( () -> {
                        try {
                            ctx.collect(event);
                        }
                        catch (Exception e) {
                            e.printStackTrace();
                        }
                    }, delay, TimeUnit.MILLISECONDS);
                }

                Thread.sleep(baseInterval);
            }
        }
        finally {
            exec.shutdownNow();
        }
    }

    @Override
    public void cancel() {
        running = false;
    }
}


text:
//
//  RKPossibility.m
//  RoundaboutKit
//
//  Created by Kevin MacWhinnie on 12/20/12.
//  Copyright (c) 2012 Roundabout Software, LLC. All rights reserved.
//

#import "RKPossibility.h"

@implementation RKPossibility {
	id _value;
	NSError *_error;
    RKPossibilityState _state;
}

- (id)initWithValue:(id)value
{
	if((self = [super init])) {
		_value = value;
        _state = kRKPossibilityStateValue;
	}

	return self;
}

- (id)initWithError:(NSError *)error
{
	if((self = [super init])) {
		_error = error;
        _state = kRKPossibilityStateError;
	}

	return self;
}

- (id)initEmpty
{
    if((self = [super init])) {
        _state = kRKPossibilityStateEmpty;
    }

    return self;
}

- (id)init
{
    return [self initEmpty];
}

#pragma mark - Properties

@synthesize value = _value;
@synthesize error = _error;
@synthesize state = _state;

#pragma mark - Refining

- (RKPossibility *)refineValue:(RKPossibility *(^)(id value))refiner
{
    NSParameterAssert(refiner);

    if(self.state != kRKPossibilityStateValue)
        return self;

    return refiner(self.value);
}

- (RKPossibility *)refineError:(RKPossibility *(^)(NSError *error))refiner
{
    NSParameterAssert(refiner);

    if(self.state != kRKPossibilityStateError)
        return self;

    return refiner(self.error);
}

- (RKPossibility *)refineEmpty:(RKPossibility *(^)())refiner
{
    NSParameterAssert(refiner);

    if(self.state != kRKPossibilityStateEmpty)
        return self;

    return refiner();
}

#pragma mark - Matching

- (void)whenValue:(void(^)(id value))matcher
{
    NSParameterAssert(matcher);

    if(self.state == kRKPossibilityStateValue)
        matcher(self.value);
}

- (void)whenError:(void(^)(NSError *error))matcher
{
    NSParameterAssert(matcher);

    if(self.state == kRKPossibilityStateError)
        matcher(self.error);
}

- (void)whenEmpty:(void(^)())matcher
{
    NSParameterAssert(matcher);

    if(self.state == kRKPossibilityStateEmpty)
        matcher();
}

@end

#if RoundaboutKit_EnableLegacyPossibilityFunctions

RKPossibility *(^kRKPossibilityDefaultValueRefiner)(id) = nil;
RKPossibility *(^kRKPossibilityDefaultEmptyRefiner)() = nil;
RKPossibility *(^kRKPossibilityDefaultErrorRefiner)(NSError *) = nil;

void(^kRKPossibilityDefaultValueMatcher)(id) = nil;
void(^kRKPossibilityDefaultEmptyMatcher)() = nil;
void(^kRKPossibilityDefaultErrorMatcher)(NSError *) = nil;

RK_OVERLOADABLE RKPossibility *RKRefinePossibility(RKPossibility *possibility,
                                                   RKPossibility *(^valueRefiner)(id value),
                                                   RKPossibility *(^emptyRefiner)(),
                                                   RKPossibility *(^errorRefiner)(NSError *error))
{
    if(!possibility)
        return nil;

    if(!valueRefiner) valueRefiner = ^(id value) { return [[RKPossibility alloc] initWithValue:value]; };
    if(!emptyRefiner) emptyRefiner = ^{ return [[RKPossibility alloc] initEmpty]; };
    if(!errorRefiner) errorRefiner = ^(NSError *error) { return [[RKPossibility alloc] initWithError:error]; };

    if(possibility.state == kRKPossibilityStateValue) {
        return valueRefiner(possibility.value);
    } else if(possibility.state == kRKPossibilityStateEmpty) {
        return emptyRefiner();
    } else if(possibility.state == kRKPossibilityStateError) {
        return errorRefiner(possibility.error);
    }

    NSCAssert(0, @"RKPossibility is in an undefined state.");

    return nil;
}

RK_OVERLOADABLE void RKMatchPossibility(RKPossibility *possibility,
                                        void(^value)(id value),
                                        void(^empty)(),
                                        void(^error)(NSError *error))
{
    if(!possibility)
        return;

    if(possibility.state == kRKPossibilityStateValue) {
        if(value)
            value(possibility.value);
    } else if(possibility.state == kRKPossibilityStateEmpty) {
        if(empty)
            empty();
    } else if(possibility.state == kRKPossibilityStateError) {
        if(error)
            error(possibility.error);
    } else {
        NSCAssert(0, @"RKPossibility is in an undefined state.");
    }
}

#endif /* RoundaboutKit_EnableLegacyPossibilityFunctions */


text:
<?xml version="1.0" encoding="utf-8"?>

<ViewAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/results_view_animator"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/tickets_recycler"
        android:background="@color/white"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/tickets_history_is_empty" />

</ViewAnimator>


text:
package es.us.lsi.hermes.util.classes;

import es.us.lsi.hermes.util.Utils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Email {

    private static final Logger LOG = Logger.getLogger(Email.class.getName());

    private static final Properties MAIL_SERVER_PROPERTIES;
    private static final Session MAIL_SESSION;

    static {
        LOG.log(Level.INFO, "Email() - Email manager init.");

        MAIL_SERVER_PROPERTIES = Utils.initProperties("Email.properties");
        MAIL_SESSION = Session.getDefaultInstance(MAIL_SERVER_PROPERTIES, null);
    }

    public static void generateAndSendEmail(String recipient, String subject, String body) throws AddressException, MessagingException {
        generateAndSendEmail(recipient, subject, body, new ArrayList());
    }

    public static void generateAndSendEmail(String recipient, String subject, String body, File attachedFile) throws AddressException, MessagingException {
        List<File> attachedFiles = new ArrayList<>();
        attachedFiles.add(attachedFile);
        generateAndSendEmail(recipient, subject, body, attachedFiles);
    }

    public static void generateAndSendEmail(String recipient, String subject, String body, List<File> attachedFiles) throws AddressException, MessagingException {
        LOG.log(Level.INFO, "generateAndSendEmail() - Generación y envío del correo a: {0}", recipient);

        Message generateMailMessage = new MimeMessage(MAIL_SESSION);
        generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

        // Asunto.
        generateMailMessage.setSubject(subject);

        // Cuerpo.
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(body, "text/html; charset=utf-8");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        // Adjuntos.
        if (attachedFiles != null && !attachedFiles.isEmpty()) {
            messageBodyPart = new MimeBodyPart();
            for (File f : attachedFiles) {
                DataSource source = new FileDataSource(f);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(f.getName());
                multipart.addBodyPart(messageBodyPart);
            }
        }

        generateMailMessage.setContent(multipart);
        LOG.log(Level.FINE, "generateAndSendEmail() - Email generado correctamente");

        Transport transport = MAIL_SESSION.getTransport("smtp");
        transport.connect((String) MAIL_SERVER_PROPERTIES.get("mail.smtp.host"), (String) MAIL_SERVER_PROPERTIES.get("mail.smtp.user"), (String) MAIL_SERVER_PROPERTIES.get("mail.smtp.password"));
        transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
        transport.close();
        LOG.log(Level.INFO, "generateAndSendEmail() - Email enviado correctamente");
    }
}