text:
using net::MockRead;

namespace data_reduction_proxy {

namespace {

class CountingURLRequestInterceptor : public net::URLRequestInterceptor {
 public:
  CountingURLRequestInterceptor()
      : request_count_(0), redirect_count_(0), response_count_(0) {
  }

  // URLRequestInterceptor implementation:
  net::URLRequestJob* MaybeInterceptRequest(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate) const override {
    request_count_++;
    return nullptr;
  }

  net::URLRequestJob* MaybeInterceptRedirect(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate,
      const GURL& location) const override {
    redirect_count_++;
    return nullptr;
  }

  net::URLRequestJob* MaybeInterceptResponse(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate) const override {
    response_count_++;
    return nullptr;
  }

  int request_count() const {
    return request_count_;
  }

  int redirect_count() const {
    return redirect_count_;
  }

  int response_count() const {
    return response_count_;
  }

 private:
  mutable int request_count_;
  mutable int redirect_count_;
  mutable int response_count_;
};

class TestURLRequestContextWithDataReductionProxy
    : public net::TestURLRequestContext {
 public:
  TestURLRequestContextWithDataReductionProxy(const net::ProxyServer& origin,
                                              net::NetworkDelegate* delegate)
      : net::TestURLRequestContext(true) {
    context_storage_.set_proxy_service(
        net::ProxyService::CreateFixed(origin.ToURI()));
    set_network_delegate(delegate);
  }

  ~TestURLRequestContextWithDataReductionProxy() override {}
};

class DataReductionProxyInterceptorTest : public testing::Test {
 public:
  DataReductionProxyInterceptorTest() {
    test_context_ =
        DataReductionProxyTestContext::Builder()
            .WithParamsFlags(DataReductionProxyParams::kAllowed)
            .WithParamsDefinitions(TestDataReductionProxyParams::HAS_EVERYTHING)
            .Build();
    default_context_.reset(new TestURLRequestContextWithDataReductionProxy(
        test_context_->config()->test_params()->proxies_for_http().front(),
        &default_network_delegate_));
    default_context_->set_network_delegate(&default_network_delegate_);
    default_context_->set_net_log(test_context_->net_log());
  }

  ~DataReductionProxyInterceptorTest() override {
    // URLRequestJobs may post clean-up tasks on destruction.
    base::RunLoop().RunUntilIdle();
  }

  void Init(std::unique_ptr<net::URLRequestJobFactory> factory) {
    job_factory_ = std::move(factory);
    default_context_->set_job_factory(job_factory_.get());
    default_context_->Init();
  }

  base::MessageLoopForIO message_loop_;
  std::unique_ptr<DataReductionProxyTestContext> test_context_;
  net::TestNetworkDelegate default_network_delegate_;
  std::unique_ptr<net::URLRequestJobFactory> job_factory_;
  std::unique_ptr<net::TestURLRequestContext> default_context_;
};

// Disabled on Mac due to flakiness. See crbug.com/601562.
#if defined(OS_MACOSX)
#define MAYBE_TestJobFactoryChaining DISABLED_TestJobFactoryChaining
#else
#define MAYBE_TestJobFactoryChaining TestJobFactoryChaining
#endif
TEST_F(DataReductionProxyInterceptorTest, MAYBE_TestJobFactoryChaining) {
  // Verifies that job factories can be chained.
  std::unique_ptr<net::URLRequestJobFactory> impl(
      new net::URLRequestJobFactoryImpl());

  CountingURLRequestInterceptor* interceptor2 =
      new CountingURLRequestInterceptor();
  std::unique_ptr<net::URLRequestJobFactory> factory2(
      new net::URLRequestInterceptingJobFactory(
          std::move(impl), base::WrapUnique(interceptor2)));

  CountingURLRequestInterceptor* interceptor1 =
      new CountingURLRequestInterceptor();
  std::unique_ptr<net::URLRequestJobFactory> factory1(
      new net::URLRequestInterceptingJobFactory(
          std::move(factory2), base::WrapUnique(interceptor1)));

  Init(std::move(factory1));

  net::TestDelegate d;
  std::unique_ptr<net::URLRequest> req(default_context_->CreateRequest(
      GURL("http://foo"), net::DEFAULT_PRIORITY, &d));

  req->Start();
  base::RunLoop().Run();
  EXPECT_EQ(1, interceptor1->request_count());
  EXPECT_EQ(0, interceptor1->redirect_count());
  EXPECT_EQ(1, interceptor1->response_count());
  EXPECT_EQ(1, interceptor2->request_count());
  EXPECT_EQ(0, interceptor2->redirect_count());
  EXPECT_EQ(1, interceptor2->response_count());
}

class DataReductionProxyInterceptorWithServerTest : public testing::Test {
 public:
  DataReductionProxyInterceptorWithServerTest()
      : context_(true) {
    context_.set_network_delegate(&network_delegate_);
    context_.set_net_log(&net_log_);
  }

  ~DataReductionProxyInterceptorWithServerTest() override {
    test_context_->io_data()->ShutdownOnUIThread();
    // URLRequestJobs may post clean-up tasks on destruction.
    test_context_->RunUntilIdle();
  }

  void SetUp() override {
    base::FilePath root_path, proxy_file_path, direct_file_path;
    PathService::Get(base::DIR_SOURCE_ROOT, &root_path);
    proxy_file_path = root_path.AppendASCII(
        "components/test/data/data_reduction_proxy/proxy");
    direct_file_path = root_path.AppendASCII(
        "components/test/data/data_reduction_proxy/direct");
    proxy_.ServeFilesFromDirectory(proxy_file_path);
    direct_.ServeFilesFromDirectory(direct_file_path);
    ASSERT_TRUE(proxy_.Start());
    ASSERT_TRUE(direct_.Start());

    test_context_ =
        DataReductionProxyTestContext::Builder()
            .WithParamsFlags(DataReductionProxyParams::kAllowed)
            .WithURLRequestContext(&context_)
            .Build();
    std::string spec;
    base::TrimString(proxy_.GetURL("/").spec(), "/", &spec);
    net::ProxyServer origin =
        net::ProxyServer::FromURI(spec, net::ProxyServer::SCHEME_HTTP);
    std::vector<net::ProxyServer> proxies_for_http;
    proxies_for_http.push_back(origin);
    test_context_->config()->test_params()->SetProxiesForHttp(proxies_for_http);
    std::string proxy_name = origin.ToURI();
    proxy_service_ = net::ProxyService::CreateFixedFromPacResult(
        "PROXY " + proxy_name + "; DIRECT");

    context_.set_proxy_service(proxy_service_.get());

    std::unique_ptr<net::URLRequestJobFactoryImpl> job_factory_impl(
        new net::URLRequestJobFactoryImpl());
    job_factory_.reset(new net::URLRequestInterceptingJobFactory(
        std::move(job_factory_impl),
        test_context_->io_data()->CreateInterceptor()));
    context_.set_job_factory(job_factory_.get());
    context_.Init();
  }

  const net::TestURLRequestContext& context() {
    return context_;
  }

  const net::EmbeddedTestServer& direct() { return direct_; }

 private:
  base::MessageLoopForIO message_loop_;
  net::TestNetLog net_log_;
  net::TestNetworkDelegate network_delegate_;
  net::TestURLRequestContext context_;
  net::EmbeddedTestServer proxy_;
  net::EmbeddedTestServer direct_;
  std::unique_ptr<net::ProxyService> proxy_service_;
  std::unique_ptr<net::URLRequestJobFactory> job_factory_;
  std::unique_ptr<DataReductionProxyTestContext> test_context_;
};

TEST_F(DataReductionProxyInterceptorWithServerTest, TestBypass) {
  // Tests the mechanics of proxy bypass work with a "real" server. For tests
  // that cover every imaginable response that could trigger a bypass, see:
  // DataReductionProxyProtocolTest.
  net::TestDelegate delegate;
  std::unique_ptr<net::URLRequest> request(context().CreateRequest(
      direct().GetURL("/block10.html"), net::DEFAULT_PRIORITY, &delegate));
  request->Start();
  EXPECT_TRUE(request->is_pending());
  base::RunLoop().Run();

  EXPECT_EQ(net::OK, delegate.request_status());
  EXPECT_EQ("hello", delegate.data_received());
}

TEST_F(DataReductionProxyInterceptorWithServerTest, TestNoBypass) {
  net::TestDelegate delegate;
  std::unique_ptr<net::URLRequest> request(context().CreateRequest(
      direct().GetURL("/noblock.html"), net::DEFAULT_PRIORITY, &delegate));
  request->Start();
  EXPECT_TRUE(request->is_pending());
  base::RunLoop().Run();

  EXPECT_EQ(net::OK, delegate.request_status());
  EXPECT_EQ("hello", delegate.data_received());
}

class DataReductionProxyInterceptorEndToEndTest : public testing::Test {
 public:
  DataReductionProxyInterceptorEndToEndTest()
      : context_(true), context_storage_(&context_) {}

  ~DataReductionProxyInterceptorEndToEndTest() override {}

  void SetUp() override {
    drp_test_context_ =
        DataReductionProxyTestContext::Builder()
            .WithURLRequestContext(&context_)
            .WithMockClientSocketFactory(&mock_socket_factory_)
            .Build();
    drp_test_context_->AttachToURLRequestContext(&context_storage_);
    context_.set_client_socket_factory(&mock_socket_factory_);
    proxy_delegate_ = drp_test_context_->io_data()->CreateProxyDelegate();
    context_.set_proxy_delegate(proxy_delegate_.get());
    context_.Init();
    drp_test_context_->EnableDataReductionProxyWithSecureProxyCheckSuccess();

    // Three proxies should be available for use: primary, fallback, and direct.
    const net::ProxyConfig& proxy_config =
        drp_test_context_->configurator()->GetProxyConfig();
    EXPECT_EQ(3U, proxy_config.proxy_rules().proxies_for_http.size());
  }

  // Creates a URLRequest using the test's TestURLRequestContext and executes
  // it. Returns the created URLRequest.
  std::unique_ptr<net::URLRequest> CreateAndExecuteRequest(const GURL& url) {
    std::unique_ptr<net::URLRequest> request(
        context_.CreateRequest(url, net::IDLE, &delegate_));
    request->Start();
    drp_test_context_->RunUntilIdle();
    return request;
  }

  const net::TestDelegate& delegate() const { return delegate_; }

  net::MockClientSocketFactory* mock_socket_factory() {
    return &mock_socket_factory_;
  }

  TestDataReductionProxyConfig* config() const {
    return drp_test_context_->config();
  }

  net::ProxyServer origin() const {
    return config()->test_params()->proxies_for_http().front();
  }

