text:
//
//  EzvizTokenKit.h
//  EzvizOpenSDK
//
//  Created by DeJohn Dong on 15/8/31.
//  Copyright (c) 2015年 Ezviz. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface EZTokenKit : NSObject

@property (nonatomic, readonly) NSString *token;  //获取第一个token
@property (nonatomic, readonly) NSInteger tokenCount; //当前tokenKit里还有多少token的数量

/**
 *  单例方法
 *
 *  @return EZTokenKit对象
 */
+ (instancetype)sharedKit;

/**
 *  设置TokenList数组
 *
 *  @param tokenList token数组
 */
- (void)setTokens:(NSArray *)tokenList;

/**
 *  清空数组
 */
- (void)clearTokens;

/**
 *  预加载取流token
 */
- (void)prepareToken:(void (^)(NSError *error))block;

@end

redpajama_set_name: RedPajamaGithub


text:
import * as actions from './actions';

const initialState = {
  errorList: [],
  formVisible: false,
};

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case actions.ADD_ERROR:
      return {
        ...state,
        errorList: [...state.errorList, action.error],
      };
    case actions.CLEAR_ERROR:
      return {
        ...state,
        errorList: state.errorList.slice(1),
        formVisible: false,
      };
    case actions.SHOW_REPORT_FORM:
      return {
        ...state,
        formVisible: true,
      };
    default:
      return state;
  }
}


text:
<!DOCTYPE html>

    <meta charset=utf-8>
    <title>RP 23 part 1</title>

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

In this problem, you must change the
          concrete syntax for function abstraction as follows. First,
          the "fn" and "=>" keywords are replaced with  "lambda" and
          a "." (period), respectively. Second, the parentheses around
          the list of formal parameters are dropped. In other words,

	    "fn (x,y) => <exp>"
	    becomes "lambda x,y . <exp>".
	    So, for example:

	    "(lambda u,v . lambda f . 3 x
	    +(x,y))" should return:

[ "Clo",
  [ "f" ],
  [ "IntExp", 3 ],
  [ "Env",
    [ [ "u", [ "Num", 1 ] ], [ "v", [ "Num", 3 ] ] ],
    [ "Env",
      [ [ "x", [ "Num", 1 ] ], [ "y", [ "Num", 2 ] ], [ "z", [ "Num", 3 ] ] ],
      [ "EmptyEnv" ] ] ] ]

and
	    "lambda . 3" should return

[ "Clo",
  [ ],
  [ "IntExp", 3 ],
  [ "Env",
    [ [ "x", [ "Num", 1 ] ], [ "y", [ "Num", 2 ] ], [ "z", [ "Num", 3 ] ] ],
    [ "EmptyEnv" ] ] ]

For your answer, check each and every
          file below that MUST be altered to implement this modification.

	  <input type="checkbox" id="absyn">absyn.js

	  <input type="checkbox" id="grammar">grammar.jison

	  <input type="checkbox" id="env">env.js

	  <input type="checkbox" id="interpreter">interpreter.js

 [
	      $('#absyn').prop('checked'),
	      $('#grammar').prop('checked'),
	      $('#env').prop('checked'),
	      $('#interpreter').prop('checked')
	      ]

	      return RP23part1Validate(guess);

Does this change impact the concrete syntax or the
	    abstract syntax of SLang 1 (or both)?

Are we adding new types of denoted values or modifying the
	    existing ones?

Are we adding new types of expressions?


text:
<?php
/**
 * functional test for /file
 */

namespace Graviton\FileBundle\Tests\Controller;

// @codingStandardsIgnoreStart
use Graviton\LinkHeaderParser\LinkHeader;
use Graviton\TestBundle\Test\RestTestCase;
use GravitonDyn\FileBundle\DataFixtures\MongoDB\LoadFileData;
use GravitonDyn\TestCaseRestListenerCondPersisterEntityBundle\DataFixtures\MongoDB\{
    LoadTestCaseRestListenerCondPersisterEntityData
};
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Response;
// @codingStandardsIgnoreEnd

/**
 * Basic functional test for /file
 *
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  https://opensource.org/licenses/MIT MIT License
 * @link     http://swisscom.ch
 */
class FileControllerTest extends RestTestCase
{

    /**
     * custom environment
     *
     * @var string
     */
    protected static $environment = 'test';

    /**
     * custom client options
     *
     * @var string[]
     */
    protected $clientOptions = ['environment' => 'test'];

    /**
     * setup client and load fixtures
     *
     * @return void
     */
    public function setUp() : void
    {
        $this->loadFixturesLocal(
            [
                LoadFileData::class,
                LoadTestCaseRestListenerCondPersisterEntityData::class
            ]
        );
    }

    /**
     * check for empty collections when no fixtures are loaded
     *
     * @return void
     */
    public function testFindAllEmptyCollection()
    {
        // reset fixtures since we already have some from setUp
        $this->loadFixturesLocal([]);
        $client = static::createRestClient();
        $client->request('GET', '/file/');

        $response = $client->getResponse();
        $results = $client->getResults();

        $this->assertResponseSchemaRel('http://localhost/schema/file/collection', $response);

        $this->assertEquals([], $results);
    }

    /**
     * validate that we can post a new file
     *
     * @return void
     */
    public function testPostAndUpdateFile()
    {
        $fixtureData = file_get_contents(__DIR__.'/fixtures/test.txt');
        $fileHash = hash('sha256', $fixtureData);
        $fileHashCustom = 'some-custom-hash-for-testing';

        $client = static::createRestClient();
        $client->post(
            '/file/',
            $fixtureData,
            [],
            [],
            ['CONTENT_TYPE' => 'text/plain'],
            false
        );
        $this->assertEmpty($client->getResults());
        $response = $client->getResponse();
        $this->assertEquals(201, $response->getStatusCode());

        $fileLocation = $response->headers->get('Location');

        // update file contents to update mod date
        $client = static::createRestClient();
        $client->put(
            $fileLocation,
            $fixtureData,
            [],
            [],
            ['CONTENT_TYPE' => 'text/plain'],
            false
        );
        $this->assertEmpty($client->getResults(), $client->getResponse()->getContent());
        $response = $client->getResponse();
        $this->assertEquals(204, $response->getStatusCode());

        $client = static::createRestClient();
        $client->request('GET', $fileLocation, [], [], ['HTTP_ACCEPT' => 'application/json']);
        $data = $client->getResults();

        // check for valid format
        $this->assertNotFalse(\DateTime::createFromFormat(\DateTime::RFC3339, $data->metadata->createDate));
        $this->assertNotFalse(\DateTime::createFromFormat(\DateTime::RFC3339, $data->metadata->modificationDate));
        // Check valid hash encoding if no hash sent
        $this->assertEquals($fileHash, $data->metadata->hash);

        $data->links = [];
        $link = new \stdClass;
        $link->{'$ref'} = 'http://localhost/core/app/tablet';
        $data->links[] = $link;

        $filename = "test.txt";
        $data->metadata->filename = $filename;
        $data->metadata->hash = $fileHashCustom;

        $client = static::createRestClient();
        $client->put(sprintf('/file/%s', $data->id), $data, [], [], ['CONTENT_TYPE' => 'application/json']);

        // re-fetch
        $client = static::createRestClient();
        $client->request('GET', sprintf('/file/%s', $data->id), [], [], ['HTTP_ACCEPT' => 'application/json']);
        $results = $client->getResults();

        $this->assertEquals($link->{'$ref'}, $results->links[0]->{'$ref'});
        $this->assertEquals($filename, $results->metadata->filename);
        $this->assertEquals($fileHashCustom, $data->metadata->hash);

        $client = static::createRestClient();
        $client->request('GET', sprintf('/file/%s', $data->id), [], [], ['HTTP_ACCEPT' => 'text/plain']);

        $results = $client->getResponse()->getContent();

        $this->assertEquals($fixtureData, $results);

        // change link and add second link
        $data->links[0]->{'$ref'} = 'http://localhost/core/app/admin';
        $link = new \stdClass;
        $link->{'$ref'} = 'http://localhost/core/app/web';
        $data->links[] = $link;

        // also add action command
        $command = new \stdClass();
        $command->command = 'print';
        $data->metadata->action = [$command];

        // also add additionalInformation
        $data->metadata->additionalInformation = 'someInfo';

        $client = static::createRestClient();
        $client->put(sprintf('/file/%s', $data->id), $data, [], [], ['CONTENT_TYPE' => 'application/json']);

        // re-fetch
        $client = static::createRestClient();
        $client->request('GET', sprintf('/file/%s', $data->id), [], [], ['HTTP_ACCEPT' => 'application/json']);
        $results = $client->getResults();

        $this->assertEquals($data->links[0]->{'$ref'}, $results->links[0]->{'$ref'});
        $this->assertEquals($data->links[1]->{'$ref'}, $results->links[1]->{'$ref'});

        // check metadata
        $this->assertEquals(18, $data->metadata->size);
        $this->assertEquals('text/plain', $data->metadata->mime);
        $this->assertEquals('test.txt', $data->metadata->filename);
        $this->assertEquals('print', $data->metadata->action[0]->command);
        $this->assertEquals('someInfo', $data->metadata->additionalInformation);
        $this->assertNotNull($data->metadata->createDate);
        $this->assertNotNull($data->metadata->modificationDate);

        // remove a link
        unset($data->links[1]);

        $client = static::createRestClient();
        $client->put(sprintf('/file/%s', $data->id), $data, [], [], ['CONTENT_TYPE' => 'application/json']);
        // re-fetch
        $client = static::createRestClient();
        $client->request('GET', sprintf('/file/%s', $data->id), [], [], ['HTTP_ACCEPT' => 'application/json']);
        $results = $client->getResults();

        $this->assertEquals($data->links[0]->{'$ref'}, $results->links[0]->{'$ref'});
        $this->assertCount(1, $results->links);

        // remove last link
        $data->links = [];
        $client = static::createRestClient();
        $client->put(sprintf('/file/%s', $data->id), $data, [], [], ['CONTENT_TYPE' => 'application/json']);

        // re-fetch
        $client = static::createRestClient();
        $client->request('GET', sprintf('/file/%s', $data->id), [], [], ['HTTP_ACCEPT' => 'application/json']);

        $results = $client->getResults();

        $this->assertEmpty($results->links);

        // Let's update links but without sending file and still have file info
        $id = $data->id;
        $data = new \stdClass;
        $data->id = $id;
        $link = new \stdClass;
        $link->{'$ref'} = 'http://localhost/core/app/web';
        $data->links = [];
        $data->links[] = $link;
        $client = static::createRestClient();
        $client->put(sprintf('/file/%s', $id), $data, [], [], ['CONTENT_TYPE' => 'application/json']);
        // re-fetch
        $client = static::createRestClient();
        $client->request('GET', sprintf('/file/%s', $data->id), [], [], ['HTTP_ACCEPT' => 'application/json']);
        $data = $client->getResults();
        // check metadata for kept file info
        $this->assertEquals(18, $data->metadata->size);
        $this->assertEquals('text/plain', $data->metadata->mime);
        $this->assertEquals('test.txt', $data->metadata->filename);
        $this->assertNotNull($data->metadata->createDate);
        $this->assertNotNull($data->metadata->modificationDate);
    }

    /**
     * validate that we can post a new file
     *
     * @return void
     */
    public function testPostNewFile()
    {
        $client = static::createRestClient();

        $client->post(
            '/file',
            file_get_contents(__DIR__.'/fixtures/test.txt'),
            [],
            [],
            ['CONTENT_TYPE' => 'text/plain'],
            false
        );

        $response = $client->getResponse();
        $linkHeader = $response->headers->get('Link');

        $this->assertEquals(201, $response->getStatusCode());
        $this->assertMatchesRegularExpression('@/file/[a-z0-9]{32}>; rel="self"@', $linkHeader);
    }

