text:
====================================
HTTP & WebSocket ASGI Message Format
====================================

**Version**: 2.3 (2021-02-02)

The HTTP+WebSocket ASGI sub-specification outlines how to transport HTTP/1.1,
HTTP/2 and WebSocket connections within ASGI.

It is deliberately intended and designed to be a superset of the WSGI format
and specifies how to translate between the two for the set of requests that
are able to be handled by WSGI.

Spec Versions
-------------

This spec has had three versions:

* ``2.0``: The first version of the spec, released with ASGI 2.0
* ``2.1``: Added the ``headers`` key to the WebSocket Accept response
* ``2.2``: Allow ``None`` in the second item of ``server`` scope value.
* ``2.3``: Added the ``reason`` key to the WebSocket close event.

Spec versions let you understand what the server you are using understands. If
a server tells you it only supports version ``2.0`` of this spec, then
sending ``headers`` with a WebSocket Accept message is an error, for example.

They are separate from the HTTP version or the ASGI version.

HTTP
----

The HTTP format covers HTTP/1.0, HTTP/1.1 and HTTP/2, as the changes in
HTTP/2 are largely on the transport level. A protocol server should give
different scopes to different requests on the same HTTP/2 connection, and
correctly multiplex the responses back to the same stream in which they came.
The HTTP version is available as a string in the scope.

Multiple header fields with the same name are complex in HTTP. RFC 7230
states that for any header field that can appear multiple times, it is exactly
equivalent to sending that header field only once with all the values joined by
commas.

However, RFC 7230 and RFC 6265 make it clear that this rule does not apply to
the various headers used by HTTP cookies (``Cookie`` and ``Set-Cookie``). The
``Cookie`` header must only be sent once by a user-agent, but the
``Set-Cookie`` header may appear repeatedly and cannot be joined by commas.
The ASGI design decision is to transport both request and response headers as
lists of 2-element ``[name, value]`` lists and preserve headers exactly as they
were provided.

The HTTP protocol should be signified to ASGI applications with a ``type``
value of ``http``.

HTTP Connection Scope
'''''''''''''''''''''

HTTP connections have a single-request *connection scope* - that is, your
application will be called at the start of the request, and will last until
the end of that specific request, even if the underlying socket is still open
and serving multiple requests.

If you hold a response open for long-polling or similar, the *connection scope*
will persist until the response closes from either the client or server side.

The *connection scope* information passed in ``scope`` contains:

* ``type`` (*Unicode string*) -- ``"http"``.

* ``asgi["version"]`` (*Unicode string*) -- Version of the ASGI spec.

* ``asgi["spec_version"]`` (*Unicode string*) -- Version of the ASGI
  HTTP spec this server understands; one of ``"2.0"``, ``"2.1"``, ``"2.2"`` or
  ``"2.3"``. Optional; if missing assume ``2.0``.

* ``http_version`` (*Unicode string*) -- One of ``"1.0"``, ``"1.1"`` or ``"2"``.

* ``method`` (*Unicode string*) -- The HTTP method name, uppercased.

* ``scheme`` (*Unicode string*) -- URL scheme portion (likely ``"http"`` or
  ``"https"``). Optional (but must not be empty); default is ``"http"``.

* ``path`` (*Unicode string*) -- HTTP request target excluding any query
  string, with percent-encoded sequences and UTF-8 byte sequences
  decoded into characters.

* ``raw_path`` (*byte string*) -- The original HTTP path component
  unmodified from the bytes that were received by the web server. Some
  web server implementations may be unable to provide this. Optional;
  if missing defaults to ``None``.

* ``query_string`` (*byte string*) -- URL portion after the ``?``,
  percent-encoded.

* ``root_path`` (*Unicode string*) -- The root path this application
  is mounted at; same as ``SCRIPT_NAME`` in WSGI. Optional; if missing
  defaults to ``""``.

* ``headers`` (*Iterable[[byte string, byte string]]*) -- An iterable of
  ``[name, value]`` two-item iterables, where ``name`` is the header name, and
  ``value`` is the header value. Order of header values must be preserved from
  the original HTTP request; order of header names is not important. Duplicates
  are possible and must be preserved in the message as received. Header names
  should be lowercased, but it is not required; servers should preserve header case
  on a best-effort basis. Pseudo headers (present in HTTP/2 and HTTP/3) must be
  removed; if ``:authority`` is present its value must be added to the start of
  the iterable with ``host`` as the header name or replace any existing host
  header already present.

* ``client`` (*Iterable[Unicode string, int]*) -- A two-item iterable
  of ``[host, port]``, where ``host`` is the remote host's IPv4 or
  IPv6 address, and ``port`` is the remote port as an
  integer. Optional; if missing defaults to ``None``.

* ``server`` (*Iterable[Unicode string, Optional[int]]*) -- Either a
  two-item iterable of ``[host, port]``, where ``host`` is the
  listening address for this server, and ``port`` is the integer
  listening port, or ``[path, None]`` where ``path`` is that of the
  unix socket. Optional; if missing defaults to ``None``.

Servers are responsible for handling inbound and outbound chunked transfer
encodings. A request with a ``chunked`` encoded body should be automatically
de-chunked by the server and presented to the application as plain body bytes;
a response that is given to the server with no ``Content-Length`` may be chunked
as the server sees fit.

Request - ``receive`` event
'''''''''''''''''''''''''''

Sent to the application to indicate an incoming request. Most of the request
information is in the connection ``scope``; the body message serves as a way to
stream large incoming HTTP bodies in chunks, and as a trigger to actually run
request code (as you should not trigger on a connection opening alone).

Note that if the request is being sent using ``Transfer-Encoding: chunked``,
the server is responsible for handling this encoding. The ``http.request``
messages should contain just the decoded contents of each chunk.

Keys:

* ``type`` (*Unicode string*) -- ``"http.request"``.

* ``body`` (*byte string*) -- Body of the request. Optional; if
  missing defaults to ``b""``. If ``more_body`` is set, treat as start
  of body and concatenate on further chunks.

* ``more_body`` (*bool*) -- Signifies if there is additional content
  to come (as part of a Request message). If ``True``, the consuming
  application should wait until it gets a chunk with this set to
  ``False``. If ``False``, the request is complete and should be
  processed. Optional; if missing defaults to ``False``.

Response Start - ``send`` event
'''''''''''''''''''''''''''''''

Sent by the application to start sending a response to the client. Needs to be
followed by at least one response content message. The protocol server must not
start sending the response to the client until it has received at least one
*Response Body* event.

You may send a ``Transfer-Encoding`` header in this message, but the server
must ignore it. Servers handle ``Transfer-Encoding`` themselves, and may opt
to use ``Transfer-Encoding: chunked`` if the application presents a response
that has no ``Content-Length`` set.

Note that this is not the same as ``Content-Encoding``, which the application
still controls, and which is the appropriate place to set ``gzip`` or other
compression flags.

Keys:

* ``type`` (*Unicode string*) -- ``"http.response.start"``.

* ``status`` (*int*) -- HTTP status code.

* ``headers`` (*Iterable[[byte string, byte string]]*) -- An iterable
  of ``[name, value]`` two-item iterables, where ``name`` is the
  header name, and ``value`` is the header value. Order must be
  preserved in the HTTP response.  Header names must be
  lowercased. Optional; if missing defaults to an empty list. Pseudo
  headers (present in HTTP/2 and HTTP/3) must not be present.

* ``trailers`` (*bool*) -- Signifies if the application will send
  trailers. If ``True``, the server must wait until it receives a
  ``"http.response.trailers"`` message after the *Response Body* event.
  Optional; if missing defaults to ``False``.

Response Body - ``send`` event
''''''''''''''''''''''''''''''

Continues sending a response to the client. Protocol servers must
flush any data passed to them into the send buffer before returning from a
send call. If ``more_body`` is set to ``False``, and the server is not
expecting *Response Trailers* this will close the connection.

Keys:

* ``type`` (*Unicode string*) -- ``"http.response.body"``.