 private:
  base::MessageLoopForIO message_loop_;
  net::TestDelegate delegate_;
  net::MockClientSocketFactory mock_socket_factory_;
  net::TestURLRequestContext context_;
  net::URLRequestContextStorage context_storage_;
  std::unique_ptr<net::ProxyDelegate> proxy_delegate_;
  std::unique_ptr<DataReductionProxyTestContext> drp_test_context_;
};

const std::string kBody = "response body";

TEST_F(DataReductionProxyInterceptorEndToEndTest, ResponseWithoutRetry) {
  // The response comes through the proxy and should not be retried.
  MockRead mock_reads[] = {
      MockRead("HTTP/1.1 200 OK\r\nVia: 1.1 Chrome-Compression-Proxy\r\n\r\n"),
      MockRead(kBody.c_str()),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider socket_data_provider(
      mock_reads, arraysize(mock_reads), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(&socket_data_provider);

  std::unique_ptr<net::URLRequest> request =
      CreateAndExecuteRequest(GURL("http://foo.com"));

  EXPECT_EQ(net::OK, delegate().request_status());
  EXPECT_EQ(200, request->GetResponseCode());
  EXPECT_EQ(kBody, delegate().data_received());
  EXPECT_EQ(origin(), request->proxy_server());
}

TEST_F(DataReductionProxyInterceptorEndToEndTest, RedirectWithoutRetry) {
  // The redirect comes through the proxy and should not be retried.
  MockRead redirect_mock_reads[] = {
      MockRead("HTTP/1.1 302 Found\r\n"
               "Via: 1.1 Chrome-Compression-Proxy\r\n"
               "Location: http://bar.com/\r\n\r\n"),
      MockRead(""),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider redirect_socket_data_provider(
      redirect_mock_reads, arraysize(redirect_mock_reads), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(&redirect_socket_data_provider);

  // The response after the redirect comes through proxy and should not be
  // retried.
  MockRead response_mock_reads[] = {
      MockRead("HTTP/1.1 200 OK\r\nVia: 1.1 Chrome-Compression-Proxy\r\n\r\n"),
      MockRead(kBody.c_str()),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider response_socket_data_provider(
      response_mock_reads, arraysize(response_mock_reads), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(&response_socket_data_provider);

  std::unique_ptr<net::URLRequest> request =
      CreateAndExecuteRequest(GURL("http://foo.com"));

  EXPECT_EQ(net::OK, delegate().request_status());
  EXPECT_EQ(200, request->GetResponseCode());
  EXPECT_EQ(kBody, delegate().data_received());
  EXPECT_EQ(origin(), request->proxy_server());
  // The redirect should have been processed and followed normally.
  EXPECT_EQ(1, delegate().received_redirect_count());
}

TEST_F(DataReductionProxyInterceptorEndToEndTest, ResponseWithBypassAndRetry) {
  // The first try gives a bypass.
  MockRead initial_mock_reads[] = {
      MockRead("HTTP/1.1 502 Bad Gateway\r\n"
               "Via: 1.1 Chrome-Compression-Proxy\r\n"
               "Chrome-Proxy: block-once\r\n\r\n"),
      MockRead(""),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider initial_socket_data_provider(
      initial_mock_reads, arraysize(initial_mock_reads), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(&initial_socket_data_provider);

  // The retry after the bypass is successful.
  MockRead retry_mock_reads[] = {
      MockRead("HTTP/1.1 200 OK\r\n\r\n"),
      MockRead(kBody.c_str()),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider retry_socket_data_provider(
      retry_mock_reads, arraysize(retry_mock_reads), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(&retry_socket_data_provider);

  std::unique_ptr<net::URLRequest> request =
      CreateAndExecuteRequest(GURL("http://foo.com"));

  EXPECT_EQ(net::OK, delegate().request_status());
  EXPECT_EQ(200, request->GetResponseCode());
  EXPECT_EQ(kBody, delegate().data_received());
  EXPECT_FALSE(request->was_fetched_via_proxy());
  // The bypassed response should have been intercepted before the response was
  // processed, so only the final response after the retry should have been
  // processed.
  EXPECT_EQ(1, delegate().response_started_count());
}

TEST_F(DataReductionProxyInterceptorEndToEndTest, RedirectWithBypassAndRetry) {
  MockRead mock_reads_array[][3] = {
      // First, get a redirect without a via header, which should be retried
      // using the fallback proxy.
      {
          MockRead("HTTP/1.1 302 Found\r\n"
                   "Location: http://bar.com/\r\n\r\n"),
          MockRead(""),
          MockRead(net::SYNCHRONOUS, net::OK),
      },
      // Same as before, but through the fallback proxy. Now both proxies are
      // bypassed, and the request should be retried over direct.
      {
          MockRead("HTTP/1.1 302 Found\r\n"
                   "Location: http://baz.com/\r\n\r\n"),
          MockRead(""),
          MockRead(net::SYNCHRONOUS, net::OK),
      },
      // Finally, a successful response is received.
      {
          MockRead("HTTP/1.1 200 OK\r\n\r\n"),
          MockRead(kBody.c_str()),
          MockRead(net::SYNCHRONOUS, net::OK),
      },
  };
  std::vector<std::unique_ptr<net::SocketDataProvider>> socket_data_providers;
  for (MockRead* mock_reads : mock_reads_array) {
    socket_data_providers.push_back(
        base::MakeUnique<net::StaticSocketDataProvider>(mock_reads, 3, nullptr,
                                                        0));
    mock_socket_factory()->AddSocketDataProvider(
        socket_data_providers.back().get());
  }

  std::unique_ptr<net::URLRequest> request =
      CreateAndExecuteRequest(GURL("http://foo.com"));

  EXPECT_EQ(net::OK, delegate().request_status());
  EXPECT_EQ(200, request->GetResponseCode());
  EXPECT_EQ(kBody, delegate().data_received());
  EXPECT_FALSE(request->was_fetched_via_proxy());

  // Each of the redirects should have been intercepted before being followed.
  EXPECT_EQ(0, delegate().received_redirect_count());
  EXPECT_EQ(std::vector<GURL>(1, GURL("http://foo.com")), request->url_chain());
}

// https://crbug.com/668197: Flaky on android_n5x_swarming_rel bot.
#if defined(OS_ANDROID)
#define MAYBE_RedirectChainToHttps DISABLED_RedirectChainToHttps
#else
#define MAYBE_RedirectChainToHttps RedirectChainToHttps
#endif
TEST_F(DataReductionProxyInterceptorEndToEndTest, MAYBE_RedirectChainToHttps) {
  // First, a redirect is successfully received through the Data Reduction
  // Proxy. HSTS is forced for play.google.com and prebaked into Chrome, so
  // http://play.google.com will automatically be redirected to
  // https://play.google.com. See net/http/transport_security_state_static.json.
  MockRead first_redirect_reads[] = {
      MockRead(
          "HTTP/1.1 302 Found\r\n"
          "Location: http://play.google.com\r\n"
          "Via: 1.1 Chrome-Compression-Proxy\r\n\r\n"),
      MockRead(""),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider first_redirect_socket(
      first_redirect_reads, arraysize(first_redirect_reads), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(&first_redirect_socket);

  // Receive the response for https://play.google.com.
  MockRead https_response_reads[] = {
      MockRead("HTTP/1.1 200 OK\r\n\r\n"),
      MockRead(kBody.c_str()),
      MockRead(net::SYNCHRONOUS, net::OK),
  };
  net::StaticSocketDataProvider https_response_socket(
      https_response_reads, arraysize(https_response_reads), nullptr, 0);
  mock_socket_factory()->AddSocketDataProvider(&https_response_socket);
  net::SSLSocketDataProvider https_response_ssl_socket(net::SYNCHRONOUS,
                                                       net::OK);
  mock_socket_factory()->AddSSLSocketDataProvider(&https_response_ssl_socket);

  std::unique_ptr<net::URLRequest> request =
      CreateAndExecuteRequest(GURL("http://music.google.com"));
  EXPECT_FALSE(delegate().request_failed());
  EXPECT_EQ(kBody, delegate().data_received());

  std::vector<GURL> expected_url_chain;
  expected_url_chain.push_back(GURL("http://music.google.com"));
  expected_url_chain.push_back(GURL("http://play.google.com"));
  expected_url_chain.push_back(GURL("https://play.google.com"));
  EXPECT_EQ(expected_url_chain, request->url_chain());
}

}  // namespace

}  // namespace data_reduction_proxy


text:
[![Cocoapods Compatible](https://img.shields.io/cocoapods/v/Crust.svg)](https://img.shields.io/cocoapods/v/Crust.svg)
[![Build Status](https://travis-ci.org/rexmas/Crust.svg)](https://travis-ci.org/rexmas/Crust)

#Crust
A flexible Swift framework for converting classes and structs to and from JSON with support for storage solutions such as Realm.

#Features
- [Structs and Classes](#structs-and-classes)
- [Separation of Concerns (Mapped Model, Mapping, Storage)](#separation-of-concerns)
- [Type safe JSON](#jsonvalue-for-type-safe-json)
- [How To Map](#how-to-map)
  - [Nested Mappings](#nested-mappings)
  - [Mapping Context](#mapping-context)
  - [Custom Transformations](#custom-transformations)
  - [Different Mappings for Same Model](#different-mappings-for-same-model)
- [Storage Adaptor](#storage-adaptor)
- [Realm](#realm)
- Supports Optional Types and Collections.

#Requirements
iOS 8.0+
Swift 2.1+

#Installation
### CocoaPods
```
platform :ios, '8.0'
use_frameworks!

pod 'Crust'
```

#Structs and Classes
Can map to/from classes or structs
```swift
class Company {

    var employees = Array<Employee>()
    var uuid: String = ""
    var name: String = ""
    var foundingDate: NSDate = NSDate()
    var founder: Employee?
    var pendingLawsuits: Int = 0
}
```
If you have no need for storage, which will generaly be the case for structs, use `AnyMappable`.
```swift
struct Person : AnyMappable {

    var bankAccounts: Array<Int> = [ 1234, 5678 ]
    var attitude: String = "awesome"
    var hairColor: HairColor = .Unknown
    var ownsCat: Bool? = nil
}
```

#Separation of Concerns

By design Crust is built with [separation of concerns](https://en.wikipedia.org/wiki/Separation_of_concerns) in mind. It makes no assumptions about how many ways a user would like to map to and from JSON and how many various ways the user would like to store their models.

Crust has 2 basic protocols:
- `Mapping`
	- How to map JSON to and from a particular model - (model is set by the `typealias MappedObject`).
	- May include primary key(s) and nested mapping(s).
- `Adaptor`
	- How to store and retrieve model objects used for mapping from a backing store (e.g. Core Data, Realm, etc.).

And 2 additional protocols when no storage `Adaptor` is required:
- `AnyMappable`
	- Inherited from the model (class or struct) to be mapped to and from JSON.
- `AnyMapping`
	- A `Mapping` that does not require an `Adaptor`.

There are no limitations on the number of various `Mapping`s and `Adaptor`s one may create per model for different use cases.

#JSONValue for type safe JSON
Crust relies on [JSONValue](https://github.com/rexmas/JSONValue) for it's JSON encoding and decoding mechanism. It offers many benefits including type safety, subscripting, and extensibility through protocols.

#How To Map

1. Create your mappings for your model using `Mapping` if with storage or `AnyMapping` if without storage.

    With storage (assume `CoreDataAdaptor` conforms to `Adaptor`)
    ```swift
    class EmployeeMapping : Mapping {

        var adaptor: CoreDataAdaptor
        var primaryKeys: Dictionary<String, CRMappingKey>? {
            return [ "uuid" : "data.uuid" ]    // Key == attribute on the model, Value == keypath in the JSON blob.
        }

        required init(adaptor: CoreDataAdaptor) {
            self.adaptor = adaptor
        }

        func mapping(inout tomap: Employee, context: MappingContext) {
            // Company must be transformed into something Core Data can use in this case.
            let companyMapping = CompanyTransformableMapping()

            tomap.employer              <- .Mapping("company", companyMapping) >*<
            tomap.uuid                  <- "data.uuid" >*<
            tomap.name                  <- "data.name" >*<
            context
        }
    }
    ```
    Without storage
    ```swift
    class CompanyMapping : AnyMapping {
        // typealias MappedObject = Company is inferred by `tomap`

        func mapping(inout tomap: Company, context: MappingContext) {
            let employeeMapping = EmployeeMapping(adaptor: CoreDataAdaptor())

            tomap.employees             <- .Mapping("employees", employeeMapping) >*<
            tomap.founder               <- .Mapping("founder", employeeMapping) >*<
            tomap.uuid                  <- "uuid" >*<
            tomap.name                  <- "name" >*<
            tomap.foundingDate          <- "data.founding_date"  >*<
            tomap.pendingLawsuits       <- "data.lawsuits.pending"  >*<
            context
        }
    }
    ```

2. Create your Crust Mapper.
    ```swift
    let mapper = CRMapper()<Company, CompanyMapping>
    ```

3. Use the mapper to convert to and from `JSONValue` objects
    ```swift
    let json = try! JSONValue(object: [
                "uuid" : "uuid123",
                "name" : "name",
                "employees" : [
                    [ "name" : "Fred", "uuid" : "ABC123" ],
                    [ "name" : "Wilma", "uuid" : "XYZ098" ]
                ]
                "founder" : NSNull(),
                "data" : [
                    "lawsuits" : [
                        "pending" : 5
                    ]
                ],
                "data.founding_date" : NSDate().toISOString(),
            ]
    )
    let company = try! mapper.mapFromJSONToNewObject(json: json, mapping: CompanyMapping())
    ```

NOTE:
`JSONValue` can be converted back to an `AnyObject` variation of json via `json.values()` and to `NSData` via `try! json.encode()`.

###Nested Mappings
Crust supports nested mappings for nested models
E.g. from above
```swift
func mapping(inout tomap: Company, context: MappingContext) {
    let employeeMapping = EmployeeMapping(adaptor: CoreDataAdaptor())

    tomap.employees <- KeyExtensions.Mapping("employees", employeeMapping) >*<
    context
}
```

###Mapping Context
Every `mapping` passes through a `context: MappingContext` which must be included during the mapping. The `context` includes error information that is propagated back from the mapping to the caller and contextual information about the json and object being mapped to/from.

There are two ways to include the context during mapping:

1. Include it as a tuple.

   ```swift
   func mapping(inout tomap: Company, context: MappingContext) {
       tomap.uuid <- ("uuid", context)
       tomap.name <- ("name", context)
   }
   ```
2. Use a specially included operator `>*<` which merges the result of the right expression with the left expression into a tuple. This may be chained in succession.

   ```swift
   func mapping(inout tomap: Company, context: MappingContext) {
       tomap.uuid <- "uuid" >*<
       tomap.name <- "name" >*<
       context
   }
   ```

###Custom Transformations
To create a simple custom transformation (such as to basic value types) implement the `Transform` protocol
```swift
public protocol Transform : AnyMapping {
    func fromJSON(json: JSONValue) throws -> MappedObject
    func toJSON(obj: MappedObject) -> JSONValue
}
```
and use it like any other `Mapping`.

###Different Mappings for Same Model
Multiple `Mapping`s are allowed for the same model.
```swift
class CompanyMapping : AnyMapping {
    func mapping(inout tomap: Company, context: MappingContext) {
        tomap.uuid <- "uuid" >*<
        tomap.name <- "name" >*<
        context
    }
}

class CompanyMappingWithNameUUIDReversed : AnyMapping {
	func mapping(inout tomap: Company, context: MappingContext) {
        tomap.uuid <- "name" >*<
        tomap.name <- "uuid" >*<
        context
    }
}
```
Just use two different mappers.
```swift
let mapper1 = CRMapper<Company, CompanyMapping>()
let mapper2 = CRMapper<Company, CompanyMappingWithNameUUIDReversed>()
```

#Storage Adaptor
Follow the `Adaptor` protocol to create a storage adaptor to Core Data, Realm, etc.

The object conforming to `Adaptor` must include two `typealias`s:
- `BaseType` - the top level class for this storage systems model objects.
  - Core Data this would be `NSManagedObject`.
  - Realm this would be `Object`.
- `ResultsType: CollectionType` - Used for object lookups. Should return a collection of `BaseType`s.

The `Mapping` must then set it's `typealias AdaptorKind = <Your Adaptor>` to use it during mapping.

#Realm
https://github.com/rexmas/RealmCrust

#Contributing

We love pull requests and solving bugs.

- Open an issue if you run into any problems.
- Fork the project and submit a pull request to contribute. Please include tests for new code.

#License
The MIT License (MIT)

Copyright (c) 2015 Rex

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.

redpajama_set_name: RedPajamaGithub


text:
namespace Kioto::Renderer::KiotoDx12Mapping
{
inline std::map<eCullMode, D3D12_CULL_MODE> CullModes
{
    { eCullMode::Front, D3D12_CULL_MODE_FRONT },
    { eCullMode::Back, D3D12_CULL_MODE_BACK },
    { eCullMode::None, D3D12_CULL_MODE_NONE }
};
inline std::map<eFillMode, D3D12_FILL_MODE> FillModes
{
    { eFillMode::Solid, D3D12_FILL_MODE_SOLID},
    { eFillMode::Wireframe, D3D12_FILL_MODE_WIREFRAME}
};
inline std::map<eBlendModes, D3D12_BLEND> BlendModes
{
    { eBlendModes::DstAlpha, D3D12_BLEND_DEST_ALPHA },
    { eBlendModes::DstColor, D3D12_BLEND_DEST_COLOR },
    { eBlendModes::One, D3D12_BLEND_ONE },
    { eBlendModes::OneMinusDstAlpha, D3D12_BLEND_INV_DEST_ALPHA },
    { eBlendModes::OneMinusDstColor, D3D12_BLEND_INV_DEST_COLOR },
    { eBlendModes::OneMinusSrcAlpha, D3D12_BLEND_INV_SRC_ALPHA },
    { eBlendModes::OneMinusSrcColor, D3D12_BLEND_INV_SRC_COLOR },
    { eBlendModes::SrcAlpha, D3D12_BLEND_SRC_ALPHA },
    { eBlendModes::SrcAlphaSat, D3D12_BLEND_SRC_ALPHA_SAT },
    { eBlendModes::SrcColor, D3D12_BLEND_SRC_COLOR },
    { eBlendModes::Zero, D3D12_BLEND_ZERO },
};
inline std::map<eBlendOps, D3D12_BLEND_OP> BlendOps
{
    { eBlendOps::Add, D3D12_BLEND_OP_ADD },
    { eBlendOps::Substract, D3D12_BLEND_OP_SUBTRACT },
    { eBlendOps::Max, D3D12_BLEND_OP_MAX },
    { eBlendOps::Min, D3D12_BLEND_OP_MIN },
    { eBlendOps::ReverseSubstract, D3D12_BLEND_OP_REV_SUBTRACT },
};
inline std::map<eColorMask, D3D12_COLOR_WRITE_ENABLE> ColorWrites
{
    { eColorMask::All, D3D12_COLOR_WRITE_ENABLE_ALL },
    { eColorMask::Red, D3D12_COLOR_WRITE_ENABLE_RED },
    { eColorMask::Green, D3D12_COLOR_WRITE_ENABLE_GREEN },
    { eColorMask::Blue, D3D12_COLOR_WRITE_ENABLE_BLUE },
    { eColorMask::Alpha, D3D12_COLOR_WRITE_ENABLE_ALPHA }
};
inline std::map<eStencilOp, D3D12_STENCIL_OP> StencilOps
{
    { eStencilOp::Keep, D3D12_STENCIL_OP_KEEP },
    { eStencilOp::Zero, D3D12_STENCIL_OP_ZERO },
    { eStencilOp::Replace, D3D12_STENCIL_OP_REPLACE },
    { eStencilOp::IncrSat, D3D12_STENCIL_OP_INCR_SAT },
    { eStencilOp::DectSat, D3D12_STENCIL_OP_DECR_SAT },
    { eStencilOp::Invert, D3D12_STENCIL_OP_INVERT },
    { eStencilOp::Incr, D3D12_STENCIL_OP_INCR },
    { eStencilOp::Decr, D3D12_STENCIL_OP_DECR }
};
inline std::map<eStencilTest, D3D12_COMPARISON_FUNC> StencilFunc
{
    { eStencilTest::Never, D3D12_COMPARISON_FUNC_NEVER },
    { eStencilTest::Less, D3D12_COMPARISON_FUNC_LESS },
    { eStencilTest::Equal, D3D12_COMPARISON_FUNC_EQUAL },
    { eStencilTest::LEqual, D3D12_COMPARISON_FUNC_LESS_EQUAL },
    { eStencilTest::Greater, D3D12_COMPARISON_FUNC_GREATER },
    { eStencilTest::NotEqual, D3D12_COMPARISON_FUNC_NOT_EQUAL },
    { eStencilTest::GEqual, D3D12_COMPARISON_FUNC_GREATER_EQUAL },
    { eStencilTest::Always, D3D12_COMPARISON_FUNC_ALWAYS }
};
inline std::map<eZTest, D3D12_COMPARISON_FUNC> DepthFunc
{
    { eZTest::Never, D3D12_COMPARISON_FUNC_NEVER },
    { eZTest::Less, D3D12_COMPARISON_FUNC_LESS },
    { eZTest::Equal, D3D12_COMPARISON_FUNC_EQUAL },
    { eZTest::LEqual, D3D12_COMPARISON_FUNC_LESS_EQUAL },
    { eZTest::Greater, D3D12_COMPARISON_FUNC_GREATER },
    { eZTest::NotEqual, D3D12_COMPARISON_FUNC_NOT_EQUAL },
    { eZTest::GEqual, D3D12_COMPARISON_FUNC_GREATER_EQUAL },
    { eZTest::Always, D3D12_COMPARISON_FUNC_ALWAYS }
};
inline std::map<eResourceFormat, DXGI_FORMAT> ResourceFormats
{
    { eResourceFormat::Format_UNKNOWN, DXGI_FORMAT_UNKNOWN },
    { eResourceFormat::Format_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32A32_TYPELESS },
    { eResourceFormat::Format_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32A32_TYPELESS },
    { eResourceFormat::Format_R32G32B32A32_UINT, DXGI_FORMAT_R32G32B32A32_UINT },
    { eResourceFormat::Format_R32G32B32A32_SINT, DXGI_FORMAT_R32G32B32A32_SINT },
    { eResourceFormat::Format_R32G32B32_TYPELESS, DXGI_FORMAT_R32G32B32_TYPELESS },
    { eResourceFormat::Format_R32G32B32_FLOAT, DXGI_FORMAT_R32G32B32_FLOAT },
    { eResourceFormat::Format_R32G32B32_UINT, DXGI_FORMAT_R32G32B32_UINT },
    { eResourceFormat::Format_R32G32B32_SINT, DXGI_FORMAT_R32G32B32_SINT },
    { eResourceFormat::Format_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_TYPELESS },
    { eResourceFormat::Format_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT },
    { eResourceFormat::Format_R16G16B16A16_UNORM, DXGI_FORMAT_R16G16B16A16_UNORM },
    { eResourceFormat::Format_R16G16B16A16_UINT, DXGI_FORMAT_R16G16B16A16_UINT },
    { eResourceFormat::Format_R16G16B16A16_SNORM, DXGI_FORMAT_R16G16B16A16_SNORM },
    { eResourceFormat::Format_R16G16B16A16_SINT, DXGI_FORMAT_R16G16B16A16_SINT },
    { eResourceFormat::Format_R32G32_TYPELESS, DXGI_FORMAT_R32G32_TYPELESS },
    { eResourceFormat::Format_R32G32_FLOAT, DXGI_FORMAT_R32G32_FLOAT },
    { eResourceFormat::Format_R32G32_UINT, DXGI_FORMAT_R32G32_UINT },
    { eResourceFormat::Format_R32G32_SINT, DXGI_FORMAT_R32G32_SINT },
    { eResourceFormat::Format_R32G8X24_TYPELESS, DXGI_FORMAT_R32G8X24_TYPELESS },
    { eResourceFormat::Format_D32_FLOAT_S8X24_UINT, DXGI_FORMAT_D32_FLOAT_S8X24_UINT },
    { eResourceFormat::Format_R32_FLOAT_X8X24_TYPELESS, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS },
    { eResourceFormat::Format_X32_TYPELESS_G8X24_UINT, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT },
    { eResourceFormat::Format_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_TYPELESS },
    { eResourceFormat::Format_R10G10B10A2_UNORM, DXGI_FORMAT_R10G10B10A2_UNORM },
    { eResourceFormat::Format_R10G10B10A2_UINT, DXGI_FORMAT_R10G10B10A2_UINT },
    { eResourceFormat::Format_R11G11B10_FLOAT, DXGI_FORMAT_R11G11B10_FLOAT },
    { eResourceFormat::Format_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_TYPELESS },
    { eResourceFormat::Format_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM },
    { eResourceFormat::Format_R8G8B8A8_UNORM_SRGB, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB },
    { eResourceFormat::Format_R8G8B8A8_UINT, DXGI_FORMAT_R8G8B8A8_UINT },
    { eResourceFormat::Format_R8G8B8A8_SNORM, DXGI_FORMAT_R8G8B8A8_SNORM },
    { eResourceFormat::Format_R8G8B8A8_SINT, DXGI_FORMAT_R8G8B8A8_SINT },
    { eResourceFormat::Format_R16G16_TYPELESS, DXGI_FORMAT_R16G16_TYPELESS },
    { eResourceFormat::Format_R16G16_FLOAT, DXGI_FORMAT_R16G16_FLOAT },
    { eResourceFormat::Format_R16G16_UNORM, DXGI_FORMAT_R16G16_UNORM },
    { eResourceFormat::Format_R16G16_UINT, DXGI_FORMAT_R16G16_UINT },
    { eResourceFormat::Format_R16G16_SNORM, DXGI_FORMAT_R16G16_SNORM },
    { eResourceFormat::Format_R16G16_SINT, DXGI_FORMAT_R16G16_SINT },
    { eResourceFormat::Format_R32_TYPELESS, DXGI_FORMAT_R32_TYPELESS },
    { eResourceFormat::Format_D32_FLOAT, DXGI_FORMAT_D32_FLOAT },
    { eResourceFormat::Format_R32_FLOAT, DXGI_FORMAT_R32_FLOAT },
    { eResourceFormat::Format_R32_UINT, DXGI_FORMAT_R32_UINT },
    { eResourceFormat::Format_R32_SINT, DXGI_FORMAT_R32_SINT },
    { eResourceFormat::Format_R24G8_TYPELESS, DXGI_FORMAT_R24G8_TYPELESS },
    { eResourceFormat::Format_D24_UNORM_S8_UINT, DXGI_FORMAT_D24_UNORM_S8_UINT },
    { eResourceFormat::Format_R24_UNORM_X8_TYPELESS, DXGI_FORMAT_R24_UNORM_X8_TYPELESS },
    { eResourceFormat::Format_X24_TYPELESS_G8_UINT, DXGI_FORMAT_X24_TYPELESS_G8_UINT },
    { eResourceFormat::Format_R8G8_TYPELESS, DXGI_FORMAT_R8G8_TYPELESS },
    { eResourceFormat::Format_R8G8_UNORM, DXGI_FORMAT_R8G8_UNORM },
    { eResourceFormat::Format_R8G8_UINT, DXGI_FORMAT_R8G8_UINT },
    { eResourceFormat::Format_R8G8_SNORM, DXGI_FORMAT_R8G8_SNORM },
    { eResourceFormat::Format_R8G8_SINT, DXGI_FORMAT_R8G8_SINT },
    { eResourceFormat::Format_R16_TYPELESS, DXGI_FORMAT_R16_TYPELESS },
    { eResourceFormat::Format_R16_FLOAT, DXGI_FORMAT_R16_FLOAT },
    { eResourceFormat::Format_D16_UNORM, DXGI_FORMAT_D16_UNORM },
    { eResourceFormat::Format_R16_UNORM, DXGI_FORMAT_R16_UNORM },
    { eResourceFormat::Format_R16_UINT, DXGI_FORMAT_R16_UINT },
    { eResourceFormat::Format_R16_SNORM,DXGI_FORMAT_R16_SNORM },
    { eResourceFormat::Format_R16_SINT, DXGI_FORMAT_R16_SINT },
    { eResourceFormat::Format_R8_TYPELESS, DXGI_FORMAT_R8_TYPELESS },
    { eResourceFormat::Format_R8_UNORM, DXGI_FORMAT_R8_UNORM },
    { eResourceFormat::Format_R8_UINT, DXGI_FORMAT_R8_UINT },
    { eResourceFormat::Format_R8_SNORM, DXGI_FORMAT_R8_SNORM },
    { eResourceFormat::Format_R8_SINT, DXGI_FORMAT_R8_SINT },
    { eResourceFormat::Format_A8_UNORM, DXGI_FORMAT_A8_UNORM },
    { eResourceFormat::Format_R1_UNORM, DXGI_FORMAT_R1_UNORM },
    { eResourceFormat::Format_R9G9B9E5_SHAREDEXP, DXGI_FORMAT_R9G9B9E5_SHAREDEXP },
    { eResourceFormat::Format_R8G8_B8G8_UNORM, DXGI_FORMAT_R8G8_B8G8_UNORM },
    { eResourceFormat::Format_G8R8_G8B8_UNORM, DXGI_FORMAT_G8R8_G8B8_UNORM },
    { eResourceFormat::Format_BC1_TYPELESS, DXGI_FORMAT_BC1_TYPELESS },
    { eResourceFormat::Format_BC1_UNORM, DXGI_FORMAT_BC1_UNORM },
    { eResourceFormat::Format_BC1_UNORM_SRGB, DXGI_FORMAT_BC1_UNORM_SRGB },
    { eResourceFormat::Format_BC2_TYPELESS, DXGI_FORMAT_BC2_TYPELESS },
    { eResourceFormat::Format_BC2_UNORM, DXGI_FORMAT_BC2_UNORM },
    { eResourceFormat::Format_BC2_UNORM_SRGB, DXGI_FORMAT_BC2_UNORM_SRGB },
    { eResourceFormat::Format_BC3_TYPELESS, DXGI_FORMAT_BC3_TYPELESS },
    { eResourceFormat::Format_BC3_UNORM, DXGI_FORMAT_BC3_UNORM },
    { eResourceFormat::Format_BC3_UNORM_SRGB, DXGI_FORMAT_BC3_UNORM_SRGB },
    { eResourceFormat::Format_BC4_TYPELESS, DXGI_FORMAT_BC4_TYPELESS },
    { eResourceFormat::Format_BC4_UNORM, DXGI_FORMAT_BC4_UNORM },
    { eResourceFormat::Format_BC4_SNORM, DXGI_FORMAT_BC4_SNORM },
    { eResourceFormat::Format_BC5_TYPELESS, DXGI_FORMAT_BC5_TYPELESS },
    { eResourceFormat::Format_BC5_UNORM, DXGI_FORMAT_BC5_UNORM },
    { eResourceFormat::Format_BC5_SNORM, DXGI_FORMAT_BC5_SNORM },
    { eResourceFormat::Format_B5G6R5_UNORM, DXGI_FORMAT_B5G6R5_UNORM },
    { eResourceFormat::Format_B5G5R5A1_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM },
    { eResourceFormat::Format_B8G8R8A8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM },
    { eResourceFormat::Format_B8G8R8X8_UNORM, DXGI_FORMAT_B8G8R8X8_UNORM },
    { eResourceFormat::Format_R10G10B10_XR_BIAS_A2_UNORM, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM },
    { eResourceFormat::Format_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_TYPELESS },
    { eResourceFormat::Format_B8G8R8A8_UNORM_SRGB, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB },
    { eResourceFormat::Format_B8G8R8X8_TYPELESS, DXGI_FORMAT_B8G8R8X8_TYPELESS },
    { eResourceFormat::Format_B8G8R8X8_UNORM_SRGB, DXGI_FORMAT_B8G8R8X8_UNORM_SRGB },
    { eResourceFormat::Format_BC6H_TYPELESS, DXGI_FORMAT_BC6H_TYPELESS },
    { eResourceFormat::Format_BC6H_UF16, DXGI_FORMAT_BC6H_UF16 },
    { eResourceFormat::Format_BC6H_SF16, DXGI_FORMAT_BC6H_SF16 },
    { eResourceFormat::Format_BC7_TYPELESS, DXGI_FORMAT_BC7_TYPELESS },
    { eResourceFormat::Format_BC7_UNORM, DXGI_FORMAT_BC7_UNORM },
    { eResourceFormat::Format_BC7_UNORM_SRGB, DXGI_FORMAT_BC7_UNORM_SRGB },
    { eResourceFormat::Format_AYUV, DXGI_FORMAT_AYUV },
    { eResourceFormat::Format_Y410, DXGI_FORMAT_Y410 },
    { eResourceFormat::Format_Y416, DXGI_FORMAT_Y416 },
    { eResourceFormat::Format_NV12, DXGI_FORMAT_NV12 },
    { eResourceFormat::Format_P010, DXGI_FORMAT_P010 },
    { eResourceFormat::Format_P016, DXGI_FORMAT_P016 },
    { eResourceFormat::Format_420_OPAQUE, DXGI_FORMAT_420_OPAQUE },
    { eResourceFormat::Format_YUY2, DXGI_FORMAT_YUY2 },
    { eResourceFormat::Format_Y210, DXGI_FORMAT_Y210 },
    { eResourceFormat::Format_Y216, DXGI_FORMAT_Y216 },
    { eResourceFormat::Format_NV11, DXGI_FORMAT_NV11 },
    { eResourceFormat::Format_AI44, DXGI_FORMAT_AI44 },
    { eResourceFormat::Format_IA44, DXGI_FORMAT_IA44 },
    { eResourceFormat::Format_P8, DXGI_FORMAT_P8 },
    { eResourceFormat::Format_A8P8,DXGI_FORMAT_A8P8 },
    { eResourceFormat::Format_B4G4R4A4_UNORM, DXGI_FORMAT_B4G4R4A4_UNORM },
    { eResourceFormat::Format_P208, DXGI_FORMAT_P208 },
    { eResourceFormat::Format_V208, DXGI_FORMAT_V208 },
    { eResourceFormat::Format_V408, DXGI_FORMAT_V408 },
    { eResourceFormat::Format_FORCE_UINT, DXGI_FORMAT_FORCE_UINT }
};
inline std::map<eResourceDim, D3D12_RESOURCE_DIMENSION> ResourceDimensions
{
    { eResourceDim::Texture2D, D3D12_RESOURCE_DIMENSION_TEXTURE2D }
};
inline std::map<eResourceFlags, D3D12_RESOURCE_FLAGS> ResourceFlags
{
     { eResourceFlags::None, D3D12_RESOURCE_FLAG_NONE },
     { eResourceFlags::AllowRenderTarget,  D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET },
     { eResourceFlags::AllowDepthStencil, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL },
     { eResourceFlags::AllowUnorderedAccess, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS },
     { eResourceFlags::DenyShaderResource, D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE },
     { eResourceFlags::AllowCrossAdapter, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER },
     { eResourceFlags::AllowSimultaneousAccess, D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS }
};
inline std::map<eResourceState, D3D12_RESOURCE_STATES> ResourceStates
{
    { eResourceState::Common, D3D12_RESOURCE_STATE_COMMON },
    { eResourceState::VertexAndConstantBuffer, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER },
    { eResourceState::IndexBuffer, D3D12_RESOURCE_STATE_INDEX_BUFFER },
    { eResourceState::RenderTarget, D3D12_RESOURCE_STATE_RENDER_TARGET },
    { eResourceState::UnorderedAccess, D3D12_RESOURCE_STATE_UNORDERED_ACCESS },
    { eResourceState::DepthWrite, D3D12_RESOURCE_STATE_DEPTH_WRITE },
    { eResourceState::DepthRead, D3D12_RESOURCE_STATE_DEPTH_READ },
    { eResourceState::NonPixelShaderResource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE },
    { eResourceState::PixelShaderResource, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE },
    { eResourceState::StreamOut, D3D12_RESOURCE_STATE_STREAM_OUT },
    { eResourceState::IndirectArgument, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT },
    { eResourceState::CopyDest, D3D12_RESOURCE_STATE_COPY_DEST },
    { eResourceState::CopySource, D3D12_RESOURCE_STATE_COPY_SOURCE },
    { eResourceState::ResolveDest, D3D12_RESOURCE_STATE_RESOLVE_DEST },
    { eResourceState::ResolveSource, D3D12_RESOURCE_STATE_RESOLVE_SOURCE },
    { eResourceState::RaytracingAccelerationStructure, D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE },
    { eResourceState::ShadingRateSource, D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE },
    { eResourceState::GenericRead, D3D12_RESOURCE_STATE_GENERIC_READ },
    { eResourceState::Present, D3D12_RESOURCE_STATE_PRESENT },
    { eResourceState::Predication, D3D12_RESOURCE_STATE_PREDICATION }
};
}


text:
package com.nirima.docker.client.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Objects;

import java.io.Serializable;
import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
public class SearchResult implements Serializable {

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class SearchResultItem implements Serializable
    {
        @JsonProperty("description")
        public String description;

        @JsonProperty("name")
        public String name;

        @Override
        public String toString() {
            return Objects.toStringHelper(this)
                    .add("description", description)
                    .add("name", name)
                    .toString();
        }
    }

    @JsonProperty("num_results")
    public int numResults;

    @JsonProperty("query")
    public String query;

    @JsonProperty("results")
    public List<SearchResultItem> results;

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("query", query)
                .add("results", results)
                .toString();
    }
}


text:
package controllers.forms;

import play.data.validation.Constraints.Required;

public class SrAddForm {

	@Required
	public String title;

	@Required
	public Integer required_num;

	@Required
	public Integer cg_id;

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">

    <title>A Pen by  Barbara</title>

        <link rel="stylesheet" href="css/style.css">

  <meta charset="UTF-8">

  <title>CodePen - A Pen by Ant</title>

Stage 1: The Basic of the Web and HTML

       How the Web Works!

     The World Wide Web (WWW) is a collection of HTLM documents.
   Hyper Text Markup Language (HTML) is the language used to write web pages- A glue that ties all file
  t ypes, images video, pictures, etc.  together in a readable format.

    As a user, when you go to a webpage like udacity,  the Web browser and
    Web server use Hypertext Transfer Protocol (HTTP) to communicate with each other over the Internet.
    The web browser connects to the webserver, the webserver sends request to HTTP for the designated webpage.
    The webserver receives the web browser's request and then sends it via HTTP, if the page exists.
    Listen to this
       video for details.

         HTML

     Hyper Text Markup Language (HTML) is use to write webpages. HTML is made up of "text content", what you see,
    and    "mark up" which describes how "what you see" looks like, references to links, images, video, etc.
    This   video  gives you a good overview.

        Tags and Elements

      HTML tags are used to mark the beginning and/or closing of an element. The name of the opening and
      closing tag must be an exact match. Opening tag determines the HTML output.
      HTML elements comprises of opening and closing tags with content.

      Inline Vs... Block Elements

      Inline elements are displayed without a line break, so you can have multiple inline elements on the same horizontal line of a page. Block elements are displayed with a line break, so you can't have multiple block elements on the same horizontal line unless you declare display: flex. All elements, inline and block, have an invisible box around them that you can target via CSS.

   Why are Computer Stupid?

The output of a computer is based on the its input. Since to error is human, and computer literally read programs, at time it
    can be  a daunting tasks to resolve human errors that the computer cannot read.

 Stage 2 : Creating Structure Document with HTML

     Developer Tools ( in the Browser)

  HTML page structure comprises of three parts: HTML version, a Head section and the Body.
  HTML version declares what version of HTML is being used. The Head section contains metadata about
  the current document, such as, cascading style sheet (css), document title, etc. The Body section contains the page content that is visible to users.

     To view a website page structure, use google chrome developer tools, for example, to show
    the website page structure as the browser interpret it. As you mouse over an element within a structure,
    the section of the page is highlighted for readiability.

  The "Tree-like Structure of HTML"

 Every browser builds a tree-like structure of a page. HTML tree is hierarchical in nature, where some of the root(parent) attributes are inherited by it dependents(child) and this can be seen by expanding or collapsing the parent record to show or hide related content. The DOM(Document Object Model) defines the tree-structure of a page.

     Text Editor

 Test editor is used for editing plan text. When writing code, text editor is especially useful for managing code,
    copy and pasting snippets of code as an example. Sublime, scrtachpad and codepen are one of the many
      text editor you can use to manage your HTML code.

     Avoid Repetition

 A fundamental tenet of programming: do not repeat yourself. Group related content together(think along the lines of how to pack for a move).Write simple code that is easy to read, follow and modify.

     Basic of CSS and HTML

  In a browser, the page structure is depicted in  series of nested boxes. Every element on a page is rendered in a box, which
    can easily  be re-arranged to represent different perspectives. HTML controls the structure of a page, where-as, Cascading Style Sheet (CSS) controls the style of a page.HTML tells the browser where the find the sytle information.While, CSS is used to add style to an HTML element.


text:
package com.github.scalatojava

import java.io.{File, StringWriter}
import java.nio.file.{Paths, Files}

import com.strobel.assembler.InputTypeLoader
import com.strobel.assembler.metadata._
import com.strobel.decompiler.languages.Languages
import com.strobel.decompiler.languages.java.JavaFormattingOptions
import com.strobel.decompiler.{PlainTextOutput, DecompilerSettings, DecompilationOptions}
import scala.collection.mutable
import scala.tools.nsc._
import java.io._
import java.util.Arrays

/**
 *  Scala-to-Java translator
 *  @author Stanley Shyiko
 */
object ScalaToJava {

  def decompile(file: File): String = {
    val settings = new DecompilerSettings
    settings.setLanguage(Languages.java)
    settings.setTypeLoader(new InputTypeLoader)
    settings.setFormattingOptions(JavaFormattingOptions.createDefault)

    val options = new DecompilationOptions
    options.setSettings(settings)
    options.setFullDecompilation(true)

    settings.getTypeLoader.tryLoadType(file.getPath,
      new Buffer(Files.readAllBytes(Paths.get(file.getPath))))

    val metadataSystem = new NoRetryMetadataSystem(settings.getTypeLoader)
    val resolvedType = metadataSystem.resolveType(file.getName.substring(0,
      file.getName.length - ".class".length), mightBePrimitive = false)
    val writer = new StringWriter
    val output = new PlainTextOutput(writer)
    settings.getLanguage.decompileType(resolvedType, output, options)
    writer.flush()
    writer.toString
  }

  def compile(input: File, output: File): Array[File] = {
    val settings = new Settings
    settings processArgumentString "-Xscript _ -usejavacp -d " + output.getPath
    val compiler = new Global(settings)
    val runner = new compiler.Run
    runner.compile(List(input.getPath))
    output.listFiles(new FilenameFilter {
      override def accept(dir: File, name: String): Boolean = name.endsWith(".class")
    })
  }

  def apply(value: String): String = {
    val output = Files.createTempDirectory("s2j").toFile
    val input = new File(output, "_.scala")
    Files.write(input.toPath, Arrays.asList(value))
    compile(input, output).map(decompile).mkString("\n\n")
  }

  class NoRetryMetadataSystem(typeLoader: ITypeLoader) extends MetadataSystem(typeLoader) {

    val failedTypes = mutable.Set[String]()

    override def resolveType(descriptor: String, mightBePrimitive: Boolean): TypeDefinition = {
      if (failedTypes.contains(descriptor)) {
        return null
      }
      val r = super.resolveType(descriptor, mightBePrimitive)
      if (r == null) {
        failedTypes.add(descriptor)
      }
      r
    }
  }
}


text:
/*!
 * @depends ../core/AudioletNode.js
 * @depends ../core/AudioletGroup.js
 */

/**
 * Port of the Freeverb Schrodoer/Moorer reverb model.  See
 * https://ccrma.stanford.edu/~jos/pasp/Freeverb.html for a description of how
 * each part works.
 *
 * **Inputs**
 *
 * - Audio
 * - Mix
 * - Room Size
 * - Damping
 *
 * **Outputs**
 *
 * - Reverberated Audio
 *
 * **Parameters**
 *
 * - mix The wet/dry mix.  Values between 0 and 1.  Linked to input 1.
 * - roomSize The reverb's room size.  Values between 0 and 1.  Linked to input
 * 2.
 * - damping The amount of high-frequency damping.  Values between 0 and 1.
 * Linked to input 3.
 *
 * @constructor
 * @extends AudioletGroup
 * @param {Audiolet} audiolet The audiolet object.
 * @param {Number} [mix=0.33] The initial wet/dry mix.
 * @param {Number} [roomSize=0.5] The initial room size.
 * @param {Number} [damping=0.5] The initial damping amount.
 */
var Reverb = function(audiolet, mix, roomSize, damping) {
    AudioletNode.call(this, audiolet, 4, 1);

    // Constants
    this.initialMix = 0.33;
    this.fixedGain = 0.015;
    this.initialDamping = 0.5;
    this.scaleDamping = 0.4;
    this.initialRoomSize = 0.5;
    this.scaleRoom = 0.28;
    this.offsetRoom = 0.7;

    // Parameters: for 44.1k or 48k
    this.combTuning = [1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617];
    this.allPassTuning = [556, 441, 341, 225];

    // Controls
    // Mix control
    var mix = mix || this.initialMix;
    this.mix = new AudioletParameter(this, 1, mix);

    // Room size control
    var roomSize = roomSize || this.initialRoomSize;
    this.roomSize = new AudioletParameter(this, 2, roomSize);

    // Damping control
    var damping = damping || this.initialDamping;
    this.damping = new AudioletParameter(this, 3, damping);

    // Damped comb filters
    this.combBuffers = [];
    this.combIndices = [];
    this.filterStores = [];

    var numberOfCombs = this.combTuning.length;
    for (var i = 0; i < numberOfCombs; i++) {
        this.combBuffers.push(new Float32Array(this.combTuning[i]));
        this.combIndices.push(0);
        this.filterStores.push(0);
    }

    // All-pass filters
    this.allPassBuffers = [];
    this.allPassIndices = [];

    var numberOfFilters = this.allPassTuning.length;
    for (var i = 0; i < numberOfFilters; i++) {
        this.allPassBuffers.push(new Float32Array(this.allPassTuning[i]));
        this.allPassIndices.push(0);
    }
};
extend(Reverb, AudioletNode);

/**
 * Process samples
 */
Reverb.prototype.generate = function() {
    var mix = this.mix.getValue();
    var roomSize = this.roomSize.getValue();
    var damping = this.damping.getValue();

    var numberOfCombs = this.combTuning.length;
    var numberOfFilters = this.allPassTuning.length;

    var value = this.inputs[0].samples[0] || 0;
    var dryValue = value;

    value *= this.fixedGain;
    var gainedValue = value;

    var damping = damping * this.scaleDamping;
    var feedback = roomSize * this.scaleRoom + this.offsetRoom;

    for (var i = 0; i < numberOfCombs; i++) {
        var combIndex = this.combIndices[i];
        var combBuffer = this.combBuffers[i];
        var filterStore = this.filterStores[i];

        var output = combBuffer[combIndex];
        filterStore = (output * (1 - damping)) +
                      (filterStore * damping);
        value += output;
        combBuffer[combIndex] = gainedValue + feedback * filterStore;

        combIndex += 1;
        if (combIndex >= combBuffer.length) {
            combIndex = 0;
        }

        this.combIndices[i] = combIndex;
        this.filterStores[i] = filterStore;
    }

    for (var i = 0; i < numberOfFilters; i++) {
        var allPassBuffer = this.allPassBuffers[i];
        var allPassIndex = this.allPassIndices[i];

        var input = value;
        var bufferValue = allPassBuffer[allPassIndex];
        value = -value + bufferValue;
        allPassBuffer[allPassIndex] = input + (bufferValue * 0.5);

        allPassIndex += 1;
        if (allPassIndex >= allPassBuffer.length) {
            allPassIndex = 0;
        }

        this.allPassIndices[i] = allPassIndex;
    }

    this.outputs[0].samples[0] = mix * value + (1 - mix) * dryValue;
};

/**
 * toString
 *
 * @return {String} String representation.
 */
Reverb.prototype.toString = function() {
    return 'Reverb';
};


text:
#pragma once

#include <nori/object.h>
#include <memory>

NORI_NAMESPACE_BEGIN

class ImageBlock;

/**
 * \brief Abstract sample generator
 *
 * A sample generator is responsible for generating the random number stream
 * that will be passed an \ref Integrator implementation as it computes the
 * radiance incident along a specified ray.
 *
 * The most simple conceivable sample generator is just a wrapper around the
 * Mersenne-Twister random number generator and is implemented in
 * <tt>independent.cpp</tt> (it is named this way because it generates
 * statistically independent random numbers).
 *
 * Fancier samplers might use stratification or low-discrepancy sequences
 * (e.g. Halton, Hammersley, or Sobol point sets) for improved convergence.
 * Another use of this class is in producing intentionally correlated
 * random numbers, e.g. as part of a Metropolis-Hastings integration scheme.
 *
 * The general interface between a sampler and a rendering algorithm is as
 * follows: Before beginning to render a pixel, the rendering algorithm calls
 * \ref generate(). The first pixel sample can now be computed, after which
 * \ref advance() needs to be invoked. This repeats until all pixel samples have
 * been exhausted.  While computing a pixel sample, the rendering
 * algorithm requests (pseudo-) random numbers using the \ref next1D() and
 * \ref next2D() functions.
 *
 * Conceptually, the right way of thinking of this goes as follows:
 * For each sample in a pixel, a sample generator produces a (hypothetical)
 * point in an infinite dimensional random number hypercube. A rendering
 * algorithm can then request subsequent 1D or 2D components of this point
 * using the \ref next1D() and \ref next2D() functions. Fancy implementations
 * of this class make certain guarantees about the stratification of the
 * first n components with respect to the other points that are sampled
 * within a pixel.
 */
class Sampler : public NoriObject {
public:
    /// Release all memory
    virtual ~Sampler() { }

    /// Create an exact clone of the current instance
    virtual std::unique_ptr<Sampler> clone() const = 0;

    /**
     * \brief Prepare to render a new image block
     *
     * This function is called when the sampler begins rendering
     * a new image block. This can be used to deterministically
     * initialize the sampler so that repeated program runs
     * always create the same image.
     */
    virtual void prepare(const ImageBlock &block) = 0;

    /**
     * \brief Prepare to generate new samples
     *
     * This function is called initially and every time the
     * integrator starts rendering a new pixel.
     */
    virtual void generate() = 0;

    /// Advance to the next sample
    virtual void advance() = 0;

    /// Retrieve the next component value from the current sample
    virtual float next1D() = 0;

    /// Retrieve the next two component values from the current sample
    virtual Point2f next2D() = 0;

    /// Return the number of configured pixel samples
    virtual size_t getSampleCount() const { return m_sampleCount; }

    /**
     * \brief Return the type of object (i.e. Mesh/Sampler/etc.)
     * provided by this instance
     * */
    EClassType getClassType() const { return ESampler; }
protected:
    size_t m_sampleCount;
};

NORI_NAMESPACE_END


text:
/**
 */
package gluemodel.COSEM.COSEMObjects.impl;

import gluemodel.COSEM.COSEMObjects.COSEMObjectsPackage;
import gluemodel.COSEM.COSEMObjects.EndOfBillingPeriodSchedule;

import gluemodel.COSEM.InterfaceClasses.impl.SingleactionscheduleImpl;

import org.eclipse.emf.ecore.EClass;

/**
 *
 * An implementation of the model object 'End Of Billing Period Schedule'.
 *
 *
 * @generated
 */
public class EndOfBillingPeriodScheduleImpl extends SingleactionscheduleImpl implements EndOfBillingPeriodSchedule {
	/**
	 *
	 *
	 * @generated
	 */
	protected EndOfBillingPeriodScheduleImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return COSEMObjectsPackage.eINSTANCE.getEndOfBillingPeriodSchedule();
	}

} //EndOfBillingPeriodScheduleImpl


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Pong</title>
    <!--Favicon-->
    <link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.js"></script>
    <script src="../js/pong.js"></script>
</head>
<body>

</body>
</html>


text:
cover_letter
============

A cover letter generator.

Requirements
------------
Install `cookiecutter` command line: `pip install cookiecutter`

Usage
-----
Generate a new Cookiecutter template layout: `cookiecutter gh:truetone/cover-letter`

License
-------
This project is licensed under the terms of the [MIT License](/LICENSE)


text:
package org.sakaiproject.evaluation.logic.entity;

import org.sakaiproject.entitybroker.entityprovider.EntityProvider;
import org.sakaiproject.evaluation.model.EvalEvaluation;

/**
 * Allows external packages to find out the prefix for the evaluation entity
 * (deals with {@link EvalEvaluation} model class)
 *
 * @author Aaron Zeckoski (aaronz@vt.edu)
 */
public interface EvaluationEntityProvider extends EntityProvider {
	public final static String ENTITY_PREFIX = "eval-evaluation";
}


text:
require 'spec_helper'

describe "events/show" do
  before(:each) do
    @event = assign(:event, stub_model(Event,
      :person => nil,
      :duration => 1,
      :level => 2,
      :scores => 3
    ))
  end

  it "renders attributes in <p>" do
    render
    # Run the generator again with the --webrat flag if you want to use webrat matchers
    rendered.should match(//)
    rendered.should match(/1/)
    rendered.should match(/2/)
    rendered.should match(/3/)
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<merge
    android:id="@+id/activity_welcome"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.view.ViewPager
        android:id="@+id/vp_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
    <LinearLayout
        android:id="@+id/ll_dot"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_gravity="bottom"
        android:gravity="center"
        android:orientation="horizontal">

    </LinearLayout>
</merge>


text:
/*
 *  regutils.c
 *
 *       Regression test utilities
 *           l_int32    regTestSetup()
 *           l_int32    regTestCleanup()
 *           l_int32    regTestCompareValues()
 *           l_int32    regTestComparePix()
 *           l_int32    regTestCompareSimilarPix()
 *           l_int32    regTestCheckFile()
 *           l_int32    regTestCompareFiles()
 *           l_int32    regTestWritePixAndCheck()
 *
 *       Static function
 *           char      *getRootNameFromArgv0()
 */

#include <string.h>
#include "allheaders.h"

extern l_int32 NumImageFileFormatExtensions;
extern const char *ImageFileFormatExtensions[];

static char *getRootNameFromArgv0(const char *argv0);

/*--------------------------------------------------------------------*
 *                      Regression test utilities                     *
 *--------------------------------------------------------------------*/
/*!
 *  regTestSetup()
 *
 *      Input:  argc (from invocation; can be either 1 or 2)
 *              argv (to regtest: @argv[1] is one of these:
 *                    "generate", "compare", "display")
 *              &rp (<return> all regression params)
 *      Return: 0 if OK, 1 on error
 *
 *  Notes:
 *      (1) Call this function with the args to the reg test.
 *          There are three cases:
 *          Case 1:
 *              The second arg is "generate".  This will cause
 *              generation of new golden files for the reg test.
 *              The results of the reg test are not recorded, and
 *              the display field is set to FALSE, preventing image display.
 *          Case 2:
 *              The second arg is "compare".  This is the mode in which
 *              you run a regression test (or a set of them), looking
 *              for failures and logging the results to a file.
 *              The output, which includes logging of all reg test
 *              failures plus a SUCCESS or FAILURE summary for each test,
 *              is appended to the file "/tmp/reg_results.txt.  For this
 *              case, as in Case 1, the display field in rp is set to FALSE.
 *          Case 3:
 *              There is either only arg, or the  second arg is "display".
 *              The test will run and files will be written.  Comparisons
 *              with golden files will not be carried out, so the only
 *              notion of success or failure is with tests that do not
 *              involve golden files.  The display field in rp is TRUE,
 *              and this is used by pixDisplayWithTitle().
 *      (2) See regutils.h for examples of usage.
 */
l_int32
regTestSetup(l_int32        argc,
             char         **argv,
             L_REGPARAMS  **prp)
{
char         *testname, *vers;
char          errormsg[64];
L_REGPARAMS  *rp;

    PROCNAME("regTestSetup");

    if (argc != 1 && argc != 2) {
        snprintf(errormsg, sizeof(errormsg),
            "Syntax: %s [generate | compare | [display]]", argv[0]);
        return ERROR_INT(errormsg, procName, 1);
    }

    if ((testname = getRootNameFromArgv0(argv[0])) == NULL)
        return ERROR_INT("invalid root", procName, 1);

    if ((rp = (L_REGPARAMS *)CALLOC(1, sizeof(L_REGPARAMS))) == NULL)
        return ERROR_INT("rp not made", procName, 1);
    *prp = rp;
    rp->testname = testname;
    rp->index = -1;  /* increment before each test */

        /* Initialize to true.  A failure in any test is registered
         * as a failure of the regression test. */
    rp->success = TRUE;

        /* Only open a stream to a temp file for the 'compare' case */
    if (argc == 1 || !strcmp(argv[1], "display")) {
        rp->mode = L_REG_DISPLAY;
        rp->display = TRUE;
    }
    else if (!strcmp(argv[1], "compare")) {
        rp->mode = L_REG_COMPARE;
        rp->tempfile = genTempFilename("/tmp", "regtest_output.txt", 0, 1);
        rp->fp = fopenWriteStream(rp->tempfile, "wb");
        if (rp->fp == NULL) {
            rp->success = FALSE;
            return ERROR_INT("stream not opened for tempfile", procName, 1);
        }
    }
    else if (!strcmp(argv[1], "generate")) {
        rp->mode = L_REG_GENERATE;
        lept_mkdir("golden");
    }
    else {
        FREE(rp);
        snprintf(errormsg, sizeof(errormsg),
            "Syntax: %s [generate | compare | [display]]", argv[0]);
        return ERROR_INT(errormsg, procName, 1);
    }

        /* Print out test name and both the leptonica and
         * image libarary versions */
    fprintf(stderr, "\n################   %s_reg   ###############\n",
            rp->testname);
    vers = getLeptonicaVersion();
    fprintf(stderr, "%s\n", vers);
    FREE(vers);
    vers = getImagelibVersions();
    fprintf(stderr, "%s\n", vers);
    FREE(vers);

    rp->tstart = startTimerNested();
    return 0;
}

/*!
 *  regTestCleanup()
 *
 *      Input:  rp (regression test parameters)
 *      Return: 0 if OK, 1 on error
 *
 *  Notes:
 *      (1) This copies anything written to the temporary file to the
 *          output file /tmp/reg_results.txt.
 */
l_int32
regTestCleanup(L_REGPARAMS  *rp)
{
char     result[512];
char    *results_file;  /* success/failure output in 'compare' mode */
char    *text, *message;
l_int32  retval;
size_t   nbytes;

    PROCNAME("regTestCleanup");

    if (!rp)
        return ERROR_INT("rp not defined", procName, 1);

    fprintf(stderr, "Time: %7.3f sec\n", stopTimerNested(rp->tstart));
    fprintf(stderr, "################################################\n");

        /* If generating golden files or running in display mode, release rp */
    if (!rp->fp) {
        FREE(rp->testname);
        FREE(rp->tempfile);
        FREE(rp);
        return 0;
    }

        /* Compare mode: read back data from temp file */
    fclose(rp->fp);
    text = (char *)l_binaryRead(rp->tempfile, &nbytes);
    FREE(rp->tempfile);
    if (!text) {
        rp->success = FALSE;
        FREE(rp);
        return ERROR_INT("text not returned", procName, 1);
    }

        /* Prepare result message */
    if (rp->success)
        snprintf(result, sizeof(result), "SUCCESS: %s_reg\n", rp->testname);
    else
        snprintf(result, sizeof(result), "FAILURE: %s_reg\n", rp->testname);
    message = stringJoin(text, result);
    FREE(text);
    results_file = genPathname("/tmp", "reg_results.txt");
    fileAppendString(results_file, message);
    retval = (rp->success) ? 0 : 1;
    FREE(results_file);
    FREE(message);

    FREE(rp->testname);
    FREE(rp);
    return retval;
}

/*!
 *  regTestCompareValues()
 *
 *      Input:  rp (regtest parameters)
 *              val1 (typ. the golden value)
 *              val2 (typ. the value computed)
 *              delta (allowed max absolute difference)
 *      Return: 0 if OK, 1 on error (a failure in comparison is not an error)
 */
l_int32
regTestCompareValues(L_REGPARAMS  *rp,
                     l_float32     val1,
                     l_float32     val2,
                     l_float32     delta)
{
l_float32  diff;

    PROCNAME("regTestCompareValues");

    if (!rp)
        return ERROR_INT("rp not defined", procName, 1);

    rp->index++;
    diff = L_ABS(val2 - val1);

        /* Record on failure */
    if (diff > delta) {
        if (rp->fp) {
            fprintf(rp->fp,
                    "Failure in %s_reg: value comparison for index %d\n"
                    "difference = %f but allowed delta = %f\n",
                    rp->testname, rp->index, diff, delta);
        }
        fprintf(stderr,
                    "Failure in %s_reg: value comparison for index %d\n"
                    "difference = %f but allowed delta = %f\n",
                    rp->testname, rp->index, diff, delta);
        rp->success = FALSE;
    }
    return 0;
}

/*!
 *  regTestComparePix()
 *
 *      Input:  rp (regtest parameters)
 *              pix1, pix2 (to be tested for equality)
 *      Return: 0 if OK, 1 on error (a failure in comparison is not an error)
 *
 *  Notes:
 *      (1) This function compares two pix for equality.  If not in compare
 *          mode, on failure it writes to stderr.
 */
l_int32
regTestComparePix(L_REGPARAMS  *rp,
                  PIX          *pix1,
                  PIX          *pix2)
{
l_int32  same;

    PROCNAME("regTestComparePix");

    if (!rp)
        return ERROR_INT("rp not defined", procName, 1);
    if (!pix1 || !pix2) {
        rp->success = FALSE;
        return ERROR_INT("pix1 and pix2 not both defined", procName, 1);
    }

    rp->index++;
    pixEqual(pix1, pix2, &same);

        /* Record on failure */
    if (!same) {
        if (rp->fp) {
            fprintf(rp->fp, "Failure in %s_reg: pix comparison for index %d\n",
                    rp->testname, rp->index);
        }
        fprintf(stderr, "Failure in %s_reg: pix comparison for index %d\n",
                rp->testname, rp->index);
        rp->success = FALSE;
    }
    return 0;
}

/*!
 *  regTestCompareSimilarPix()
 *
 *      Input:  rp (regtest parameters)
 *              pix1, pix2 (to be tested for equality)
 *              mindiff (minimum pixel difference to be counted; > 0)
 *              maxfract (maximum fraction of pixels allowed to have
 *                        diff greater than or equal to mindiff)
 *              printstats (use 1 to print normalized histogram to stderr)
 *      Return: 0 if OK, 1 on error (a failure in similarity comparison
 *              is not an error)
 *
 *  Notes:
 *      (1) This function compares two pix for equality.  If not in compare
 *          mode, on failure it writes to stderr.
 *      (2) To identify two images as 'similar', select @maxfract to be
 *          the upper bound for what you expect.  Typical values might
 *          be @mindiff = 15 and @maxfract = 0.01.
 *      (3) Normally, use @printstats = 0.  In debugging mode, to see
 *          the relation between @mindiff and the minimum value of
 *          @maxfract for success, set this to 1.
 */
l_int32
regTestCompareSimilarPix(L_REGPARAMS  *rp,
                         PIX          *pix1,
                         PIX          *pix2,
                         l_int32       mindiff,
                         l_float32     maxfract,
                         l_int32       printstats)
{
l_int32  w, h, factor, similar;

    PROCNAME("regTestCompareSimilarPix");

    if (!rp)
        return ERROR_INT("rp not defined", procName, 1);
    if (!pix1 || !pix2) {
        rp->success = FALSE;
        return ERROR_INT("pix1 and pix2 not both defined", procName, 1);
    }

    rp->index++;
    pixGetDimensions(pix1, &w, &h, NULL);
    factor = L_MAX(w, h) / 400;
    factor = L_MAX(1, L_MIN(factor, 4));   /* between 1 and 4 */
    pixTestForSimilarity(pix1, pix2, factor, mindiff, maxfract, 0.0,
                         &similar, printstats);

        /* Record on failure */
    if (!similar) {
        if (rp->fp) {
            fprintf(rp->fp,
                    "Failure in %s_reg: pix similarity comp for index %d\n",
                    rp->testname, rp->index);
        }
        fprintf(stderr, "Failure in %s_reg: pix similarity comp for index %d\n",
                rp->testname, rp->index);
        rp->success = FALSE;
    }
    return 0;
}

/*!
 *  regTestCheckFile()
 *
 *      Input:  rp (regtest parameters)
 *              localname (name of output file from reg test)
 *      Return: 0 if OK, 1 on error (a failure in comparison is not an error)
 *
 *  Notes:
 *      (1) This function does one of three things, depending on the mode:
 *           * "generate": makes a "golden" file as a copy @localname.
 *           * "compare": compares @localname contents with the golden file
 *           * "display": makes the @localname file but does no comparison
 *      (2) The canonical format of the golden filenames is:
 *            /tmp/golden/<root of main name>_golden.<index>.<ext of localname>
 *          e.g.,
 *             /tmp/golden/maze_golden.0.png
 *          It is important to add an extension to the local name, because
 *          the extension is added to the name of the golden file.
 */
l_int32
regTestCheckFile(L_REGPARAMS  *rp,
                 const char   *localname)
{
char    *ext;
char     namebuf[256];
l_int32  ret, same;

    PROCNAME("regTestCheckFile");

    if (!rp)
        return ERROR_INT("rp not defined", procName, 1);
    if (!localname) {
        rp->success = FALSE;
        return ERROR_INT("local name not defined", procName, 1);
    }
    if (rp->mode != L_REG_GENERATE && rp->mode != L_REG_COMPARE &&
        rp->mode != L_REG_DISPLAY) {
        rp->success = FALSE;
        return ERROR_INT("invalid mode", procName, 1);
    }
    rp->index++;

    if (rp->mode == L_REG_DISPLAY) return 0;

        /* Generate the golden file name; used in 'generate' and 'compare' */
    splitPathAtExtension(localname, NULL, &ext);
    snprintf(namebuf, sizeof(namebuf), "/tmp/golden/%s_golden.%d%s",
             rp->testname, rp->index, ext);
    FREE(ext);

    if (rp->mode == L_REG_GENERATE) {
            /* Save the file as a golden file */
/*        fprintf(stderr, "%d: %s\n", rp->index, namebuf);  */
        ret = fileCopy(localname, namebuf);
        if (!ret)
            fprintf(stderr, "Copy: %s to %s\n", localname, namebuf);
        return ret;
    }

        /* Compare mode: test and record on failure */
    filesAreIdentical(localname, namebuf, &same);
    if (!same) {
        fprintf(rp->fp, "Failure in %s_reg, index %d: comparing %s with %s\n",
                rp->testname, rp->index, localname, namebuf);
        fprintf(stderr, "Failure in %s_reg, index %d: comparing %s with %s\n",
                rp->testname, rp->index, localname, namebuf);
        rp->success = FALSE;
    }

    return 0;
}

/*!
 *  regTestCompareFiles()
 *
 *      Input:  rp (regtest parameters)
 *              index1 (of one output file from reg test)
 *              index2 (of another output file from reg test)
 *      Return: 0 if OK, 1 on error (a failure in comparison is not an error)
 *
 *  Notes:
 *      (1) This only does something in "compare" mode.
 *      (2) The canonical format of the golden filenames is:
 *            /tmp/golden/<root of main name>_golden.<index>.<ext of localname>
 *          e.g.,
 *            /tmp/golden/maze_golden.0.png
 */
l_int32
regTestCompareFiles(L_REGPARAMS  *rp,
                    l_int32       index1,
                    l_int32       index2)
{
char    *name1, *name2;
char     namebuf[256];
l_int32  same;
SARRAY  *sa;

    PROCNAME("regTestCompareFiles");

    if (!rp)
        return ERROR_INT("rp not defined", procName, 1);
    if (index1 < 0 || index2 < 0) {
        rp->success = FALSE;
        return ERROR_INT("index1 and/or index2 is negative", procName, 1);
    }
    if (index1 == index2) {
        rp->success = FALSE;
        return ERROR_INT("index1 must differ from index2", procName, 1);
    }

    rp->index++;
    if (rp->mode != L_REG_COMPARE) return 0;

        /* Generate the golden file names */
    snprintf(namebuf, sizeof(namebuf), "%s_golden.%d.", rp->testname, index1);
    sa = getSortedPathnamesInDirectory("/tmp/golden", namebuf, 0, 0);
    if (sarrayGetCount(sa) != 1) {
        sarrayDestroy(&sa);
        rp->success = FALSE;
        L_ERROR_STRING("golden file %s not found", procName, namebuf);
        return 1;
    }
    name1 = sarrayGetString(sa, 0, L_COPY);
    sarrayDestroy(&sa);

    snprintf(namebuf, sizeof(namebuf), "%s_golden.%d.", rp->testname, index2);
    sa = getSortedPathnamesInDirectory("/tmp/golden", namebuf, 0, 0);
    if (sarrayGetCount(sa) != 1) {
        sarrayDestroy(&sa);
        rp->success = FALSE;
        FREE(name1);
        L_ERROR_STRING("golden file %s not found", procName, namebuf);
        return 1;
    }
    name2 = sarrayGetString(sa, 0, L_COPY);
    sarrayDestroy(&sa);

        /* Test and record on failure */
    filesAreIdentical(name1, name2, &same);
    if (!same) {
        fprintf(rp->fp,
                "Failure in %s_reg, index %d: comparing %s with %s\n",
                rp->testname, rp->index, name1, name2);
        fprintf(stderr,
                "Failure in %s_reg, index %d: comparing %s with %s\n",
                rp->testname, rp->index, name1, name2);
        rp->success = FALSE;
    }

    FREE(name1);
    FREE(name2);
    return 0;
}

/*!
 *  regTestWritePixAndCheck()
 *
 *      Input:  rp (regtest parameters)
 *              pix (to be written)
 *              format (of output pix)
 *      Return: 0 if OK, 1 on error (a failure in comparison is not an error)
 *
 *  Notes:
 *      (1) This function makes it easy to write the pix in a numbered
 *          sequence of files, and either to:
 *             (a) write the golden file ("generate" arg to regression test)
 *             (b) make a local file and "compare" with the golden file
 *             (c) make a local file and "display" the results
 *      (3) The canonical format of the local filename is:
 *            /tmp/<root of main name>.<count>.<format extension string>
 *          e.g., for scale_reg,
 *            /tmp/scale.0.png
 */
l_int32
regTestWritePixAndCheck(L_REGPARAMS  *rp,
                        PIX          *pix,
                        l_int32       format)
{
char   namebuf[256];

    PROCNAME("regTestWritePixAndCheck");

    if (!rp)
        return ERROR_INT("rp not defined", procName, 1);
    if (!pix) {
        rp->success = FALSE;
        return ERROR_INT("pix not defined", procName, 1);
    }
    if (format < 0 || format >= NumImageFileFormatExtensions) {
        rp->success = FALSE;
        return ERROR_INT("invalid format", procName, 1);
    }

        /* Generate the local file name */
    snprintf(namebuf, sizeof(namebuf), "/tmp/%s.%d.%s", rp->testname,
             rp->index + 1, ImageFileFormatExtensions[format]);

        /* Write the local file */
    pixWrite(namebuf, pix, format);

        /* Either write the golden file ("generate") or check the
           local file against an existing golden file ("compare") */
    regTestCheckFile(rp, namebuf);

    return 0;
}

/*!
 *  getRootNameFromArgv0()
 *
 *      Input:  argv0
 *      Return: root name (without the '_reg'), or null on error
 *
 *  Notes:
 *      (1) For example, from psioseg_reg, we want to extract
 *          just 'psioseg' as the root.
 *      (2) In unix with autotools, the executable is not X,
 *          but ./.libs/lt-X.   So in addition to stripping out the
 *          last 4 characters of the tail, we have to check for
 *          the '-' and strip out the "lt-" prefix if we find it.
 */
static char *
getRootNameFromArgv0(const char  *argv0)
{
l_int32  len;
char    *root;

    PROCNAME("getRootNameFromArgv0");

    splitPathAtDirectory(argv0, NULL, &root);
    if ((len = strlen(root)) <= 4) {
        FREE(root);
        return (char *)ERROR_PTR("invalid argv0; too small", procName, NULL);
    }

#ifndef _WIN32
    {
        char    *newroot;
        l_int32  loc;
        if (stringFindSubstr(root, "-", &loc)) {
            newroot = stringNew(root + loc + 1);  /* strip out "lt-" */
            FREE(root);
            root = newroot;
            len = strlen(root);
        }
    }
#else
    if (strstr(root, ".exe") != NULL)
        len -= 4;
#endif  /* ! _WIN32 */

    root[len - 4] = '\0';  /* remove the suffix */
    return root;
}


text:
const request = require('request');

class CoindeskConsumer {
    constructor() {
        this.endpoint = 'http://api.coindesk.com/v1/bpi/currentprice/EUR.json';
        this.feed = 'Coindesk';
        this.pid = process.pid;
        this.cache = {};
    }

    start() {
        this.fetchData();

        setInterval(() => {
            this.fetchData();
        }, 60000); // every 1 min
    }

    fetchData() {
        this._fetchRate(rate => {
            this._sendMessage(rate);
        })
    }

    _sendMessage(message) {
        let uptime = process.uptime();
        process.send(message);
    }

    _fetchRate(cb) {
        request({ url: this.endpoint, json: true }, (err, res, body) => {
            if (err || res.statusCode != 200) {
                console.log('CoindeskConsumer error fetching rate: ', err);
            }

            try {
                this.cache = {eur: +body.bpi.EUR.rate_float, feed: this.feed};
            } catch (ex) {
                console.log('CoindeskConsumer format exception: ', err);
            } finally {
                cb(this.cache);
            }
        })
    }
}

var coindeskConsumer = new CoindeskConsumer();
coindeskConsumer.start();

process.on('disconnect', () => {
    process.kill(coindeskConsumer.pid);
})


text:
//
// MonitorModel.java
// Open XAL
//
// Created by Pelaia II, Tom on 9/4/12
// Copyright 2012 Oak Ridge National Lab. All rights reserved.
//

package xal.app.launcher;

import java.util.*;
import java.util.concurrent.Callable;

import xal.extension.service.*;
import xal.tools.dispatch.DispatchQueue;
import xal.extension.application.ApplicationStatus;
import xal.tools.messaging.MessageCenter;

/** MonitorModel */
public class MonitorModel extends java.lang.Object {
	/** queue to manage access to the remote apps list and map */
	final private DispatchQueue REMOTE_APPS_ACCESS_QUEUE;

	/** list of remote applications */
	final private List<RemoteAppRecord> REMOTE_APPS;

	/** table of remote apps keyed by name */
	final private Map<String,RemoteAppRecord> REMOTE_APPS_TABLE;

	/** proxy for dispatching events */
	final private MonitorModelListener EVENT_PROXY;

	/** Constructor */
    public MonitorModel() {
		EVENT_PROXY = MessageCenter.defaultCenter().registerSource( this, MonitorModelListener.class );

		REMOTE_APPS_ACCESS_QUEUE = DispatchQueue.createConcurrentQueue( "Remote Apps Access" );
		REMOTE_APPS = new ArrayList<RemoteAppRecord>();
		REMOTE_APPS_TABLE = new HashMap<String,RemoteAppRecord>();

		monitorRemoteApplications();
    }

	/** Get the list of remote apps */
	public List<RemoteAppRecord> getRemoteApps() {
		return REMOTE_APPS_ACCESS_QUEUE.dispatchSync( new Callable<List<RemoteAppRecord>>() {
			public List<RemoteAppRecord> call() {
				return new ArrayList<RemoteAppRecord>( REMOTE_APPS );
			}
		});
	}

	/** Add the listener to receive events from this monitor */
	public void addMonitorModelListener( final MonitorModelListener listener ) {
		MessageCenter.defaultCenter().registerTarget( listener, this, MonitorModelListener.class );
	}

	/** Remove the listener from receiving events from this monitor */
	public void removeMonitorModelListener( final MonitorModelListener listener ) {
		MessageCenter.defaultCenter().removeTarget( listener, this, MonitorModelListener.class );
	}

	/** Monitor remote applications */
	private void monitorRemoteApplications() {
		System.out.println( "Begin monitoring for remote applications..." );
		ServiceDirectory.defaultDirectory().addServiceListener( ApplicationStatus.class, new ServiceListener() {
			/**
			 * This method is called when a new service has been added.
			 * @param directory identifies the directory sending this notification
			 * @param serviceRef The service reference of service provided.
			 */
			public void serviceAdded( final ServiceDirectory directory, final ServiceRef serviceRef ) {
				final ApplicationStatus proxy = directory.getProxy( ApplicationStatus.class, serviceRef );
				final RemoteAppRecord remoteRecord = new RemoteAppRecord( proxy );
				final String serviceID = serviceRef.getRawName();

				System.out.println( "Found remote application with ID: " + serviceID );

				REMOTE_APPS_ACCESS_QUEUE.dispatchBarrierAsync( new Runnable() {
					public void run() {
						REMOTE_APPS_TABLE.put( serviceID, remoteRecord );
						REMOTE_APPS.add( remoteRecord );
					}
				});

				EVENT_PROXY.remoteAppsChanged( MonitorModel.this, getRemoteApps() );
			}

			/**
			 * This method is called when a service has been removed.
			 * @param directory identifies the directory sending this notification
			 * @param type The type of the removed service.
			 * @param name The name of the removed service.
			 */
			public void serviceRemoved( final ServiceDirectory directory, final String type, final String name ) {
				System.out.println( "Removing application with name: " + name );

				REMOTE_APPS_ACCESS_QUEUE.dispatchBarrierAsync( new Runnable() {
					public void run() {
						final RemoteAppRecord remoteRecord = REMOTE_APPS_TABLE.get( name );
						REMOTE_APPS_TABLE.remove( name );
						REMOTE_APPS.remove( remoteRecord );
					}
				});

				EVENT_PROXY.remoteAppsChanged( MonitorModel.this, getRemoteApps() );
			}
		});
	}
}


text:
from graphics import*
win=GraphWin("clique o mouse!")
print('Clique o mouse!:')
for i in range (10):
    p=win.getMouse()
    print("Você clicou em: " , p.getX(),p.getY())
win.close()


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/darkly/bootstrap.min.css" integrity="sha384-nNK9n28pDUDDgIiIqZ/MiyO3F4/9vsMtReZK39klb/MtkZI3/LtjSjlmyVPS3KdN" crossorigin="anonymous">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.14.0/css/all.css" integrity="sha384-HzLeBuhoNPvSl5KYnjx0BT+WB0QEEqLprO+NBkkk5gbc67FTaL7XIGa2w1L0Xbgc" crossorigin="anonymous">

        <title>{{ env('SITE_TITLE', 'DecAPI') }} | {{ $page ?? '[Undefined]' }}</title>

Privacy Policy for DecAPI

Last updated: October 16th, 2020.

This privacy policy describes the information that the DecAPI service collects from you when using the service.

                    Information that is automatically collected

                        Certain information is automatically collected when you visit our website or use our service:

Your IP address

Your browser's user agent

What page you were visiting

Date & time of visit

                        Information is only stored for up to 14 days on the DecAPI web servers (using the NGINX access log feature) before being automatically rotated & deleted.

                        The information is only stored in raw log files and is not processed or shared with any other parties.

                    Twitch

                        When accessing Twitch-related information, we may store and cache public user information provided for up to 30 days.

                        Public user information includes:

Unique Twitch ID

Twitch username

                        Cached user information is only used to prevent excessive requests to the Twitch API.

                    Authenticated information from Twitch

                        For Twitch-related information that requires authentication (such as subscription-related information), DecAPI will store the following information indefinitely:

Unique Twitch ID (public)

Twitch username (public)

Access token ("OAuth token") used for accessing restricted user information via Twitch's API (private)

                        If you no longer want DecAPI to store this information, do the following:

Go to your Twitch settings, the "Connections" page

Scroll down to the "Other connections" section

Find "DecAPI" and click "Disconnect"

                        Once you have disconnected DecAPI from your Twitch account, your information will automatically be deleted in less than 24 hours.

                    YouTube and Google

                        DecAPI uses YouTube API Services for accessing YouTube-related data.

                        By using DecAPI for YouTube-related data, you accept YouTube's Terms of Service and Google's privacy policy.

                        No YouTube-related user information is stored or cached in the DecAPI service.

                        No YouTube-related user information is not being shared with any other parties via the DecAPI service.

                        Information from the YouTube API is processed by extracting the relevant information (such as video title or video ID) and then returning it with the response.


text:
package org.seqcode.viz.colors;

import java.util.*;
import java.awt.*;

public class ColorRange {

	public static int VOLUME=256*3;
	public static int AREA=256*2;
	public static int WIDTH=256;

	private Color[] array;

	public ColorRange(int size) {
		array = new Color[size];
		int blockSize = VOLUME/(size+1);
		int[] c = new int[3];

		for(int i = 0; i < size; i++) {
			int offset = (i+1) * blockSize;
			offsetToColor(offset, c);
			array[i] = new Color(c[0], c[1], c[2]);
		}
	}

	public int size() { return array.length; }
	public Color getColor(int i) { return array[i]; }

	private void offsetToColor(int offset, int[] array) {
		array[2] = offset % WIDTH;
		array[1] = ((offset-array[2]) / WIDTH) % WIDTH;
		array[0] = ((offset-array[1]) / AREA) % WIDTH;
	}
}


text:
#import <IDEKit/IDERefactoringInputValidator.h>

@class IDEIndex, IDEIndexSymbol;

@interface IDERefactoringRenameInputValidator : IDERefactoringInputValidator
{
    IDEIndexSymbol *_originalSymbol;
    IDEIndex *_index;
    BOOL _symbolIsGlobal;
}

- (void).cxx_destruct;
- (id)_sameAsExistingSymbolLocalizedMessage;
- (id)_sameAsOriginalLocalizedMessage;
@property(retain) IDEIndex *index; // @synthesize index=_index;
- (BOOL)isStringValid:(id)arg1 otherStrings:(id)arg2 localizedMessage:(id *)arg3 invalidRange:(struct _NSRange *)arg4;
@property(retain, nonatomic) IDEIndexSymbol *originalSymbol; // @synthesize originalSymbol=_originalSymbol;

@end