    /**
     * validate that we can put a new file with a custom id
     *
     * @return void
     */
    public function testPutNewFile()
    {
        $client = static::createRestClient();

        $client->put(
            '/file/testPutNewFile',
            file_get_contents(__DIR__ . '/fixtures/test.txt'),
            [],
            [],
            ['CONTENT_TYPE' => 'text/plain'],
            false
        );

        $response = $client->getResponse();
        $linkHeader = $response->headers->get('Link');

        $this->assertEquals(204, $response->getStatusCode());
        $this->assertStringContainsString('file/testPutNewFile>; rel="self"', $linkHeader);
    }

    /**
     * validate that we can delete a file
     *
     * @return void
     */
    public function testDeleteFile()
    {
        $fixtureData = file_get_contents(__DIR__.'/fixtures/test.txt');
        $client = static::createRestClient();
        $client->post(
            '/file/',
            $fixtureData,
            [],
            [],
            ['CONTENT_TYPE' => 'text/plain'],
            false
        );
        $response = $client->getResponse();
        $this->assertEquals(201, $response->getStatusCode());

        // re-fetch
        $client = static::createRestClient();
        $client->request('GET', $response->headers->get('Location'), [], [], ['HTTP_ACCEPT' => 'application/json']);
        $data = $client->getResults();

        $client = static::createRestClient();
        $client->request('DELETE', sprintf('/file/%s', $data->id));

        $client = static::createRestClient();
        $client->request('GET', sprintf('/file/%s', $data->id));

        $response = $client->getResponse();
        $this->assertEquals(404, $response->getStatusCode());
    }

    /**
     * validate that we can update the content from a file
     *
     * @return void
     */
    public function testUpdateFileContent()
    {
        $fixtureData = file_get_contents(__DIR__.'/fixtures/test.txt');
        $contentType = 'text/plain';
        $newData = "This is a new text!!!";
        $client = static::createRestClient();
        $client->post(
            '/file/',
            $fixtureData,
            [],
            [],
            ['CONTENT_TYPE' => $contentType],
            false
        );
        $response = $client->getResponse();
        $this->assertEquals(201, $response->getStatusCode());

        $linkHeader = $response->headers->get('Link');
        $this->assertMatchesRegularExpression('@/file/[a-z0-9]{32}>; rel="self"@', $linkHeader);

        // re-fetch
        $client = static::createRestClient();
        $client->request('GET', $response->headers->get('Location'), [], [], ['HTTP_ACCEPT' => 'application/json']);
        $retData = $client->getResults();

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertEquals(strlen($fixtureData), $retData->metadata->size);
        $this->assertEquals($contentType, $retData->metadata->mime);

        $this->updateFileContent($retData->id, $newData, $contentType);
    }

    /**
     * post a file without any mime type.. check if that mime type is correctly determined.
     * fetch content back and compare the contents of the file
     *
     * @return void
     */
    public function testPostFileContentMimeDetectionAndContent()
    {
        $testData = file_get_contents(__DIR__.'/resources/testpicture.jpg');
        $contentType = 'image/jpeg';
        $client = static::createRestClient();

        $client->post(
            '/file/',
            $testData,
            [],
            [],
            [],
            false
        );
        $response = $client->getResponse();
        $this->assertEquals(201, $response->getStatusCode());

        $linkHeader = $response->headers->get('Link');
        $this->assertMatchesRegularExpression('@/file/[a-z0-9]{32}>; rel="self"@', $linkHeader);

        // re-fetch
        $client = static::createRestClient();
        $client->request('GET', $response->headers->get('Location'), [], [], ['HTTP_ACCEPT' => 'application/json']);
        $retData = $client->getResults();

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertEquals($contentType, $retData->metadata->mime);

        $client = static::createRestClient();
        $client->request(
            'GET',
            $response->headers->get('Location'),
            [],
            [],
            ['ACCEPT' => $contentType]
        );

        $response = $client->getInternalResponse();

        $this->assertTrue(($response->getContent() === $testData));
    }

    /**
     * here we PUT a file, then try to update the mimetype in the metadata
     * to 'something/other' and see if we can still GET it and receive the correct mime type
     * (meaning we were not able to modify the mime type)
     *
     * @return void
     */
    public function testIllegalMimeTypeModificationHandling()
    {
        $fileData = "This is a new text!!!";
        $contentType = 'text/plain';

        $client = static::createRestClient();
        $client->put(
            '/file/mimefile',
            $fileData,
            [],
            [],
            [],
            [],
            false
        );
        $response = $client->getResponse();
        $this->assertEquals(Response::HTTP_NO_CONTENT, $response->getStatusCode());

        // GET the metadata
        $client = static::createRestClient();
        $client->request('GET', '/file/mimefile', [], [], ['HTTP_ACCEPT' => 'application/json']);
        $retData = $client->getResults();

        $this->assertEquals($retData->metadata->mime, $contentType);

        // change metadata and save
        $retData->metadata->mime = 'something/other';

        $client = static::createRestClient();
        $client->put('/file/mimefile', $retData, [], [], ['CONTENT_TYPE' => 'application/json']);

        $client = static::createRestClient();
        $client->request(
            'GET',
            '/file/mimefile',
            [],
            [],
            ['ACCEPT' => '*/*']
        );

        $response = $client->getInternalResponse();

        // still the good one?
        $this->assertStringContainsString($contentType, $response->getHeader('content-type'));

        $client = static::createRestClient();
        $client->request('DELETE', '/file/mimefile');
    }

    /**
     * test getting collection schema
     *
     * @return void
     */
    public function testGetFileCollectionSchemaInformation()
    {
        $client = static::createRestClient();
        $client->request('GET', '/schema/file/collection');

        $response = $client->getResponse();
        $results = $client->getResults();

        $this->assertResponseContentType('application/schema+json', $response);
        $this->assertEquals(200, $response->getStatusCode());

        $this->assertEquals('Array of file objects', $results->title);
        $this->assertEquals('array', $results->type);
        $this->assertIsFileSchema($results->items);

        $linkHeader = LinkHeader::fromString($response->headers->get('Link'));

        $this->assertEquals(
            'http://localhost/schema/file/collection',
            $linkHeader->getRel('self')->getUri()
        );
    }

    /**
     * test behavior when data sent was multipart/form-data
     *
     * @return void
     */
    public function testPutNewFileViaForm()
    {
        copy(__DIR__ . '/fixtures/test.txt', sys_get_temp_dir() . '/test.txt');
        $file = sys_get_temp_dir() . '/test.txt';
        $uploadedFile = new UploadedFile($file, 'test.txt', 'text/plain');

        $jsonData = '{
          "id": "myPersonalFile",
          "links": [
            {
              "$ref": "http://localhost/testcase/readonly/101",
              "type": "owner"
            },
            {
              "$ref": "http://localhost/testcase/readonly/102",
              "type": "module"
            }
          ],
          "metadata": {
            "hash": "fix,Not,allowEd,%&ç*2$a-here-demo-test-hash",
            "action":[{"command":"print"},{"command":"archive"}],
            "additionalInformation": "someInfo",
            "additionalProperties": [
                {"name": "testName", "value": "testValue"},
                {"name": "testName2", "value": "testValue2"}
            ],
            "filename": "customFileName"
          }
        }';

        $client = static::createRestClient();
        $client->put(
            '/file/myPersonalFile',
            null,
            [
                'metadata' => $jsonData,
            ],
            [
                'upload' => $uploadedFile,
            ],
            [],
            false
        );

        $response = $client->getResponse();

        $this->assertEquals(Response::HTTP_NO_CONTENT, $response->getStatusCode());
        $this->assertNotContains('location', $response->headers->all());

        $response = $this->updateFileContent('myPersonalFile', "This is a new text!!!");

        $metaData = json_decode($jsonData, true);
        $returnData = json_decode($response->getContent(), true);

        $this->assertEquals($metaData['links'], $returnData['links']);
        $this->assertEquals($metaData['metadata']['action'], $returnData['metadata']['action']);
        $this->assertEquals(
            $metaData['metadata']['additionalInformation'],
            $returnData['metadata']['additionalInformation']
        );
        $this->assertEquals(
            $metaData['metadata']['additionalProperties'],
            $returnData['metadata']['additionalProperties']
        );
        $this->assertCount(2, $returnData['metadata']['additionalProperties']);
        $this->assertEquals($metaData['metadata']['filename'], $returnData['metadata']['filename']);
        $this->assertEquals('fix-Not-allowEd------2-a-here-demo-test-hash', $returnData['metadata']['hash']);