* ``body`` (*byte string*) -- HTTP body content. Concatenated onto any
  previous ``body`` values sent in this connection scope. Optional; if
  missing defaults to ``b""``.

* ``more_body`` (*bool*) -- Signifies if there is additional content
  to come (as part of a *Response Body* message). If ``False``, and the
  server is not expecting *Response Trailers* response will be taken as
  complete and closed, and any further messages on the channel will be
  ignored. Optional; if missing defaults to ``False``.

Disconnect - ``receive`` event
''''''''''''''''''''''''''''''

Sent to the application if receive is called after a response has been
sent or after the HTTP connection has been closed. This is mainly useful
for long-polling, where you may want to trigger cleanup code if the
connection closes early.

Keys:

* ``type`` (*Unicode string*) -- ``"http.disconnect"``.

WebSocket
---------

WebSockets share some HTTP details - they have a path and headers - but also
have more state. Again, most of that state is in the ``scope``, which will live
as long as the socket does.

WebSocket protocol servers should handle PING/PONG messages themselves, and
send PING messages as necessary to ensure the connection is alive.

WebSocket protocol servers should handle message fragmentation themselves,
and deliver complete messages to the application.

The WebSocket protocol should be signified to ASGI applications with
a ``type`` value of ``websocket``.

Websocket Connection Scope
''''''''''''''''''''''''''

WebSocket connections' scope lives as long as the socket itself - if the
application dies the socket should be closed, and vice-versa.

The *connection scope* information passed in ``scope`` contains initial connection
metadata (mostly from the HTTP request line and headers):

* ``type`` (*Unicode string*) -- ``"websocket"``.

* ``asgi["version"]`` (*Unicode string*) -- The version of the ASGI spec.

* ``asgi["spec_version"]`` (*Unicode string*) -- Version of the ASGI
  HTTP spec this server understands; one of ``"2.0"``, ``"2.1"``, ``"2.2"`` or
  ``"2.3"``. Optional; if missing assume ``"2.0"``.

* ``http_version`` (*Unicode string*) -- One of ``"1.1"`` or
  ``"2"``. Optional; if missing default is ``"1.1"``.

* ``scheme`` (*Unicode string*) -- URL scheme portion (likely ``"ws"`` or
  ``"wss"``). Optional (but must not be empty); default is ``"ws"``.

* ``path`` (*Unicode string*) -- HTTP request target excluding any query
  string, with percent-encoded sequences and UTF-8 byte sequences
  decoded into characters.

* ``raw_path`` (*byte string*) -- The original HTTP path component
  unmodified from the bytes that were received by the web server. Some
  web server implementations may be unable to provide this. Optional;
  if missing defaults to ``None``.

* ``query_string`` (*byte string*) -- URL portion after the
  ``?``. Optional; if missing or ``None`` default is empty string.

* ``root_path`` (*Unicode string*) -- The root path this application is
  mounted at; same as ``SCRIPT_NAME`` in WSGI. Optional; if missing
  defaults to empty string.

* ``headers`` (*Iterable[[byte string, byte string]]*) -- An iterable of
  ``[name, value]`` two-item iterables, where ``name`` is the header name and
  ``value`` is the header value. Order should be preserved from the original
  HTTP request; duplicates are possible and must be preserved in the message
  as received. Header names should be lowercased, but it is not required;
  servers should preserve header case on a best-effort basis.
  Pseudo headers (present in HTTP/2 and HTTP/3) must be removed;
  if ``:authority`` is present its value must be added to the
  start of the iterable with ``host`` as the header name
  or replace any existing host header already present.

* ``client`` (*Iterable[Unicode string, int]*) -- A two-item iterable
  of ``[host, port]``, where ``host`` is the remote host's IPv4 or
  IPv6 address, and ``port`` is the remote port. Optional; if missing
  defaults to ``None``.

* ``server`` (*Iterable[Unicode string, Optional[int]]*) -- Either a
  two-item iterable of ``[host, port]``, where ``host`` is the
  listening address for this server, and ``port`` is the integer
  listening port, or ``[path, None]`` where ``path`` is that of the
  unix socket. Optional; if missing defaults to ``None``.

* ``subprotocols`` (*Iterable[Unicode string]*) -- Subprotocols the
  client advertised. Optional; if missing defaults to empty list.

Connect - ``receive`` event
'''''''''''''''''''''''''''

Sent to the application when the client initially opens a connection and is about
to finish the WebSocket handshake.

This message must be responded to with either an *Accept* message
or a *Close* message before the socket will pass ``websocket.receive``
messages. The protocol server must send this message
during the handshake phase of the WebSocket and not complete the handshake
until it gets a reply, returning HTTP status code ``403`` if the connection is
denied.

Keys:

* ``type`` (*Unicode string*) -- ``"websocket.connect"``.

Accept - ``send`` event
'''''''''''''''''''''''

Sent by the application when it wishes to accept an incoming connection.

* ``type`` (*Unicode string*) -- ``"websocket.accept"``.

* ``subprotocol`` (*Unicode string*) -- The subprotocol the server
  wishes to accept. Optional; if missing defaults to ``None``.

* ``headers`` (*Iterable[[byte string, byte string]]*) -- An iterable
  of ``[name, value]`` two-item iterables, where ``name`` is the
  header name, and ``value`` is the header value. Order must be
  preserved in the HTTP response.  Header names must be
  lowercased. Must not include a header named
  ``sec-websocket-protocol``; use the ``subprotocol`` key
  instead. Optional; if missing defaults to an empty list. *Added in
  spec version 2.1*. Pseudo headers (present in HTTP/2 and HTTP/3)
  must not be present.

Receive - ``receive`` event
'''''''''''''''''''''''''''

Sent to the application when a data message is received from the client.

Keys:

* ``type`` (*Unicode string*) -- ``"websocket.receive"``.

* ``bytes`` (*byte string*) -- The message content, if it was binary
  mode, or ``None``. Optional; if missing, it is equivalent to
  ``None``.

* ``text`` (*Unicode string*) -- The message content, if it was text
  mode, or ``None``. Optional; if missing, it is equivalent to
  ``None``.

Exactly one of ``bytes`` or ``text`` must be non-``None``. One or both
keys may be present, however.

Send - ``send`` event
'''''''''''''''''''''

Sent by the application to send a data message to the client.

Keys:

* ``type`` (*Unicode string*) -- ``"websocket.send"``.

* ``bytes`` (*byte string*) -- Binary message content, or ``None``.
   Optional; if missing, it is equivalent to ``None``.

* ``text`` (*Unicode string*) -- Text message content, or ``None``.
   Optional; if missing, it is equivalent to ``None``.

Exactly one of ``bytes`` or ``text`` must be non-``None``. One or both
keys may be present, however.

.. _disconnect-receive-event-ws:

Disconnect - ``receive`` event
''''''''''''''''''''''''''''''

Sent to the application when either connection to the client is lost, either from
the client closing the connection, the server closing the connection, or loss of the
socket.

Keys:

* ``type`` (*Unicode string*) -- ``"websocket.disconnect"``

* ``code`` (*int*) -- The WebSocket close code, as per the WebSocket spec. If no code
  was received in the frame from the client, the server should set this to ``1005``
  (the default value in the WebSocket specification).

