text:
---
id: 2015-01-26-psr-7-by-example
author: matthew
title: 'PSR-7 By Example'
draft: false
public: true
created: '2015-01-26T09:20:00-06:00'
updated: '2015-05-18T22:00:00-05:00'
tags:
    - http
    - php
    - programming
    - psr-7
---
[PSR-7](http://www.php-fig.org/psr/psr-7) is now accepted!!!

~~I'm still hearing some grumbles both of "simplify!" *and* "not far enough!"
so I'm writing this posts to demonstrate usage of the currently published
interfaces, and to illustrate both the ease of use and the completeness and
robustness they offer.~~

First, though I want to clarify what PSR-7 is attempting.

<!--- EXTENDED -->

HTTP Messages
-------------

HTTP messages are relatively simple, which is why the protocol has succeeded
over the years. All messages have the following structure:

```http
<message line>
Header: value
Another-Header: value

Message body
```

Headers are key/value pairs. The keys are case insensitive. Values are strings.
The same header type may be emitted multiple times, in which case (typically)
the values are considered as a list; in most cases, these can also be expressed
by concatenating the values with comma delimiters.

The message body is a string, but typically handled by servers and clients as a
stream in order to conserve memory and processing overhead. This is incredibly
important when you transmit large data sets, and particularly when transmitting
files. As an example, PHP natively represents the incoming request body as the
stream `php://input`, and uses output buffers — a form of stream — to return a
response.

The message line is what differentiates a request from a response.

The message line of a request is called the request line, and has the following
format:

```http
METHOD request-target HTTP/VERSION
```

`METHOD` indicates the operation requested: GET, POST, PUT, PATCH, DELETE,
OPTIONS, HEAD, etc. The `VERSION` is typically 1.0 or 1.1 (usually 1.1 in
modern web clients). The `request-target` is where things get complex.

A request target can be one of four different forms:

- `origin-form`, which is the path and query string (if present) of the URI.
- `absolute-form`, which is an absolute URI.
- `authority-form`, which is the authority portion of the uri (`user-info`, if
  present; `host`; and `port`, if non-standard).
- `asterisk-form`, which is the string `*`.

Typically, an HTTP client will use the scheme and authority from a URI to make
the connection to the HTTP server, and then pass an origin-form target in the
transmitted HTTP request message. However, it's perfectly valid to send the
absolute URI as well. authority-form is typically only used with CONNECT
requests, which are usually performed when working with a proxy server.
asterisk-form is used with OPTIONS requests to get general capabilities of a
web server.

In short, there's a lot of moving parts in the request-target.

Now, to make things more complicated, when we look at URIs, we have the
following:

```
<scheme>://<authority>[/<path>][?<query string>]
```

The scheme, when doing HTTP requests, will be one of `http` or `https`. The
path is a well-known format as well. But what about authority?

```
[user-info@]host[:port]
```

The authority *always* contains the host, which can be a domain name or an IP
address. The port is optional, and only needs to be included if it's
non-standard for the current scheme (or if the scheme is unknown). user-info is
of the form:

```
user[:pass]
```

where password is optional. In fact, in current specifications, the
recommendation is to never include the password in a URI, to force prompting
for the value by the client.

The query string is a set of key-value pairs delimited by ampersands:

```
?foo=bar&baz&quz=1
```

Depending on the language implementation, it can also model lists and hashes:

```
?sort[]=ASC&sort[]=date&filter[product]=name
```

PHP will parse the above to:

```php
[
    'sort' => [
        'ASC',
        'date'
    ],
    'filter' => [
        'product' => 'name'
    ],
]
```

So, as if the request-target was not complex enough, URIs also present a fair
amount of moving parts!

Fortunately, responses are simpler. The response line looks like this:

```http
HTTP/VERSION <status>[ <reason>]
```

The `VERSION` is as stated earlier — usually 1.0 or 1.1, and typically 1.1. The
`status` code is an integer from 100—599 inclusive; usually the `reason` phrase
will be standard for a given status code.

That's the birds-eye view of HTTP messages. Let's look at how PSR-7 currently
models them.

Message Headers
---------------

Message header names are case insensitive. Unfortunately, most languages and
libraries do some sort of normalization that makes consumption difficult. As an
example, PHP has them in `$_SERVER` as all-caps, prefixed with `HTTP_`, and
substituting `_` for `-` (this is to conform with the [Common Gateway
Interface](http://www.w3.org/CGI/) (CGI) specification).

PSR-7 simplifies access to the headers by providing an object-oriented layer on
top of them:

```php
// Returns an empty array if not found:
$header = $message->getHeader('Accept');

// Returns an empty string if not found:
$header = $message->getHeaderLine('Accept');

// Test for a header:
if (! $message->hasHeader('Accept')) {
}

// If the header has multiple values, fetch them
// as an array:
$values = $message->getHeader('X-Foo');

// Or as a comma-separated string:
$values = $message->getHeaderLine('X-Foo');
```

All of the above work regardless of the case you specify for the header;
`accept`, `ACCEPT`, or even `aCCePt` would all have been valid header names and
received the same result.

PSR-7 stipulates that fetching all headers will return a structure in the form:

```php
/* Returns the following structure:
    [
        'Header' => [
            'value1'
            'value2'
        ]
    ]
 */
foreach ($message->getHeaders() as $header => $values) {
}
```

By specifying the structure to return, consumers know exactly what to expect,
and can process headers in a uniform manner — regardless of the
implementation.

But what about when you want to add headers to a message — for instance, to
create a request to pass to an HTTP client?

The messages in PSR-7 are modeled as [value objects](http://en.wikipedia.org/wiki/Value_object);
this means that any change to state is essentially a different value. So,
assigning a header will result in a new message instance:

```php
$new = $message->withHeader('Location', 'http://example.com');
```

If you are only interested in the updated value, you can just re-assign it:

```php
$message = $message->withHeader('Location', 'http://example.com');
```

If you want to append another value to a header that may already be present,
you can also do that:

```php
$message = $message->withAddedHeader('X-Foo', 'bar');
```

Or even remove a header:

```php
$message = $message->withoutHeader('X-Foo');
```

Message Bodies
--------------

As noted above, message bodies are usually treated as streams for performance
reasons. This is particularly important when you're transmitting files over
HTTP, as you don't want to use up all available memory to your current process.
Most HTTP message implementations I've surveyed forget this or try to hack it
on after-the-fact (yes, even ZF2 is guilty of this!). If you need more
convincing, or just more background on why this is a good idea, [Michael Dowling blogged about the rationale to use streams in PSR-7](http://mtdowling.com/blog/2014/07/03/a-case-for-higher-level-php-streams/)
last summer.

Accordingly, message bodies in PSR-7 are modeled as
[streams](https://github.com/php-fig/http-message/blog/master/src/StreamInterface.php).

"But that's too hard for the 80% use case of using a string!" is the most
common argument we hear on the list about this aspect of the proposal. Well,
then, consider this:

```php
$body = new Stream('php://temp');
$body->write('Here is the content for my message!');
```

> The above example, and all concrete examples of messages in this post will be
> using [phly/http](https://github.com/phly/http), a library I've written that
> tracks the progress of PSR-7. In this case, `Stream` implements
> `StreamInterface`.

Essentially, you get a slim, object oriented interface to the body that allows
you to append to it, read it, and more. Want to replace it? Create a new
message body and update your HTTP message:

```php
$message = $message->withBody(new Stream('php://temp'));
```

My point is that while the concept of streams may be hard to wrap your head
around, the actual implementation and usage is not.

One benefit to having the `StreamInterface` in PSR-7 is that it provides
flexibility for a number of different patterns. As an example, you could create
a "callback" implementation that on a `read()` or `getContents()` operation
delegates to a callback to return the message content (Drupal, in particular,
uses this pattern). Or an "iterator" implementation that uses any `Traversable`
to return and/or aggregate content. The point is, you can get creative with the
interface in order to accomplish a variety of different patterns for modeling
the message body, and you are not restricted to simply strings or files.

The `StreamInterface` exposes the subset of stream operations that will be of
most use with HTTP message bodies; it is by no means comprehensive, but it
covers a large set of possible operations.

I'm personally a fan of using `php://temp` streams, as they are in-memory
unless they grow too big — at which point they write to temp files on disk. The
approach can be quite performant.

Responses
---------

So far, I've looked at features common to any message. I'm now going to look at
responses in particular.

A response has a status code and a reason phrase:

```php
$status = $response->getStatusCode();
$reason = $response->getReasonPhrase();
```

That's pretty easy to remember. Now, what if I'm *building* a response?

Reason phrases are considered optional — but also specific to the status code
being set. As such, the only response-specific mutator is `withStatus()`:

```php
$response = $response->withStatus(418, "I'm a teapot");
```

> Again, messages are modeled as value objects; a change to any value results
> in a new instance, which needs to be assigned. In most cases, you'll just
> reassign the current instance.

Requests
--------

Requests contain the following:

- Method.
- URI/request-target.

The latter provides a bit of a challenge to model. In likely 99% of use cases,
we'll be seeing an origin-form request-target — in other words, something that
looks like a URI. However, we still need to accommodate other request-target
types. As such, the request interface does the following:

- It composes a `UriInterface` instance, which models the URI itself
- It provides two methods around request-targets: `getRequestTarget()`, which
  will return the request target, and calculate it if not present (using the
  composed URI to return an origin-form, or to return a "/" if no URI is
  composed or it does not have a path); and `withRequestTarget()`, to create a
  new instance with a specific request target.

This latter allows you to address the non-origin-form requests targets when
needed — while keeping the URI information present in the request, which you
may need for establishing HTTP client connections.

Let's get the method and URI from the request:

```php
$method = $request->getMethod();
$uri    = $request->getUri();
```

`$uri` in this case will be an instance of the `UriInterface`, and allows you
to introspect the URI:

```php
// URI parts:
$scheme    = $uri->getScheme();
$userInfo  = $uri->getUserInfo();
$host      = $uri->getHost();
$port      = $uri->getPort();
$path      = $uri->getPath();
$query     = $uri->getQuery();     // the query STRING
$authority = $uri->getAuthority(); // [user-info@]host[:port]
```

Just like the HTTP messages, URIs are treated as value objects, as changing any
portion of a URI changes its value; as such, mutator operations return a new
instance:

```php
$uri = $uri
    ->withScheme('http')
    ->withHost('example.com')
    ->withPath('/foo/bar')
    ->withQuery('?baz=bat');
```

Because changing the URI means a new instance, if you want the changes
reflected in your request, you'll need to notify the request; and, as with any
message, if you need to change the method or URI in your request instance, use
the `with` methods:

```php
$request = $request
    ->withMethod('POST')
    ->withUri($uri->withPath('/api/user'));
```

Typically for requests, you want the `Host` header to match the value in the
URI. As such, by default, `withUri()` will also set the `Host` header on the
returned instance based on the value present in the URI. If you want to keep
the original value, the method takes an optional second argument,
`$preserveHost`, which, if set to a boolean `true` value, will do exactly what
it says.

Server-Side requests
--------------------

Server-side requests have some slightly different concerns than a standard HTTP
request message. PHP's Server API (SAPI) does a number of things for us
normally that, as PHP developers, we've come to rely on:

- Deserialization of query string arguments (`$_GET`).
- Deserialization of urlencoded form data submitted via POST (`$_POST`).
- Deserialization of cookies (`$_COOKIE`).
- Identification and handling of file uploads (`$_FILES`).
- Encapsulation of CGI/SAPI parameters (`$_SERVER`).

Query string arguments, form data, and cookies can be discovered from other
aspects of the request, but it's convenient to have them already parsed for us.
That said, there are cases where we may want to manipulate those values:

- For APIs, the data may be in XML or JSON, and may be submitted over methods
  other than POST. As such, we'll need to deserialize the data — and then
  re-inject it into the request.
- Many frameworks are now encrypting cookies — which means that they need to be
  decrypted, and re-injected into the request.

So, PSR-7 offers another interface, `ServerRequestInterface`, which extends the
base `RequestInterface`, and offers features around these values:

```php
$query   = $request->getQueryParams();
$body    = $request->getBodyParams();
$cookies = $request->getCookieParams();
$files   = $request->getUploadedFiles();
$server  = $request->getServerParams();
```

Let's say you are writing an API, and want to accept JSON requests; doing so
might look like the following:

```php
$accept = $request->getHeader('Accept');
if (! $accept || ! preg_match('#^application/([^+\s]+\+)?json#', $accept)) {
    $response->getBody()->write(json_encode([
        'status' => 405,
        'detail' => 'This API can only provide JSON representations',
    ]));
    emit($response
        ->withStatus(405, 'Not Acceptable')
        ->withHeader('Content-Type', 'application/problem+json')
    );
    exit();
}

$body = (string) $request->getBody();
$request = $request
    ->withBodyParams(json_decode($body));
```

The above demonstrates several features. First, it shows retrieving a request
header, and branching logic based on that header. Second, it shows populating a
response object in the case of an error. (`emit()` is a hypothetical function
that would take the response object and emit headers and content.) Finally, it
shows retrieving the body, deserializing it, and re-injecting the request.

`with` methods exist for each of the various input types available to
`ServerRequestInterface` instances.

### Uploaded Files

Uploaded files seem like they should be relatively straight-forward: just use
`$_FILES`, right? Wrong.

- In cases where you have arrays of uploads (for example, when you're using
  JavaScript to allow people to incrementally upload more files), `$_FILES`
  generates a very different structure.
- In non-SAPI environments (for example, testing, or when using
  [ReactPHP](http://reactphp.org)), `$_FILES` is not populated.
- Even in SAPI environments, if you're not in a `POST` request, `$_FILES` is
  not populated

PSR-7 smooths this over by having uploaded files represented as a tree of
`UploadedFileInterface` instances. This interface defines methods for
introspecting the upload (for example, the filename associated, the media type,
and the size), but also provides some behavior:

- `getStream()` will return a `StreamInterface` instance, allowing you to
  manipulate the upload as a stream; this can be useful to stream it to a CDN,
  for instance.
- `moveTo()` allows you to move the upload — after validating it, of course! —
  to another location; on SAPI environments, this will use
  `move_uploaded_file()`, ensuring proper garbage cleanup by PHP.

Practically speaking, it means you can interact with file uploads very simply:

```php
// Single upload:
$avatar = $request->getFileUploads()['avatar']; // UploadedFileInterface!

// Arrays of uploads:
$icon1 = $request->getFileUploads()['profile']['icons'][0]; // UploadedFileInterface!
$icon2 = $request->getFileUploads()['profile']['icons'][1]; // UploadedFileInterface!

// Move an uploaded file:
$icon1->moveTo('data/uploads/icons/', UUID::idv4() . '.png');

// Stream an uploaded file:
// Note: StreamRegister is a fictional utility for creating a PHP stream
//       wrapper from a StreamInterface instance.
stream_copy_to_stream(StreamRegister($avatar->getStream()), $s3Stream);
```

### Attributes

Another feature of server-side requests are "attributes." These are intended
for storing values that are computed from the current request. A common use
case is for storing the results of routing (decomposing the URI to key/value
pairs).

The `attributes` API includes:

- `getAttribute($name, $default = null)` to retrieve a single named attribute, and return a default value if the attribute is not present.
- `getAttributes()` to retrieve the entire set of attributes currently stored.
- `withAttribute($name, $value)` to return a new `ServerRequestInterface` instance that composes the given attribute.
- `withoutAttribute()` to return a new `ServerRequestInterface` instance that does not compose the given attribute.

As an example, let's use the [Aura Router](https://github.com/auraphp/Aura.Router)
with our request instance:

```php
use Aura\Router\Generator;
use Aura\Router\RouteCollection;
use Aura\Router\RouteFactory;
use Aura\Router\Router;

$router = new Router(
    new RouteCollection(new RouteFactory()),
    new Generator()
);

$path  = $request->getUri()->getPath();
$route = $router->match($path, $request->getServerParams());
foreach ($route->params as $param => $value) {
    $request = $request->withAttribute($param, $value);
}
```

The request instance, in this case, is used to marshal data to feed to the
router, and then the results of routing are used to seed the request instance.

Use Cases
---------

Now that you've had a whirlwind tour of the various components of PSR-7, let's
turn to some concrete use cases.

### Clients

The editor prior to myself on PSR-7, [Michael Dowling](http://mtdowling.com),
is the author of the popular HTTP client [Guzzle](http://guzzlephp.org) — so
it's a perfectly natural leap that PSR-7 will benefit HTTP clients. Let's
consider how.

First, it means that developers will have a unified message interface to use
for making requests; they can pass PSR-7 request instances to a client, and
will get PSR-7 response instances in return.

```php
$response = $client->send($request);
```

Because messages and URIs are modeled as value objects, it also means that
developers can create base instances of requests and URIs, and create discrete
requests and URIs from them:

```php
$baseUri     = new Uri('https://api.example.com');
$baseRequest = (new Request())
    ->withUri($baseUri)
    ->withHeader('Authorization', $apiToken);

while ($action = $queue->dequeue()) {
    // New response instance! Only contains
    // URI and Authorization header from base.
    $request = $baseRequest
        ->withMethod($action->method)
        ->withUri($baseUri->withPath($action->path)); // new URI!

    foreach ($action->headers as $header => $value) {
        // The base request WILL NOT receive these headers, ensuring subsequent
        // requests only compose the headers they need!
        $request = $request->withHeader($header, $value);
    }

    $response = $client->send($request);
    $status   = $response->getStatusCode();
    if (! in_array($status, range(200, 204))) {
        // Request failed!
        break;
    }

    // Grab the data!
    $data->enqueue(json_decode((string) $response->getBody()));
}
```

What PSR-7 provides is a standard way to interact with the requests you send
with the client, and the responses you receive. By implementing value objects,
we enable some interesting use cases with regards to simplifying the "reset
request" pattern — changing the request always results in a new instance,
allowing us to have a base instance with a known state that we can always build
from.

### Middleware

I won't go too much into this, as [I've already done so before](https://mwop.net/blog/2015-01-08-on-http-middleware-and-psr-7.html).
The basic idea, however, is this:

```php
function (
    ServerRequestInterface $request,
    ResponseInterface $response,
    callable $next = null
) {
}
```

The function accepts the two HTTP messages, and does something with them —
which might include delegating to the "next" middleware available. Middleware
usually returns a response.

Another pattern often used is the "lambda" pattern (thanks to [Larry Garfield](http://www.garfieldtech.com/)
for coining this term on the mailing list!):

```php
/* response = */ function (ServerRequestInterface $request) {
    /* ... */
    return $response;
}
```

In lambda middleware, you compose one into another:

```php
$inner = function (ServerRequestInterface $request) {
    /* ... */
    return $response;
};
$outer = function (ServerRequestInterface $request) use ($inner) {
    /* ... */
    $response = $inner($request);
    /* ... */
    return $response;
};
$response = $outer($request);
```

And then there's the pattern popularized by Rack and WSGI, in which the each
middleware is an object, and is passed to the outer:

```php
class Command
{
    private $wrapped;

    public function __construct(callable $wrapped)
    {
        $this->wrapped = $wrapped;
    }

    public function __invoke(
        ServerRequestInterface $request,
        ResponseInterface $response
    ) {
        // manipulate the request, maybe
        $new = $request->withAttribute('foo', 'bar');

        // delegate to the middleware we wrap:
        $result = ($this->wrapped)($new, $response);

        // see if we got a response
        if ($result instanceof ResponseInterface) {
            $response = $result;
        }

        // manipulate the response before returning
        return $reponse->withHeader('X-Foo', 'Bar');
    }
}
```

The idea behind middleware is that it's composable, and follows a standard,
predictable pattern with predictable behavior. It's a great way to write
re-usable web components.

### Frameworks

One thing frameworks have been providing for many years is… HTTP message
abstraction. PSR-7 aims to provide a common set of interfaces so that
frameworks can use the same set of abstractions. This will enable developers to
write re-usable, framework-agnostic web components that frameworks can consume
— or, at least, that's what *I* would like to see!

Consider Zend Framework 2: it defines the interface
`Zend\Stdlib\DispatchableInterface` which is the base interface for any
controller you want to use in the framework:

```php
use Zend\Http\RequestInterface;
use Zend\Http\ResponseInterface;

interface DispatchableInterface
{
    public function dispatch(
        RequestInterface $request,
        ResponseInterface $response
    );
}
```

This actually looks a lot like the middleware examples above; the only real
difference is that it consumes framework-specific HTTP message implementations.
What if, instead, it could consume PSR-7?

Most implementations of HTTP messages in frameworks are mutable, which means
that you can change the state of the message at any time. This can lead to
problems at times, particularly if you have assumptions about message state
that are no longer true. The other problem, though, is tracking down when state
changes.

PSR-7's messages are value objects. As such, you would need to notify the
application somehow of any change to one of the messages. This becomes more
explicit, and thus easier to trace in your code (both with step debuggers as
well as static analysis tools).

As an example, if ZF2 were updated to use PSR-7 messages, developers would need
to notify the `MvcEvent` of any changes they want propagated to later
consumers:

```php
// Inside a controller:
$request  = $request->withAttribute('foo', 'bar');
$response = $response->withHeader('X-Foo', 'bar');

$event = $this->getEvent();
$event->setRequest($request)
      ->setResponse($response);
```

The above code makes it explicit that we are changing application state.

Having value objects makes simpler one specific practice: the idea of
dispatching "sub-requests" or implementing Hierarchical MVC (HMVC). In these
cases, you can create new requests based on the current without altering it,
*ensuring the application state remains unchanged.*

Essentially, for many frameworks, dropping in the PSR-7 messages will lead to
portable abstractions that can be used across frameworks, and make it possible
to consume generic middleware relatively easily. To adopt the messages,
however, will likely require some minor changes such as the above when
developers need to modify the messages for use with the application state.

Resources
---------

Hopefully, you're starting to see the benefits PSR-7 will provide: a unified,
complete abstraction around HTTP messages. Further, the abstraction can be used
for either side of the HTTP transaction — whether you're sending requests via
an HTTP client, or handling a server-side request.

The PSR-7 specification is not yet final, but what I've outlined above is not
likely to undergo significant change before putting it forth for a vote. If you
want more details, you can read the specification:

- [https://github.com/php-fig/fig-standards/blob/master/proposed/http-message.md](https://github.com/php-fig/fig-standards/blob/master/proposed/http-message.md)

I also encourage you to read the metadocument for the proposal, as it describes
the goals, design decisions, and results of the (endless) debates over the past
two years:

- [https://github.com/php-fig/fig-standards/blob/master/proposed/http-message-meta.md](https://github.com/php-fig/fig-standards/blob/master/proposed/http-message-meta.md)

The actual interfaces are published as the package `psr/http-message`, which
you can install via composer. It is always updated at the same time as the
proposal.

I've created a library, `phly/http`, which provides concrete implementations of
the proposed interfaces; I update it whenever I update the proposal. It, too,
is installable via composer.

Finally, if you want to play with middleware based on PSR-7, you have a couple
of options:

- [phly/conduit](https://github.com/phly/conduit), a port of Sencha's [Connect](https://github.com/senchalabs/connect) to PHP using `phly/http` and `psr/http-message` as its foundation.
- [Stacker](https://github.com/Crell/stacker), a [StackPHP](http://stackphp.com)-like implementation written by Larry Garfield.

I'm looking forward to passage of PSR-7; I think it will enable a whole new
breed of PHP applications.

#### Updates

- *2015-01-28*: Updated post to reflect psr/http-message 0.8.0. That version
  renamed `UriTargetInterface` to `UriInterface`, and modified it such that it
  now only models URIs. `RequestInterface` was modified to add the methods
  `getRequestTarget()` and `withRequestTarget()`, which allow simpler and
  better flexibility around non-origin-form request-targets. The post was
  updated to reflect these changes.
- *2015-01-29*: Fixed links to FIG proposal/meta document.
- *2015-02-01*: Corrected description of lambda middleware, and noted the last middleware pattern is that popularized by Rack and WSGI.
- *2015-05-04*: Updated to ensure it follows the interfaces as outlined at the end of the second Review period of PSR-7 (psr/http-message 0.11.0); added section on file uploads.
- *2015-05-18*: PSR-7 is now accepted!


text:
layout: post
title: "IntelliJ Rust Changelog #82"
date: 2018-09-13 09:33:29 +0300
---

## New Features

* Now `Goto Declaration` action navigates to `derive` meta item if the corresponding trait is implemented via `#[derive]` attribute

* Implement name resolution and completion of paths in include macros and `#[path]` attribute

* Support `Context Info` action

* Show nested items of function in structure view

* Support type hints for generic type parameters (by [@dem1tris])

* Initial implementation of `iter` postfix template (by [@Voronchikhin])

* Implement preliminary inspection of anchored paths for Rust 2018. Note, it's disabled by default because final design of `use` item paths is not fixed yet

* Create error annotation for [E0404](https://doc.rust-lang.org/error-index.html#E0404) error

* Support type inference in [box](https://github.com/rust-lang/rust/blob/master/src/doc/unstable-book/src/language-features/box-patterns.md) pattern

## Fixes

* Now `Different impl member order from the trait` annotation doesn't highlight comments and attributes

* Correctly resolve `extern crate` items with dependency on the same crate with a different version

* Fix false positive error highlighting of `Unresolved Reference` inspection for trait objects and generic type parameters

## Internal Improvements

* Implement expression categorization as part of borrow checker implementation

* Various refactorings in tests

[@Voronchikhin]: https://github.com/Voronchikhin
[@dem1tris]: https://github.com/dem1tris

redpajama_set_name: RedPajamaGithub


text:
`FeedbackStatus`
================

.. autoclass:: typepad.api.FeedbackStatus
   :members:


text:
package com.vaadin.tests.components.textfield;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import com.vaadin.data.Item;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.BeanContainer;
import com.vaadin.data.util.BeanItem;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.tests.components.TestBase;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalSplitPanel;

public class OutOfSyncIssueWithKeyboardShortcut extends TestBase {

    public static class TestToppingsView extends CustomComponent {

        public static class Topping {
            private Long id;
            private String name = "ham";

            public void setId(Long id) {
                this.id = id;
            }

            public Long getId() {
                return id;
            }

            public void setName(String name) {
                this.name = name;
            }

            public String getName() {
                return name;
            }
        }

        private Table table = new Table();

        private Form form = new Form();

        private Map<Long, Topping> toppings = new HashMap<Long, Topping>();
        private long index = 1;

        private String previousFragment = null;

        public TestToppingsView() {
            setSizeFull();

            VerticalSplitPanel mainLayout = new VerticalSplitPanel();
            mainLayout.setSplitPosition(30);
            setCompositionRoot(mainLayout);

            table.setSizeFull();
            table.setImmediate(true);
            table.setSelectable(true);

            mainLayout.setFirstComponent(table);
            mainLayout.setSecondComponent(form);

            form.setImmediate(true);
            // this is critical for the problem to occur
            form.setBuffered(true);

            HorizontalLayout footer = new HorizontalLayout();
            footer.setSpacing(true);
            form.setFooter(footer);
            Button saveButton = new Button("Save");
            footer.addComponent(saveButton);

            // make saving the form the default action on Enter keypress
            saveButton.setClickShortcut(KeyCode.ENTER);

            table.addListener(new ValueChangeListener() {
                @Override
                public void valueChange(ValueChangeEvent event) {
                    Object value = event.getProperty().getValue();
                    if (value != null) {
                        String fragment = "edit/"
                                + String.valueOf(value)
                                        .replaceAll("[^0-9]", "");
                        if (!fragment.equals(previousFragment)) {
                            navigateTo(fragment);
                        }
                    }
                }
            });

            saveButton.addListener(new ClickListener() {
                @Override
                public void buttonClick(ClickEvent event) {
                    form.commit();
                    Topping entity = getEntityForItem(form.getItemDataSource());
                    if (entity != null && entity.getId() == null) {
                        entity.setId(index++);
                        toppings.put(entity.getId(), entity);
                    }
                    refreshTable();
                    navigateTo(null);
                }
            });

            // create new entity at the beginning
            refreshTable();
            navigateTo("new");
        }

        public void navigateTo(String requestedDataId) {
            previousFragment = requestedDataId;

            if ("new".equals(requestedDataId)) {
                table.setValue(null);
                form.setVisible(true);
                setCurrentEntity(new Topping());
                form.focus();
            } else if (requestedDataId != null
                    && requestedDataId.startsWith("edit/")) {
                try {
                    Long id = Long.valueOf(requestedDataId.substring(5));
                    setCurrentEntity(getEntityForItem(table.getItem(id)));
                    form.focus();
                } catch (NumberFormatException e) {
                    setCurrentEntity(null);
                }
            } else {
                setCurrentEntity(null);
            }
        }

        private void refreshTable() {
            // refresh table
            BeanContainer<Long, Topping> container = new BeanContainer<Long, Topping>(
                    Topping.class);
            container.setBeanIdProperty("id");
            for (Topping entity : toppings.values()) {
                container.addBean(entity);
            }
            table.setContainerDataSource(container);
        }

        protected void setCurrentEntity(Topping entity) {
            form.setVisible(entity != null);
            if (entity != null) {
                Item item = table.getItem(entity.getId());
                if (item == null) {
                    item = new BeanItem<Topping>(entity);
                }
                form.setItemDataSource(item, Collections.singleton("name"));
            } else {
                form.setItemDataSource(null);
            }
        }

        public Topping getEntityForItem(Item item) {
            if (item != null) {
                return ((BeanItem<Topping>) item).getBean();
            } else {
                return null;
            }
        }

    }

    @Override
    protected void setup() {
        TestToppingsView testToppingsView = new TestToppingsView();
        addComponent(testToppingsView);
        getLayout().setSizeFull();
        getLayout().setExpandRatio(testToppingsView, 1);
    }

    @Override
    protected String getDescription() {
        return "Focus the text field and press ENTER.\n"
                + "Click on the table row to edit it, change the text to \"ahm\" using the keyboard and press ENTER again.\n"
                + "Then select the table row again.\n"
                + "This causes an Out of Sync error if the cursor position for the text field is sent too late to a component that is no longer in the layout.";
    }

    @Override
    protected Integer getTicketNumber() {
        return 6834;
    }
}


text:
suite('ready', function() {
  /* globals configureList readyList clearTestLists */

  var configure = ['x-ready', 'x-zot#a', 'x-zot#b', 'x-zot#c', 'x-zot#d', 'x-foo#foo', 'x-bar#bar1', 'x-zot', 'x-bar#bar2', 'x-zot'];
  var ready = ['x-zot#a', 'x-zot#b', 'x-zot#c', 'x-zot#d', 'x-zot', 'x-bar#bar1', 'x-zot', 'x-bar#bar2', 'x-foo#foo', 'x-ready'];

  test('element create in dom calls configure/ready/attached in proper order', function() {
    assert.deepEqual(configureList, configure);
    assert.deepEqual(readyList, ready);
  });

  test('element create + attach calls configure/ready/attached in proper order', function() {
    clearTestLists();
    document.body.appendChild(document.createElement('x-ready'));
    CustomElements.takeRecords(document);
    assert.deepEqual(configureList, configure);
    assert.deepEqual(readyList, ready);
  });

});


text:
<!doctype html>
<title>embed default style, video</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<embed src=../../support/240x160.ogv>
<script>
test(function() {
  var e = document.body.firstChild;
  assert_equals(getComputedStyle(e, '').OObjectFit, 'auto');
  assert_equals(getComputedStyle(e, '').OObjectPosition, '50% 50%');
}, window, 'load', 2000);
</script>


text:
package org.apache.helix.rest.common;

import java.util.HashMap;
import java.util.Map;

public class HelixRestNamespace {

  public enum HelixMetadataStoreType {
    ZOOKEEPER,
    NO_METADATA_STORE
  }

  public enum HelixRestNamespaceProperty {
    NAME,
    METADATA_STORE_TYPE,
    METADATA_STORE_ADDRESS,
    IS_DEFAULT,
    MULTI_ZK_ENABLED,
    MSDS_ENDPOINT
  }

  /**
   * Namespaced object will have path such as /url_prefix/namespaces/{namespace_name}/clusters/...
   * We are going to have path /url_prefix/clusters/... point to default namespace if there is one
   */
  public static final String DEFAULT_NAMESPACE_PATH_SPEC = "/*";
  public static final String DEFAULT_NAMESPACE_NAME = "default";

  /**
   * Name of Helix namespace
   */
  private String _name;

  /**
   * Type of a metadata store that belongs to Helix namespace
   */
  private HelixMetadataStoreType _metadataStoreType;

  /**
   * Address of metadata store. Should be in the format of
   * "[ip-address]:[port]" or "[dns-name]:[port]"
   */
  private String _metadataStoreAddress;

  /**
   * Flag indicating whether this namespace is default or not
   */
  private boolean _isDefault;

  /**
   * Flag indicating whether this namespace should have multi-zk feature enabled.
   */
  private boolean _isMultiZkEnabled;

  /**
   * Endpoint for accessing MSDS for this namespace.
   */
  private String _msdsEndpoint;

  public HelixRestNamespace(String metadataStoreAddress) throws IllegalArgumentException {
    this(DEFAULT_NAMESPACE_NAME, HelixMetadataStoreType.ZOOKEEPER, metadataStoreAddress, true);
  }

  public HelixRestNamespace(String name, HelixMetadataStoreType metadataStoreType,
      String metadataStoreAddress, boolean isDefault) throws IllegalArgumentException {
    this(name, metadataStoreType, metadataStoreAddress, isDefault, false, null);
  }

  public HelixRestNamespace(String name, HelixMetadataStoreType metadataStoreType,
      String metadataStoreAddress, boolean isDefault, boolean isMultiZkEnabled,
      String msdsEndpoint) {
    _name = name;
    _metadataStoreAddress = metadataStoreAddress;
    _metadataStoreType = metadataStoreType;
    _isDefault = isDefault;
    _isMultiZkEnabled = isMultiZkEnabled;
    _msdsEndpoint = msdsEndpoint;
    validate();
  }

  private void validate() throws IllegalArgumentException {
    // TODO: add more strict validation for NAME as this will be part of URL
    if (_name == null || _name.length() == 0) {
      throw new IllegalArgumentException("Name of namespace not provided");
    }
    if (_metadataStoreType != HelixMetadataStoreType.NO_METADATA_STORE && (_metadataStoreAddress == null
        || _metadataStoreAddress.isEmpty())) {
      throw new IllegalArgumentException(
          String.format("Metadata store address \"%s\" is not valid for namespace %s", _metadataStoreAddress, _name));
    }
  }

  public boolean isDefault() {
    return _isDefault;
  }

  public String getName() {
    return _name;
  }

  public String getMetadataStoreAddress() {
    return _metadataStoreAddress;
  }

  public Map<String, String> getRestInfo() {
    // In REST APIs we currently don't expose metadata store information
    Map<String, String> ret = new HashMap<>();
    ret.put(HelixRestNamespaceProperty.NAME.name(), _name);
    ret.put(HelixRestNamespaceProperty.IS_DEFAULT.name(), String.valueOf(_isDefault));
    ret.put(HelixRestNamespaceProperty.MULTI_ZK_ENABLED.name(), String.valueOf(_isMultiZkEnabled));
    ret.put(HelixRestNamespaceProperty.MSDS_ENDPOINT.name(), String.valueOf(_msdsEndpoint));
    return ret;
  }

  public boolean isMultiZkEnabled() {
    return _isMultiZkEnabled;
  }

  public String getMsdsEndpoint() {
    return _msdsEndpoint;
  }
}


text:
package com.amazonaws.services.securityhub.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.securityhub.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * AwsRedshiftClusterHsmStatus JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AwsRedshiftClusterHsmStatusJsonUnmarshaller implements Unmarshaller<AwsRedshiftClusterHsmStatus, JsonUnmarshallerContext> {

    public AwsRedshiftClusterHsmStatus unmarshall(JsonUnmarshallerContext context) throws Exception {
        AwsRedshiftClusterHsmStatus awsRedshiftClusterHsmStatus = new AwsRedshiftClusterHsmStatus();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("HsmClientCertificateIdentifier", targetDepth)) {
                    context.nextToken();
                    awsRedshiftClusterHsmStatus.setHsmClientCertificateIdentifier(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("HsmConfigurationIdentifier", targetDepth)) {
                    context.nextToken();
                    awsRedshiftClusterHsmStatus.setHsmConfigurationIdentifier(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Status", targetDepth)) {
                    context.nextToken();
                    awsRedshiftClusterHsmStatus.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return awsRedshiftClusterHsmStatus;
    }

    private static AwsRedshiftClusterHsmStatusJsonUnmarshaller instance;

    public static AwsRedshiftClusterHsmStatusJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new AwsRedshiftClusterHsmStatusJsonUnmarshaller();
        return instance;
    }
}


text:
package server

import (
	"fmt"
	"net/http"

	"github.com/fnproject/fn/api"
	"github.com/gin-gonic/gin"
)

func (s *Server) handleFnGet(c *gin.Context) {
	ctx := c.Request.Context()

	f, err := s.datastore.GetFnByID(ctx, c.Param(api.FnID))
	if err != nil {
		handleErrorResponse(c, err)
		return
	}

	app, err := s.datastore.GetAppByID(ctx, f.AppID)
	if err != nil {
		handleErrorResponse(c, fmt.Errorf("unexpected error - fn app not available: %s", err))
		return
	}

	f, err = s.fnAnnotator.AnnotateFn(c, app, f)
	if err != nil {
		handleErrorResponse(c, err)
		return
	}

	c.JSON(http.StatusOK, f)
}


text:
import React from "react";

interface Props {}

const TestRoute: React.FC<Props> = props => {
  return (

Test

  );
};

export default TestRoute;


text:
describe ServiceTemplateCatalog do
  let(:root_tenant) do
    Tenant.seed
  end

  describe "#name" do
    it "is unique per tenant" do
      FactoryBot.create(:service_template_catalog, :name => "common", :tenant => root_tenant)
      expect { FactoryBot.create(:service_template_catalog, :name => "common", :tenant => root_tenant) }
        .to raise_error(ActiveRecord::RecordInvalid, /Name has already been taken/)
    end

    it "can be the same across tenants" do
      tenant1 = FactoryBot.create(:tenant, :parent => root_tenant)
      tenant2 = FactoryBot.create(:tenant, :parent => root_tenant)
      FactoryBot.create(:service_template_catalog, :name => "common", :tenant => tenant1)
      expect do
        FactoryBot.build(:service_template_catalog, :name => "common", :tenant => tenant2)
      end.not_to raise_error
    end
  end
end


text:
/**
 * Constructor
 * Document
 *
 * @see
 * @since: 2015.07.15
 * @author: hw.shim
 */

// @formatter:off
define([
    'webida-lib/plugins/workbench/ui/EditorModel',
    'webida-lib/plugins/workbench/ui/PartModel',
    'webida-lib/plugins/workbench/ui/PartModelEvent',
    'webida-lib/util/genetic',
    'webida-lib/util/logger/logger-client'
], function(
    EditorModel,
    PartModel,
    PartModelEvent,
    genetic,
    Logger
) {
    'use strict';
// @formatter:on

    /**
     * @typedef {Object} DataSource
     */

    var logger = new Logger();
    //logger.setConfig('level', Logger.LEVELS.log);
    //logger.off();

    function Document(text) {
        logger.info('new Document(' + text + ')', this);

        PartModel.call(this, text);

        if ( typeof text === 'undefined' || text === null) {
            text = '';
        }
        if ( typeof text === 'object') {
            text = text.toString();
        }

        this.setContents(text);
    }

    genetic.inherits(Document, EditorModel, {

        /**
         * From given data, build new contents for the model.
         * @param {String} data Source data to build new contents of the model.
         */
        createContents: function(data) {
            this.setContents(data);
            this.emit(PartModel.CONTENTS_CREATED, data);
        },

        /**
         * Serializes model to a string
         * For Document, just return it's working text.
         * @return {String} Serialized Data
         */
        serialize: function() {
            return this.getContents();
        },

        /**
         * @param {Object} contents
         */
        update: function(newText) {
            logger.info('update(' + newText + ')');
            var old = this.getContents();
            var modelEvent = new PartModelEvent();
            if (old !== newText) {
                this.setContents(newText);
                modelEvent.setDelta(newText);
                modelEvent.setContents(this.getContents());
                this.emit(PartModel.CONTENTS_CHANGE, modelEvent);
            }
        },

        /**
         * Alias for setContents with respect to Document
         * @param {string} text
         * @param {Viewer} [viewer]
         */
        setText: function(text, viewer) {
            this.setContents(text, viewer);
        },

        /**
         * Alias for setContents with respect to Document
         * @return {string}
         */
        getText: function() {
            return this.getContents();
        },

        /**
         * @return {number}
         */
        getLength: function() {
            return this.getContents().length;
        },

        /**
         * @return {string}
         */
        getCharAt: function(position) {
            return this.getContents().charAt(position);
        },

        /**
         * @return {number}
         */
        getNumberOfLines: function() {
            return this.getContents().split(/\r\n|\r|\n/).length;
        },

        toString: function() {
            var suffix = '';
            var res = '<' + this.constructor.name + '>#' + this._partModelId;
            if (this.getContents()) {
                if (this.getLength() > 10) {
                    suffix = '...';
                }
                res += '(' + this.getContents().substr(0, 10) + suffix + ')';
            }
            return res;
        }
    });

    return Document;
});


text:
(function() {
    "use strict";

    angular
        .module("hotelApp")
        .controller("shoppingHistoryController", shoppingHistoryController);

    shoppingHistoryController.$inject = [
        "$scope", "$location", "$timeout", "$state", "$anchorScroll",   "usSpinnerService", "currentSession",   "dialogService"
    ];

    function shoppingHistoryController($scope, $location, $timeout, $state, $anchorScroll, usSpinnerService, currentSession, dialogService) {
        var shoppingHistory = this;

        shoppingHistory.currentSession = currentSession;
        shoppingHistory.disableRenewButton = true;
        shoppingHistory.disableUpgradeableButton = true;
        shoppingHistory.disableRecissionButton = true;
        var url = "/api/v1/searchhistory?nameid=" + currentSession.identity.ice_name_id + "&agentid=" + currentSession.identity.ng_agent_id + "&allactivity=false";
        shoppingHistory.gridOptions = {
                dataSource: {
                    type: "json",
                    transport: {
                        read: url,
                        timeout: 1000
                    },
                    error: function (e) {
        // handle error
        alert(" Error Retrieving Search History - Status: " + e.status + "; Error message: " + e.errorThrown);
    },
                    schema: {
                        model: {
                            id: "searchHistory",
                            fields: {
                                activityOccurredAt : {
                                    editable: false,
                                    filterable: true,
                                    type: "date"
                                },
                                longAgo : {
                                    editable: false,
                                    filterable: false,
                                    type: "string"
                                },

                                action : {
                                    editable: false,
                                    type: "string"
                                },
                                subAction : {
                                    editable: false,
                                    type: "string"
                                },
                                name : {
                                    editable: false,
                                    type: "string"
                                },
                                browser : {
                                    editable: false,
                                    type: "string"
                                },
                                agentName : {
                                    editable: false,
                                    type: "string"
                                },
                                searchStorageId : {
                                    editable: false,
                                    type: "string"
                                }
                            }
                        }
                    }
                },
                        requestStart: function () {
                //kendo.ui.progress($("#loading"), true); <-- this works on initial load, but gives two spinners on every page or sort change
            },
            requestEnd: function () {
                //kendo.ui.progress($("#loading"), false);

            },
                sortable: true,
                filterable: true,
                pageable: false,
                columns: [
                {
                    field: "activityOccurredAt",
                    format: "{0: yyyy-MM-dd h:mm:ss tt}",
                    title: "When",
                    width: "100px",
                    filterable: true
                },
                    {
                    field: "longAgo",
                    title: "Freshness",
                    width: "60px",
                    filterable: false
                    },{
                    field: "action",
                    title: "Product",
                        filterable: true,
                    width: "40px"
                    },{
                        field: "subAction",
                        title: "Search Type",
                        filterable: true,
                    width: "100px"
                    },{
                        field: "name",
                        title: "Details",
                    width: "240px"
                    }, {
                    field: "agentName",
                    title: "Agent",
                    width: "80px",
                    filterable: false

                },{
                        field: "browser",
                        title: "Browser",
                        width: "30px",
                        filterable: false
                },
                                      { width:"30px", "template": "<kendo-button class='k-command' ng-click=\"shoppingHistory.showDetail('#=searchStorageId#')\">Detail</kendo-button>" }
                ]
        };

        shoppingHistory.showDetail = function (i) {
            var res = i.split(":");
            alert(res[0]);
        }
        shoppingHistory.refreshHistory = function() {
            shoppingHistory.shoppingHistoryGrid.dataSource.read();
        };
        function startSpin() {
            usSpinnerService.spin("spinner-1");
        };
        function stopSpin() {
            usSpinnerService.stop("spinner-1");
        };
    }
})();


text:
<!DOCTYPE html>

		<meta http-equiv="Content-type" content="text/html; charset=utf-8">
		<title>Froot Wars</title>

		<link rel="stylesheet" href="styles.css" type="text/css" media="screen" charset="utf-8">

			<canvas id="gamecanvas" width="640" height="480" class="gamelayer">
			</canvas>

				Score: 0

The Level Is Over Message

 Replay Current Level

 Play Next Level

 Return to Level Screen

		<canvas id="debugcanvas" width="1000" height="480" style="border:1px solid black;"></canvas>


text:
// CodeGarden app Services module
angular.module('codegarden.services', [])

.factory('Sessions', function($http, $q) {

  return {

    // The job of the factory is to get us the schedule
    schedule: function() {

      var isOffline = 'onLine' in navigator && !navigator.onLine,
          cached = localStorage["sessions"],
          timestamp = localStorage["timestamp"],
          duration = 60 * 60 * 1000,
          deferred = $q.defer();

      if (isOffline)
      {

        //Offline and no cached data - return empty object
        if (!cached){
          console.log('OFFline, no cache...');
          deferred.reject();

        //Offline but with cached data - return it
        } else {
          console.log('OFFline, cached data...');
          deferred.resolve(angular.fromJson(cached));
        }

      } else {

        //Online, with cached data or expired cache
        if (cached && timestamp && timestamp > new Date().getTime() - duration){
          console.log('ONline, cached data...');
          deferred.resolve(angular.fromJson(cached));

        // Online, with no or expired data
        } else {
          console.log('ONline, from umbraco...');
          data = $http
            .get('http://codegarden14.projects.growcreate.co.uk/umbraco/api/sessionapi/getschedule')
            .then(function(response){
              localStorage["sessions"] = angular.toJson(response.data);
              localStorage["timestamp"] = new Date().getTime();
              deferred.resolve(response.data);

              // Mock a server delay
              /*setTimeout(function() {
                return deferred.resolve(response.data);
              }, 3000);*/
            });
        }
      }
      return deferred.promise;
    }
  }

})
.factory('Favs', function() {

  // This factory gets and sets the favourites
  return {

    get: function(){
    	// Create an artificial 'day' to display favourites
    	return {
	        id: 0,
	        name: 'My favourites',
	        sessions: angular.fromJson(localStorage["favs"]) || []
	      };
    },

    // Save favourites in local storate
    save: function(favs){
    	localStorage["favs"] = angular.toJson(favs);
    	return true;
    }

  }

});


text:
{% extends "../index.html" %}

{% block nav %}

			Reading

	{{ parent() }}
{% endblock nav %}

{% block tabs %}

 {{ current_page.title }}

           	{{ content }}

			{% if noquiz %}

			{% else %}

Vocabulary Quiz

													This is the defintion of a term that was in this section and is pretty long

												    <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
												   Option One

												    <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
												    Option two can be something else and selecting it will deselect option one

												    <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
												    Option two can be something else and selecting it will deselect option one

												    <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
												    Option two can be something else and selecting it will deselect option one

			                                    <button class="btn btn-success btn-sm" type="button">Check Answer</button> <button class="btn btn-primary disabled btn-sm" type="button">Next Question</button>

			{% endif %}

← {{ next_page.title }}

{{ prev_page.title }} →

	{{ parent() }}

{% endblock tabs %}

{% block topscript %}

{% endblock topscript %}

{% block btmscript %}

{% endblock btmscript %}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using AwfulForumsLibrary.Managers;
using AwfulRedux.UI.Models.Smilies;
using Newtonsoft.Json;

namespace SmiliesParser
{
	class MainClass
	{
		public static void Main (string [] args)
		{
			MainAsync().GetAwaiter().GetResult();
		}

		static async Task MainAsync()
		{
			var authManager = new AuthenticationManager();

			// Set the username / password of the user.
			var username = "";
			var password = "";

			var authResult = await authManager.AuthenticateAsync(username, password);

			// Once authed, we can setup the web manager and make authed calls.
			var webManager = new WebManager(authResult.AuthenticationCookie);

			var smileManager = new SmileManager(webManager);
			var result = await smileManager.GetSmileList();
			var list = JsonConvert.DeserializeObject<List<SmileCategory>>(result.ResultJson);

            File.WriteAllText("smileList.json", JsonConvert.SerializeObject(list, Formatting.Indented));
		}
	}
}


text:
'use strict';

/* Directives */

var portalSMBDirectives = angular.module('portalSMB.directives', []);
portalSMBDirectives.directive('ngTopBannerHeight', [function() {
        return {
            link: function($scope, $element, $attr) {
                var isPadding = $attr.ngTopBannerHeight === 'padding' ? true : false;
                var bannerMaxPercent = 3.5,
                        articleHeight = isPadding ? $element[0].clientHeight : angular.element($element[0].nextElementSibling)[0].clientHeight,
                        topTitleHeight = 56;
                var height = (window.innerHeight - topTitleHeight) / 10 * bannerMaxPercent > window.innerHeight - 56 - articleHeight ? window.innerHeight - topTitleHeight - articleHeight : (window.innerHeight - 56) / 10 * bannerMaxPercent;
                if (isPadding) {
                    $element.css({'padding-top': height + 'px'});
                    return;
                }
                $element.css({'height': height + 'px'});
            }
        };
    }]);
portalSMBDirectives.directive('ngPieChart', ['d3Service', '$window', function(d3Service, $window) {
        return {
            restrict: 'EA',
            scope: {
                data: '='
            },
            link: function(scope, element, attrs) {
                d3Service.d3().then(function(d3) {
                    // Browser onresize event
                    $window.onresize = function() {
                        scope.$apply();
                    };

                    // Watch for resize event
                    scope.$watch(function() {
                        scope.render(scope.data);
                    });

                    scope.$watch('data', function(newVals, oldVals) {
                        return scope.render(newVals);
                    }, true);

                    scope.render = function(data) {
                        if (!data)
                            return;
                        var h = (angular.element(element[0])[0].clientHeight),
                                w = $window.innerWidth >= h ? h : $window.innerWidth, //width
                                r = (Math.min(w, h) / 2) * 0.95, //radius
                                color = d3.scale.ordinal()
                                .range(['#ff6600', '#ff7519', '#ff8432', '#ff934c', '#ffa366', '#ffb27f', '#ffc199', '#ffd1b2']);     //builtin range of colors
                        angular.element(element).children('*').remove();
                        var vis = d3.select((element[0]))
                                .append("svg:svg")              //create the SVG element inside the <body>
                                .data([data])                   //associate our data with the document
                                .attr("width", w)          //set the width and height of our visualization (these will be attributes of the <svg> tag
                                .attr("align", "center")
                                .attr("height", h)
                                .append("svg:g")                //make a group to hold our pie chart
                                .attr("transform", "translate(" + r + "," + r + ")");    //move the center of the pie chart from 0, 0 to radius, radius

                        var arc = d3.svg.arc().outerRadius(r);

                        var pie = d3.layout.pie()           //this will create arc data for us given a list of values
                                .value(function(d) {
                                    return d.value;
                                });    //we must tell it out to access the value of each element in our data array

                        var arcs = vis.selectAll("g.slice")     //this selects all <g> elements with class slice (there aren't any yet)
                                .data(pie)                          //associate the generated pie data (an array of arcs, each having startAngle, endAngle and value properties)
                                .enter()                            //this will create <g> elements for every "extra" data element that should be associated with a selection. The result is creating a <g> for every object in the data array
                                .append("svg:g")                //create a group to hold each slice (we will have a <path> and a <text> element associated with each slice)
                                .attr("class", "slice");    //allow us to style things in the slices (like text)

                        arcs.append("svg:path")
                                .attr("fill", function(d, i) {
                                    return color(i);
                                }) //set the color for each slice to be chosen from the color function defined above
                                .attr("d", arc);                                    //this creates the actual SVG path using the associated data (pie) with the arc drawing function

                        arcs.append("svg:text")                                     //add a label to each slice
                                .attr("transform", function(d) {                    //set the label's origin to the center of the arc
                                    //we have to make sure to set these before calling arc.centroid
                                    d.innerRadius = 0;
                                    d.outerRadius = r;
                                    return "translate(" + arc.centroid(d) + ")";        //this gives us a pair of coordinates like [50, 50]
                                })
                                .attr("text-anchor", "middle")                          //center the text on it's origin
                                .text(function(d, i) {
                                    return data[i].label;
                                });        //get the label from our original data array
                    };
                });
            }};
    }]);
portalSMBDirectives.directive('ngConnectionsMaps', ['d3Service', '$window', function(d3Service, $window) {
        return {
            restrict: 'EA',
            scope: {
                data: '='
            },
            link: function(scope, element, attrs) {
                d3Service.d3().then(function(d3) {
                    // Browser onresize event
                    $window.onresize = function() {
                        scope.$apply();
                    };
                    // Watch for resize event
                    scope.$watch(function() {
                        scope.render(scope.data);
                    });
                    scope.$watch('data', function(newVals) {
                        if (newVals !== undefined) {
                            return scope.render(newVals);
                        }
                        return false;
                    });
                    scope.render = function(data) {
                        angular.element(angular.element(element[0]).children()[0]).children().remove();

                        var minDim = function(size, type) {
                            if (!type) {
                                return Math.max(size['width'], size['height']) === size['width'] ? 'width' : 'height';
                            }
                            return Math.max(size['width'], size['height']) === size['width'] ? 'height' : 'width';
                        };

                        var margin = {top: 20, right: 20, bottom: 20, left: 20};

                        var size = {width: $window.innerWidth - margin.left - margin.right,
                            height: $window.innerHeight - 76 - margin.top - margin.bottom};
                        size[minDim(size)] = size[minDim(size, 'second')];

                        var zoom = function(d) {
                            svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
                            setTimeout(function() {
                                scope.$parent.setRefresh();
                            }, 1000);
                        };

                        var tree = d3.layout.tree()
                                .size([size['width'], size['height']]);

                        var getChildCount = function(root) {
                            var childCount = function(level, n) {
                                if (n.children && n.children.length > 0) {
                                    if (levelWidth.length <= level + 1)
                                        levelWidth.push(0);
                                    levelWidth[level + 1] += n.children.length;
                                    n.children.forEach(function(d) {
                                        childCount(level + 1, d);
                                    });
                                }
                            };
                            var levelWidth = [1];
                            childCount(0, root);
                            return levelWidth;
                        };

                        var svgArticle = angular.element(element[0]).children('article');

                        var root = data,
                                nodes = tree.nodes(root),
                                links = tree.links(nodes),
                                iconsMaxLength = getChildCount(root),
                                iconsMaxLength = iconsMaxLength[iconsMaxLength.length - 1],
                                iconsSize = (size['width'] / iconsMaxLength) - 10;

                        var iconsTranslator = {
                            "internet": "img/internet5.svg",
                            "box": "img/wireless17.svg",
                            "comp": "img/computer73.svg",
                            "phone": "img/phone35.svg",
                            "storage": "img/universal4.svg"
                        };

                        margin = {top: (iconsSize / 2) + 10, right: margin['right'], bottom: (iconsSize / 2) + 10, left: margin['left']};
                        size = {width: $window.innerWidth - margin.left - margin.right,
                            height: $window.innerHeight - 76 - margin.top - margin.bottom};

                        var diagonal = d3.svg.diagonal()
                                .source(function(d) {
                                    return {"x": d.source.x, "y": d.source.y + (iconsSize / 2)};
                                })
                                .target(function(d) {
                                    return {"x": d.target.x, "y": d.target.y - (iconsSize / 2)};
                                })
                                .projection(function(d) {
                                    return [d.x, d.y];
                                });
                        var svg = d3.select(svgArticle[0]).append("svg")
                                .attr("width", (size['width'] + margin.left + margin.right))
                                .attr("height", (size['height'] + margin.top + margin.bottom))
                                .attr("transform", "scale(2)")
                                .attr("align", "center")
                                .append("g")
                                .attr("transform", "translate(" + (margin.left*2) + "," + (margin.top*2) + "), scale(1.5)");

                        var link = svg.selectAll(".link")
                                .data(links)
                                .enter()
                                .append("path")
                                .attr("d", diagonal);

                        var node = svg.selectAll(".node")
                                .data(nodes)
                                .enter()
                                .append("g")
                                .attr("class", "node")
                                .attr("transform", function(d) {
                                    return "translate(" + d.x + "," + d.y + ")";
                                });

                        node.append("svg:image")
                                .attr('x', -(iconsSize / 2))
                                .attr('y', -(iconsSize / 2))
                                .attr('width', iconsSize)
                                .attr('height', iconsSize)
                                .attr("xlink:href", function(d) {
                                    return iconsTranslator[d.type];
                                })
                                .on("touchend", function(e) {
                                    scope.$parent.openPopUp(e);
                                });

                        setTimeout(function() {
                            scope.$parent.setRefresh();
                        }, 1000);
                    };
                });
            }};
    }]);


text:
#ifndef WEBRTC_BASE_TESTUTILS_H__
#define WEBRTC_BASE_TESTUTILS_H__

// Utilities for testing rtc infrastructure in unittests

#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>

// X defines a few macros that stomp on types that gunit.h uses.
#undef None
#undef Bool
#endif

#include <algorithm>
#include <map>
#include <memory>
#include <vector>
#include "webrtc/base/arraysize.h"
#include "webrtc/base/asyncsocket.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/gunit.h"
#include "webrtc/base/nethelpers.h"
#include "webrtc/base/pathutils.h"
#include "webrtc/base/stream.h"
#include "webrtc/base/stringencode.h"
#include "webrtc/base/stringutils.h"
#include "webrtc/base/thread.h"

namespace testing {

using namespace rtc;

///////////////////////////////////////////////////////////////////////////////
// StreamSink - Monitor asynchronously signalled events from StreamInterface
// or AsyncSocket (which should probably be a StreamInterface.
///////////////////////////////////////////////////////////////////////////////

// Note: Any event that is an error is treaded as SSE_ERROR instead of that
// event.

enum StreamSinkEvent {
  SSE_OPEN  = SE_OPEN,
  SSE_READ  = SE_READ,
  SSE_WRITE = SE_WRITE,
  SSE_CLOSE = SE_CLOSE,
  SSE_ERROR = 16
};

class StreamSink : public sigslot::has_slots<> {
 public:
  void Monitor(StreamInterface* stream) {
   stream->SignalEvent.connect(this, &StreamSink::OnEvent);
   events_.erase(stream);
  }
  void Unmonitor(StreamInterface* stream) {
   stream->SignalEvent.disconnect(this);
   // In case you forgot to unmonitor a previous object with this address
   events_.erase(stream);
  }
  bool Check(StreamInterface* stream, StreamSinkEvent event, bool reset = true) {
    return DoCheck(stream, event, reset);
  }
  int Events(StreamInterface* stream, bool reset = true) {
    return DoEvents(stream, reset);
  }

  void Monitor(AsyncSocket* socket) {
   socket->SignalConnectEvent.connect(this, &StreamSink::OnConnectEvent);
   socket->SignalReadEvent.connect(this, &StreamSink::OnReadEvent);
   socket->SignalWriteEvent.connect(this, &StreamSink::OnWriteEvent);
   socket->SignalCloseEvent.connect(this, &StreamSink::OnCloseEvent);
   // In case you forgot to unmonitor a previous object with this address
   events_.erase(socket);
  }
  void Unmonitor(AsyncSocket* socket) {
   socket->SignalConnectEvent.disconnect(this);
   socket->SignalReadEvent.disconnect(this);
   socket->SignalWriteEvent.disconnect(this);
   socket->SignalCloseEvent.disconnect(this);
   events_.erase(socket);
  }
  bool Check(AsyncSocket* socket, StreamSinkEvent event, bool reset = true) {
    return DoCheck(socket, event, reset);
  }
  int Events(AsyncSocket* socket, bool reset = true) {
    return DoEvents(socket, reset);
  }

 private:
  typedef std::map<void*,int> EventMap;

  void OnEvent(StreamInterface* stream, int events, int error) {
    if (error) {
      events = SSE_ERROR;
    }
    AddEvents(stream, events);
  }
  void OnConnectEvent(AsyncSocket* socket) {
    AddEvents(socket, SSE_OPEN);
  }
  void OnReadEvent(AsyncSocket* socket) {
    AddEvents(socket, SSE_READ);
  }
  void OnWriteEvent(AsyncSocket* socket) {
    AddEvents(socket, SSE_WRITE);
  }
  void OnCloseEvent(AsyncSocket* socket, int error) {
    AddEvents(socket, (0 == error) ? SSE_CLOSE : SSE_ERROR);
  }

  void AddEvents(void* obj, int events) {
    EventMap::iterator it = events_.find(obj);
    if (events_.end() == it) {
      events_.insert(EventMap::value_type(obj, events));
    } else {
      it->second |= events;
    }
  }
  bool DoCheck(void* obj, StreamSinkEvent event, bool reset) {
    EventMap::iterator it = events_.find(obj);
    if ((events_.end() == it) || (0 == (it->second & event))) {
      return false;
    }
    if (reset) {
      it->second &= ~event;
    }
    return true;
  }
  int DoEvents(void* obj, bool reset) {
    EventMap::iterator it = events_.find(obj);
    if (events_.end() == it)
      return 0;
    int events = it->second;
    if (reset) {
      it->second = 0;
    }
    return events;
  }

  EventMap events_;
};

///////////////////////////////////////////////////////////////////////////////
// StreamSource - Implements stream interface and simulates asynchronous
// events on the stream, without a network.  Also buffers written data.
///////////////////////////////////////////////////////////////////////////////

class StreamSource : public StreamInterface {
public:
  StreamSource() {
    Clear();
  }

  void Clear() {
    readable_data_.clear();
    written_data_.clear();
    state_ = SS_CLOSED;
    read_block_ = 0;
    write_block_ = SIZE_UNKNOWN;
  }
  void QueueString(const char* data) {
    QueueData(data, strlen(data));
  }
  void QueueStringF(const char* format, ...) {
    va_list args;
    va_start(args, format);
    char buffer[1024];
    size_t len = vsprintfn(buffer, sizeof(buffer), format, args);
    RTC_CHECK(len < sizeof(buffer) - 1);
    va_end(args);
    QueueData(buffer, len);
  }
  void QueueData(const char* data, size_t len) {
    readable_data_.insert(readable_data_.end(), data, data + len);
    if ((SS_OPEN == state_) && (readable_data_.size() == len)) {
      SignalEvent(this, SE_READ, 0);
    }
  }
  std::string ReadData() {
    std::string data;
    // avoid accessing written_data_[0] if it is undefined
    if (written_data_.size() > 0) {
      data.insert(0, &written_data_[0], written_data_.size());
    }
    written_data_.clear();
    return data;
  }
  void SetState(StreamState state) {
    int events = 0;
    if ((SS_OPENING == state_) && (SS_OPEN == state)) {
      events |= SE_OPEN;
      if (!readable_data_.empty()) {
        events |= SE_READ;
      }
    } else if ((SS_CLOSED != state_) && (SS_CLOSED == state)) {
      events |= SE_CLOSE;
    }
    state_ = state;
    if (events) {
      SignalEvent(this, events, 0);
    }
  }
  // Will cause Read to block when there are pos bytes in the read queue.
  void SetReadBlock(size_t pos) { read_block_ = pos; }
  // Will cause Write to block when there are pos bytes in the write queue.
  void SetWriteBlock(size_t pos) { write_block_ = pos; }

  virtual StreamState GetState() const { return state_; }
  virtual StreamResult Read(void* buffer, size_t buffer_len,
                            size_t* read, int* error) {
    if (SS_CLOSED == state_) {
      if (error) *error = -1;
      return SR_ERROR;
    }
    if ((SS_OPENING == state_) || (readable_data_.size() <= read_block_)) {
      return SR_BLOCK;
    }
    size_t count = std::min(buffer_len, readable_data_.size() - read_block_);
    memcpy(buffer, &readable_data_[0], count);
    size_t new_size = readable_data_.size() - count;
    // Avoid undefined access beyond the last element of the vector.
    // This only happens when new_size is 0.
    if (count < readable_data_.size()) {
      memmove(&readable_data_[0], &readable_data_[count], new_size);
    }
    readable_data_.resize(new_size);
    if (read) *read = count;
    return SR_SUCCESS;
  }
  virtual StreamResult Write(const void* data, size_t data_len,
                             size_t* written, int* error) {
    if (SS_CLOSED == state_) {
      if (error) *error = -1;
      return SR_ERROR;
    }
    if (SS_OPENING == state_) {
      return SR_BLOCK;
    }
    if (SIZE_UNKNOWN != write_block_) {
      if (written_data_.size() >= write_block_) {
        return SR_BLOCK;
      }
      if (data_len > (write_block_ - written_data_.size())) {
        data_len = write_block_ - written_data_.size();
      }
    }
    if (written) *written = data_len;
    const char* cdata = static_cast<const char*>(data);
    written_data_.insert(written_data_.end(), cdata, cdata + data_len);
    return SR_SUCCESS;
  }
  virtual void Close() { state_ = SS_CLOSED; }

private:
  typedef std::vector<char> Buffer;
  Buffer readable_data_, written_data_;
  StreamState state_;
  size_t read_block_, write_block_;
};

///////////////////////////////////////////////////////////////////////////////
// SocketTestClient
// Creates a simulated client for testing.  Works on real and virtual networks.
///////////////////////////////////////////////////////////////////////////////

class SocketTestClient : public sigslot::has_slots<> {
public:
 SocketTestClient() { Init(nullptr, AF_INET); }
 SocketTestClient(AsyncSocket* socket) {
   Init(socket, socket->GetLocalAddress().family());
  }
  SocketTestClient(const SocketAddress& address) {
    Init(nullptr, address.family());
    socket_->Connect(address);
  }

  AsyncSocket* socket() { return socket_.get(); }

  void QueueString(const char* data) {
    QueueData(data, strlen(data));
  }
  void QueueStringF(const char* format, ...) {
    va_list args;
    va_start(args, format);
    char buffer[1024];
    size_t len = vsprintfn(buffer, sizeof(buffer), format, args);
    RTC_CHECK(len < sizeof(buffer) - 1);
    va_end(args);
    QueueData(buffer, len);
  }
  void QueueData(const char* data, size_t len) {
    send_buffer_.insert(send_buffer_.end(), data, data + len);
    if (Socket::CS_CONNECTED == socket_->GetState()) {
      Flush();
    }
  }
  std::string ReadData() {
    std::string data(&recv_buffer_[0], recv_buffer_.size());
    recv_buffer_.clear();
    return data;
  }

  bool IsConnected() const {
    return (Socket::CS_CONNECTED == socket_->GetState());
  }
  bool IsClosed() const {
    return (Socket::CS_CLOSED == socket_->GetState());
  }

private:
  typedef std::vector<char> Buffer;

  void Init(AsyncSocket* socket, int family) {
    if (!socket) {
      socket = Thread::Current()->socketserver()
          ->CreateAsyncSocket(family, SOCK_STREAM);
    }
    socket_.reset(socket);
    socket_->SignalConnectEvent.connect(this,
      &SocketTestClient::OnConnectEvent);
    socket_->SignalReadEvent.connect(this, &SocketTestClient::OnReadEvent);
    socket_->SignalWriteEvent.connect(this, &SocketTestClient::OnWriteEvent);
    socket_->SignalCloseEvent.connect(this, &SocketTestClient::OnCloseEvent);
  }

  void Flush() {
    size_t sent = 0;
    while (sent < send_buffer_.size()) {
      int result = socket_->Send(&send_buffer_[sent],
                                 send_buffer_.size() - sent);
      if (result > 0) {
        sent += result;
      } else {
        break;
      }
    }
    size_t new_size = send_buffer_.size() - sent;
    memmove(&send_buffer_[0], &send_buffer_[sent], new_size);
    send_buffer_.resize(new_size);
  }

  void OnConnectEvent(AsyncSocket* socket) {
    if (!send_buffer_.empty()) {
      Flush();
    }
  }
  void OnReadEvent(AsyncSocket* socket) {
    char data[64 * 1024];
    int result = socket_->Recv(data, arraysize(data), nullptr);
    if (result > 0) {
      recv_buffer_.insert(recv_buffer_.end(), data, data + result);
    }
  }
  void OnWriteEvent(AsyncSocket* socket) {
    if (!send_buffer_.empty()) {
      Flush();
    }
  }
  void OnCloseEvent(AsyncSocket* socket, int error) {
  }

  std::unique_ptr<AsyncSocket> socket_;
  Buffer send_buffer_, recv_buffer_;
};

///////////////////////////////////////////////////////////////////////////////
// SocketTestServer
// Creates a simulated server for testing.  Works on real and virtual networks.
///////////////////////////////////////////////////////////////////////////////

class SocketTestServer : public sigslot::has_slots<> {
 public:
  SocketTestServer(const SocketAddress& address)
      : socket_(Thread::Current()->socketserver()
                ->CreateAsyncSocket(address.family(), SOCK_STREAM))
  {
    socket_->SignalReadEvent.connect(this, &SocketTestServer::OnReadEvent);
    socket_->Bind(address);
    socket_->Listen(5);
  }
  virtual ~SocketTestServer() {
    clear();
  }

  size_t size() const { return clients_.size(); }
  SocketTestClient* client(size_t index) const { return clients_[index]; }
  SocketTestClient* operator[](size_t index) const { return client(index); }

  void clear() {
    for (size_t i=0; i<clients_.size(); ++i) {
      delete clients_[i];
    }
    clients_.clear();
  }

 private:
  void OnReadEvent(AsyncSocket* socket) {
    AsyncSocket* accepted = static_cast<AsyncSocket*>(socket_->Accept(nullptr));
    if (!accepted)
      return;
    clients_.push_back(new SocketTestClient(accepted));
  }

  std::unique_ptr<AsyncSocket> socket_;
  std::vector<SocketTestClient*> clients_;
};

///////////////////////////////////////////////////////////////////////////////
// Unittest predicates which are similar to STREQ, but for raw memory
///////////////////////////////////////////////////////////////////////////////

inline AssertionResult CmpHelperMemEq(const char* expected_expression,
                                      const char* expected_length_expression,
                                      const char* actual_expression,
                                      const char* actual_length_expression,
                                      const void* expected,
                                      size_t expected_length,
                                      const void* actual,
                                      size_t actual_length)
{
  if ((expected_length == actual_length)
      && (0 == memcmp(expected, actual, expected_length))) {
    return AssertionSuccess();
  }

  Message msg;
  msg << "Value of: " << actual_expression
      << " [" << actual_length_expression << "]";
  if (true) {  //!actual_value.Equals(actual_expression)) {
    size_t buffer_size = actual_length * 2 + 1;
    char* buffer = STACK_ARRAY(char, buffer_size);
    hex_encode(buffer, buffer_size,
               reinterpret_cast<const char*>(actual), actual_length);
    msg << "\n  Actual: " << buffer << " [" << actual_length << "]";
  }

  msg << "\nExpected: " << expected_expression
      << " [" << expected_length_expression << "]";
  if (true) {  //!expected_value.Equals(expected_expression)) {
    size_t buffer_size = expected_length * 2 + 1;
    char* buffer = STACK_ARRAY(char, buffer_size);
    hex_encode(buffer, buffer_size,
               reinterpret_cast<const char*>(expected), expected_length);
    msg << "\nWhich is: " << buffer << " [" << expected_length << "]";
  }

  return AssertionFailure(msg);
}

#define EXPECT_MEMEQ(expected, expected_length, actual, actual_length) \
  EXPECT_PRED_FORMAT4(::testing::CmpHelperMemEq, expected, expected_length, \
                      actual, actual_length)

#define ASSERT_MEMEQ(expected, expected_length, actual, actual_length) \
  ASSERT_PRED_FORMAT4(::testing::CmpHelperMemEq, expected, expected_length, \
                      actual, actual_length)

///////////////////////////////////////////////////////////////////////////////
// Helpers for initializing constant memory with integers in a particular byte
// order
///////////////////////////////////////////////////////////////////////////////

#define BYTE_CAST(x) static_cast<uint8_t>((x)&0xFF)

// Declare a N-bit integer as a little-endian sequence of bytes
#define LE16(x) BYTE_CAST(((uint16_t)x) >> 0), BYTE_CAST(((uint16_t)x) >> 8)

#define LE32(x) \
  BYTE_CAST(((uint32_t)x) >> 0), BYTE_CAST(((uint32_t)x) >> 8), \
      BYTE_CAST(((uint32_t)x) >> 16), BYTE_CAST(((uint32_t)x) >> 24)

#define LE64(x) \
  BYTE_CAST(((uint64_t)x) >> 0), BYTE_CAST(((uint64_t)x) >> 8),       \
      BYTE_CAST(((uint64_t)x) >> 16), BYTE_CAST(((uint64_t)x) >> 24), \
      BYTE_CAST(((uint64_t)x) >> 32), BYTE_CAST(((uint64_t)x) >> 40), \
      BYTE_CAST(((uint64_t)x) >> 48), BYTE_CAST(((uint64_t)x) >> 56)

// Declare a N-bit integer as a big-endian (Internet) sequence of bytes
#define BE16(x) BYTE_CAST(((uint16_t)x) >> 8), BYTE_CAST(((uint16_t)x) >> 0)

#define BE32(x) \
  BYTE_CAST(((uint32_t)x) >> 24), BYTE_CAST(((uint32_t)x) >> 16), \
      BYTE_CAST(((uint32_t)x) >> 8), BYTE_CAST(((uint32_t)x) >> 0)

#define BE64(x) \
  BYTE_CAST(((uint64_t)x) >> 56), BYTE_CAST(((uint64_t)x) >> 48),     \
      BYTE_CAST(((uint64_t)x) >> 40), BYTE_CAST(((uint64_t)x) >> 32), \
      BYTE_CAST(((uint64_t)x) >> 24), BYTE_CAST(((uint64_t)x) >> 16), \
      BYTE_CAST(((uint64_t)x) >> 8), BYTE_CAST(((uint64_t)x) >> 0)

// Declare a N-bit integer as a this-endian (local machine) sequence of bytes
#ifndef BIG_ENDIAN
#define BIG_ENDIAN 1
#endif  // BIG_ENDIAN

#if BIG_ENDIAN
#define TE16 BE16
#define TE32 BE32
#define TE64 BE64
#else  // !BIG_ENDIAN
#define TE16 LE16
#define TE32 LE32
#define TE64 LE64
#endif  // !BIG_ENDIAN

///////////////////////////////////////////////////////////////////////////////

// Helpers for determining if X/screencasting is available (on linux).

#define MAYBE_SKIP_SCREENCAST_TEST() \
  if (!testing::IsScreencastingAvailable()) { \
    LOG(LS_WARNING) << "Skipping test, since it doesn't have the requisite " \
                    << "X environment for screen capture."; \
    return; \
  } \

#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
struct XDisplay {
  XDisplay() : display_(XOpenDisplay(nullptr)) {}
  ~XDisplay() { if (display_) XCloseDisplay(display_); }
  bool IsValid() const { return display_ != nullptr; }
  operator Display*() { return display_; }
 private:
  Display* display_;
};
#endif

// Returns true if screencasting is available. When false, anything that uses
// screencasting features may fail.
inline bool IsScreencastingAvailable() {
#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
  XDisplay display;
  if (!display.IsValid()) {
    LOG(LS_WARNING) << "No X Display available.";
    return false;
  }
  int ignored_int, major_version, minor_version;
  if (!XRRQueryExtension(display, &ignored_int, &ignored_int) ||
      !XRRQueryVersion(display, &major_version, &minor_version) ||
      major_version < 1 ||
      (major_version < 2 && minor_version < 3)) {
    LOG(LS_WARNING) << "XRandr version: " << major_version << "."
                    << minor_version;
    LOG(LS_WARNING) << "XRandr is not supported or is too old (pre 1.3).";
    return false;
  }
#endif
  return true;
}
}  // namespace testing

#endif  // WEBRTC_BASE_TESTUTILS_H__


text:
extern crate mg_settings;
#[macro_use]
extern crate mg_settings_macros;

#[derive(Commands)]
pub enum AppCommand {
    #[help(text="Show the text in the label")]
    Show(String),
    Quit,
}

#[derive(Settings)]
pub struct AppSettings {
    boolean: bool,
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>Wyatt-STM: WSTM::Internal::WStmOpVoid< Trans_t, Op_t > Struct Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Wyatt-STM
    1.0.0

Software transactional memory system developed at Wyatt Technology

Main Page

Modules

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

WSTM

Internal

WStmOpVoid

Public Member Functions |
Public Attributes |
List of all members

WSTM::Internal::WStmOpVoid< Trans_t, Op_t > Struct Template Reference

Inheritance diagram for WSTM::Internal::WStmOpVoid< Trans_t, Op_t >:

  <map id="WSTM::Internal::WStmOpVoid< Trans_t, Op_t >_map" name="WSTM::Internal::WStmOpVoid< Trans_t, Op_t >_map">
<area href="struct_w_s_t_m_1_1_internal_1_1_w_stm_op.html" alt="WSTM::Internal::WStmOp< Trans_t >" shape="rect" coords="0,0,279,24"/>
</map>

Public Member Functions

 	WStmOpVoid (Op_t &op)

virtual void 	Run (Trans_t &t) override

Public Attributes

Op_t & 	m_op

Detailed Description

template<typename Trans_t, typename Op_t>

struct WSTM::Internal::WStmOpVoid< Trans_t, Op_t >

Definition at line 681 of file stm.h.

The documentation for this struct was generated from the following file:

C:/projects/Wyatt-STM/wstm/stm.h

<address class="footer">
Generated by

 1.8.10
</address>


text:
package com.yammer.dropwizard.config;

import com.google.common.collect.ImmutableMultimap;
import org.eclipse.jetty.servlet.FilterHolder;

import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Strings.isNullOrEmpty;

/**
 * The configuration for a servlet {@link javax.servlet.Filter}.
 */
public class FilterConfiguration {
    private final FilterHolder holder;
    private final ImmutableMultimap.Builder<String, FilterHolder> mappings;

    /**
     * Creates a new {@link FilterConfiguration}.
     *
     * @param holder   the {@link FilterHolder} containing the {@link javax.servlet.Filter}
     * @param mappings the mappings of URL patterns to {@link javax.servlet.Filter}s
     */
    public FilterConfiguration(FilterHolder holder,
                               ImmutableMultimap.Builder<String, FilterHolder> mappings) {
        this.holder = holder;
        this.mappings = mappings;
    }

    /**
     * Sets the filter's name.
     *
     * @param name the name of the filter
     * @return {@code this}
     */
    public FilterConfiguration setName(String name) {
        checkArgument(!isNullOrEmpty(name), "name must be non-empty");
        holder.setName(name);
        return this;
    }

    /**
     * Sets the given filter initialization parameter.
     *
     * @param name  the name of the initialization parameter
     * @param value the value of the parameter
     * @return {@code this}
     */
    public FilterConfiguration setInitParam(String name, String value) {
        holder.setInitParameter(checkNotNull(name), checkNotNull(value));
        return this;
    }

    /**
     * Sets the given filter initialization parameters.
     *
     * @param params the initialization parameters
     * @return {@code this}
     */
    public FilterConfiguration addInitParams(Map<String, String> params) {
        for (Map.Entry<String, String> entry : checkNotNull(params).entrySet()) {
            setInitParam(entry.getKey(), entry.getValue());
        }
        return this;
    }

    /**
     * Adds the given URL pattern as a filter mapping.
     *
     * @param urlPattern the URL pattern
     * @return {@code this}
     */
    public FilterConfiguration addUrlPattern(String urlPattern) {
        mappings.put(checkNotNull(urlPattern), holder);
        return this;
    }

    /**
     * Adds the given URL patterns as a filter mappings.
     *
     * @param urlPattern  the URL pattern
     * @param urlPatterns additional URL patterns
     * @return {@code this}
     */
    public FilterConfiguration addUrlPatterns(String urlPattern, String... urlPatterns) {
        addUrlPattern(checkNotNull(urlPattern));
        for (String pattern : checkNotNull(urlPatterns)) {
            addUrlPattern(checkNotNull(pattern));
        }
        return this;
    }
}


text:
get '/reports/:report_id' do
	@report = Report.find(params[:report_id])
	@report_creator = User.find(@report.user_id)
	# if request.xhr?
	# 	content_type :json
	# 	{report: @report}.to_json
	# else
	# 	redirect '/'
	# end
	erb :new_comment
end

post '/reports/:report_id/new_comment' do
	id = params[:report_id]
	comment = Comment.new(content: params[:content])
	comment.user_id = session[:user_id]
	comment.report_id = params[:report_id]
	comment.save
	# redirect '/'
	redirect "/reports/#{id}"
end


text:
@interface InstallerTypeSourceListItemMO ()

// Private interface goes here.

@end

@implementation InstallerTypeSourceListItemMO

// Custom logic goes here.

@end


text:
//********************************************************************
//*
//* Warning: This file was generated by ecore4CPP Generator
//*
//********************************************************************

#ifndef PSCS_SEMANTICSPACKAGE_HPP
#define PSCS_SEMANTICSPACKAGE_HPP

// namespace macro header include
#include "PSCS/PSCS.hpp"

#include "ecore/EPackage.hpp"

namespace ecore
{
	class EParameter;
	class EEnumLiteral;
	class EEnum;
	class EOperation;
	class EDataType;
	class EPackage;
	class EAnnotation;
	class EClass;
	class EReference;
	class EStringToStringMapEntry;
	class EAttribute;
	class EGenericType;
}

namespace PSCS::Semantics
{
	namespace Actions
	{
		class ActionsPackage;
	}

	namespace Classification
	{
		class ClassificationPackage;
	}

	namespace CommonBehavior
	{
		class CommonBehaviorPackage;
	}

	namespace Loci
	{
		class LociPackage;
	}

	namespace StructuredClassifiers
	{
		class StructuredClassifiersPackage;
	}

	namespace Values
	{
		class ValuesPackage;
	}

}

namespace PSCS::Semantics
{
	/*!
	The Metamodel Package for the Semantics metamodel. This package is used to enable the reflection of model elements. It contains all model elements
	which were described in an ecore file.
	*/

	class PSCS_API SemanticsPackage : virtual public ecore::EPackage
	{
		private:
			SemanticsPackage(SemanticsPackage const&) = delete;
			SemanticsPackage& operator=(SemanticsPackage const&) = delete;

		protected:
			SemanticsPackage(){}

		public:
			//static variables
			static const std::string eNAME;
			static const std::string eNS_URI;
			static const std::string eNS_PREFIX;

			virtual std::shared_ptr<PSCS::Semantics::Actions::ActionsPackage> getActions_Package() const = 0;
			virtual std::shared_ptr<PSCS::Semantics::Classification::ClassificationPackage> getClassification_Package() const = 0;
			virtual std::shared_ptr<PSCS::Semantics::CommonBehavior::CommonBehaviorPackage> getCommonBehavior_Package() const = 0;
			virtual std::shared_ptr<PSCS::Semantics::Loci::LociPackage> getLoci_Package() const = 0;
			virtual std::shared_ptr<PSCS::Semantics::StructuredClassifiers::StructuredClassifiersPackage> getStructuredClassifiers_Package() const = 0;
			virtual std::shared_ptr<PSCS::Semantics::Values::ValuesPackage> getValues_Package() const = 0;

			//Singleton Instance and Getter
			private:
				static std::shared_ptr<SemanticsPackage> instance;
			public:
				static std::shared_ptr<SemanticsPackage> eInstance();
	};
}
#endif /* end of include guard: PSCS_SEMANTICSPACKAGE_HPP */