        // clean up
        $client = $this->createRestClient();
        $client->request(
            'DELETE',
            '/file/myPersonalFile'
        );
    }

    /**
     * test behavior when data sent was multipart/form-data
     *
     * @return void
     */
    public function testPutNewFileViaFormHashToLong()
    {
        copy(__DIR__ . '/fixtures/test.txt', sys_get_temp_dir() . '/test.txt');
        $file = sys_get_temp_dir() . '/test.txt';
        $uploadedFile = new UploadedFile($file, 'test.txt', 'text/plain');

        $fixtureData = file_get_contents(__DIR__.'/fixtures/test.txt');
        $correctHash = hash('sha256', $fixtureData);

        // Max 64 length, should not contain the extra bitsasd
        $toLongHashExtra = $correctHash . '-some-extra-bits ';

        $jsonData = '{
          "id": "myPersonalFile2",
          "metadata": {
            "hash": "'.$toLongHashExtra.'",
            "action":[{"command":"archive"}],
            "filename": "customFileName"
          }
        }';

        $client = static::createRestClient();
        $client->put(
            '/file/myPersonalFile2',
            null,
            [
                'metadata' => $jsonData,
            ],
            [
                'upload' => $uploadedFile,
            ],
            [],
            false
        );

        $response = $client->getResponse();

        $this->assertEquals(Response::HTTP_NO_CONTENT, $response->getStatusCode());
        $this->assertNotContains('location', $response->headers->all());

        $response = $this->updateFileContent('myPersonalFile2', "This is a new text!!!");

        $metaData = json_decode($jsonData, true);
        $returnData = json_decode($response->getContent(), true);

        $this->assertEquals($metaData['metadata']['filename'], $returnData['metadata']['filename']);

        // Should NOT be equal as hash was to long and was chopped.
        $this->assertNotEquals($metaData['metadata']['hash'], $returnData['metadata']['hash']);
        // But it should be equal to to first part of the hash
        $this->assertEquals($correctHash, $returnData['metadata']['hash']);

        // clean up
        $client = $this->createRestClient();
        $client->request(
            'DELETE',
            '/file/myPersonalFile2'
        );
    }

    /**
    /**
     * test behavior when data sent was multipart/form-data
     *
     * @return void
     */
    public function testPutNewJsonFileViaForm()
    {
        $fileId = 'simple-json-content';
        $newContent = '{
          "id": "myPersonalFile",
          "someArrayData": [
            {
              "field1": "fieldDataValue"
            }
          ],
          "UnknownData": {
            "testField": "filed"
          }
        }';

        $this->updateFileContent($fileId, $newContent);

        $client = $this->createRestClient([], ['CONTENT_TYPE' => 'text/plain']);
        $client->request('GET', sprintf('/file/%s', $fileId));

        $retData = $client->getResponse()->getContent();

        $this->assertEquals($retData, $newContent);

        // clean up
        $client = $this->createRestClient();
        $client->request(
            'DELETE',
            '/file/'.$fileId
        );
    }

    /**
     * check if a schema is of the file type
     *
     * @param \stdClass $schema schema from service to validate
     *
     * @return void
     */
    private function assertIsFileSchema(\stdClass $schema)
    {
        $this->assertEquals('File', $schema->title);
        $this->assertEquals('File storage service', $schema->description);
        $this->assertEquals('object', $schema->type);

        $this->assertEquals('string', $schema->properties->id->type);
        $this->assertEquals('ID', $schema->properties->id->title);
        $this->assertEquals('Unique identifier', $schema->properties->id->description);
        $this->assertObjectNotHasAttribute('readOnly', $schema->properties->id);

        // Metadata
        $this->assertEquals('object', $schema->properties->metadata->type);
        $this->assertEquals('Metadata', $schema->properties->metadata->title);
        $this->assertObjectNotHasAttribute('readOnly', $schema->properties->metadata);

        // Metadata size
        $this->assertEquals('integer', $schema->properties->metadata->properties->size->type);
        $this->assertEquals('File size', $schema->properties->metadata->properties->size->title);
        $this->assertEquals('Size of file.', $schema->properties->metadata->properties->size->description);

        // Metadata mime
        $this->assertContains('string', $schema->properties->metadata->properties->mime->type);
        $this->assertEquals('MIME Type', $schema->properties->metadata->properties->mime->title);
        $this->assertEquals('MIME-Type of file.', $schema->properties->metadata->properties->mime->description);

        // Metadata createDate
        $this->assertEquals(['string', 'null'], $schema->properties->metadata->properties->createDate->type);
        $this->assertEquals('date-time', $schema->properties->metadata->properties->createDate->format);
        $this->assertEquals('Creation date', $schema->properties->metadata->properties->createDate->title);
        $this->assertEquals(
            'Timestamp of file upload.',
            $schema->properties->metadata->properties->createDate->description
        );

        // Metadata modificationDate
        $this->assertEquals(['string', 'null'], $schema->properties->metadata->properties->modificationDate->type);
        $this->assertEquals('date-time', $schema->properties->metadata->properties->modificationDate->format);
        $this->assertEquals('Modification date', $schema->properties->metadata->properties->modificationDate->title);
        $this->assertEquals(
            'Timestamp of the last file change.',
            $schema->properties->metadata->properties->modificationDate->description
        );

        // Metadata filename
        $this->assertContains('string', $schema->properties->metadata->properties->filename->type);
        $this->assertEquals('File name', $schema->properties->metadata->properties->filename->title);
        $this->assertEquals(
            'Name of the file as it should get displayed to the user.',
            $schema->properties->metadata->properties->filename->description
        );
        $this->assertObjectNotHasAttribute('readOnly', $schema->properties->metadata->properties->filename);

        // metadata action.command array
        $this->assertContains(
            'string',
            $schema->properties->metadata->properties->action->items->properties->command->type
        );
        $this->assertEquals(
            'Action command array',
            $schema->properties->metadata->properties->action->items->properties->command->title
        );
        $this->assertObjectNotHasAttribute(
            'readOnly',
            $schema->properties->metadata->properties->action->items->properties->command
        );

        // metadata additionalInformation
        $this->assertContains(
            'string',
            $schema->properties->metadata->properties->additionalInformation->type
        );
        $this->assertEquals(
            'Additional Information',
            $schema->properties->metadata->properties->additionalInformation->title
        );
        $this->assertObjectNotHasAttribute(
            'readOnly',
            $schema->properties->metadata->properties->additionalInformation
        );

        // metadata additionalProperties
        $additionalPropertiesSchema = $schema->properties->metadata->properties->additionalProperties;
        $this->assertEquals('array', $additionalPropertiesSchema->type);
        $this->assertEquals('object', $additionalPropertiesSchema->items->type);
        $this->assertEquals('string', $additionalPropertiesSchema->items->properties->name->type);
        $this->assertEquals('property name', $additionalPropertiesSchema->items->properties->name->title);
        $this->assertEquals('string', $additionalPropertiesSchema->items->properties->value->type);
        $this->assertEquals('property value', $additionalPropertiesSchema->items->properties->value->title);

        // Links
        $this->assertEquals('array', $schema->properties->links->type);
        $this->assertEquals('many', $schema->properties->links->format);
        $this->assertEquals('Links', $schema->properties->links->title);
        $this->assertEquals('@todo replace me', $schema->properties->links->description);
        $this->assertObjectNotHasAttribute('readOnly', $schema->properties->links);

        // Links items
        $this->assertEquals('object', $schema->properties->links->items->type);
        $this->assertEquals('Links', $schema->properties->links->items->title);
        $this->assertObjectNotHasAttribute('readOnly', $schema->properties->links->items);

        // Links item type
        $this->assertContains('string', $schema->properties->links->items->properties->type->type);
        $this->assertEquals('Type', $schema->properties->links->items->properties->type->title);
        $this->assertEquals('Type of the link.', $schema->properties->links->items->properties->type->description);
        $this->assertObjectNotHasAttribute('readOnly', $schema->properties->links->items->properties->type);

        // Links item $ref
        $this->assertEquals(['string', 'null'], $schema->properties->links->items->properties->{'$ref'}->type);
        $this->assertEquals('extref', $schema->properties->links->items->properties->{'$ref'}->format);
        $this->assertEquals('Link', $schema->properties->links->items->properties->{'$ref'}->title);
        $this->assertEquals(
            'Link to any document.',
            $schema->properties->links->items->properties->{'$ref'}->description
        );
        $this->assertEquals(
            ['*'],
            $schema->properties->links->items->properties->{'$ref'}->{'x-collection'}
        );

        $this->assertEquals(
            [
                'document.file.file.update',
                'document.file.file.create',
                'document.file.file.delete'
            ],
            $schema->{'x-events'}
        );

        $this->assertObjectNotHasAttribute('readOnly', $schema->properties->links->items->properties->{'$ref'});
    }

    /**
     * Verifies the update of a file content.
     *
     * @param string $fileId      identifier of the file to be updated
     * @param string $newContent  new content to be stored in the file
     * @param string $contentType Content-Type of the file
     *
     * @return null|Response
     */
    private function updateFileContent($fileId, $newContent, $contentType = 'text/plain')
    {
        $client = static::createRestClient();
        $client->put(
            sprintf('/file/%s', $fileId),
            $newContent,
            [],
            [],
            ['CONTENT_TYPE' => $contentType],
            false
        );

        $client = static::createRestClient();
        $client->request('GET', sprintf('/file/%s', $fileId), [], [], ['HTTP_ACCEPT' => 'application/json']);

        $retData = $client->getResults();
        $response = $client->getResponse();
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals($contentType, $retData->metadata->mime);

        return $response;
    }
}


text:
/* $Id: sph_echo.h 216 2010-06-08 09:46:57Z tp $ */
/**
 * ECHO interface. ECHO is a family of functions which differ by
 * their output size; this implementation defines ECHO for output
 * sizes 224, 256, 384 and 512 bits.
 *
 * ==========================(LICENSE BEGIN)============================
 *
 * Copyright (c) 2007-2010  Projet RNRT SAPHIR
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * ===========================(LICENSE END)=============================
 *
 * @file     sph_echo.h
 * @author   Thomas Pornin <thomas.pornin@cryptolog.com>
 */

#ifndef SPH_ECHO_H__
#define SPH_ECHO_H__

#ifdef __cplusplus
extern "C"{
#endif

#include <stddef.h>
#include <crypto/sph_types.h>

/**
 * Output size (in bits) for ECHO-224.
 */
#define SPH_SIZE_echo224   224

/**
 * Output size (in bits) for ECHO-256.
 */
#define SPH_SIZE_echo256   256

/**
 * Output size (in bits) for ECHO-384.
 */
#define SPH_SIZE_echo384   384

/**
 * Output size (in bits) for ECHO-512.
 */
#define SPH_SIZE_echo512   512

/**
 * This structure is a context for ECHO computations: it contains the
 * intermediate values and some data from the last entered block. Once
 * an ECHO computation has been performed, the context can be reused for
 * another computation. This specific structure is used for ECHO-224
 * and ECHO-256.
 *
 * The contents of this structure are private. A running ECHO computation
 * can be cloned by copying the context (e.g. with a simple
 * memcpy()).
 */
typedef struct {
#ifndef DOXYGEN_IGNORE
	unsigned char buf[192];    /* first field, for alignment */
	size_t ptr;
	union {
		sph_u32 Vs[4][4];
#if SPH_64
		sph_u64 Vb[4][2];
#endif
	} u;
	sph_u32 C0, C1, C2, C3;
#endif
} sph_echo_small_context;

/**
 * This structure is a context for ECHO computations: it contains the
 * intermediate values and some data from the last entered block. Once
 * an ECHO computation has been performed, the context can be reused for
 * another computation. This specific structure is used for ECHO-384
 * and ECHO-512.
 *
 * The contents of this structure are private. A running ECHO computation
 * can be cloned by copying the context (e.g. with a simple
 * memcpy()).
 */
typedef struct {
#ifndef DOXYGEN_IGNORE
	unsigned char buf[128];    /* first field, for alignment */
	size_t ptr;
	union {
		sph_u32 Vs[8][4];
#if SPH_64
		sph_u64 Vb[8][2];
#endif
	} u;
	sph_u32 C0, C1, C2, C3;
#endif
} sph_echo_big_context;

/**
 * Type for a ECHO-224 context (identical to the common "small" context).
 */
typedef sph_echo_small_context sph_echo224_context;

/**
 * Type for a ECHO-256 context (identical to the common "small" context).
 */
typedef sph_echo_small_context sph_echo256_context;

/**
 * Type for a ECHO-384 context (identical to the common "big" context).
 */
typedef sph_echo_big_context sph_echo384_context;

/**
 * Type for a ECHO-512 context (identical to the common "big" context).
 */
typedef sph_echo_big_context sph_echo512_context;

/**
 * Initialize an ECHO-224 context. This process performs no memory allocation.
 *
 * @param cc   the ECHO-224 context (pointer to a
 *             sph_echo224_context)
 */
void sph_echo224_init(void *cc);

/**
 * Process some data bytes. It is acceptable that len is zero
 * (in which case this function does nothing).
 *
 * @param cc     the ECHO-224 context
 * @param data   the input data
 * @param len    the input data length (in bytes)
 */
void sph_echo224(void *cc, const void *data, size_t len);

/**
 * Terminate the current ECHO-224 computation and output the result into
 * the provided buffer. The destination buffer must be wide enough to
 * accomodate the result (28 bytes). The context is automatically
 * reinitialized.
 *
 * @param cc    the ECHO-224 context
 * @param dst   the destination buffer
 */
void sph_echo224_close(void *cc, void *dst);

/**
 * Add a few additional bits (0 to 7) to the current computation, then
 * terminate it and output the result in the provided buffer, which must
 * be wide enough to accomodate the result (28 bytes). If bit number i
 * in ub has value 2^i, then the extra bits are those
 * numbered 7 downto 8-n (this is the big-endian convention at the byte
 * level). The context is automatically reinitialized.
 *
 * @param cc    the ECHO-224 context
 * @param ub    the extra bits
 * @param n     the number of extra bits (0 to 7)
 * @param dst   the destination buffer
 */
void sph_echo224_addbits_and_close(
	void *cc, unsigned ub, unsigned n, void *dst);

/**
 * Initialize an ECHO-256 context. This process performs no memory allocation.
 *
 * @param cc   the ECHO-256 context (pointer to a
 *             sph_echo256_context)
 */
void sph_echo256_init(void *cc);

/**
 * Process some data bytes. It is acceptable that len is zero
 * (in which case this function does nothing).
 *
 * @param cc     the ECHO-256 context
 * @param data   the input data
 * @param len    the input data length (in bytes)
 */
void sph_echo256(void *cc, const void *data, size_t len);

/**
 * Terminate the current ECHO-256 computation and output the result into
 * the provided buffer. The destination buffer must be wide enough to
 * accomodate the result (32 bytes). The context is automatically
 * reinitialized.
 *
 * @param cc    the ECHO-256 context
 * @param dst   the destination buffer
 */
void sph_echo256_close(void *cc, void *dst);

/**
 * Add a few additional bits (0 to 7) to the current computation, then
 * terminate it and output the result in the provided buffer, which must
 * be wide enough to accomodate the result (32 bytes). If bit number i
 * in ub has value 2^i, then the extra bits are those
 * numbered 7 downto 8-n (this is the big-endian convention at the byte
 * level). The context is automatically reinitialized.
 *
 * @param cc    the ECHO-256 context
 * @param ub    the extra bits
 * @param n     the number of extra bits (0 to 7)
 * @param dst   the destination buffer
 */
void sph_echo256_addbits_and_close(
	void *cc, unsigned ub, unsigned n, void *dst);

/**
 * Initialize an ECHO-384 context. This process performs no memory allocation.
 *
 * @param cc   the ECHO-384 context (pointer to a
 *             sph_echo384_context)
 */
void sph_echo384_init(void *cc);

/**
 * Process some data bytes. It is acceptable that len is zero
 * (in which case this function does nothing).
 *
 * @param cc     the ECHO-384 context
 * @param data   the input data
 * @param len    the input data length (in bytes)
 */
void sph_echo384(void *cc, const void *data, size_t len);

/**
 * Terminate the current ECHO-384 computation and output the result into
 * the provided buffer. The destination buffer must be wide enough to
 * accomodate the result (48 bytes). The context is automatically
 * reinitialized.
 *
 * @param cc    the ECHO-384 context
 * @param dst   the destination buffer
 */
void sph_echo384_close(void *cc, void *dst);

/**
 * Add a few additional bits (0 to 7) to the current computation, then
 * terminate it and output the result in the provided buffer, which must
 * be wide enough to accomodate the result (48 bytes). If bit number i
 * in ub has value 2^i, then the extra bits are those
 * numbered 7 downto 8-n (this is the big-endian convention at the byte
 * level). The context is automatically reinitialized.
 *
 * @param cc    the ECHO-384 context
 * @param ub    the extra bits
 * @param n     the number of extra bits (0 to 7)
 * @param dst   the destination buffer
 */
void sph_echo384_addbits_and_close(
	void *cc, unsigned ub, unsigned n, void *dst);

/**
 * Initialize an ECHO-512 context. This process performs no memory allocation.
 *
 * @param cc   the ECHO-512 context (pointer to a
 *             sph_echo512_context)
 */
void sph_echo512_init(void *cc);

/**
 * Process some data bytes. It is acceptable that len is zero
 * (in which case this function does nothing).
 *
 * @param cc     the ECHO-512 context
 * @param data   the input data
 * @param len    the input data length (in bytes)
 */
void sph_echo512(void *cc, const void *data, size_t len);

/**
 * Terminate the current ECHO-512 computation and output the result into
 * the provided buffer. The destination buffer must be wide enough to
 * accomodate the result (64 bytes). The context is automatically
 * reinitialized.
 *
 * @param cc    the ECHO-512 context
 * @param dst   the destination buffer
 */
void sph_echo512_close(void *cc, void *dst);

/**
 * Add a few additional bits (0 to 7) to the current computation, then
 * terminate it and output the result in the provided buffer, which must
 * be wide enough to accomodate the result (64 bytes). If bit number i
 * in ub has value 2^i, then the extra bits are those
 * numbered 7 downto 8-n (this is the big-endian convention at the byte
 * level). The context is automatically reinitialized.
 *
 * @param cc    the ECHO-512 context
 * @param ub    the extra bits
 * @param n     the number of extra bits (0 to 7)
 * @param dst   the destination buffer
 */
void sph_echo512_addbits_and_close(
	void *cc, unsigned ub, unsigned n, void *dst);

#ifdef __cplusplus
}
#endif