Close - ``send`` event
''''''''''''''''''''''

Sent by the application to tell the server to close the connection.

If this is sent before the socket is accepted, the server
must close the connection with a HTTP 403 error code
(Forbidden), and not complete the WebSocket handshake; this may present on some
browsers as a different WebSocket error code (such as 1006, Abnormal Closure).

If this is sent after the socket is accepted, the server must close the socket
with the close code passed in the message (or 1000 if none is specified).

* ``type`` (*Unicode string*) -- ``"websocket.close"``.

* ``code`` (*int*) -- The WebSocket close code, as per the WebSocket
  spec.  Optional; if missing defaults to ``1000``.

* ``reason`` (*Unicode string*) -- A reason given for the closure, can
  be any string. Optional; if missing or ``None`` default is empty
  string.

WSGI Compatibility
------------------

Part of the design of the HTTP portion of this spec is to make sure it
aligns well with the WSGI specification, to ensure easy adaptability
between both specifications and the ability to keep using WSGI
applications with ASGI servers.

WSGI applications, being synchronous, must be run in a threadpool in order
to be served, but otherwise their runtime maps onto the HTTP connection scope's
lifetime.

There is an almost direct mapping for the various special keys in
WSGI's ``environ`` variable to the ``http`` scope:

* ``REQUEST_METHOD`` is the ``method``
* ``SCRIPT_NAME`` is ``root_path``
* ``PATH_INFO`` can be derived by stripping ``root_path`` from ``path``
* ``QUERY_STRING`` is ``query_string``
* ``CONTENT_TYPE`` can be extracted from ``headers``
* ``CONTENT_LENGTH`` can be extracted from ``headers``
* ``SERVER_NAME`` and ``SERVER_PORT`` are in ``server``
* ``REMOTE_HOST``/``REMOTE_ADDR`` and ``REMOTE_PORT`` are in ``client``
* ``SERVER_PROTOCOL`` is encoded in ``http_version``
* ``wsgi.url_scheme`` is ``scheme``
* ``wsgi.input`` is a ``StringIO`` based around the ``http.request`` messages
* ``wsgi.errors`` is directed by the wrapper as needed

The ``start_response`` callable maps similarly to ``http.response.start``:

* The ``status`` argument becomes ``status``, with the reason phrase dropped.
* ``response_headers`` maps to ``headers``

Yielding content from the WSGI application maps to sending
``http.response.body`` messages.

WSGI encoding differences
-------------------------

The WSGI specification (as defined in PEP 3333) specifies that all strings
sent to or from the server must be of the ``str`` type but only contain
codepoints in the ISO-8859-1 ("latin-1") range. This was due to it originally
being designed for Python 2 and its different set of string types.

The ASGI HTTP and WebSocket specifications instead specify each entry of the
``scope`` dict as either a byte string or a Unicode string. HTTP, being an
older protocol, is sometimes imperfect at specifying encoding, so some
decisions of what is Unicode versus bytes may not be obvious.

* ``path``: URLs can have both percent-encoded and UTF-8 encoded sections.
  Because decoding these is often done by the underlying server (or sometimes
  even proxies in the path), this is a Unicode string, fully decoded from both
  UTF-8 encoding and percent encodings.

* ``headers``: These are byte strings of the exact byte sequences sent by the
  client/to be sent by the server. While modern HTTP standards say that headers
  should be ASCII, older ones did not and allowed a wider range of characters.
  Frameworks/applications should decode headers as they deem appropriate.

* ``query_string``: Unlike the ``path``, this is not as subject to server
  interference and so is presented as its raw byte string version,
  percent-encoded.

* ``root_path``: Unicode string to match ``path``.

Version History
---------------

* 2.0 (2017-11-28): Initial non-channel-layer based ASGI spec

Copyright
---------

This document has been placed in the public domain.


text:
using System;
using System.Collections.Generic;
using System.Reflection.Metadata;
using System.Text;
using Microsoft.CodeAnalysis;
using Pchp.CodeAnalysis.CodeGen;
using Pchp.CodeAnalysis.Semantics.TypeRef;
using Pchp.CodeAnalysis.Symbols;

namespace Pchp.CodeAnalysis.Semantics
{
    internal static class BoundTypeRefExtensions
    {
        public static ITypeSymbol EmitLoadTypeInfo(this IBoundTypeRef tref, CodeGenerator cg, bool throwOnError = false) => ((BoundTypeRef)tref).EmitLoadTypeInfo(cg, throwOnError);

        public static void EmitClassName(this IBoundTypeRef tref, CodeGenerator cg)
        {
            if (tref is BoundIndirectTypeRef it)
            {
                it.EmitClassName(cg);
            }
            else if (tref is BoundClassTypeRef ct)
            {
                cg.Builder.EmitStringConstant(ct.ClassName.ToString());
            }
            else
            {
                // Template: {LOAD PhpTypeInfo}.Name
                tref.EmitLoadTypeInfo(cg, true);
                cg.EmitCall(ILOpCode.Call, cg.CoreMethods.Operators.GetName_PhpTypeInfo.Getter)
                    .Expect(SpecialType.System_String);
            }
        }

        /// <summary>
        /// Gets <see cref="TypeSymbol"/> suitable to be used for the runtime operations.
        /// Does not return <c>null</c> nor <see cref="ErrorTypeSymbol"/>.
        /// </summary>
        public static TypeSymbol ResolveRuntimeType(this IBoundTypeRef tref, PhpCompilation compilation)
        {
            var boundType = (BoundTypeRef)tref;

            var t = boundType.ResolvedType ?? (TypeSymbol)boundType.ResolveTypeSymbol(compilation);

            if (t.IsErrorTypeOrNull()) // error type => class could not be found
            {
                if (t is AmbiguousErrorTypeSymbol ambiguous)
                {
                    // ambiguity -> try to find a common base
                    var common = compilation.FindCommonBase(ambiguous._candidates);
                    if (common.IsValidType())
                    {

                        return common;
                    }
                }

                t = compilation.CoreTypes.Object.Symbol;
            }

            return t;
        }

        /// <summary>
        /// Gets value indicating the <paramref name="tref"/> represents <c>self</c> keyword.
        /// </summary>
        public static bool IsSelf(this IBoundTypeRef tref) => tref is BoundReservedTypeRef reserved && reserved.ReservedType == Devsense.PHP.Syntax.Ast.ReservedTypeRef.ReservedType.self;

        /// <summary>
        /// Gets value indicating the <paramref name="tref"/> represents <c>parent</c> keyword.
        /// </summary>
        public static bool IsParent(this IBoundTypeRef tref) => tref is BoundReservedTypeRef reserved && reserved.ReservedType == Devsense.PHP.Syntax.Ast.ReservedTypeRef.ReservedType.parent;

        /// <summary>
        /// Gets value indicating the <paramref name="tref"/> represents <c>static</c> keyword.
        /// </summary>
        public static bool IsStatic(this IBoundTypeRef tref) => tref is BoundReservedTypeRef reserved && reserved.ReservedType == Devsense.PHP.Syntax.Ast.ReservedTypeRef.ReservedType.@static;
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""Deploys Fuchsia packages to a package repository in a Fuchsia
build output directory."""

import pkg_repo
import argparse
import os
import sys

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--package',
                      action='append',
                      required=True,
                      help='Paths to packages to install.')
  parser.add_argument('--fuchsia-out-dir',
                      required=True,
                      help='Path to a Fuchsia build output directory. '
                      'Setting the GN arg '
                      '"default_fuchsia_build_dir_for_installation" '
                      'will cause it to be passed here.')
  args, _ = parser.parse_known_args()
  assert args.package

  fuchsia_out_dir = os.path.expanduser(args.fuchsia_out_dir)
  repo = pkg_repo.ExternalPkgRepo(os.path.join(fuchsia_out_dir, 'amber-files'),
                                  os.path.join(fuchsia_out_dir, '.build-id'))
  print('Installing packages and symbols in package repo %s...' %
        repo.GetPath())

  for package in args.package:
    repo.PublishPackage(package)

  print('Installation success.')

  return 0

if __name__ == '__main__':
  sys.exit(main())


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Message',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('handle', models.TextField()),
                ('message', models.TextField()),
                ('timestamp', models.DateTimeField(db_index=True, default=django.utils.timezone.now)),
            ],
        ),
        migrations.CreateModel(
            name='Room',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.TextField()),
                ('label', models.SlugField(unique=True)),
            ],
        ),
        migrations.AddField(
            model_name='message',
            name='room',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to='chat.Room'),
        ),
    ]


text:
#ifndef MONGOC_TOPOLOGY_DESCRIPTION_H
#define MONGOC_TOPOLOGY_DESCRIPTION_H

#include <bson.h>
#include "mongoc-read-prefs.h"

typedef struct _mongoc_topology_description_t mongoc_topology_description_t;

BSON_API
bool                          mongoc_topology_description_has_readable_server (mongoc_topology_description_t       *td,
                                                                               const mongoc_read_prefs_t           *prefs);
BSON_API
bool                          mongoc_topology_description_has_writable_server (mongoc_topology_description_t       *td);
BSON_API
const char                   *mongoc_topology_description_type                (const mongoc_topology_description_t *td);
BSON_API
mongoc_server_description_t **mongoc_topology_description_get_servers         (const mongoc_topology_description_t *td,
                                                                               size_t                              *n);

#endif /* MONGOC_TOPOLOGY_DESCRIPTION_H */


text:
NSString* const OEXExternalRegistrationWithExistingAccountNotification = @"OEXExternalRegistrationWithExistingAccountNotification";

@interface OEXRegistrationViewController () <OEXExternalRegistrationOptionsViewDelegate>

/// Contents are id <OEXRegistrationFieldController>
@property (strong, nonatomic) NSArray* fieldControllers;

@property (strong, nonatomic) IBOutlet UIScrollView* scrollView;

// Used in auth from an external provider
@property (strong, nonatomic) UIView* currentHeadingView;
@property (strong, nonatomic) id <OEXExternalAuthProvider> externalProvider;
@property (copy, nonatomic) NSString* externalAccessToken;

@property (strong, nonatomic) UIButton* registerButton;
@property (strong, nonatomic) UILabel* agreementLabel;
@property (strong, nonatomic) UIButton* agreementLink;
@property (strong, nonatomic) UIButton* toggleOptionalFieldsButton;
@property (strong, nonatomic) UIImageView* optionalFieldsSeparator;
@property (strong, nonatomic) UIActivityIndicatorView* progressIndicator;

@property (assign, nonatomic) BOOL isShowingOptionalFields;

@property (strong, nonatomic) OEXRegistrationStyles* styles;
@property (nonatomic) OEXMutableTextStyle *buttonsTitleStyle;

@end

@implementation OEXRegistrationViewController

- (id)initWithEnvironment:(RouterEnvironment *)environment {
    self = [super initWithNibName:nil bundle:nil];
    if(self != nil) {
        self.environment = environment;
        self.styles = [[OEXRegistrationStyles alloc] init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.loadController = [[LoadStateViewController alloc] init];
    [self.loadController setupInController:self contentView:self.scrollView];

    self.navigationController.navigationBarHidden = NO;

    [self setTitle:[Strings registerText]];

    UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_cancel"] style:UIBarButtonItemStylePlain target:self action:@selector(navigateBack:)];
    closeButton.accessibilityLabel = [Strings close];
    self.navigationItem.leftBarButtonItem = closeButton;

    //By default we only shows required fields
    self.isShowingOptionalFields = NO;

    _buttonsTitleStyle = [[OEXMutableTextStyle alloc] initWithWeight:OEXTextWeightBold size:OEXTextSizeBase color:[self.environment.styles primaryBaseColor]];

    [self getFormFields];
}

- (void)getFormFields {

    [self getRegistrationFormDescription:^(OEXRegistrationDescription * _Nonnull response) {
        self.registrationDescription = response;
        [self makeFieldControllers];
        [self initializeViews];
        [self refreshFormFields];
    }];
}

//Currently using asset file only to get from description
- (void)makeFieldControllers {
    NSArray* fields = self.registrationDescription.registrationFormFields;
    self.fieldControllers = [fields oex_map:^id < OEXRegistrationFieldController > (OEXRegistrationFormField* formField)
                             {
                                 id <OEXRegistrationFieldController> fieldController = [OEXRegistrationFieldControllerFactory registrationFieldViewController:formField];
                                 if(formField.fieldType == OEXRegistrationFieldTypeAgreement) {
                                     // These don't have explicit representations in the apps
                                     return nil;
                                 }
                                 return fieldController;
                             }];
}

// This method will set default ui.

- (void)initializeViews {

    NSString* platform = self.environment.config.platformName;

    ////Create and initalize 'btnCreateAccount' button
    self.registerButton = [[UIButton alloc] init];

    [self.registerButton oex_addAction:^(id  _Nonnull control) {
        [self createAccount:nil];
    } forEvents:UIControlEventTouchUpInside];

    [self.registerButton applyButtonStyle:[self.environment.styles filledPrimaryButtonStyle] withTitle:[Strings registrationCreateMyAccount]];
    self.registerButton.accessibilityIdentifier = @"register";

    ////Create progrssIndicator as subview to btnCreateAccount
    self.progressIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    [self.registerButton addSubview:self.progressIndicator];
    [self.progressIndicator hidesWhenStopped];
    self.optionalFieldsSeparator = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"separator3"]];
    //Initialize label above agreement view
    self.agreementLabel = [[UILabel alloc] init];
    self.agreementLabel.font = [self.environment.styles sansSerifOfSize:10.f];
    self.agreementLabel.textAlignment = NSTextAlignmentCenter;
    self.agreementLabel.numberOfLines = 0;
    self.agreementLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.agreementLabel.isAccessibilityElement = NO;
    self.agreementLabel.text = [Strings registrationAgreementMessage];
    self.agreementLink = [[UIButton alloc] init];
    [self.agreementLink setTitle:[Strings registrationAgreementButtonTitleWithPlatformName:platform] forState:UIControlStateNormal];
    [self.agreementLink.titleLabel setFont:[self.environment.styles semiBoldSansSerifOfSize:10]];
    [self.agreementLink setTitleColor:[UIColor colorWithRed:0.16 green:0.44 blue:0.84 alpha:1] forState:UIControlStateNormal];
    self.agreementLink.accessibilityTraits = UIAccessibilityTraitLink;
    self.agreementLink.titleLabel.adjustsFontSizeToFitWidth = YES;
    self.agreementLink.titleLabel.textAlignment = NSTextAlignmentCenter;

    [self.agreementLink oex_addAction:^(id  _Nonnull control) {
        [self agreementButtonTapped:nil];
    } forEvents:UIControlEventTouchUpInside];
    self.agreementLink.accessibilityLabel = [NSString stringWithFormat:@"%@ %@",[Strings registrationAgreementMessage],[Strings registrationAgreementButtonTitleWithPlatformName:platform]];

    //This button will show and hide optional fields
    self.toggleOptionalFieldsButton = [[UIButton alloc] init];
    [self.toggleOptionalFieldsButton setBackgroundColor:[UIColor whiteColor]];
    [self.toggleOptionalFieldsButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [self.toggleOptionalFieldsButton setTitle:[Strings registrationShowOptionalFields]  forState:UIControlStateNormal];
    [self.toggleOptionalFieldsButton.titleLabel setFont:[self.environment.styles semiBoldSansSerifOfSize:14.0]];

    [self.toggleOptionalFieldsButton addTarget:self action:@selector(toggleOptionalFields:) forControlEvents:UIControlEventTouchUpInside];

    UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc] init];
    [tapGesture addTarget:self action:@selector(scrollViewTapped:)];
    [self.scrollView addGestureRecognizer:tapGesture];

    NSMutableArray* providers = [[NSMutableArray alloc] init];
    if(self.environment.config.googleConfig.enabled) {
        [providers addObject:[[OEXGoogleAuthProvider alloc] init]];
    }
    if(self.environment.config.facebookConfig.enabled) {
        [providers addObject:[[OEXFacebookAuthProvider alloc] init]];
    }
    if(providers.count > 0) {
        OEXExternalRegistrationOptionsView* headingView = [[OEXExternalRegistrationOptionsView alloc] initWithFrame:CGRectZero providers:providers];
        headingView.delegate = self;
        [self useHeadingView:headingView];
    }
}

- (void)useHeadingView:(UIView*)headingView {
    [self.currentHeadingView removeFromSuperview];
    self.currentHeadingView = headingView;
    [self.scrollView addSubview:self.currentHeadingView];
    [self.view setNeedsUpdateConstraints];
    [self.view setNeedsLayout];
}

- (IBAction)navigateBack:(id)sender {
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    // Scrolling on keyboard hide and show
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardFrameChanged:)
                                                 name:UIKeyboardWillChangeFrameNotification object:nil];
    //Analytics Screen record
    [self.environment.analytics trackScreenWithName:OEXAnalyticsScreenRegister];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    // This  will remove observer for keyboard
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (BOOL)shouldFilterField:(OEXRegistrationFormField*)field {
    return self.externalProvider != nil && [field.name isEqualToString:@"password"];
}

- (void)refreshFormFields {
    for(id <OEXRegistrationFieldController>fieldController in self.fieldControllers) {
        // Add view to scroll view if field is not optional and it is not agreement field.
        UIView* view = fieldController.view;
        if(fieldController.field.isRequired && ![self shouldFilterField:fieldController.field]) {
            [self.scrollView addSubview:view];
            [view setNeedsLayout];
            [view layoutIfNeeded];
        }
        else {
            [view removeFromSuperview];
        }
    }

    // Actually show the optional fields if necessary
    if(self.isShowingOptionalFields) {
        for(id <OEXRegistrationFieldController>fieldController in self.fieldControllers) {
            if(![fieldController field].isRequired && ![self shouldFilterField:fieldController.field]) {
                UIView* view = fieldController.view;
                [self.scrollView addSubview:view];
                [view setNeedsLayout];
                [view layoutIfNeeded];
            }
        }
    }
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
    UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil);
}

- (void)updateViewConstraints {
    CGFloat margin = self.styles.formMargin;
    [self.currentHeadingView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView);
        make.centerX.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView).offset(-2 * margin);
    }];
    [super updateViewConstraints];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    // Add space if the heading view won't do it for us
    NSInteger topSpacing = self.currentHeadingView == nil ? 10 : 0;
    NSInteger horizontalSpacing = self.styles.formMargin;
    NSInteger offset = 0;
    CGFloat width = self.scrollView.frame.size.width;
    NSInteger contentWidth = width - 2 * horizontalSpacing;

    // Force the heading view to layout, so we get its height
    [self.currentHeadingView setNeedsLayout];
    [self.currentHeadingView layoutIfNeeded];

    // Then do it again since we may have updated the preferred size of some text
    [self.currentHeadingView setNeedsLayout];

    //Setting offset as topspacing
    CGSize size = [self.currentHeadingView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    offset = topSpacing + size.height;

    BOOL isOptionalFieldPresent = NO;

    for(id <OEXRegistrationFieldController>fieldController in self.fieldControllers) {
        UIView* view = fieldController.view;
        // Add view to scroll view if field is not optional and it is not agreement field.
        if([fieldController field].isRequired && view.superview != nil) {
            [view layoutIfNeeded];
            [view setFrame:CGRectMake(0, offset, width, view.frame.size.height)];
            offset = offset + view.frame.size.height;
        }
        if(![fieldController field].isRequired) {
            isOptionalFieldPresent = YES;
        }
    }

    if (isOptionalFieldPresent) {
        //Add the optional field toggle
        CGFloat buttonWidth = 150;
        CGFloat buttonHeight = 30;
        [self.scrollView addSubview:self.optionalFieldsSeparator];
        [self.toggleOptionalFieldsButton setFrame:CGRectMake(self.view.frame.size.width / 2 - buttonWidth / 2, offset, buttonWidth, buttonHeight)];
        [self.scrollView addSubview:self.toggleOptionalFieldsButton];
        self.optionalFieldsSeparator.frame = CGRectMake(horizontalSpacing, self.toggleOptionalFieldsButton.center.y, contentWidth, 1);
        self.optionalFieldsSeparator.center = self.toggleOptionalFieldsButton.center;

        offset = offset + buttonHeight + 10;
    }

    // Actually show the optional fields if necessary
    for(id <OEXRegistrationFieldController>fieldController in self.fieldControllers) {
        UIView* view = fieldController.view;
        if(![fieldController field].isRequired && view.superview != nil) {
            [view layoutIfNeeded];
            [view setFrame:CGRectMake(0, offset, width, view.frame.size.height)];
            [self.scrollView addSubview:view];
            offset = offset + view.frame.size.height;
        }
    }

    [self.registerButton setFrame:CGRectMake(horizontalSpacing, offset, contentWidth, 40)];

    const int progressIndicatorCenterX = [self isRTL] ? 40 : self.registerButton.frame.size.width - 40;

    self.progressIndicator.center = CGPointMake(progressIndicatorCenterX, self.registerButton.frame.size.height / 2);

    [self.scrollView addSubview:self.registerButton];
    offset = offset + 40;

    NSInteger buttonLabelSpacing = 10;

    [self.agreementLabel setFrame:CGRectMake(horizontalSpacing, offset + buttonLabelSpacing, width - 2 * horizontalSpacing, 20)];
    [self.scrollView addSubview:self.agreementLabel];
    offset = offset + self.agreementLabel.frame.size.height;
    [self.scrollView addSubview:self.agreementLink];
    [self.agreementLink setFrame:CGRectMake(horizontalSpacing, offset, contentWidth, 40)];
    offset = offset + self.agreementLink.frame.size.height;
    [self.scrollView setContentSize:CGSizeMake(width, offset)];
}

//This method will hide and unhide optional fields
//using isRequired flag for corresponding field.

- (void)toggleOptionalFields:(id)sender {
    self.isShowingOptionalFields = !self.isShowingOptionalFields;
    if(self.isShowingOptionalFields) {
        [self.toggleOptionalFieldsButton setTitle:[Strings registrationHideOptionalFields] forState:UIControlStateNormal];
    }
    else {
        [self.toggleOptionalFieldsButton setTitle:[Strings registrationShowOptionalFields] forState:UIControlStateNormal];
    }

    [self refreshFormFields];
}

#pragma mark ExternalRegistrationOptionsDelegate

- (void)optionsView:(OEXExternalRegistrationOptionsView *)view choseProvider:(id<OEXExternalAuthProvider>)provider {
    [provider authorizeServiceFromController:self requestingUserDetails:YES withCompletion:^(NSString *accessToken, OEXRegisteringUserDetails *userProfile, NSError *error) {
        if(error == nil) {
            [view beginIndicatingActivity];
            self.view.userInteractionEnabled = NO;
            [self attemptExternalLoginWithProvider:provider token:accessToken completion:^(NSData* data, NSHTTPURLResponse* response, NSError *error) {
                [view endIndicatingActivity];
                self.view.userInteractionEnabled = YES;
                if(response.statusCode == OEXHTTPStatusCode200OK) {
                    [self.delegate registrationViewControllerDidRegister:self completion: ^{
                        // Need to show on login screen that we already had an account
                        [[NSNotificationCenter defaultCenter] postNotificationName:OEXExternalRegistrationWithExistingAccountNotification object:provider.displayName];
                    }];
                }
                else {
                    // No account already, so continue registration process
                    UIView* headingView = [[OEXUsingExternalAuthHeadingView alloc] initWithFrame:CGRectZero serviceName:provider.displayName];
                    [self useHeadingView:headingView];
                    [self receivedFields:userProfile fromProvider:provider withAccessToken:accessToken];
                }
            }];
        }
        else if([error oex_isNoInternetConnectionError]){
            [view endIndicatingActivity];
            [[OEXFlowErrorViewController sharedInstance] showNoConnectionErrorOnView:self.view];
        }
        else {
            [view endIndicatingActivity];
            // Do nothing. Typically this happens because the user hits cancel and so they know it didn't work already
        }
    }];
}

- (void)receivedFields:(OEXRegisteringUserDetails*)profile fromProvider:(id <OEXExternalAuthProvider>)provider withAccessToken:(NSString*)accessToken {
    self.externalAccessToken = accessToken;
    self.externalProvider = provider;
    // Long term, we should update the registration.json description to provide this mapping.
    // We will need to do this if we ever transition to fetching that from the server
    for(id <OEXRegistrationFieldController> controller in self.fieldControllers) {
        if([[controller field].name isEqualToString:@"email"]) {
            [controller takeValue:profile.email];
        }
        if([[controller field].name isEqualToString:@"name"]) {
            [controller takeValue:profile.name];
        }
        if([[controller field].name isEqualToString:@"year_of_birth"]) {
            [controller takeValue:profile.birthYear];
        }
    }
    [self refreshFormFields];
}

- (void)attemptExternalLoginWithProvider:(id <OEXExternalAuthProvider>)provider token:(NSString*)token completion:(void(^)(NSData* data, NSHTTPURLResponse* response, NSError* error))completion {
    [OEXAuthentication requestTokenWithProvider:provider externalToken:token completion:completion];
}

#pragma mark IBAction

- (void)registerWithParameters:(NSDictionary*)parameters {
    __weak id weakSelf = self;
    [self showProgress:YES];

    [self.environment.analytics trackRegistrationWithProvider:self.externalProvider.backendName];

    [OEXAuthentication registerUserWithParameters:parameters completionHandler:^(NSData* data, NSURLResponse* response, NSError* error) {
        if(!error) {
            NSDictionary* dictionary = [NSJSONSerialization oex_JSONObjectWithData:data error:&error];
            OEXLogInfo(@"REGISTRATION", @"Register user response ==>> %@", dictionary);
            NSHTTPURLResponse* httpResp = (NSHTTPURLResponse*) response;

            void(^completion)(NSData*, NSURLResponse*, NSError*) = ^(NSData* data, NSURLResponse* response, NSError* error){
                NSHTTPURLResponse* httpResp = (NSHTTPURLResponse*) response;
                if(httpResp.statusCode == OEXHTTPStatusCode200OK) {
                    [self.delegate registrationViewControllerDidRegister:weakSelf completion:nil];
                }
                else if([error oex_isNoInternetConnectionError]) {
                    [[OEXFlowErrorViewController sharedInstance] showNoConnectionErrorOnView:self.view];
                }
                [self showProgress:NO];
            };

            if(httpResp.statusCode == OEXHTTPStatusCode200OK) {
                if(self.externalProvider == nil) {
                    NSString* username = parameters[@"username"];
                    NSString* password = parameters[@"password"];
                    [OEXAuthentication requestTokenWithUser:username password:password completionHandler:completion];
                }
                else {
                    [self attemptExternalLoginWithProvider:self.externalProvider token:self.externalAccessToken completion:completion];
                }

            }
            else {
                NSMutableDictionary* controllers = [[NSMutableDictionary alloc] init];
                for(id <OEXRegistrationFieldController> controller in self.fieldControllers) {
                    [controllers safeSetObject:controller forKey:controller.field.name];
                    [controller handleError:nil];
                }
                [dictionary enumerateKeysAndObjectsUsingBlock:^(NSString* fieldName, NSArray* errorInfos, BOOL* stop) {
                    id <OEXRegistrationFieldController> controller = controllers[fieldName];
                    NSArray* errorStrings = [errorInfos oex_map:^id (NSDictionary* info) {
                        return [[OEXRegistrationFieldError alloc] initWithDictionary:info].userMessage;
                    }];

                    NSString* errors = [errorStrings componentsJoinedByString:@" "];
                    [controller handleError:errors];
                }];
                [self showProgress:NO];
                [self refreshFormFields];
            }
        }
        else {
            if([error oex_isNoInternetConnectionError]) {
                NSString* title = [Strings networkNotAvailableTitle];
                NSString* message = [Strings networkNotAvailableMessage];
                [[OEXFlowErrorViewController sharedInstance] showErrorWithTitle:title message:message onViewController:self.view shouldHide:YES];
            }
            [self showProgress:NO];
        }
    }];
}

- (IBAction)createAccount:(id)sender {
    // Clear error for all views
    [self.fieldControllers makeObjectsPerformSelector:@selector(handleError:) withObject:nil];
    // Dictionary for registration parameters
    NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
    BOOL hasError = NO;

    for(id <OEXRegistrationFieldController> controller in self.fieldControllers) {
        if([controller isValidInput]) {
            if([controller hasValue]) {
                [parameters safeSetObject:[controller currentValue] forKey:[controller field].name];
            }
        }
        else if(![self shouldFilterField:controller.field]){
            hasError = YES;
        }
    }

    if(hasError) {
        [self showProgress:NO];
        [self refreshFormFields];
        return;
    }
    //Setting parameter 'honor_code'='true'
    [parameters setObject:@"true" forKey:@"honor_code"];

    //As user is agree to the license setting 'terms_of_service'='true'
    [parameters setObject:@"true" forKey:@"terms_of_service"];

    if(self.externalProvider != nil) {
        [parameters safeSetObject:self.externalAccessToken forKey: @"access_token"];
        [parameters safeSetObject:self.externalProvider.backendName forKey:@"provider"];
        [parameters safeSetObject:self.environment.config.oauthClientID forKey:@"client_id"];
    }

    [self registerWithParameters:parameters];

}

- (void)scrollViewTapped:(id)sender {
    [self.view endEditing:YES];
}

- (void)agreementButtonTapped:(id)sender {
    NSURL* url = [[NSBundle mainBundle] URLForResource:@"Terms-and-Services" withExtension:@"htm"];
    OEXUserLicenseAgreementViewController* viewController = [[OEXUserLicenseAgreementViewController alloc] initWithContentURL:url];
    [self presentViewController:viewController animated:YES completion:nil];
}

- (void)showProgress:(BOOL)status {
    if(status) {
        [self.progressIndicator startAnimating];
        [self.registerButton applyButtonStyle:[self.environment.styles filledPrimaryButtonStyle] withTitle:[Strings registrationCreatingAccount]];
        [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    }
    else {
        [self.progressIndicator stopAnimating];
        [self.registerButton applyButtonStyle:[self.environment.styles filledPrimaryButtonStyle] withTitle:[Strings registrationCreateMyAccount]];
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return self.environment.styles.standardStatusBarStyle;
}

- (BOOL) shouldAutorotate {
    return false;
}

- (UIInterfaceOrientationMask) supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

#pragma mark - Scolling on Keyboard Hide/Show

// Called when the UIKeyboardDidChangeFrameNotification is sent.
- (void)keyboardFrameChanged:(NSNotification*)notification {
    CGRect globalFrame = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect localFrame = [self.view convertRect:globalFrame fromView:nil];
    CGRect intersection = CGRectIntersection(localFrame, self.view.bounds);
    CGFloat keyboardHeight = intersection.size.height;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardHeight, 0.0);
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;
}

- (BOOL) isRTL {
    return [UIApplication sharedApplication].userInterfaceLayoutDirection == UIUserInterfaceLayoutDirectionRightToLeft;
}

@end

@implementation OEXRegistrationViewController (Testing)

- (OEXRegistrationDescription*)t_registrationFormDescription {
    return self.registrationDescription;
}

- (NSUInteger)t_visibleFieldCount {
    NSIndexSet* visibleIndexes = [self.fieldControllers indexesOfObjectsPassingTest:^BOOL (id < OEXRegistrationFieldController > controller, NSUInteger idx, BOOL* stop) {
        return controller.view.superview != nil;
    }];
    return visibleIndexes.count;
}

- (void)t_toggleOptionalFields {
    [self toggleOptionalFields:nil];
}

- (void)t_registerWithParameters:(NSDictionary*)parameters {
    [self registerWithParameters:parameters];
}

@end


text:
require_relative '../../api1600/c7000/volume'

module OneviewSDK
  module API1800
    module C7000
      # Volume resource implementation on API1800 C7000
      class Volume < OneviewSDK::API1600::C7000::Volume
      end
    end
  end
end


text:
namespace blink {

PresentationController::PresentationController(LocalFrame& frame,
                                               WebPresentationClient* client)
    : Supplement<LocalFrame>(frame),
      ContextLifecycleObserver(frame.document()),
      m_client(client) {
  if (m_client)
    m_client->setController(this);
}

PresentationController::~PresentationController() {
  if (m_client)
    m_client->setController(nullptr);
}

// static
PresentationController* PresentationController::create(
    LocalFrame& frame,
    WebPresentationClient* client) {
  return new PresentationController(frame, client);
}

// static
const char* PresentationController::supplementName() {
  return "PresentationController";
}

// static
PresentationController* PresentationController::from(LocalFrame& frame) {
  return static_cast<PresentationController*>(
      Supplement<LocalFrame>::from(frame, supplementName()));
}

// static
void PresentationController::provideTo(LocalFrame& frame,
                                       WebPresentationClient* client) {
  Supplement<LocalFrame>::provideTo(
      frame, PresentationController::supplementName(),
      PresentationController::create(frame, client));
}

WebPresentationClient* PresentationController::client() {
  return m_client;
}

DEFINE_TRACE(PresentationController) {
  visitor->trace(m_presentation);
  visitor->trace(m_connections);
  Supplement<LocalFrame>::trace(visitor);
  ContextLifecycleObserver::trace(visitor);
}

void PresentationController::didStartDefaultSession(
    const WebPresentationSessionInfo& sessionInfo) {
  if (!m_presentation || !m_presentation->defaultRequest())
    return;
  PresentationConnection::take(this, sessionInfo,
                               m_presentation->defaultRequest());
}

void PresentationController::didChangeSessionState(
    const WebPresentationSessionInfo& sessionInfo,
    WebPresentationConnectionState state) {
  PresentationConnection* connection = findConnection(sessionInfo);
  if (!connection)
    return;
  connection->didChangeState(state);
}

void PresentationController::didCloseConnection(
    const WebPresentationSessionInfo& sessionInfo,
    WebPresentationConnectionCloseReason reason,
    const WebString& message) {
  PresentationConnection* connection = findConnection(sessionInfo);
  if (!connection)
    return;
  connection->didClose(reason, message);
}

void PresentationController::didReceiveSessionTextMessage(
    const WebPresentationSessionInfo& sessionInfo,
    const WebString& message) {
  PresentationConnection* connection = findConnection(sessionInfo);
  if (!connection)
    return;
  connection->didReceiveTextMessage(message);
}

void PresentationController::didReceiveSessionBinaryMessage(
    const WebPresentationSessionInfo& sessionInfo,
    const uint8_t* data,
    size_t length) {
  PresentationConnection* connection = findConnection(sessionInfo);
  if (!connection)
    return;
  connection->didReceiveBinaryMessage(data, length);
}

void PresentationController::setPresentation(Presentation* presentation) {
  m_presentation = presentation;
}

void PresentationController::setDefaultRequestUrl(
    const WTF::Vector<KURL>& urls) {
  if (!m_client)
    return;

  WebVector<WebURL> presentationUrls(urls.size());
  for (size_t i = 0; i < urls.size(); ++i) {
    if (urls[i].isValid())
      presentationUrls[i] = urls[i];
  }

  m_client->setDefaultPresentationUrls(presentationUrls);
}

void PresentationController::registerConnection(
    PresentationConnection* connection) {
  m_connections.add(connection);
}

void PresentationController::contextDestroyed(ExecutionContext*) {
  if (m_client) {
    m_client->setController(nullptr);
    m_client = nullptr;
  }
}

PresentationConnection* PresentationController::findExistingConnection(
    const blink::WebVector<blink::WebURL>& presentationUrls,
    const blink::WebString& presentationId) {
  for (const auto& connection : m_connections) {
    for (const auto& presentationUrl : presentationUrls) {
      if (connection->getState() !=
              WebPresentationConnectionState::Terminated &&
          connection->matches(presentationId, presentationUrl)) {
        return connection.get();
      }
    }
  }
  return nullptr;
}

PresentationConnection* PresentationController::findConnection(
    const WebPresentationSessionInfo& sessionInfo) {
  for (const auto& connection : m_connections) {
    if (connection->matches(sessionInfo))
      return connection.get();
  }

  return nullptr;
}

}  // namespace blink


text:
using System;
using System.Collections.Concurrent;
using System.Net;

namespace LaCore.Hyperion.Adapters.QuickBloxIntegration
{
    public static class Log4NetExtensions
    {
        static ConcurrentDictionary<string, DateTime> deadList = new ConcurrentDictionary<string, DateTime>();

        public static void LogWebException(this log4net.ILog log, string server, string message, WebException ex, double timeoutThreshholdInMinutes = 60)
        {
            var now = DateTime.UtcNow;
            if (ex.Status == WebExceptionStatus.Timeout)
            {
                DateTime timeoutSince;
                if (!deadList.TryGetValue(server, out timeoutSince))
                {
                    timeoutSince = now;
                    deadList.AddOrUpdate(server, now, (key, val) => timeoutSince);
                }
                else if (timeoutSince.AddMinutes(timeoutThreshholdInMinutes) <= now)
                {
                    log.Error("Frequent timeouts detected for '" + server + "' since " + timeoutSince, ex);
                    deadList.TryRemove(server, out timeoutSince);
                }
            }
        }
    }
}


text:
package list

import "bytes"

// Container is base interface that all data structures implement.
type Container interface {
	Empty() bool
	Size() int
	Clear()
	Values() []*bytes.Buffer
}

// GetSortedValues returns sorted container's elements with respect to the passed comparator.
// Does not effect the ordering of elements within the container.
func GetSortedValues(container Container, comparator Comparator) []*bytes.Buffer {
	values := container.Values()
	if len(values) < 2 {
		return values
	}
	Sort(values, comparator)
	return values
}


text:
#pragma once
#include <aws/serverlessrepo/ServerlessApplicationRepository_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace ServerlessApplicationRepository
{
namespace Model
{

  /**
   *
An application version summary.

See Also:
   AWS
   * API Reference

   */
  class AWS_SERVERLESSAPPLICATIONREPOSITORY_API VersionSummary
  {
  public:
    VersionSummary();
    VersionSummary(Aws::Utils::Json::JsonView jsonValue);
    VersionSummary& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The application Amazon Resource Name (ARN).

     */
    inline const Aws::String& GetApplicationId() const{ return m_applicationId; }

    /**
     *
The application Amazon Resource Name (ARN).

     */
    inline void SetApplicationId(const Aws::String& value) { m_applicationIdHasBeenSet = true; m_applicationId = value; }

    /**
     *
The application Amazon Resource Name (ARN).

     */
    inline void SetApplicationId(Aws::String&& value) { m_applicationIdHasBeenSet = true; m_applicationId = std::move(value); }

    /**
     *
The application Amazon Resource Name (ARN).

     */
    inline void SetApplicationId(const char* value) { m_applicationIdHasBeenSet = true; m_applicationId.assign(value); }

    /**
     *
The application Amazon Resource Name (ARN).

     */
    inline VersionSummary& WithApplicationId(const Aws::String& value) { SetApplicationId(value); return *this;}

    /**
     *
The application Amazon Resource Name (ARN).

     */
    inline VersionSummary& WithApplicationId(Aws::String&& value) { SetApplicationId(std::move(value)); return *this;}

    /**
     *
The application Amazon Resource Name (ARN).

     */
    inline VersionSummary& WithApplicationId(const char* value) { SetApplicationId(value); return *this;}

    /**
     *
The date and time this resource was created.

     */
    inline const Aws::String& GetCreationTime() const{ return m_creationTime; }

    /**
     *
The date and time this resource was created.

     */
    inline void SetCreationTime(const Aws::String& value) { m_creationTimeHasBeenSet = true; m_creationTime = value; }

    /**
     *
The date and time this resource was created.

     */
    inline void SetCreationTime(Aws::String&& value) { m_creationTimeHasBeenSet = true; m_creationTime = std::move(value); }

    /**
     *
The date and time this resource was created.

     */
    inline void SetCreationTime(const char* value) { m_creationTimeHasBeenSet = true; m_creationTime.assign(value); }

    /**
     *
The date and time this resource was created.

     */
    inline VersionSummary& WithCreationTime(const Aws::String& value) { SetCreationTime(value); return *this;}

    /**
     *
The date and time this resource was created.

     */
    inline VersionSummary& WithCreationTime(Aws::String&& value) { SetCreationTime(std::move(value)); return *this;}

    /**
     *
The date and time this resource was created.

     */
    inline VersionSummary& WithCreationTime(const char* value) { SetCreationTime(value); return *this;}

    /**
     *
The semantic version of the application:

 https://semver.org/

     */
    inline const Aws::String& GetSemanticVersion() const{ return m_semanticVersion; }

    /**
     *
The semantic version of the application:

 https://semver.org/

     */
    inline void SetSemanticVersion(const Aws::String& value) { m_semanticVersionHasBeenSet = true; m_semanticVersion = value; }

    /**
     *
The semantic version of the application:

 https://semver.org/

     */
    inline void SetSemanticVersion(Aws::String&& value) { m_semanticVersionHasBeenSet = true; m_semanticVersion = std::move(value); }

    /**
     *
The semantic version of the application:

 https://semver.org/

     */
    inline void SetSemanticVersion(const char* value) { m_semanticVersionHasBeenSet = true; m_semanticVersion.assign(value); }

    /**
     *
The semantic version of the application:

 https://semver.org/

     */
    inline VersionSummary& WithSemanticVersion(const Aws::String& value) { SetSemanticVersion(value); return *this;}

    /**
     *
The semantic version of the application:

 https://semver.org/

     */
    inline VersionSummary& WithSemanticVersion(Aws::String&& value) { SetSemanticVersion(std::move(value)); return *this;}

    /**
     *
The semantic version of the application:

 https://semver.org/

     */
    inline VersionSummary& WithSemanticVersion(const char* value) { SetSemanticVersion(value); return *this;}

    /**
     *
A link to a public repository for the source code of your application.

     */
    inline const Aws::String& GetSourceCodeUrl() const{ return m_sourceCodeUrl; }

    /**
     *
A link to a public repository for the source code of your application.

     */
    inline void SetSourceCodeUrl(const Aws::String& value) { m_sourceCodeUrlHasBeenSet = true; m_sourceCodeUrl = value; }

    /**
     *
A link to a public repository for the source code of your application.

     */
    inline void SetSourceCodeUrl(Aws::String&& value) { m_sourceCodeUrlHasBeenSet = true; m_sourceCodeUrl = std::move(value); }

    /**
     *
A link to a public repository for the source code of your application.

     */
    inline void SetSourceCodeUrl(const char* value) { m_sourceCodeUrlHasBeenSet = true; m_sourceCodeUrl.assign(value); }

    /**
     *
A link to a public repository for the source code of your application.

     */
    inline VersionSummary& WithSourceCodeUrl(const Aws::String& value) { SetSourceCodeUrl(value); return *this;}

    /**
     *
A link to a public repository for the source code of your application.

     */
    inline VersionSummary& WithSourceCodeUrl(Aws::String&& value) { SetSourceCodeUrl(std::move(value)); return *this;}

    /**
     *
A link to a public repository for the source code of your application.

     */
    inline VersionSummary& WithSourceCodeUrl(const char* value) { SetSourceCodeUrl(value); return *this;}

  private:

    Aws::String m_applicationId;
    bool m_applicationIdHasBeenSet;

    Aws::String m_creationTime;
    bool m_creationTimeHasBeenSet;

    Aws::String m_semanticVersion;
    bool m_semanticVersionHasBeenSet;

    Aws::String m_sourceCodeUrl;
    bool m_sourceCodeUrlHasBeenSet;
  };

} // namespace Model
} // namespace ServerlessApplicationRepository
} // namespace Aws


text:
set -ex

# Check whether there is a passwd entry for the container UID
myuid=$(id -u)
mygid=$(id -g)
# turn off -e for getent because it will return error code in anonymous uid case
set +e
uidentry=$(getent passwd $myuid)
set -e

# If there is no passwd entry for the container UID, attempt to create one
if [ -z "$uidentry" ] ; then
    if [ -w /etc/passwd ] ; then
	echo "$myuid:x:$myuid:$mygid:${SPARK_USER_NAME:-anonymous uid}:$SPARK_HOME:/bin/false" >> /etc/passwd
    else
	echo "Container ENTRYPOINT failed to add passwd entry for anonymous UID"
    fi
fi

if [ -z "$JAVA_HOME" ]; then
  JAVA_HOME=$(java -XshowSettings:properties -version 2>&1 > /dev/null | grep 'java.home' | awk '{print $3}')
fi

SPARK_CLASSPATH="$SPARK_CLASSPATH:${SPARK_HOME}/jars/*"
env | grep SPARK_JAVA_OPT_ | sort -t_ -k4 -n | sed 's/[^=]*=\(.*\)/\1/g' > /tmp/java_opts.txt
readarray -t SPARK_EXECUTOR_JAVA_OPTS < /tmp/java_opts.txt

if [ -n "$SPARK_EXTRA_CLASSPATH" ]; then
  SPARK_CLASSPATH="$SPARK_CLASSPATH:$SPARK_EXTRA_CLASSPATH"
fi

if ! [ -z ${PYSPARK_PYTHON+x} ]; then
    export PYSPARK_PYTHON
fi
if ! [ -z ${PYSPARK_DRIVER_PYTHON+x} ]; then
    export PYSPARK_DRIVER_PYTHON
fi

# If HADOOP_HOME is set and SPARK_DIST_CLASSPATH is not set, set it here so Hadoop jars are available to the executor.
# It does not set SPARK_DIST_CLASSPATH if already set, to avoid overriding customizations of this value from elsewhere e.g. Docker/K8s.
if [ -n "${HADOOP_HOME}"  ] && [ -z "${SPARK_DIST_CLASSPATH}"  ]; then
  export SPARK_DIST_CLASSPATH="$($HADOOP_HOME/bin/hadoop classpath)"
fi

if ! [ -z ${HADOOP_CONF_DIR+x} ]; then
  SPARK_CLASSPATH="$HADOOP_CONF_DIR:$SPARK_CLASSPATH";
fi

if ! [ -z ${SPARK_CONF_DIR+x} ]; then
  SPARK_CLASSPATH="$SPARK_CONF_DIR:$SPARK_CLASSPATH";
elif ! [ -z ${SPARK_HOME+x} ]; then
  SPARK_CLASSPATH="$SPARK_HOME/conf:$SPARK_CLASSPATH";
fi

case "$1" in
  driver)
    shift 1
    CMD=(
      "$SPARK_HOME/bin/spark-submit"
      --conf "spark.driver.bindAddress=$SPARK_DRIVER_BIND_ADDRESS"
      --deploy-mode client
      "$@"
    )
    ;;
  executor)
    shift 1
    CMD=(
      ${JAVA_HOME}/bin/java
      "${SPARK_EXECUTOR_JAVA_OPTS[@]}"
      -Xms$SPARK_EXECUTOR_MEMORY
      -Xmx$SPARK_EXECUTOR_MEMORY
      -cp "$SPARK_CLASSPATH:$SPARK_DIST_CLASSPATH"
      org.apache.spark.scheduler.cluster.k8s.KubernetesExecutorBackend
      --driver-url $SPARK_DRIVER_URL
      --executor-id $SPARK_EXECUTOR_ID
      --cores $SPARK_EXECUTOR_CORES
      --app-id $SPARK_APPLICATION_ID
      --hostname $SPARK_EXECUTOR_POD_IP
      --resourceProfileId $SPARK_RESOURCE_PROFILE_ID
      --podName $SPARK_EXECUTOR_POD_NAME
    )
    ;;

  *)
    echo "Non-spark-on-k8s command provided, proceeding in pass-through mode..."
    CMD=("$@")
    ;;
esac

# Execute the container CMD under tini for better hygiene
exec /usr/bin/tini -s -- "${CMD[@]}"


text:
<?php

namespace App\Http\Middleware;

use Closure;

class NoCache
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $response->header('Cache-Control', 'no-cache, must-revalidate');

        return $response;
    }
}