#endif


text:
@interface ReferenceCountController ()

@end

@implementation ReferenceCountController

- (void)viewDidLoad {
    [super viewDidLoad];

    UILabel *_label = [UILabel makeLabelWithContent:@"Please see the .h file"];
    _label.center = self.view.center;
    [self.view addSubview:_label];
}

@end


text:
<?php
namespace Nemesis\LaravelRest\Traits\Actions;

use Illuminate\Http\Response;

/**
 * Save entity
 *
 * Class StoreAction
 * @package Nemesis\LaravelRest\Traits\Actions
 *
 * @version 1.0.0
 * @author Bondarenko Kirill <bondarenko.kirill@gmail.com>
 */
trait StoreAction
{
    /**
     * @return Response
     */
    public function store()
    {
        $request = $this->getRequestObject();

        $model = $this->modelClass;
        $item = $model::create($request->all());

        return $this->setStatusCode(Response::HTTP_CREATED)->respond($item);
    }
}


text:
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Data.Entity.Infrastructure;
using System.Linq.Expressions;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data.Entity.ModelConfiguration;
using System.Threading;
using DatabaseGeneratedOption = System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption;

namespace MapperExemple.Entity.EF
{
    // Region
    internal class RegionConfiguration : EntityTypeConfiguration<Region>
    {
        public RegionConfiguration()
            : this("dbo")
        {
        }

        public RegionConfiguration(string schema)
        {
            ToTable(schema + ".Region");
            HasKey(x => x.RegionId);

            Property(x => x.RegionId).HasColumnName("RegionID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
            Property(x => x.RegionDescription).HasColumnName("RegionDescription").IsRequired().IsFixedLength().HasColumnType("nchar").HasMaxLength(50);
        }
    }

}


text:
#include "private-libwebsockets.h"

int lws_context_init_server(struct lws_context_creation_info *info,
			    struct lws_context *context)
{
#ifdef LWS_USE_IPV6
	struct sockaddr_in6 serv_addr6;
#endif
#if LWS_POSIX
	struct sockaddr_in serv_addr4;
	socklen_t len = sizeof(struct sockaddr);
	struct sockaddr_in sin;
	struct sockaddr *v;
	int n, opt = 1;
#endif
	lws_sockfd_type sockfd;
	struct lws *wsi;

	/* set up our external listening socket we serve on */

	if (info->port == CONTEXT_PORT_NO_LISTEN)
		return 0;

#if LWS_POSIX
#ifdef LWS_USE_IPV6
	if (LWS_IPV6_ENABLED(context))
		sockfd = socket(AF_INET6, SOCK_STREAM, 0);
	else
#endif
		sockfd = socket(AF_INET, SOCK_STREAM, 0);

	if (sockfd == -1) {
#else
	sockfd = mbed3_create_tcp_stream_socket();
	if (!lws_sockfd_valid(sockfd)) {
#endif
		lwsl_err("ERROR opening socket\n");
		return 1;
	}

#if LWS_POSIX
	/*
	 * allow us to restart even if old sockets in TIME_WAIT
	 */
	if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
		       (const void *)&opt, sizeof(opt)) < 0) {
		compatible_close(sockfd);
		return 1;
	}
#endif
	lws_plat_set_socket_options(context, sockfd);

#if LWS_POSIX
#ifdef LWS_USE_IPV6
	if (LWS_IPV6_ENABLED(context)) {
		v = (struct sockaddr *)&serv_addr6;
		n = sizeof(struct sockaddr_in6);
		bzero((char *) &serv_addr6, sizeof(serv_addr6));
		serv_addr6.sin6_addr = in6addr_any;
		serv_addr6.sin6_family = AF_INET6;
		serv_addr6.sin6_port = htons(info->port);
	} else
#endif
	{
		v = (struct sockaddr *)&serv_addr4;
		n = sizeof(serv_addr4);
		bzero((char *) &serv_addr4, sizeof(serv_addr4));
		serv_addr4.sin_addr.s_addr = INADDR_ANY;
		serv_addr4.sin_family = AF_INET;

		if (info->iface && interface_to_sa(context, info->iface,
				   (struct sockaddr_in *)v, n) < 0) {
			lwsl_err("Unable to find interface %s\n", info->iface);
			goto bail;
		}

		serv_addr4.sin_port = htons(info->port);
	} /* ipv4 */

	n = bind(sockfd, v, n);
	if (n < 0) {
		lwsl_err("ERROR on binding to port %d (%d %d)\n",
					      info->port, n, LWS_ERRNO);
		goto bail;
	}

	if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
		lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO));
	else
		info->port = ntohs(sin.sin_port);
#endif

	context->listen_port = info->port;

	wsi = lws_zalloc(sizeof(struct lws));
	if (wsi == NULL) {
		lwsl_err("Out of mem\n");
		goto bail;
	}
	wsi->context = context;
	wsi->sock = sockfd;
	wsi->mode = LWSCM_SERVER_LISTENER;
	wsi->protocol = context->protocols;

	if (insert_wsi_socket_into_fds(context, wsi))
		goto bail;

	context->lserv_mod = LWS_lserv_mod;
	context->lserv_count = 0;
	context->lserv_fd = sockfd;

#if LWS_POSIX
	listen(sockfd, LWS_SOMAXCONN);
#else
	mbed3_tcp_stream_bind(sockfd, info->port, wsi);
#endif
	lwsl_notice(" Listening on port %d\n", info->port);

	return 0;

bail:
	compatible_close(sockfd);

	return 1;
}

int
_lws_rx_flow_control(struct lws *wsi)
{
	if (!wsi || wsi->context->being_destroyed)
		return 0;

	/* there is no pending change */
	if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE))
		return 0;

	/* stuff is still buffered, not ready to really accept new input */
	if (wsi->rxflow_buffer) {
		/* get ourselves called back to deal with stashed buffer */
		lws_callback_on_writable(wsi);
		return 0;
	}

	/* pending is cleared, we can change rxflow state */

	wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE;

	lwsl_info("rxflow: wsi %p change_to %d\n", wsi,
			      wsi->rxflow_change_to & LWS_RXFLOW_ALLOW);

	/* adjust the pollfd for this wsi */

	if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) {
		if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) {
			lwsl_info("%s: fail\n", __func__);
			return -1;
		}
	} else
		if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
			return -1;

	return 0;
}

int lws_http_action(struct lws *wsi)
{
	enum http_connection_type connection_type;
	enum http_version request_version;
	char content_length_str[32];
	unsigned int n, count = 0;
	char http_version_str[10];
	char http_conn_str[20];
	int http_version_len;
	char *uri_ptr = NULL;
	int uri_len = 0;

	static const unsigned char methods[] = {
		WSI_TOKEN_GET_URI,
		WSI_TOKEN_POST_URI,
		WSI_TOKEN_OPTIONS_URI,
		WSI_TOKEN_PUT_URI,
		WSI_TOKEN_PATCH_URI,
		WSI_TOKEN_DELETE_URI,
#ifdef LWS_USE_HTTP2
		WSI_TOKEN_HTTP_COLON_PATH,
#endif
	};
#ifdef _DEBUG
	static const char * const method_names[] = {
		"GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
#ifdef LWS_USE_HTTP2
		":path",
#endif
	};
#endif

	/* it's not websocket.... shall we accept it as http? */

	for (n = 0; n < ARRAY_SIZE(methods); n++)
		if (lws_hdr_total_length(wsi, methods[n]))
			count++;
	if (!count) {
		lwsl_warn("Missing URI in HTTP request\n");
		goto bail_nuke_ah;
	}

	if (count != 1) {
		lwsl_warn("multiple methods?\n");
		goto bail_nuke_ah;
	}

	if (lws_ensure_user_space(wsi))
		goto bail_nuke_ah;

	for (n = 0; n < ARRAY_SIZE(methods); n++)
		if (lws_hdr_total_length(wsi, methods[n])) {
			uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
			uri_len = lws_hdr_total_length(wsi, methods[n]);
			lwsl_info("Method: %s request for '%s'\n",
				  	method_names[n], uri_ptr);
			break;
		}

	/* HTTP header had a content length? */

	wsi->u.http.content_length = 0;
	if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
		lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
		lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
		wsi->u.http.content_length = 100 * 1024 * 1024;

	if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
		lws_hdr_copy(wsi, content_length_str,
			     sizeof(content_length_str) - 1,
			     WSI_TOKEN_HTTP_CONTENT_LENGTH);
		wsi->u.http.content_length = atoi(content_length_str);
	}

	/* http_version? Default to 1.0, override with token: */
	request_version = HTTP_VERSION_1_0;

	/* Works for single digit HTTP versions. : */
	http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
	if (http_version_len > 7) {
		lws_hdr_copy(wsi, http_version_str,
				sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
		if (http_version_str[5] == '1' && http_version_str[7] == '1')
			request_version = HTTP_VERSION_1_1;
	}
	wsi->u.http.request_version = request_version;

	/* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
	if (request_version == HTTP_VERSION_1_1)
		connection_type = HTTP_CONNECTION_KEEP_ALIVE;
	else
		connection_type = HTTP_CONNECTION_CLOSE;

	/* Override default if http "Connection:" header: */
	if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
		lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
			     WSI_TOKEN_CONNECTION);
		http_conn_str[sizeof(http_conn_str) - 1] = '\0';
		if (!strcasecmp(http_conn_str, "keep-alive"))
			connection_type = HTTP_CONNECTION_KEEP_ALIVE;
		else
			if (!strcasecmp(http_conn_str, "close"))
				connection_type = HTTP_CONNECTION_CLOSE;
	}
	wsi->u.http.connection_type = connection_type;

	n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
				    wsi->user_space, uri_ptr, uri_len);

	if (!n) {
		/*
		 * if there is content supposed to be coming,
		 * put a timeout on it having arrived
		 */
		lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
				AWAITING_TIMEOUT);

		n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
					    wsi->user_space, uri_ptr, uri_len);
	}

	/* now drop the header info we kept a pointer to */
	lws_free_set_NULL(wsi->u.http.ah);

	if (n) {
		lwsl_info("LWS_CALLBACK_HTTP closing\n");
		return 1; /* struct ah ptr already nuked */		}

	/*
	 * If we're not issuing a file, check for content_length or
	 * HTTP keep-alive. No keep-alive header allocation for
	 * ISSUING_FILE, as this uses HTTP/1.0.
	 *
	 * In any case, return 0 and let lws_read decide how to
	 * proceed based on state
	 */
	if (wsi->state != LWSS_HTTP_ISSUING_FILE)
		/* Prepare to read body if we have a content length: */
		if (wsi->u.http.content_length > 0)
			wsi->state = LWSS_HTTP_BODY;

	return 0;

bail_nuke_ah:
	/* drop the header info */
	lws_free_set_NULL(wsi->u.hdr.ah);

	return 1;
}

int lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
{
	struct lws_context *context = lws_get_context(wsi);
	struct allocated_headers *ah;
	int protocol_len, n, hit;
	char protocol_list[128];
	char protocol_name[32];
	char *p;

	/* LWSCM_WS_SERVING */

	while (len--) {

		assert(wsi->mode == LWSCM_HTTP_SERVING);

		if (lws_parse(wsi, *(*buf)++)) {
			lwsl_info("lws_parse failed\n");
			goto bail_nuke_ah;
		}

		if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
			continue;

		lwsl_parser("lws_parse sees parsing complete\n");

		wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
		lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);

		/* is this websocket protocol or normal http 1.0? */

		if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
			if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
					"websocket")) {
				lwsl_info("Upgrade to ws\n");
				goto upgrade_ws;
			}
#ifdef LWS_USE_HTTP2
			if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
					"h2c-14")) {
				lwsl_info("Upgrade to h2c-14\n");
				goto upgrade_h2c;
			}
#endif
			lwsl_err("Unknown upgrade\n");
			/* dunno what he wanted to upgrade to */
			goto bail_nuke_ah;
		}

		/* no upgrade ack... he remained as HTTP */

		lwsl_info("No upgrade\n");
		ah = wsi->u.hdr.ah;

		lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
		wsi->state = LWSS_HTTP;
		wsi->u.http.fd = LWS_INVALID_FILE;

		/* expose it at the same offset as u.hdr */
		wsi->u.http.ah = ah;
		lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi, (void *)wsi->u.hdr.ah);

		n = lws_http_action(wsi);

		return n;

#ifdef LWS_USE_HTTP2
upgrade_h2c:
		if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
			lwsl_err("missing http2_settings\n");
			goto bail_nuke_ah;
		}

		lwsl_err("h2c upgrade...\n");

		p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
		/* convert the peer's HTTP-Settings */
		n = lws_b64_decode_string(p, protocol_list,
					  sizeof(protocol_list));
		if (n < 0) {
			lwsl_parser("HTTP2_SETTINGS too long\n");
			return 1;
		}

		/* adopt the header info */

		ah = wsi->u.hdr.ah;

		lws_union_transition(wsi, LWSCM_HTTP2_SERVING);

		/* http2 union member has http union struct at start */
		wsi->u.http.ah = ah;

		lws_http2_init(&wsi->u.http2.peer_settings);
		lws_http2_init(&wsi->u.http2.my_settings);

		/* HTTP2 union */

		lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
				(unsigned char *)protocol_list, n);

		strcpy(protocol_list,
		       "HTTP/1.1 101 Switching Protocols\x0d\x0a"
		      "Connection: Upgrade\x0d\x0a"
		      "Upgrade: h2c\x0d\x0a\x0d\x0a");
		n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
					strlen(protocol_list));
		if (n != strlen(protocol_list)) {
			lwsl_debug("http2 switch: ERROR writing to socket\n");
			return 1;
		}

		wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;

		return 0;
#endif

upgrade_ws:
		if (!wsi->protocol)
			lwsl_err("NULL protocol at lws_read\n");

		/*
		 * It's websocket
		 *
		 * Select the first protocol we support from the list
		 * the client sent us.
		 *
		 * Copy it to remove header fragmentation
		 */

		if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
				 WSI_TOKEN_PROTOCOL) < 0) {
			lwsl_err("protocol list too long");
			goto bail_nuke_ah;
		}

		protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
		protocol_list[protocol_len] = '\0';
		p = protocol_list;
		hit = 0;

		while (*p && !hit) {
			unsigned int n = 0;
			while (n < sizeof(protocol_name) - 1 && *p && *p !=',')
				protocol_name[n++] = *p++;
			protocol_name[n] = '\0';
			if (*p)
				p++;

			lwsl_info("checking %s\n", protocol_name);

			n = 0;
			while (wsi->protocol && context->protocols[n].callback) {
				if (!wsi->protocol->name) {
					n++;
					continue;
				}
				if (!strcmp(context->protocols[n].name,
					    protocol_name)) {
					lwsl_info("prot match %d\n", n);
					wsi->protocol = &context->protocols[n];
					hit = 1;
					break;
				}

				n++;
			}
		}

		/* we didn't find a protocol he wanted? */

		if (!hit) {
			if (!lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
				/*
				 * some clients only have one protocol and
				 * do not sent the protocol list header...
				 * allow it and match to protocol 0
				 */
				lwsl_info("defaulting to prot 0 handler\n");
				wsi->protocol = &context->protocols[0];
			} else {
				lwsl_err("No protocol from list \"%s\" supported\n",
					 protocol_list);
				goto bail_nuke_ah;
			}
		}

		/* allocate wsi->user storage */
		if (lws_ensure_user_space(wsi))
			goto bail_nuke_ah;

		/*
		 * Give the user code a chance to study the request and
		 * have the opportunity to deny it
		 */

		if ((wsi->protocol->callback)(wsi,
				LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
				wsi->user_space,
			      lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
			lwsl_warn("User code denied connection\n");
			goto bail_nuke_ah;
		}

		/*
		 * Perform the handshake according to the protocol version the
		 * client announced
		 */

		switch (wsi->ietf_spec_revision) {
		case 13:
			lwsl_parser("lws_parse calling handshake_04\n");
			if (handshake_0405(context, wsi)) {
				lwsl_info("hs0405 has failed the connection\n");
				goto bail_nuke_ah;
			}
			break;

		default:
			lwsl_warn("Unknown client spec version %d\n",
						       wsi->ietf_spec_revision);
			goto bail_nuke_ah;
		}

		/* drop the header info -- no bail_nuke_ah after this */
		lws_free_header_table(wsi);

		lws_union_transition(wsi, LWSCM_WS_SERVING);

		/*
		 * create the frame buffer for this connection according to the
		 * size mentioned in the protocol definition.  If 0 there, use
		 * a big default for compatibility
		 */

		n = wsi->protocol->rx_buffer_size;
		if (!n)
			n = LWS_MAX_SOCKET_IO_BUF;
		n += LWS_SEND_BUFFER_PRE_PADDING + LWS_SEND_BUFFER_POST_PADDING;
		wsi->u.ws.rx_user_buffer = lws_malloc(n);
		if (!wsi->u.ws.rx_user_buffer) {
			lwsl_err("Out of Mem allocating rx buffer %d\n", n);
			return 1;
		}
		wsi->u.ws.rx_ubuf_alloc = n;
		lwsl_info("Allocating RX buffer %d\n", n);
#if LWS_POSIX
		if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF,
			       (const char *)&n, sizeof n)) {
			lwsl_warn("Failed to set SNDBUF to %d", n);
			return 1;
		}
#endif
		lwsl_parser("accepted v%02d connection\n", wsi->ietf_spec_revision);

		return 0;
	} /* while all chars are handled */

	return 0;

bail_nuke_ah:
	/* drop the header info */
	lws_free_header_table(wsi);
	return 1;
}

struct lws *
lws_create_new_server_wsi(struct lws_context *context)
{
	struct lws *new_wsi;

	new_wsi = lws_zalloc(sizeof(struct lws));
	if (new_wsi == NULL) {
		lwsl_err("Out of memory for new connection\n");
		return NULL;
	}

	new_wsi->context = context;
	new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
	new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;

	/* intialize the instance struct */

	new_wsi->state = LWSS_HTTP;
	new_wsi->mode = LWSCM_HTTP_SERVING;
	new_wsi->hdr_parsing_completed = 0;

#ifdef LWS_OPENSSL_SUPPORT
	new_wsi->use_ssl = LWS_SSL_ENABLED(context);
#endif

	if (lws_allocate_header_table(new_wsi)) {
		lws_free(new_wsi);
		return NULL;
	}

	/*
	 * these can only be set once the protocol is known
	 * we set an unestablished connection's protocol pointer
	 * to the start of the supported list, so it can look
	 * for matching ones during the handshake
	 */
	new_wsi->protocol = context->protocols;
	new_wsi->user_space = NULL;
	new_wsi->ietf_spec_revision = 0;
	new_wsi->sock = LWS_SOCK_INVALID;

	/*
	 * outermost create notification for wsi
	 * no user_space because no protocol selection
	 */
	context->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE, NULL,
				       NULL, 0);

	return new_wsi;
}

/**
 * lws_http_transaction_completed() - wait for new http transaction or close
 * @wsi:	websocket connection
 *
 *	Returns 1 if the HTTP connection must close now
 *	Returns 0 and resets connection to wait for new HTTP header /
 *	  transaction if possible
 */

LWS_VISIBLE
int lws_http_transaction_completed(struct lws *wsi)
{
	/* if we can't go back to accept new headers, drop the connection */
	if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
		lwsl_info("%s: close connection\n", __func__);
		return 1;
	}

	/* otherwise set ourselves up ready to go again */
	wsi->state = LWSS_HTTP;
	wsi->mode = LWSCM_HTTP_SERVING;
	wsi->u.http.content_length = 0;

	/* He asked for it to stay alive indefinitely */
	lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);

	if (lws_allocate_header_table(wsi))
		return 1;

	/* If we're (re)starting on headers, need other implied init */
	wsi->u.hdr.ues = URIES_IDLE;

	lwsl_info("%s: keep-alive await new transaction\n", __func__);

	return 0;
}

LWS_VISIBLE
int lws_server_socket_service(struct lws_context *context,
			      struct lws *wsi, struct lws_pollfd *pollfd)
{
	lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
#if LWS_POSIX
	struct sockaddr_in cli_addr;
	socklen_t clilen;
#endif
	struct lws *new_wsi = NULL;
	int n, len;

	switch (wsi->mode) {

	case LWSCM_HTTP_SERVING:
	case LWSCM_HTTP_SERVING_ACCEPTED:
	case LWSCM_HTTP2_SERVING:

		/* handle http headers coming in */

		/* pending truncated sends have uber priority */

		if (wsi->trunc_len) {
			if (!(pollfd->revents & LWS_POLLOUT))
				break;

			if (lws_issue_raw(wsi, wsi->trunc_alloc + wsi->trunc_offset,
					  wsi->trunc_len) < 0)
				goto fail;
			/*
			 * we can't afford to allow input processing send
			 * something new, so spin around he event loop until
			 * he doesn't have any partials
			 */
			break;
		}

		/* any incoming data ready? */

		if (!(pollfd->revents & LWS_POLLIN))
			goto try_pollout;

		len = lws_ssl_capable_read(wsi, context->serv_buf,
					   sizeof(context->serv_buf));
		lwsl_debug("%s: read %d\r\n", __func__, len);
		switch (len) {
		case 0:
			lwsl_info("lws_server_skt_srv: read 0 len\n");
			/* lwsl_info("   state=%d\n", wsi->state); */
			if (!wsi->hdr_parsing_completed)
				lws_free_header_table(wsi);
			/* fallthru */
		case LWS_SSL_CAPABLE_ERROR:
			goto fail;
		case LWS_SSL_CAPABLE_MORE_SERVICE:
			goto try_pollout;
		}

		/* just ignore incoming if waiting for close */
		if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
			/*
			 * hm this may want to send
			 * (via HTTP callback for example)
			 */
			n = lws_read(wsi, context->serv_buf, len);
			if (n < 0) /* we closed wsi */
				return 1;

			/* hum he may have used up the
			 * writability above */
			break;
		}

try_pollout:
		/* this handles POLLOUT for http serving fragments */

		if (!(pollfd->revents & LWS_POLLOUT))
			break;

		/* one shot */
		if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
			goto fail;

		lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_WRITE);

		if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
			n = user_callback_handle_rxflow(
					wsi->protocol->callback,
					wsi, LWS_CALLBACK_HTTP_WRITEABLE,
					wsi->user_space, NULL, 0);
			if (n < 0)
				goto fail;
			break;
		}

		/* >0 == completion, <0 == error */
		n = lws_serve_http_file_fragment(wsi);
		if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi)))
			goto fail;
		break;

	case LWSCM_SERVER_LISTENER:

#if LWS_POSIX
		/* pollin means a client has connected to us then */

		if (!(pollfd->revents & LWS_POLLIN))
			break;

		/* listen socket got an unencrypted connection... */

		clilen = sizeof(cli_addr);
		lws_latency_pre(context, wsi);
		accept_fd  = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
				    &clilen);
		lws_latency(context, wsi,
			"unencrypted accept LWSCM_SERVER_LISTENER",
						     accept_fd, accept_fd >= 0);
		if (accept_fd < 0) {
			if (LWS_ERRNO == LWS_EAGAIN ||
			    LWS_ERRNO == LWS_EWOULDBLOCK) {
				lwsl_debug("accept asks to try again\n");
				break;
			}
			lwsl_warn("ERROR on accept: %s\n", strerror(LWS_ERRNO));
			break;
		}

		lws_plat_set_socket_options(context, accept_fd);
#else
		/* not very beautiful... */
		accept_fd = (lws_sockfd_type)pollfd;
#endif
		/*
		 * look at who we connected to and give user code a chance
		 * to reject based on client IP.  There's no protocol selected
		 * yet so we issue this to protocols[0]
		 */

		if ((context->protocols[0].callback)(wsi,
				LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
					   NULL, (void *)(long)accept_fd, 0)) {
			lwsl_debug("Callback denied network connection\n");
			compatible_close(accept_fd);
			break;
		}

		new_wsi = lws_create_new_server_wsi(context);
		if (new_wsi == NULL) {
			compatible_close(accept_fd);
			break;
		}

		new_wsi->sock = accept_fd;

		/* the transport is accepted... give him time to negotiate */
		lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
				AWAITING_TIMEOUT);

#if LWS_POSIX == 0
		mbed3_tcp_stream_accept(accept_fd, new_wsi);
#endif

		/*
		 * A new connection was accepted. Give the user a chance to
		 * set properties of the newly created wsi. There's no protocol
		 * selected yet so we issue this to protocols[0]
		 */
		(context->protocols[0].callback)(new_wsi,
			LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED,
			NULL, NULL, 0);

		lws_libev_accept(new_wsi, accept_fd);

		if (!LWS_SSL_ENABLED(context)) {
#if LWS_POSIX
			lwsl_debug("accepted new conn  port %u on fd=%d\n",
					  ntohs(cli_addr.sin_port), accept_fd);
#endif
			if (insert_wsi_socket_into_fds(context, new_wsi))
				goto fail;
		}
		break;

	default:
		break;
	}

	if (!lws_server_socket_service_ssl(&wsi, new_wsi, accept_fd, pollfd))
		return 0;

fail:
	lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);

	return 1;
}

/**
 * lws_serve_http_file() - Send a file back to the client using http
 * @wsi:		Websocket instance (available from user callback)
 * @file:		The file to issue over http
 * @content_type:	The http content type, eg, text/html
 * @other_headers:	NULL or pointer to header string
 * @other_headers_len:	length of the other headers if non-NULL
 *
 *	This function is intended to be called from the callback in response
 *	to http requests from the client.  It allows the callback to issue
 *	local files down the http link in a single step.
 *
 *	Returning <0 indicates error and the wsi should be closed.  Returning
 *	>0 indicates the file was completely sent and
 *	lws_http_transaction_completed() called on the wsi (and close if != 0)
 *	==0 indicates the file transfer is started and needs more service later,
 *	the wsi should be left alone.
 */

LWS_VISIBLE int lws_serve_http_file(struct lws *wsi, const char *file,
				    const char *content_type,
				    const char *other_headers,
				    int other_headers_len)
{
	struct lws_context *context = lws_get_context(wsi);
	unsigned char *response = context->serv_buf +
				  LWS_SEND_BUFFER_PRE_PADDING;
	unsigned char *p = response;
	unsigned char *end = p + sizeof(context->serv_buf) -
			     LWS_SEND_BUFFER_PRE_PADDING;
	int ret = 0;

	wsi->u.http.fd = lws_plat_file_open(wsi, file, &wsi->u.http.filelen,
					    O_RDONLY);

	if (wsi->u.http.fd == LWS_INVALID_FILE) {
		lwsl_err("Unable to open '%s'\n", file);
		lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);

		return -1;
	}

	if (lws_add_http_header_status(wsi, 200, &p, end))
		return -1;
	if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
					 (unsigned char *)"libwebsockets", 13,
					 &p, end))
		return -1;
	if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
					 (unsigned char *)content_type,
					 strlen(content_type), &p, end))
		return -1;
	if (lws_add_http_header_content_length(wsi, wsi->u.http.filelen, &p, end))
		return -1;

	if (other_headers) {
		if ((end - p) < other_headers_len)
			return -1;
		memcpy(p, other_headers, other_headers_len);
		p += other_headers_len;
	}

	if (lws_finalize_http_header(wsi, &p, end))
		return -1;

	ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
	if (ret != (p - response)) {
		lwsl_err("_write returned %d from %d\n", ret, (p - response));
		return -1;
	}

	wsi->u.http.filepos = 0;
	wsi->state = LWSS_HTTP_ISSUING_FILE;

	return lws_serve_http_file_fragment(wsi);
}

int
lws_interpret_incoming_packet(struct lws *wsi, unsigned char *buf, size_t len)
{
	size_t n = 0;
	int m;

#if 0
	lwsl_parser("received %d byte packet\n", (int)len);
	lwsl_hexdump(buf, len);
#endif

	/* let the rx protocol state machine have as much as it needs */

	while (n < len) {
		/*
		 * we were accepting input but now we stopped doing so
		 */
		if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
			lws_rxflow_cache(wsi, buf, n, len);

			return 1;
		}

		/* account for what we're using in rxflow buffer */
		if (wsi->rxflow_buffer)
			wsi->rxflow_pos++;

		/* process the byte */
		m = lws_rx_sm(wsi, buf[n++]);
		if (m < 0)
			return -1;
	}

	return 0;
}

LWS_VISIBLE void
lws_server_get_canonical_hostname(struct lws_context *context,
				  struct lws_context_creation_info *info)
{
	if (info->options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)
		return;
#if LWS_POSIX
	/* find canonical hostname */
	gethostname((char *)context->canonical_hostname,
				       sizeof(context->canonical_hostname) - 1);

	lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
#else
	(void)context;
#endif
}


text:
package exchangerates

import (
	"errors"
	"time"

	"github.com/thrasher-corp/gocryptotrader/currency/forexprovider/base"
	"github.com/thrasher-corp/gocryptotrader/exchanges/request"
)

const (
	exchangeRatesAPI         = "api.exchangeratesapi.io"
	exchangeRatesLatest      = "latest"
	exchangeRatesTimeSeries  = "timeseries"
	exchangeRatesConvert     = "convert"
	exchangeRatesFluctuation = "fluctuation"

	rateLimitInterval = time.Second * 10
	requestRate       = 10
	timeLayout        = "2006-01-02"

	apiKeyFree = iota
	apiKeyBasic
	apiKeyProfessional
	apiKeyBusiness
)

var (
	errCannotSetBaseCurrencyOnFreePlan = errors.New("base currency cannot be set on the free plan")
	errAPIKeyLevelRestrictedAccess     = errors.New("apiKey level function access denied")
	errStartEndDatesInvalid            = errors.New("startDate and endDate params must be set")
	errStartAfterEnd                   = errors.New("startDate must be before endDate")
)

// ExchangeRates stores the struct for the ExchangeRatesAPI API
type ExchangeRates struct {
	base.Base
	supportedCurrencies []string
	Requester           *request.Requester
}

// Rates holds the latest forex rates info
type Rates struct {
	Base      string             `json:"base"`
	Timestamp int64              `json:"timestamp"`
	Date      string             `json:"date"`
	Rates     map[string]float64 `json:"rates"`
}

// HistoricalRates stores the historical rate info
type HistoricalRates struct {
	Historical bool `json:"historical"`
	Rates
}

// ConvertCurrency stores the converted currency info
type ConvertCurrency struct {
	Query struct {
		From   string  `json:"from"`
		To     string  `json:"to"`
		Amount float64 `json:"amount"`
	} `json:"query"`
	Info struct {
		Timestamp int64   `json:"timestamp"`
		Rate      float64 `json:"rate"`
	} `json:"info"`
	Historical bool    `json:"historical"`
	Result     float64 `json:"result"`
}

// TimeSeriesRates stores time series rate info
type TimeSeriesRates struct {
	Timeseries bool                          `json:"timeseries"`
	StartDate  string                        `json:"start_date"`
	EndDate    string                        `json:"end_date"`
	Base       string                        `json:"base"`
	Rates      map[string]map[string]float64 `json:"rates"`
}

// FlucutationItem stores an individual rate fluctuation
type FlucutationItem struct {
	StartRate        float64 `json:"start_rate"`
	EndRate          float64 `json:"end_rate"`
	Change           float64 `json:"change"`
	ChangePercentage float64 `json:"change_pct"`
}

// Fluctuations stores a collection of rate fluctuations
type Fluctuations struct {
	Fluctuation bool                       `json:"fluctuation"`
	StartDate   string                     `json:"start_date"`
	EndDate     string                     `json:"end_date"`
	Base        string                     `json:"base"`
	Rates       map[string]FlucutationItem `json:"rates"`
}


text:
from setuptools import setup, find_packages

setup(
        name='pylife',
        version='0.1.0',
        description='Conway\'s Game of Life with kivy',
        author='yukirin',
        author_email='standupdown@gmail.com',
        url='https://github.com/yukirin/LifeGame-kivy',
        license='MIT',
        keywords=['python', 'game', 'life game', 'kivy'],
        zip_safe=False,
        platforms=['Linux'],
        packages=find_packages(),
        package_data={'pylife': ['lifegame*.*']},
        classifiers=[
          'Programming Language :: Python',
          'Programming Language :: Python :: 3.4',
          'Development Status :: 4 - Beta',
          'Operating System :: POSIX :: Linux',
          'Natural Language :: Japanese',
          'License :: OSI Approved :: MIT License',
          'Topic :: Games/Entertainment'
            ],
        install_requires = ['kivy'],
        entry_points={
            'gui_scripts': ['pylife = pylife.main:run']
            },
        )


text:
module Bundleup
  VERSION = "2.2.4".freeze
end


text:
class GenericComment < ApplicationRecord
  include ModelBase

  hobo_model # Don't put anything above this

  fields do
    body  HoboFields::Types::TextilePlusString
    timestamps
  end
  attr_accessible :body, :creator_id

  default_scope { order('created_at DESC') }

  after_initialize :add_defaults
  after_save :notify
  after_create do |c|
    ::FayeCommentControllerHelper.new.run(c)
  end

  belongs_to :company, :null => false, :inverse_of => :company_comments
  belongs_to :creator, :class_name => "User", :creator => true

  def add_defaults
    self.company_id ||= Company.current_id if self.new_record?
    self.creator_id ||= User.current_id if self.new_record?
  end

  def notify
    mentions = Differ.diff(body || '', body_was || '').new_mentions
    mentions.each do |user, message|
      UserCompanyMailer.mention(User.current_user, user, self.owner, message).deliver_later
    end
  end

  def model
    self.type.to_s[/\A(\w+)Comment\Z/,1].constantize
  end

  def owner
    self.send model.name.underscore
  end

  def model_id
    self.send model.name.underscore + '_id'
  end

  # --- Permissions --- #

  def create_permitted?
    acting_user.administrator? || same_company
  end

  def update_permitted?
    acting_user.administrator?
  end

  def destroy_permitted?
    acting_user.administrator?
  end

  def view_permitted?(field)
    acting_user.administrator? || same_company
  end

end


text:
using Ogooreck.API;
using static Ogooreck.API.ApiSpecification;
using Warehouse.Products.RegisteringProduct;
using Xunit;

namespace Warehouse.Api.Tests.Products.RegisteringProduct;

public class RegisterProductTests: IClassFixture<WarehouseTestWebApplicationFactory>
{
    private readonly ApiSpecification<Program> API;

    public RegisterProductTests(WarehouseTestWebApplicationFactory webApplicationFactory) =>
        API = ApiSpecification<Program>.Setup(webApplicationFactory);

    [Theory]
    [MemberData(nameof(ValidRequests))]
    public Task ValidRequest_ShouldReturn_201(RegisterProductRequest validRequest) =>
        API.Given(
                URI("/api/products/"),
                BODY(validRequest)
            )
            .When(POST)
            .Then(CREATED);

    [Theory]
    [MemberData(nameof(InvalidRequests))]
    public Task InvalidRequest_ShouldReturn_400(RegisterProductRequest invalidRequest) =>
        API.Given(
                URI("/api/products"),
                BODY(invalidRequest)
            )
            .When(POST)
            .Then(BAD_REQUEST);

    [Fact]
    public async Task RequestForExistingSKUShouldFail_ShouldReturn_409()
    {
        // Given
        var request = new RegisterProductRequest("AA2039485", ValidName, ValidDescription);

        // first one should succeed
        await API.Given(
                URI("/api/products/"),
                BODY(request)
            )
            .When(POST)
            .Then(CREATED);

        // second one will fail with conflict
        await API.Given(
                URI("/api/products/"),
                BODY(request)
            )
            .When(POST)
            .Then(CONFLICT);
    }

    private const string ValidName = "VALID_NAME";
    private static string ValidSKU => $"CC{DateTime.Now.Ticks}";
    private const string ValidDescription = "VALID_DESCRIPTION";

    public static TheoryData<RegisterProductRequest> ValidRequests = new()
    {
        new RegisterProductRequest(ValidSKU, ValidName, ValidDescription),
        new RegisterProductRequest(ValidSKU, ValidName, null)
    };

    public static TheoryData<RegisterProductRequest> InvalidRequests = new()
    {
        new RegisterProductRequest(null, ValidName, ValidDescription),
        new RegisterProductRequest("INVALID_SKU", ValidName, ValidDescription),
        new RegisterProductRequest(ValidSKU, null, ValidDescription),
    };
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>colourl HTTP API</title>
    <link rel="stylesheet" href="static/colourl.css"/>

Colourl

            <form method="get">

                    URL
                    <input type="text" name="url" value="{{.URL}}"/>

                    Width
                    <input type="number" name="w" value="{{.Job.Width}}"/>

                    Height
                    <input type="number" name="h" value="{{.Job.Height}}"/>

                    Max colors
                    <input type="number" name="max" value="{{.Job.Max}}"/>

                    Style
                    <select name="style">
                        {{range $key, $value := .Painters}}
                        <option{{if eq $key $.Style }} selected{{end}}>{{$key}}</option>
                        {{end}}
                    </select>

                    <input type="submit" value="Draw SVG" class="button-primary">

                    SVG URL
                    <input type="text" value="{{.SVGURL}}">

            </form>


text:
package aether.emblem;

import java.awt.*;

public class AxeChar extends Character {
	private Image CharacterImage = Generator.axeImg;

	public AxeChar(String title, int hp, int attack, int def, int skill, Weapon wep, int xLocation,
			int yLocation, int team) {
		super(title, hp, attack, def, skill, wep, xLocation, yLocation, team);
		/*
		 * int gender = (int)(Math.random()*2); if(gender==0) {CharacterFace = Generator.FaceFighterMale;} else
		 * {CharacterFace = Generator.FaceFighterFemale;}
		 */
	}

	@Override
	public Image getImage() {
		if(!this.alive) {
			return Generator.remove;
		}

		if(this.getTeam() == 1) {
			if(this.getMoved() == false) {
				CharacterImage = Generator.axeImg;
			} else {
				CharacterImage = Generator.grayaxeImg;
			}
		}
		if(this.getTeam() == 2) {
			characterFace = Generator.FaceFighterFemale;
			if(this.getMoved() == false)
				CharacterImage = Generator.redaxeImg;
			else {
				CharacterImage = Generator.grayredaxeImg;
			}
		}
		return CharacterImage;
	}

	@Override
	public int getMovement() {
		return 2;
	}

	@Override
	public int getRange() {
		return 1;
	}
}


text:
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    public class TimingCommandHandler<TCommand, TResult> : ICommandHandler<TCommand, TResult>
        where TCommand : ICommand<TResult>
    {
        public TimingCommandHandler(ICommandHandler<TCommand, TResult> innerHandler, ILogger logger)
        {
            InnerHandler = innerHandler;
            Logger = logger;
        }

        private ICommandHandler<TCommand, TResult> InnerHandler { get; }

        private ILogger Logger { get; }

        public async Task<TResult> Handle(TCommand command, CancellationToken cancellationToken)
        {
            Logger.Info($"Executing command '{typeof(TCommand).Name}'.");

            var stopwatch = Stopwatch.StartNew();

            var result = await InnerHandler.Handle(command, cancellationToken);

            var elapsed = stopwatch.Elapsed;

            Logger.Info($"Finished executing command '{typeof(TCommand).Name}' in {elapsed.TotalMilliseconds}ms.");

            return result;
        }
    }
}


text:
<?php

namespace Hubzero\Config\Processor;

use Hubzero\Config\Exception\UnsupportedFormatException;
use Hubzero\Config\Exception\ParseException;
use Hubzero\Config\Processor as Base;

/**
 * PHP class processor
 */
class Php extends Base
{
	/**
	 * Returns an array of allowed file extensions for this parser
	 *
	 * @return  array
	 */
	public function getSupportedExtensions()
	{
		return array('php');
	}

	/**
	 * Loads a PHP file and gets its' contents as an array
	 *
	 * @param   string  $path
	 * @return  array
	 * @throws  ParseException              If the PHP file throws an exception
	 * @throws  UnsupportedFormatException  If the PHP file does not return an array
	 */
	public function parse($path)
	{
		// Require the file, if it throws an exception, rethrow it
		try
		{
			$temp = require $path;
		}
		catch (\Exception $exception)
		{
			throw new ParseException(
				array(
					'message'   => 'PHP file threw an exception',
					'exception' => $exception,
				)
			);
		}

		// If we have a callable, run it and expect an array back
		if (is_callable($temp))
		{
			$temp = call_user_func($temp);
		}

		// Check for array, if its anything else, throw an exception
		if (!$temp || !is_array($temp))
		{
			throw new UnsupportedFormatException('PHP file does not return an array');
		}

		return $temp;
	}

	/**
	 * Converts an object into a php class or array string.
	 *
	 * @param   object  $object   Data Source Object
	 * @param   array   $options  Parameters used by the formatter
	 * @return  string  Config class formatted string
	 */
	public function objectToString($object, $options = array())
	{
		if (is_string($object))
		{
			return $object;
		}

		$format = 'object';
		if (isset($options['format']) && $options['format'])
		{
			$format = $options['format'];
		}

		// Build the object variables string
		$vars = '';
		foreach (get_object_vars($object) as $k => $v)
		{
			if (is_scalar($v))
			{
				switch ($format)
				{
					case 'object':
						$vars .= "\tvar $" . $k . " = '" . addcslashes($v, '\\\'') . "';\n";
					break;
					case 'array':
						$vars .= "\t'" . $k . "' => '" . addcslashes($v, '\\\'') . "',\n";
					break;
				}
			}
			elseif (is_array($v) || is_object($v))
			{
				switch ($format)
				{
					case 'object':
						$vars .= "\tvar $" . $k . " = " . $this->getArrayString((array) $v) . ";\n";
					break;
					case 'array':
						$vars .= "\t'" . $k . "' => " . $this->getArrayString((array) $v) . ",\n";
					break;
				}
			}
			elseif (is_null($v))
			{
				switch ($format)
				{
					case 'object':
						$vars .= "\tvar $" . $k . " = '';\n";
					break;
					case 'array':
						$vars .= "\t'" . $k . "' => '',\n";
					break;
				}
			}
		}

		$str  = "<?php\n";
		switch ($format)
		{
			case 'object':
				if (!isset($options['class']) || !$options['class'])
				{
					$options['class'] = 'Config';
				}
				$str .= "class " . $options['class'] . "\n";
				$str .= "{\n";
				$str .= $vars;
				$str .= "}";
			break;
			case 'array':
				$str .= "return array(\n";
				$str .= $vars;
				$str .= ");";
			break;
		}

		// Use the closing tag if it not set to false in parameters.
		if (isset($options['closingtag']) && $options['closingtag'])
		{
			$str .= "\n?>";
		}

		return $str;
	}

	/**
	 * Parse a PHP class formatted string and convert it into an object.
	 *
	 * @param   string  $data     PHP Class formatted string to convert.
	 * @param   array   $options  Options used by the formatter.
	 * @return  object  Data object.
	 */
	public function stringToObject($data, $options = array())
	{
		return true;
	}

	/**
	 * Method to get an array as an exported string.
	 *
	 * @param   array  $a  The array to get as a string.
	 * @return  array
	 */
	protected function getArrayString($a)
	{
		$s = 'array(';
		$i = 0;
		foreach ($a as $k => $v)
		{
			$s .= ($i) ? ', ' : '';
			$s .= '"' . $k . '" => ';
			if (is_array($v) || is_object($v))
			{
				$s .= $this->getArrayString((array) $v);
			}
			else
			{
				$s .= '"' . addslashes($v) . '"';
			}
			$i++;
		}
		$s .= ')';
		return $s;
	}
}


text:
<?php

namespace Vich\UploaderBundle\Adapter\ORM;

use Vich\UploaderBundle\Adapter\AdapterInterface;

/**
 * DoctrineORMAdapter.
 *
 * @author Dustin Dobervich <ddobervich@gmail.com>
 */
class DoctrineORMAdapter implements AdapterInterface
{
    /**
     * {@inheritDoc}
     */
    public function getObjectFromArgs($event)
    {
        return $event->getEntity();
    }

    /**
     * {@inheritDoc}
     */
    public function recomputeChangeSet($event)
    {
        $object = $this->getObjectFromArgs($event);

        $em = $event->getEntityManager();
        $uow = $em->getUnitOfWork();
        $metadata = $em->getClassMetadata(get_class($object));
        $uow->recomputeSingleEntityChangeSet($metadata, $object);
    }
}


text:
require 'rails_helper'

RSpec.describe LocaleProjectsShowPresenter do
  before :each do
    allow_any_instance_of(Article).to receive(:import!) # prevent auto imports
    @user = FactoryBot.create(:user)
  end

  describe "#selectable_commits" do
    it "returns selectable Commits" do
      project = FactoryBot.create(:project)

      commit1 = FactoryBot.create(:commit, revision: 'abcd', message: "hello", project: project)
      commit2 = FactoryBot.create(:commit, revision: '1234', message: "world", project: project)

      presenter = LocaleProjectsShowPresenter.new(project, @user, {})
      expect(presenter.selectable_commits).to eql( [["ALL COMMITS", nil], ["1234: world", "1234"], ["abcd: hello", "abcd"]] )
    end
  end

  describe "#selected_commit" do
    it "returns the selected Commit if there is one" do
      commit = FactoryBot.create(:commit, revision: 'abcd')
      presenter = LocaleProjectsShowPresenter.new(commit.project, @user, {commit: 'abcd'})
      expect(presenter.selected_commit).to eql(commit)
    end
  end

  describe "#selected_article" do
    it "returns the selected Article if there is one" do
      article = FactoryBot.create(:article, name: 'abcd')
      presenter = LocaleProjectsShowPresenter.new(article.project, @user, { article_id: article.id })
      expect(presenter.selected_article).to eql(article)
    end
  end

  describe "#selected_group" do
    it "returns the selected Group if there is one" do
      group = FactoryBot.create(:group, name: "hello", display_name: 'test display name')
      presenter = LocaleProjectsShowPresenter.new(group.project, @user, { group: group.display_name })
      expect(presenter.selected_group).to eql(group)
    end
  end

  describe "#selectable_sections" do
    before :each do
      @project = FactoryBot.create(:project)
      @article1 = FactoryBot.create(:article, name: 'article1', project: @project)
      @section1 = FactoryBot.create(:section, name: 'section1', article: @article1)
      @article2 = FactoryBot.create(:article, name: 'article2', project: @project)
      @section2 = FactoryBot.create(:section, name: 'section2', article: @article2)
    end

    it "returns selectable Sections under the Article if an Article is selected" do
      presenter = LocaleProjectsShowPresenter.new(@project, @user, { article_id: @article1.id })
      expect(presenter.selectable_sections).to eql( [["ALL SECTIONS", nil], ["section1", @section1.id]] )
    end

    it "returns selectable Sections under the Project if an Article is NOT selected" do
      presenter = LocaleProjectsShowPresenter.new(@project, @user, { })
      expect(presenter.selectable_sections).to match_array( [["ALL SECTIONS", nil], ["section1", @section1.id], ["section2", @section2.id]])
    end

    it "doesn't include inactive Sections in the result" do
      @section1.update_columns active: false
      presenter = LocaleProjectsShowPresenter.new(@project, @user, { })
      expect(presenter.selectable_sections).to eql( [["ALL SECTIONS", nil], ["section2", @section2.id]] )
    end
  end

  describe "#selected_section" do
    before :each do
      @project = FactoryBot.create(:project)
      @article1 = FactoryBot.create(:article, name: 'article1', project: @project)
      @section1 = FactoryBot.create(:section, name: 'section1', article: @article1)
      @article2 = FactoryBot.create(:article, name: 'article2', project: @project)
      @section2 = FactoryBot.create(:section, name: 'section2', article: @article2, active: false)
    end

    it "returns selected Section" do
      presenter = LocaleProjectsShowPresenter.new(@project, @user, { section_id: @section1.id })
      expect(presenter.selected_section).to eql( @section1 )
    end

    it "doesn't return inactive Section even if user attempted to select it" do
      presenter = LocaleProjectsShowPresenter.new(@project, @user, { section_id: @section2.id })
      expect(presenter.selected_section).to be_nil
    end
  end
end


text:
#include "app.h"
#include "mainframe.h"
#include "panels.h"
#include <wx/splash.h>
#include <wx/cmdline.h>
#include <wx/stdpaths.h>
#include <wx/artprov.h>

IMPLEMENT_APP(MyApp)

void MyApp::OnInitCmdLine(wxCmdLineParser& parser)
{
    wxApp::OnInitCmdLine(parser);
	parser.AddParam("File to open", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL);
//    parser.AddSwitch("v", "verbose",
//                     "run in MDI mode: multiple documents, single window");
//    parser.AddSwitch("", "sdi",
//                     "run in SDI mode: multiple documents, multiple windows");
//    parser.AddSwitch("", "single",
 //                    "run in single document mode");
}

bool MyApp::OnCmdLineParsed(wxCmdLineParser& parser)
{
	if ( !wxApp::OnCmdLineParsed(parser))
		return false;

	if ( parser.GetParamCount() )
		m_file2open = parser.GetParam(0);
  //  int numModeOptions = 0;
   // if ( parser.Found("verbose") )
   // {
        //m_mode = Mode_SDI;
        //numModeOptions++;
    //}
	return true;
}

wxLocale* locale;
long language;

void initLanguageSupport()
{
    language =  wxLANGUAGE_DEFAULT;

    // fake functions, use proper implementation
    //if( userWantsAnotherLanguageThanDefault() )
    //    language = getUsersFavoriteLanguage();
 	language = wxLANGUAGE_CZECH;

    // load language if possible, fall back to english otherwise
    if(wxLocale::IsAvailable(language))
    {
        locale = new wxLocale( language );

        #ifdef __WXGTK__
        // add locale search paths
        locale->AddCatalogLookupPathPrefix(wxT("/usr"));
        locale->AddCatalogLookupPathPrefix(wxT("/usr/local"));
        locale->AddCatalogLookupPathPrefix(wxT("/home/gejza/usr"));
        wxStandardPaths* paths = (wxStandardPaths*) &wxStandardPaths::Get();
        wxString prefix = paths->GetInstallPrefix();
		std::cerr << "prefix is " << prefix << std::endl;
        locale->AddCatalogLookupPathPrefix( prefix );
        #endif

        locale->AddCatalog(wxT("SceneEditor"));

        if(! locale->IsOk() )
        {
            std::cerr << "selected language is wrong" << std::endl;
            delete locale;
            locale = new wxLocale( wxLANGUAGE_ENGLISH );
            language = wxLANGUAGE_ENGLISH;
        }
    }
    else
    {
        std::cout << "The selected language is not supported by your system."
                  << "Try installing support for this language." << std::endl;
        locale = new wxLocale( wxLANGUAGE_ENGLISH );
        language = wxLANGUAGE_ENGLISH;
    }

}

bool MyApp::OnInit()
{
	if ( !wxApp::OnInit() )
        return false;

	// make sure to call this first
	::wxInitAllImageHandlers();

    // Fill in the application information fields before creating wxConfig.
    SetVendorName(wxT("CanBee"));
    SetAppName(wxT("oxygine2d-editor"));
    SetAppDisplayName(wxT("Oxygine Scene editor"));

	wxConfigBase *pConfig = wxConfigBase::Get();
	pConfig->SetRecordDefaults();

	initLanguageSupport();
	wxLog::AddTraceMask(wxTRACE_ResAlloc);

	//cfg_show_splash = true;

	if (cfg_show_splash.GetBool(true)) {
		//Splash screen
		wxBitmap bitmap;
		if (bitmap.LoadFile("res/splash.png", wxBITMAP_TYPE_PNG))
		{
			wxSplashScreen* splash = new wxSplashScreen(bitmap,
				wxSPLASH_CENTRE_ON_SCREEN|wxSPLASH_TIMEOUT,
				4000, NULL, wxID_ANY, wxDefaultPosition, wxDefaultSize,
				wxBORDER_SIMPLE|wxSTAY_ON_TOP);
		}
		wxYield();
	}

	wxLogVerbose("Verbose logging enabled!");
	MainFrame* frame = new MainFrame(NULL,
                                 wxID_ANY,
                                 GetAppDisplayName(),
                                 wxDefaultPosition,
                                 wxSize(800, 600));

	/*
    SplashScreen * splash = new SplashScreen(bitmap, 8, 0, -1, wxNO_BORDER | wxFRAME_SHAPED);
	std::cout << "* Splash Screen created" << std::endl;
	*/

	//sleep(3);
    frame->Show(true);

	if (m_file2open != "") {
		frame->OpenFile(m_file2open);
	}
    return true;
}

int MyApp::OnExit()
{
    // clean up: Set() returns the active config object as Get() does, but unlike
    // Get() it doesn't try to create one if there is none (definitely not what
    // we want here!)
    delete wxConfigBase::Set((wxConfigBase *) NULL);

    return 0;
}

void MyApp::ShowPreferencesEditor(wxWindow* parent)
{
#ifdef USE_PREFS
    if ( !m_prefEditor )
    {
        m_prefEditor.reset(new wxPreferencesEditor);
        m_prefEditor->AddPage(new PrefsPageGeneral());
        m_prefEditor->AddPage(new PrefsPageTopics());
    }

    m_prefEditor->Show(parent);
#endif
}

void MyApp::DismissPreferencesEditor()
{
#ifdef USE_PREFS
	if ( m_prefEditor )
		m_prefEditor->Dismiss();
#endif
}


text:
//
//  Created by Brian Romanko on 8/5/11.
//  Copyright 2011 BigBig Bomb, LLC. All rights reserved.
//
#import <UIKit/UIKit.h>

@protocol BBViewControllerDelegate;

/**
 * Category helper methods for UIViewController. Most of these methods support fluent programming or method chaining.
 */
@interface UIViewController(BBCommon)

/**
 * Sets the background of the current view controller to a screenshot image of the passed in view controller.
 * @param viewController The view controller from which the screenshot will be taken.
 */
- (UIViewController *)insertScreenshotOfControllerAsBackground:(UIViewController *)viewController;

/**
 * Displays a model view that supports transparent backgrounds
 */
- (void)bbPresentViewController:(UIViewController *)viewControllerToPresent;

/**
 * Dismisses the modal view
 */
- (void)bbDismissViewController;

@property (nonatomic, assign) id<BBViewControllerDelegate> bbViewControllerDelegate;

@end

@protocol BBViewControllerDelegate <NSObject>

@optional
- (void)viewControllerWillBePresented:(UIViewController *)viewController;
- (void)viewControllerDidGetPresented:(UIViewController *)viewController;
- (void)viewControllerWillBeDismissed:(UIViewController *)viewController;
- (void)viewControllerDidGetDismissed:(UIViewController *)viewController;

@end