text:
var request = require('urllib').request;

// Eportal object
function Eportal(params) {
  params = params || {};
  this.host = params.auth_host;
  this.data_host = params.eportal_host || params.auth_host;
  this.api_key = params.api_key;
  this.api_secret = params.api_secret;
  this.grant_type = params.grant_type || "client_credentials";
  this.scope = params.scope || "dbok read_full write_full";
  return this;
};

// Two legged OAuth server side workflow
Eportal.prototype.getToken = function(callback) {
  var _ = this;
  var token_url = this.host + "/OAuth/Token";
  request(token_url, {
    method: 'POST',
    headers: {
      'Content-Type': 'Application/x-www-form-urlencoded'
    },
    dataType: 'json',
    data: {
      client_id: this.api_key,
      client_secret: this.api_secret,
      grant_type: this.grant_type,
      scope: this.scope
    }
  }, function (err, data, res) {
    callback(err, data);
  });
};

// Create new book
Eportal.prototype.addBook = function(params, callback) {
  var _ = this;
  this.getToken(function(err, data) {
    if (err) {
      console.error("Couldn't fetch access token");
      callback(err, null);
      return;
    }
    else {
      var access_token = data.access_token
      request(_.data_host + "/add/book", {
        method: 'POST',
        dataType: 'json',
        headers: {
          'Authorization': 'Bearer '+ access_token,
          'Content-Type': 'application/json'
        },
        content: JSON.stringify(params),
        }, function(err, book, res) {
          if (err || res.statusCode !== 200) {
            callback(true, null);
            return;
          }
          else {
            callback(false, book);
          }
      });
    }
  });
};

// Update book
// Keep API sane
Eportal.prototype.upsertBook = function(id, params, callback) {
  if (typeof id === "undefined") {
    console.error("Book ID is required to update book");
    return;
  }
  // use api upsert method
  params["ExternalID"] = id;
  this.addBook(params, callback);
};

// Create new book
Eportal.prototype.getBook = function(id, callback) {
  var _ = this;
  this.getToken(function(err, data) {
    if (err) {
      console.error("Couldn't fetch access token");
      callback(err, null);
      return;
    }
    else {
      var access_token = data.access_token
      request(_.data_host + "/get/book/"+ id, {
        method: 'GET',
        dataType: 'json',
        headers: {
          'Authorization': 'Bearer '+ access_token
        }
        }, function(err, book, res) {
          if (err || res.statusCode !== 200) {
            callback(true, null);
            return;
          }
          else {
            callback(false, book);
          }
      });
    }
  });
};

// Delete book
Eportal.prototype.deleteBook = function(id, callback) {
  var _ = this;
  this.getToken(function(err, data) {
    if (err) {
      console.error("Couldn't fetch access token");
      callback(err, null);
      return;
    }
    else {
      var access_token = data.access_token
      request(_.data_host + "/delete/book/"+ id, {
        method: 'GET',
        dataType: 'json',
        headers: {
          'Authorization': 'Bearer '+ access_token
        }
        }, function(err, book, res) {
          if (err && res.statusCode !== 200) {
            callback(true, null);
            return;
          }
          else {
            callback(false, book);
          }
      });
    }
  });
};

module.exports = Eportal;


text:
/**
 * @fileoverview
 * Exports of symbols required by the `soy.` and `soydata.`
 * namespaces and which are generated by required by outputs of SoyToJavaScript.
 * This allows compiling a standalone bundle of closure dependencies for soy
 * templates.
 */

goog.require('goog.Uri');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.debug');
goog.require('goog.dom.DomHelper');
goog.require('goog.format');
goog.require('goog.html.SafeHtml');
goog.require('goog.html.SafeScript');
goog.require('goog.html.SafeStyle');
goog.require('goog.html.SafeStyleSheet');
goog.require('goog.html.SafeUrl');
goog.require('goog.html.TrustedResourceUrl');
goog.require('goog.html.uncheckedconversions');
goog.require('goog.i18n.BidiFormatter');
goog.require('goog.i18n.MessageFormat');
goog.require('goog.i18n.NumberFormat');
goog.require('goog.i18n.bidi');
goog.require('goog.i18n.bidi.Dir');
goog.require('goog.object');
goog.require('goog.soy');
goog.require('goog.soy.data.SanitizedContent');
goog.require('goog.soy.data.SanitizedContentKind');
goog.require('goog.soy.data.SanitizedCss');
goog.require('goog.soy.data.SanitizedHtml');
goog.require('goog.soy.data.SanitizedHtmlAttribute');
goog.require('goog.soy.data.SanitizedJs');
goog.require('goog.soy.data.SanitizedTrustedResourceUri');
goog.require('goog.soy.data.SanitizedUri');
goog.require('goog.string');
goog.require('goog.string.Const');
goog.require('google3.javascript.template.soy.soyutils_idom');
goog.require('proto.webutil.html.types.SafeHtmlProto');
goog.require('proto.webutil.html.types.SafeScriptProto');
goog.require('proto.webutil.html.types.SafeStyleProto');
goog.require('proto.webutil.html.types.SafeStyleSheetProto');
goog.require('proto.webutil.html.types.SafeUrlProto');
goog.require('proto.webutil.html.types.TrustedResourceUrlProto');
goog.require('security.html.jspbconversions');
goog.require('soydata.converters.idom');
goog.require('xid');

goog.scope(function() {

goog.exportSymbol('goog.DEBUG', goog.DEBUG);
goog.exportSymbol('goog.Uri', goog.Uri);
goog.exportSymbol('goog.array', goog.array);
goog.exportSymbol('goog.array.range', goog.array.range);
goog.exportSymbol('goog.asserts.ENABLE_ASSERTS', goog.asserts.ENABLE_ASSERTS);
goog.exportSymbol('goog.asserts.assert', goog.asserts.assert);
goog.exportSymbol('goog.asserts.fail', goog.asserts.fail);
goog.exportSymbol('goog.debug.runtimeType', goog.debug.runtimeType);
goog.exportSymbol('goog.dom.DomHelper', goog.dom.DomHelper);
goog.exportSymbol('goog.format.insertWordBreaks', goog.format.insertWordBreaks);
goog.exportSymbol('goog.getCssName', goog.getCssName);
goog.exportSymbol('goog.getMsg', goog.getMsg);
goog.exportSymbol('goog.getMsgWithFallback', goog.getMsgWithFallback);
goog.exportSymbol('goog.html.SafeHtml', goog.html.SafeHtml);
goog.exportSymbol('goog.html.SafeScript', goog.html.SafeScript);
goog.exportSymbol('goog.html.SafeStyle', goog.html.SafeStyle);
goog.exportSymbol('goog.html.SafeStyleSheet', goog.html.SafeStyleSheet);
goog.exportSymbol('goog.html.SafeUrl', goog.html.SafeUrl);
goog.exportSymbol('goog.html.TrustedResourceUrl', goog.html.TrustedResourceUrl);
goog.exportSymbol('goog.html.uncheckedconversions', goog.html.uncheckedconversions);
goog.exportSymbol('goog.i18n.BidiFormatter', goog.i18n.BidiFormatter);
goog.exportSymbol('goog.i18n.MessageFormat', goog.i18n.MessageFormat);
goog.exportSymbol('goog.i18n.NumberFormat', goog.i18n.NumberFormat);
goog.exportSymbol('goog.i18n.NumberFormat.Format.COMPACT_LONG', goog.i18n.NumberFormat.Format.COMPACT_LONG);
goog.exportSymbol('goog.i18n.NumberFormat.Format.COMPACT_SHORT', goog.i18n.NumberFormat.Format.COMPACT_SHORT);
goog.exportSymbol('goog.i18n.NumberFormat.Format.CURRENCY', goog.i18n.NumberFormat.Format.CURRENCY);
goog.exportSymbol('goog.i18n.NumberFormat.Format.DECIMAL', goog.i18n.NumberFormat.Format.DECIMAL);
goog.exportSymbol('goog.i18n.NumberFormat.Format.PERCENT', goog.i18n.NumberFormat.Format.PERCENT);
goog.exportSymbol('goog.i18n.NumberFormat.Format.SCIENTIFIC', goog.i18n.NumberFormat.Format.SCIENTIFIC);
goog.exportSymbol('goog.i18n.bidi.IS_RTL', goog.i18n.bidi.IS_RTL);
goog.exportSymbol('goog.i18n.bidi.Dir.LTR', goog.i18n.bidi.Dir.LTR);
goog.exportSymbol('goog.i18n.bidi.Dir.NEUTRAL', goog.i18n.bidi.Dir.NEUTRAL);
goog.exportSymbol('goog.i18n.bidi.Dir.RTL', goog.i18n.bidi.Dir.RTL);
goog.exportSymbol('goog.i18n.bidi.estimateDirection', goog.i18n.bidi.estimateDirection);
goog.exportSymbol('goog.isFunction', goog.isFunction);
goog.exportSymbol('goog.isObject', goog.isObject);
goog.exportSymbol('goog.module', goog.module);
goog.exportSymbol('goog.module.get', goog.module.get);
goog.exportSymbol('goog.object', goog.object);
goog.exportSymbol('goog.inherits', goog.inherits);
goog.exportSymbol('goog.provide', goog.provide);
goog.exportSymbol('goog.require', goog.require);
goog.exportSymbol('goog.requireType', goog.requireType);
goog.exportSymbol('goog.soy.IjData', goog.soy.IjData);
goog.exportSymbol('goog.soy.data.SanitizedContent', goog.soy.data.SanitizedContent);
goog.exportSymbol('goog.soy.data.SanitizedContentKind', goog.soy.data.SanitizedContentKind);
goog.exportSymbol('goog.soy.data.SanitizedCss', goog.soy.data.SanitizedCss);
goog.exportSymbol('goog.soy.data.SanitizedHtml', goog.soy.data.SanitizedHtml);
goog.exportSymbol('goog.soy.data.SanitizedHtml.isCompatibleWith', goog.soy.data.SanitizedHtml.isCompatibleWith);
goog.exportSymbol('goog.soy.data.SanitizedHtmlAttribute', goog.soy.data.SanitizedHtmlAttribute);
goog.exportSymbol('goog.soy.data.SanitizedJs', goog.soy.data.SanitizedJs);
goog.exportSymbol('goog.soy.data.SanitizedTrustedResourceUri', goog.soy.data.SanitizedTrustedResourceUri);
goog.exportSymbol('goog.soy.data.SanitizedUri', goog.soy.data.SanitizedUri);
goog.exportSymbol('goog.string.Const', goog.string.Const);
goog.exportSymbol('goog.string.contains', goog.string.contains);
goog.exportSymbol('goog.string.htmlEscape', goog.string.htmlEscape);
goog.exportSymbol('goog.string.quote', goog.string.quote);
goog.exportSymbol('goog.string.regExpEscape', goog.string.regExpEscape);
goog.exportSymbol('goog.string.unescapeEntities', goog.string.unescapeEntities);
goog.exportSymbol('goog.string.newLineToBr', goog.string.newLineToBr);
goog.exportSymbol('goog.string.urlEncode', goog.string.urlEncode);
goog.exportSymbol('google3.javascript.template.soy.soyutils_idom', goog.module.get('google3.javascript.template.soy.soyutils_idom'));
goog.exportSymbol('proto.webutil.html.types.SafeHtmlProto', proto.webutil.html.types.SafeHtmlProto);
goog.exportSymbol('proto.webutil.html.types.SafeScriptProto', proto.webutil.html.types.SafeScriptProto);
goog.exportSymbol('proto.webutil.html.types.SafeStyleProto', proto.webutil.html.types.SafeStyleProto);
goog.exportSymbol('proto.webutil.html.types.SafeStyleSheetProto', proto.webutil.html.types.SafeStyleSheetProto);
goog.exportSymbol('proto.webutil.html.types.SafeUrlProto', proto.webutil.html.types.SafeUrlProto);
goog.exportSymbol('proto.webutil.html.types.TrustedResourceUrlProto', proto.webutil.html.types.TrustedResourceUrlProto);
goog.exportSymbol('security.html.jspbconversions', security.html.jspbconversions);
goog.exportSymbol('soydata.converters.idom', goog.module.get('soydata.converters.idom'));
goog.exportSymbol('xid', xid);

});

redpajama_set_name: RedPajamaGithub


text:
<?php defined('SYSPATH') or die('No direct script access.');

class TransactionEmail {

	public static function send_email($data)
	{

		/*
		/	Purpose: Send transactional email to user
		/
		/	Parms:
		/		Array containing:
		/			'recipient' >> Email recipient
		/			'sender' >> Email sender
		/			'sender_descr' >> Email sender description
		/			'subject' >> Email subject
		/			'body'	>> Email body
		/			'placeholder_arr' >> Array keyed by email body placeholders and containing
		/				replacement values for placeholders
		/
		/	Returns:
		/		NULL
		*/

		// Retrieve subject and body of validation email from email_text messages file
		$email_subject = Kohana::message('email_text', $data['subject']);
		$email_body = Kohana::message('email_text', $data['body']);

		// Make substitutions
		foreach ($data['placeholder_arr'] as $placeholder => $placeholder_val)
		{
			$email_body = str_replace('['.$placeholder.']', $placeholder_val, $email_body);
		}

		// Create email object, default message to '', as we want to override it to use HTML formatting
		$email = Email::factory($email_subject, '')
			->to($data['recipient'])
			->from(Kohana::message('email_text', $data['sender']),
				Kohana::message('email_text', $data['sender_descr']));

		// Identify that email body contains HTML
		$email->message($email_body, 'text/html');

		// Actually send email
		$email->send();

		return;

	}

} // End TransactionEmail


text:
This document serves as a detailed description for an implementation of gRPC carried over HTTP2 draft 17 framing. It assumes familiarity with the HTTP2 specification.

## Protocol
Production rules are using ABNF syntax.

### Outline

The following is the general sequence of message atoms in a GRPC request & response message stream

* Request → Request-Headers \*Length-Prefixed-Message EOS
* Response → (Response-Headers \*Length-Prefixed-Message Trailers) / Trailers-Only

### Requests

* Request → Request-Headers \*Length-Prefixed-Message EOS

Request-Headers are delivered as HTTP2 headers in HEADERS + CONTINUATION frames.

* **Request-Headers** → Call-Definition \*Custom-Metadata
* **Call-Definition** → Method Scheme Path TE [Authority] [Timeout] Content-Type [Message-Type] [Message-Encoding] [Message-Accept-Encoding] [User-Agent]
* **Method** →  ":method POST"
* **Scheme** → ":scheme "  ("http" / "https")
* **Path** → ":path"  {_path identifying method within exposed API_}
* **Authority** → ":authority" {_virtual host name of authority_}
* **TE** → "te" "trailers"  # Used to detect incompatible proxies
* **Timeout** → "grpc-timeout" TimeoutValue TimeoutUnit
* **TimeoutValue** → {_positive integer as ASCII string of at most 8 digits_}
* **TimeoutUnit** → Hour / Minute / Second / Millisecond / Microsecond / Nanosecond
* **Hour** → "H"
* **Minute** → "M"
* **Second** → "S"
* **Millisecond** → "m"
* **Microsecond** → "u"
* **Nanosecond** → "n"
* **Content-Type** → "content-type" "application/grpc" [("+proto" / "+json" / {_custom_})]
* **Content-Coding** → "identity" / "gzip" / "deflate" / "snappy" / {_custom_}
* **Message-Encoding** → "grpc-encoding" Content-Coding
* **Message-Accept-Encoding** → "grpc-accept-encoding" Content-Coding \*("," Content-Coding)
* **User-Agent** → "user-agent" {_structured user-agent string_}
* **Message-Type** → "grpc-message-type" {_type name for message schema_}
* **Custom-Metadata** → Binary-Header / ASCII-Header
* **Binary-Header** → {Header-Name "-bin" } {_base64 encoded value_}
* **ASCII-Header** → Header-Name ASCII-Value
* **Header-Name** → 1\*( %x30-39 / %x61-7A / "\_" / "-") ; 0-9 a-z \_ -
* **ASCII-Value** → 1\*( %x20-%x7E ) ; space and printable ASCII

HTTP2 requires that reserved headers, ones starting with ":" appear before all other headers. Additionally implementations should send **Timeout** immediately after the reserved headers and they should send the **Call-Definition** headers before sending **Custom-Metadata**.

If **Timeout** is omitted a server should assume an infinite timeout. Client implementations are free to send a default minimum timeout based on their deployment requirements.

**Custom-Metadata** is an arbitrary set of key-value pairs defined by the application layer. Header names starting with "grpc-" but not listed here are reserved for future GRPC use and should not be used by applications as **Custom-Metadata**.

Note that HTTP2 does not allow arbitrary octet sequences for header values so binary header values must be encoded using Base64 as per https://tools.ietf.org/html/rfc4648#section-4. Implementations MUST accept padded and un-padded values and should emit un-padded values. Applications define binary headers by having their names end with "-bin". Runtime libraries use this suffix to detect binary headers and properly apply base64 encoding & decoding as headers are sent and received.

**Custom-Metadata** header order is not guaranteed to be preserved except for
values with duplicate header names. Duplicate header names may have their values
joined with "," as the delimiter and be considered semantically equivalent.
Implementations must split **Binary-Header**s on "," before decoding the
Base64-encoded values.

**ASCII-Value** should not have leading or trailing whitespace. If it contains
leading or trailing whitespace, it may be stripped. The **ASCII-Value**
character range defined is more strict than HTTP. Implementations must not error
due to receiving an invalid **ASCII-Value** that's a valid **field-value** in
HTTP, but the precise behavior is not strictly defined: they may throw the value
away or accept the value. If accepted, care must be taken to make sure that the
application is permitted to echo the value back as metadata. For example, if the
metadata is provided to the application as a list in a request, the application
should not trigger an error by providing that same list as the metadata in the
response.

Servers may limit the size of **Request-Headers**, with a default of 8 KiB
suggested.  Implementations are encouraged to compute total header size like
HTTP/2's `SETTINGS_MAX_HEADER_LIST_SIZE`: the sum of all header fields, for each
field the sum of the uncompressed field name and value lengths plus 32, with
binary values' lengths being post-Base64.

The repeated sequence of **Length-Prefixed-Message** items is delivered in DATA frames

* **Length-Prefixed-Message** → Compressed-Flag Message-Length Message
* **Compressed-Flag** → 0 / 1   # encoded as 1 byte unsigned integer
* **Message-Length** → {_length of Message_}  # encoded as 4 byte unsigned integer
* **Message** → \*{binary octet}

A **Compressed-Flag** value of 1 indicates that the binary octet sequence of **Message** is compressed using the mechanism declared by the **Message-Encoding** header. A value of 0 indicates that no encoding of **Message** bytes has occurred. Compression contexts are NOT maintained over message boundaries, implementations must create a new context for each message in the stream. If the **Message-Encoding** header is omitted then the **Compressed-Flag** must be 0.

For requests, **EOS** (end-of-stream) is indicated by the presence of the END_STREAM flag on the last received DATA frame. In scenarios where the **Request** stream needs to be closed but no data remains to be sent implementations MUST send an empty DATA frame with this flag set.

###Responses

* **Response** → (Response-Headers \*Length-Prefixed-Message Trailers) / Trailers-Only
* **Response-Headers** → HTTP-Status [Message-Encoding] [Message-Accept-Encoding] Content-Type \*Custom-Metadata
* **Trailers-Only** → HTTP-Status Content-Type Trailers
* **Trailers** → Status [Status-Message] \*Custom-Metadata
* **HTTP-Status** → ":status 200"
* **Status** → "grpc-status" <status-code-as-ASCII-string>
* **Status-Message** → "grpc-message" <descriptive text for status as ASCII string>

**Response-Headers** & **Trailers-Only** are each delivered in a single HTTP2 HEADERS frame block. Most responses are expected to have both headers and trailers but **Trailers-Only** is permitted for calls that produce an immediate error. Status must be sent in **Trailers** even if the status code is OK.

For responses end-of-stream is indicated by the presence of the END_STREAM flag on the last received HEADERS frame that carries **Trailers**.

Implementations should expect broken deployments to send non-200 HTTP status codes in responses as well as a variety of non-GRPC content-types and to omit **Status** & **Status-Message**. Implementations must synthesize a **Status** & **Status-Message** to propagate to the application layer when this occurs.

Clients may limit the size of **Response-Headers**, **Trailers**, and
**Trailers-Only**, with a default of 8 KiB each suggested.

####Example

Sample unary-call showing HTTP2 framing sequence

**Request**

```
HEADERS (flags = END_HEADERS)
:method = POST
:scheme = http
:path = /google.pubsub.v2.PublisherService/CreateTopic
:authority = pubsub.googleapis.com
grpc-timeout = 1S
content-type = application/grpc+proto
grpc-encoding = gzip
authorization = Bearer y235.wef315yfh138vh31hv93hv8h3v

DATA (flags = END_STREAM)
<Length-Prefixed Message>
```
**Response**
```
HEADERS (flags = END_HEADERS)
:status = 200
grpc-encoding = gzip

DATA
<Length-Prefixed Message>

HEADERS (flags = END_STREAM, END_HEADERS)
grpc-status = 0 # OK
trace-proto-bin = jher831yy13JHy3hc
```
####User Agents

While the protocol does not require a user-agent to function it is recommended that clients provide a structured user-agent string that provides a basic description of the calling library, version & platform to facilitate issue diagnosis in heterogeneous environments. The following structure is recommended to library developers
```
User-Agent → "grpc-" Language ?("-" Variant) "/" Version ?( " ("  *(AdditionalProperty ";") ")" )
```
E.g.

```
grpc-java/1.2.3
grpc-ruby/1.2.3
grpc-ruby-jruby/1.3.4
grpc-java-android/0.9.1 (gingerbread/1.2.4; nexus5; tmobile)
```
####HTTP2 Transport Mapping

#####Stream Identification
All GRPC calls need to specify an internal ID. We will use HTTP2 stream-ids as call identifiers in this scheme. NOTE: These id's are contextual to an open HTTP2 session and will not be unique within a given process that is handling more than one HTTP2 session nor can they be used as GUIDs.

#####Data Frames
DATA frame boundaries have no relation to **Length-Prefixed-Message** boundaries and implementations should make no assumptions about their alignment.

#####Errors

When an application or runtime error occurs during an RPC a **Status** and **Status-Message** are delivered in **Trailers**.

In some cases it is possible that the framing of the message stream has become corrupt and the RPC runtime will choose to use an **RST_STREAM** frame to indicate this state to its peer. RPC runtime implementations should interpret RST_STREAM as immediate full-closure of the stream and should propagate an error up to the calling application layer.

The following mapping from RST_STREAM error codes to GRPC error codes is applied.

HTTP2 Code|GRPC Code
----------|-----------
NO_ERROR(0)|INTERNAL - An explicit GRPC status of OK should have been sent but this might be used to aggressively lameduck in some scenarios.
PROTOCOL_ERROR(1)|INTERNAL
INTERNAL_ERROR(2)|INTERNAL
FLOW_CONTROL_ERROR(3)|INTERNAL
SETTINGS_TIMEOUT(4)|INTERNAL
STREAM_CLOSED|No mapping as there is no open stream to propagate to. Implementations should log.
FRAME_SIZE_ERROR|INTERNAL
REFUSED_STREAM|UNAVAILABLE - Indicates that no processing occurred and the request can be retried, possibly elsewhere.
CANCEL(8)|Mapped to call cancellation when sent by a client.Mapped to CANCELLED when sent by a server. Note that servers should only use this mechanism when they need to cancel a call but the payload byte sequence is incomplete.
COMPRESSION_ERROR|INTERNAL
CONNECT_ERROR|INTERNAL
ENHANCE_YOUR_CALM|RESOURCE_EXHAUSTED ...with additional error detail provided by runtime to indicate that the exhausted resource is bandwidth.
INADEQUATE_SECURITY| PERMISSION_DENIED … with additional detail indicating that permission was denied as protocol is not secure enough for call.

#####Security

The HTTP2 specification mandates the use of TLS 1.2 or higher when TLS is used with HTTP2. It also places some additional constraints on the allowed ciphers in deployments to avoid known-problems as well as requiring SNI support. It is also expected that HTTP2 will be used in conjunction with proprietary transport security mechanisms about which the specification can make no meaningful recommendations.

#####Connection Management
######GOAWAY Frame
Sent by servers to clients to indicate that they will no longer accept any new streams on the associated connections. This frame includes the id of the last successfully accepted stream by the server. Clients should consider any stream initiated after the last successfully accepted stream as UNAVAILABLE and retry the call elsewhere. Clients are free to continue working with the already accepted streams until they complete or the connection is terminated.

Servers should send GOAWAY before terminating a connection to reliably inform clients which work has been accepted by the server and is being executed.

######PING Frame
Both clients and servers can send a PING frame that the peer must respond to by precisely echoing what they received. This is used to assert that the connection is still live as well as providing a means to estimate end-to-end latency. If a server initiated PING does not receive a response within the deadline expected by the runtime all outstanding calls on the server will be closed with a CANCELLED status. An expired client initiated PING will cause all calls to be closed with an UNAVAILABLE status. Note that the frequency of PINGs is highly dependent on the network environment, implementations are free to adjust PING frequency based on network and application requirements.

######Connection failure
If a detectable connection failure occurs on the client all calls will be closed with an UNAVAILABLE status. For servers open calls will be closed with a CANCELLED status.

### Appendix A - GRPC for Protobuf

The service interfaces declared by protobuf are easily mapped onto GRPC by code generation extensions to protoc. The following defines the mapping to be used

* **Path** → / Service-Name / {_method name_}
* **Service-Name** → ?( {_proto package name_} "." ) {_service name_}
* **Message-Type** → {_fully qualified proto message name_}
* **Content-Type** → "application/grpc+proto"


text:
namespace Zu.ChromeDevTools.DOMStorage
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Represents an adapter for the DOMStorage domain to simplify the command interface.
    /// </summary>
    public class DOMStorageAdapter
    {
        private readonly ChromeSession m_session;

        public DOMStorageAdapter(ChromeSession session)
        {
            m_session = session ?? throw new ArgumentNullException(nameof(session));
        }

        /// <summary>
        /// Gets the ChromeSession associated with the adapter.
        /// </summary>
        public ChromeSession Session
        {
            get { return m_session; }
        }

        /// <summary>
        ///
        /// </summary>
        public async Task<ClearCommandResponse> Clear(ClearCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<ClearCommand, ClearCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Disables storage tracking, prevents storage events from being sent to the client.
        /// </summary>
        public async Task<DisableCommandResponse> Disable(DisableCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<DisableCommand, DisableCommandResponse>(command ?? new DisableCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        /// Enables storage tracking, storage events will now be delivered to the client.
        /// </summary>
        public async Task<EnableCommandResponse> Enable(EnableCommand command = null, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<EnableCommand, EnableCommandResponse>(command ?? new EnableCommand(), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        ///
        /// </summary>
        public async Task<GetDOMStorageItemsCommandResponse> GetDOMStorageItems(GetDOMStorageItemsCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<GetDOMStorageItemsCommand, GetDOMStorageItemsCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        ///
        /// </summary>
        public async Task<RemoveDOMStorageItemCommandResponse> RemoveDOMStorageItem(RemoveDOMStorageItemCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<RemoveDOMStorageItemCommand, RemoveDOMStorageItemCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }
        /// <summary>
        ///
        /// </summary>
        public async Task<SetDOMStorageItemCommandResponse> SetDOMStorageItem(SetDOMStorageItemCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
        {
            return await m_session.SendCommand<SetDOMStorageItemCommand, SetDOMStorageItemCommandResponse>(command, cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
        }

        /// <summary>
        ///
        /// </summary>
        public void SubscribeToDomStorageItemAddedEvent(Action<DomStorageItemAddedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        ///
        /// </summary>
        public void SubscribeToDomStorageItemRemovedEvent(Action<DomStorageItemRemovedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        ///
        /// </summary>
        public void SubscribeToDomStorageItemUpdatedEvent(Action<DomStorageItemUpdatedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
        /// <summary>
        ///
        /// </summary>
        public void SubscribeToDomStorageItemsClearedEvent(Action<DomStorageItemsClearedEvent> eventCallback)
        {
            m_session.Subscribe(eventCallback);
        }
    }
}


text:
package org.semanticweb.yars.nx.clean;

import java.io.PrintStream;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Pattern;

import org.semanticweb.yars.nx.DateTimeLiteral;
import org.semanticweb.yars.nx.Literal;
import org.semanticweb.yars.nx.Node;
import org.semanticweb.yars.nx.Resource;
import org.semanticweb.yars.nx.parser.ParseException;

public class Cleaner {
	static SimpleDateFormat _iso = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

	static SimpleDateFormat[] _formats = {
		new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"),
		new SimpleDateFormat("dd-MMM-yy"),
		new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss"),
		new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z"),
		new SimpleDateFormat("MM/dd/yy")
	};

	public static void clean(Iterator<Node[]> in, PrintStream out, int length, boolean datatype) {
		int drop = 0;
		long linecount = 0;

		while(in.hasNext()){
			boolean write = true;
			Node[] line = in.next();
			linecount++;
			if (length != -1 && length != line.length) {
				System.err.println(linecount + ": doesn't have " + length + " elements but " + line.length);
				drop++;
				continue;
			}
			Node[] clean = new Node[line.length];

			for(int i=0; i<line.length; i++){
				try {
					clean[i] = clean(line[i], datatype);
				} catch (Exception e) {
					drop++;
					write = false;
					System.err.println(linecount + ": cannot parse entry "+line[i] +  " " + e.getMessage());
				}
			}
			if(write) {
				for (Node n:clean) {
					out.print(n.toN3()+" ");
				}
				out.println(".");
			}
		}

		System.err.println("Processed  "+linecount+" statements");

		System.err.println("Dropped "+drop+" statements");
	}

	public static Node clean(Node raw, boolean datatype) throws URISyntaxException, MalformedURLException {
		if(raw instanceof Resource) {
			return new Resource(normaliseURI(raw.toString()));
		} else if(raw instanceof Literal){
			Literal l = (Literal) raw;

			String data = removeControlChars(l.toString());
			data = stripHTML(data);
			data = data.trim();

			// dropping empty literals
			if (data.length() <= 0) {
				throw new URISyntaxException("", "dropping emtpy literals");
			}

			data = Literal.escapeForNx(data);

			if(l.getDatatype()==null && l.getLanguageTag()==null)
				return normaliseLiteral(new Literal(data), datatype);
			else if(l.getDatatype()!=null && l.getLanguageTag()!=null)
				return new Literal(data, l.getLanguageTag(), l.getDatatype());
			else if(l.getDatatype()!=null)
				return new Literal(data, l.getDatatype());
			else
				return new Literal(data, l.getLanguageTag());

		} else {
			return raw;
		}
	}

	public static Literal normaliseLiteral(Literal l, boolean datatype) throws URISyntaxException {
		// we know language or datatype already? -> skip
		if (l.getLanguageTag() != null || l.getDatatype() != null) {
			String data = l.getData().trim();

			Literal n = null;

			if (l.getLanguageTag() != null) {
				n = new Literal(data, l.getLanguageTag());
			} else {
				n = new Literal(data, l.getDatatype());
			}

			return n;
		}

		// no datatype normalisation
		if (datatype == false) {
			String data = l.getData().trim();

			Literal n = null;

			if (l.getLanguageTag() != null) {
				n = new Literal(data, l.getLanguageTag());
			} else {
				n = new Literal(data, l.getDatatype());
			}

			return n;
		}

		Literal n = null;
		String data = l.getData().trim();

		Pattern numex = Pattern.compile("^[-+]?[0-9]*.?[0-9]+$");

		// we have a number
		/*
		if (numex.matcher(data).matches() == true) {
			NumberFormat nf = NumberFormat.getInstance();
			try {
				Number num = nf.parse(data);
				if (num instanceof Integer || num instanceof BigInteger ||
						num instanceof Short || num instanceof Long ||
						num instanceof Byte) {
					n = new Literal(num.toString(), Literal.DECIMAL);
				} else if (num instanceof Float) {
					n = new Literal(num.toString(), Literal.FLOAT);
				} else if (num instanceof Double) {
					n = new Literal(num.toString(), Literal.DOUBLE);
				} else {
					throw new URISyntaxException("", "dropping bogus number literal");
				}
			} catch (java.text.ParseException e) {
				;
			} catch (NumberFormatException nfe) {
				;
			}
		} else {
		*/
			// try date
			Date date = null;

			try {
				date = DateTimeLiteral.parseISO8601(data);
				n = new DateTimeLiteral(data); //, Literal.DATETIME);
				if (n != null) {
					return n;
				}
			} catch (ParseException nfe) {
				;
			} catch (Throwable e) {
				;
			}

			for (SimpleDateFormat f:_formats) {
				try {
					date = (Date)f.parse(data);
					n = new DateTimeLiteral(_iso.format(date)); //, Literal.DATETIME);
					if (n != null) {
						break;
					}
				} catch (java.text.ParseException pe) {
					;
				} catch (Throwable e) {
					;
				}
			}
//		}

        if (n != null) {
        	return n;
        }
        return l;
	}

	/**
	 * Uses some heurisitics to clean URIs
	 * e.g. http://en.wikipedia.org/wiki/URL_normalization
	 * @param uri
	 * @return
	 * @throws URISyntaxException
	 * @throws MalformedURLException
	 * @throws MalformedURLException
	 */
	public static String normaliseURI(String uri) throws URISyntaxException, MalformedURLException {
		URI raw = new URI(uri.replaceAll(" ", "%20"));

		raw = raw.normalize();

		//raw.toURL();

		if (!raw.isOpaque()) {
			String scheme = raw.getScheme();
			if (scheme != null) {
				scheme = scheme.toLowerCase();
			} else {
				throw new URISyntaxException(uri, "dropping uris without scheme");
			}

			if (scheme.startsWith("http")) {
				raw.toURL();
			}

			String path = raw.getPath();
			if (path != null) {
				// fucks up foaf uris
				//path = path.toLowerCase();

				if (path.equals("")) {
					path = "/";
				} else if (path.endsWith("/index.html")
						|| path.endsWith("/index.htm")
						|| path.endsWith("/index.asp")
						|| path.toLowerCase().endsWith("/default.asp")
						|| path.toLowerCase().endsWith("/default.aspx")
						|| path.endsWith("/index.jsp")
						|| path.endsWith("/index.php") ) {
					path = path.substring(0, path.lastIndexOf('/')+1);
				}
			}

			String host = raw.getHost();
			if (host != null) {
				host = host.toLowerCase();
				//if (host.startsWith("www.")) {
				//	host = host.substring(4, host.length());
				//}
			}

			int port = raw.getPort();
			if(port==80) {
				port = -1;
			}

			URI u = new URI(scheme, raw.getUserInfo(), host, port, path, raw.getQuery(), raw.getFragment());

			return u.toString();
		}

		// if there's no : (and hence no scheme), skip
		String scheme = raw.getScheme();
		//System.out.println("schem" + scheme);
		if (scheme == null) {
			/*
			scheme = scheme.toLowerCase();
		}
		if (uri.indexOf(':') == -1 || uri.indexOf(':') > 7) {
		*/
			throw new URISyntaxException("", "dropping uris without scheme");
		}

		return uri;
	}

	private static String removeControlChars(String lit) {
		StringBuffer result = new StringBuffer();

		for (int i = 0; i < lit.length(); i++) {
			char c = lit.charAt(i);
			int cInt = (int)c;
			if (cInt >= 0 && cInt <= 31) {
				result.append(" ");
			} else {
				result.append(c);
			}
		}

		return result.toString();
	}

	private static String stripHTML(String literal){
		return literal.replaceAll("\\<.*?\\>", "");
		/*
		if (literal.indexOf(">") > 0) {
			StringBean sb = new StringBean();
			Parser parser = Parser.createParser(literal, "UTF-8");
			String result = literal;
			try {
				parser.visitAllNodesWith (sb);
				result = sb.getStrings ();
			} catch(EncodingChangeException eEx){
				String msg = eEx.getMessage();
				String enc = msg.substring(msg.indexOf(" to ")+4);
				enc = enc.substring(0, enc.indexOf(" "));
				System.err.println("Switch to "+enc+" encoding");
				try{
					parser = Parser.createParser(literal, enc);
					sb = new StringBean ();
					parser.visitAllNodesWith(sb);
					result = sb.getStrings();
				} catch(Exception ex){
					return result;
				}
			}catch (ParserException e) {
				e.printStackTrace(System.err);
			}
			return result;
		}
		return literal;
		*/
//		HTMLTextExtractor parser = new HTMLTextExtractor();
//		try {
//			parser.parse(new StringReader(literal));
//		} catch (IOException e) {
//			e.printStackTrace();
//			return literal;
//		} catch (NumberFormatException e) {
//			return literal;
//		}
//		return literal;
//
	}
}


text:
package cards;

import server.*;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Taxman extends Card {

    @Override
    public String name() {
        return "Taxman";
    }

    @Override
    public String plural() {
        return "Taxmen";
    }

    @Override
    public Set<Type> types() {
        return types(Type.ACTION, Type.ATTACK);
    }

    @Override
    public int cost() {
        return 4;
    }

    @Override
    public String[] description() {
        return new String[] {"You may trash a_Treasure from your_hand. Each other_player with 5_or_more cards discards a_copy of_it (or_reveals a_hand without_it). Gain a_Treasure card costing up_to 3$_more than the_trashed card, putting_it on_top of your_deck."};
    }

    @Override
    public void onAttack(Player player, Game game, List<Player> targets) {
        // you may trash a treasure from your hand
        Set<Card> trashable = player.getHand().stream()
                .filter(Card::isTreasure)
                .collect(Collectors.toSet());
        if (!trashable.isEmpty()) {
            Card toTrash = chooseTrash(player, game, trashable);
            if (toTrash != null) {
                game.messageAll("trashing " + toTrash.htmlName());
                player.removeFromHand(toTrash);
                game.trash(player, toTrash);
                // each other player with 5 or more cards in hand discards a copy of it (or reveals a hand without it)
                targets.forEach(target -> {
                    if (target.getHand().size() >= 5) {
                        if (target.getHand().contains(toTrash)) {
                            game.message(target, "You discard " + toTrash.htmlName());
                            game.messageOpponents(target, target.username + " discards " + toTrash.htmlName());
                            target.putFromHandIntoDiscard(toTrash);
                        } else {
                            game.message(target, "You reveal your hand: " + Card.htmlList(target.getHand()));
                            game.messageOpponents(target, target.username + " reveals their hand: " + Card.htmlList(target.getHand()));
                        }
                    }
                });
                // gain a treasure card costing up to $3 more than the trashed card, putting it on top of your deck
                Set<Card> gainable = game.cardsCostingAtMost(toTrash.cost(game) + 3).stream()
                        .filter(Card::isTreasure)
                        .collect(Collectors.toSet());
                if (!gainable.isEmpty()) {
                    Card toGain = promptChooseGainFromSupply(
                            player,
                            game,
                            gainable,
                            this.toString() + ": Choose a treasure to gain onto your deck costing up to $3 more."
                    );
                    game.message(player, "gaining " + toGain.htmlName() + " onto your deck");
                    game.messageOpponents(player, "gaining " + toGain.htmlName() + " onto their deck");
                    game.gainToTopOfDeck(player, toGain);
                }
            } else {
                game.messageAll("trashing nothing");
            }
        } else {
            game.messageAll("having no treasure to trash");
        }
    }

    private Card chooseTrash(Player player, Game game, Set<Card> trashable) {
        if (player instanceof Bot) {
            Card toTrash = ((Bot) player).taxmanTrash(Collections.unmodifiableSet(trashable));
            checkContains(trashable, toTrash, false);
            return toTrash;
        }
        return new Prompt(player, game)
                .type(Prompt.Type.DANGER)
                .message(this.toString() + ": You may trash a treasure from your hand.")
                .orNone("Trash nothing")
                .responseCard();
    }

}


text:
package logging

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/krschwab/xlxd/shared"

	log "gopkg.in/inconshreveable/log15.v2"
)

// GetLogger returns a logger suitable for using as shared.Log.
func GetLogger(syslog string, logfile string, verbose bool, debug bool, customHandler log.Handler) (shared.Logger, error) {
	Log := log.New()

	var handlers []log.Handler

	var syshandler log.Handler

	// System specific handler
	syshandler = getSystemHandler(syslog, debug)
	if syshandler != nil {
		handlers = append(handlers, syshandler)
	}

	// FileHandler
	if logfile != "" {
		if !pathExists(filepath.Dir(logfile)) {
			return nil, fmt.Errorf("Log file path doesn't exist: %s", filepath.Dir(logfile))
		}

		if !debug {
			handlers = append(
				handlers,
				log.LvlFilterHandler(
					log.LvlInfo,
					log.Must.FileHandler(logfile, log.LogfmtFormat()),
				),
			)
		} else {
			handlers = append(handlers, log.Must.FileHandler(logfile, log.LogfmtFormat()))
		}
	}

	// StderrHandler
	if verbose || debug {
		if !debug {
			handlers = append(
				handlers,
				log.LvlFilterHandler(
					log.LvlInfo,
					log.StderrHandler,
				),
			)
		} else {
			handlers = append(handlers, log.StderrHandler)
		}
	} else {
		handlers = append(
			handlers,
			log.LvlFilterHandler(
				log.LvlWarn,
				log.StderrHandler,
			),
		)
	}

	if customHandler != nil {
		handlers = append(handlers, customHandler)
	}

	Log.SetHandler(log.MultiHandler(handlers...))

	return Log, nil
}

func AddContext(logger shared.Logger, ctx log.Ctx) shared.Logger {
	log15logger, ok := logger.(log.Logger)
	if !ok {
		logger.Error("couldn't downcast logger to add context", log.Ctx{"logger": log15logger, "ctx": ctx})
		return logger
	}

	return log15logger.New(ctx)
}

func pathExists(name string) bool {
	_, err := os.Lstat(name)
	if err != nil && os.IsNotExist(err) {
		return false
	}
	return true
}


text:
'use strict';
// helper
const isDefined = (function() {
  const global_ = typeof window === 'object' ? window : global;
  return (globalVar) => global_.hasOwnProperty(globalVar);
})();

module.exports = isDefined;


text:
require 'spec_helper'

describe "jig proposal manipulation" do
  # make sure that the there's a crowbar deploment (named 'test')
  include_context "crowbar test deployment"
  # just 2 nodes.
  include_context "2 dummy nodes"

  context "test deployment with 2 nodes" do

    let(:active)   { deployment.head}

    before(:all) {
      # add node
    }

    it "we can commit the deployment" do
      #deployment.commit
    end

  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/Preferhythm.iml" filepath="$PROJECT_DIR$/Preferhythm.iml" />
      <module fileurl="file://$PROJECT_DIR$/annotations/annotations.iml" filepath="$PROJECT_DIR$/annotations/annotations.iml" />
      <module fileurl="file://$PROJECT_DIR$/library/library.iml" filepath="$PROJECT_DIR$/library/library.iml" />
      <module fileurl="file://$PROJECT_DIR$/processor/processor.iml" filepath="$PROJECT_DIR$/processor/processor.iml" />
      <module fileurl="file://$PROJECT_DIR$/samplejava/samplejava.iml" filepath="$PROJECT_DIR$/samplejava/samplejava.iml" />
      <module fileurl="file://$PROJECT_DIR$/samplekotlin/samplekotlin.iml" filepath="$PROJECT_DIR$/samplekotlin/samplekotlin.iml" />
    </modules>
  </component>
</project>


text:
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/classes'

describe "IO#to_i" do
  it "return the numeric file descriptor of the given IO object" do
    $stdout.to_i.should == 1
  end

  it "raises IOError on closed stream" do
    lambda { IOSpecs.closed_file.to_i }.should raise_error(IOError)
  end
end


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Selenium.Internal.SeleniumEmulation
{
    /// <summary>
    /// Defines the command for the deleteCookie keyword.
    /// </summary>
    internal class DeleteCookie : SeleneseCommand
    {
        /// <summary>
        /// Handles the command.
        /// </summary>
        /// <param name="driver">The driver used to execute the command.</param>
        /// <param name="locator">The first parameter to the command.</param>
        /// <param name="value">The second parameter to the command.</param>
        /// <returns>The result of the command.</returns>
        protected override object HandleSeleneseCommand(OpenQA.Selenium.IWebDriver driver, string locator, string value)
        {
            driver.Manage().Cookies.DeleteCookieNamed(locator);
            return null;
        }
    }
}


text:
<?php

namespace Concrete\Tests\Page\Collection\Version;

use Concrete\Core\Page\Page;
use Concrete\Core\Support\Facade\Application;
use Concrete\TestHelpers\Page\PageTestCase;

class ApproveTest extends PageTestCase
{
    /**
     * @var \Concrete\Core\Localization\Service\Date
     */
    protected $dateHelper;

    /**
     * @var int
     */
    protected $numCollectionVersions = 3;

    /**
     * @var \Concrete\Core\Page\Page
     */
    private $page;

    /**
     * @var int[]
     */
    private $cvIDs;

    public function setUp(): void
    {
        parent::setUp();
        $this->dateHelper = Application::getFacadeApplication()->make('date');
        $this->page = Page::getByID(Page::getHomePageID());
        $this->cvIDs = [];
        for ($i = 0; $i < $this->numCollectionVersions; ++$i) {
            $this->page->loadVersionObject($i + 1);
            if ($this->page->getVersionID() === null) {
                $this->page->loadVersionObject('RECENT');
                $cv = $this->page->cloneVersion('')->getVersionObject();
            } else {
                $cv = $this->page->getVersionObject();
            }
            $this->cvIDs[] = $cv->getVersionID();
        }
        $this->resetVersions();
    }

    public function testWithoutStartEndDate()
    {
        $this->getVersion(0)->approve(false);
        $this->assertTrue((bool) $this->getVersion(0)->isApproved());
        $this->assertFalse((bool) $this->getVersion(1)->isApproved());
        $this->assertFalse((bool) $this->getVersion(2)->isApproved());
        $this->getVersion(1)->approve(false);
        $this->assertFalse((bool) $this->getVersion(0)->isApproved());
        $this->assertTrue((bool) $this->getVersion(1)->isApproved());
        $this->assertFalse((bool) $this->getVersion(2)->isApproved());
    }

    public function testStartDate()
    {
        $now = strtotime('2018-10-23 12:00:00');
        $startDate = $this->dateHelper->toDB($now);
        $startDatePlus1 = $this->dateHelper->toDB($now + 1);
        $startDatePlus2 = $this->dateHelper->toDB($now + 2);

        $this->getVersion(0)->approve(false, $startDate);
        $this->getVersion(1)->setPublishInterval($startDate, null);

        $this->assertTrue((bool) $this->getVersion(0)->isApproved());
        $this->assertFalse((bool) $this->getVersion(1)->isApproved());
        $this->assertSame($startDate, $this->getVersion(0)->getPublishDate());
        $this->assertSame($startDate, $this->getVersion(1)->getPublishDate());

        $this->getVersion(1)->approve(false, $startDate, null);

        $this->assertFalse((bool) $this->getVersion(0)->isApproved());
        $this->assertTrue((bool) $this->getVersion(1)->isApproved());
        $this->assertSame($startDate, $this->getVersion(0)->getPublishDate());
        $this->assertSame($startDate, $this->getVersion(1)->getPublishDate());

        $this->getVersion(2)->approve(false, $startDatePlus2, null);
        $this->assertTrue((bool) $this->getVersion(1)->isApproved());
        $this->assertTrue((bool) $this->getVersion(2)->isApproved());
        $this->assertSame($startDate, $this->getVersion(1)->getPublishDate());
        $this->assertSame($startDatePlus1, $this->getVersion(1)->getPublishEndDate());
        $this->assertSame($startDatePlus2, $this->getVersion(2)->getPublishDate());
    }

    public function testEndDate()
    {
        $now = strtotime('2018-10-23 12:00:00');
        $endDate = $this->dateHelper->toDB($now);
        $endDateMinus1 = $this->dateHelper->toDB($now - 1);
        $endDateMinus2 = $this->dateHelper->toDB($now - 2);

        $this->getVersion(0)->approve(false, null, $endDate);
        $this->getVersion(1)->setPublishInterval(null, $endDate);

        $this->assertTrue((bool) $this->getVersion(0)->isApproved());
        $this->assertFalse((bool) $this->getVersion(1)->isApproved());
        $this->assertSame($endDate, $this->getVersion(0)->getPublishEndDate());
        $this->assertSame($endDate, $this->getVersion(1)->getPublishEndDate());

        $this->getVersion(1)->approve(false, null, $endDate);

        $this->assertFalse((bool) $this->getVersion(0)->isApproved());
        $this->assertTrue((bool) $this->getVersion(1)->isApproved());
        $this->assertSame($endDate, $this->getVersion(0)->getPublishEndDate());
        $this->assertSame($endDate, $this->getVersion(1)->getPublishEndDate());

        $this->getVersion(2)->approve(false, null, $endDateMinus2);
        $this->assertTrue((bool) $this->getVersion(1)->isApproved());
        $this->assertTrue((bool) $this->getVersion(2)->isApproved());
        $this->assertSame($endDateMinus1, $this->getVersion(1)->getPublishDate());
        $this->assertSame($endDate, $this->getVersion(1)->getPublishEndDate());
        $this->assertSame($endDateMinus2, $this->getVersion(2)->getPublishEndDate());
    }

    public function testStartEndDate()
    {
        $now = strtotime('2018-10-23 12:00:00');
        $startDate = $this->dateHelper->toDB($now - 10);
        $endDate = $this->dateHelper->toDB($now + 10);
        $endDatePlus1 = $this->dateHelper->toDB($now + 10 + 1);

        $this->getVersion(0)->approve(false);
        $this->getVersion(1)->approve(false, $startDate, $endDate);

        $this->assertTrue((bool) $this->getVersion(0)->isApproved());
        $this->assertSame($endDatePlus1, $this->getVersion(0)->getPublishDate());
        $this->assertNull($this->getVersion(0)->getPublishEndDate());

        $this->resetVersions();
        $this->getVersion(0)->approve(false, $startDate, $endDate);
        $this->getVersion(1)->approve(false, $startDate, $endDate);
        $this->assertTrue((bool) $this->getVersion(1)->isApproved());
        $this->assertFalse((bool) $this->getVersion(0)->isApproved());
    }

    /**
     * @param int $index
     *
     * @return \Concrete\Core\Page\Collection\Version\Version
     */
    protected function getVersion($index)
    {
        $this->page->loadVersionObject($this->cvIDs[$index]);

        return $this->page->getVersionObject();
    }

    protected function resetVersions()
    {
        foreach (array_keys($this->cvIDs) as $index) {
            $cv = $this->getVersion($index);
            $cv->deny();
            $cv->setPublishInterval(null, null);
        }
    }
}


text:
void register_godotsteam_types();
void unregister_godotsteam_types();


text:
package org.minimalj.repository.memory;

import java.util.List;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.minimalj.repository.query.By;
import org.minimalj.repository.query.Criteria;
import org.minimalj.repository.query.SearchCriteria;

public class InMemoryDbCriteriaTest {

	private static InMemoryRepository respository;

	@BeforeClass
	public static void setupRepository() {
		respository = new InMemoryRepository(G.class);
	}

	@AfterClass
	public static void shutdownRepository() {
	}

	@Test
	public void testQuery() {
		respository.insert(new G("abc"));
		respository.insert(new G("abcd"));
		respository.insert(new G("abcxyz"));

		Criteria s1 = By.search("abc");
		Criteria s2 = By.search("xyz");
		List<G> g = respository.find(G.class, s1.and(s2));
		Assert.assertEquals(1, g.size());

		s1 = By.search("d");
		s2 = By.search("x");
		g = respository.find(G.class, s1.or(s2));
		Assert.assertEquals(2, g.size());

		g = respository.find(G.class, s1.and(s2));
		Assert.assertEquals(0, g.size());

		s1 = By.search("y");
		s2 = By.search("x");
		g = respository.find(G.class, s1.and(s2));
		Assert.assertEquals(1, g.size());

		s1 = By.search("y");
		s2 = By.search("z");
		Criteria s3 = By.search("d");
		SearchCriteria s4 = (SearchCriteria) By.search("y");
		g = respository.find(G.class, s1.and(s2).or(s3.and(s4.negate())));
		Assert.assertEquals(2, g.size());
	}
}


text:
COMPUTERDIR="./catscripts/Technology/Computers"

if [ "$1" == "" ]; #Normal operation
then

  debug_start "Computers"

  . $COMPUTERDIR/Computer_programming/Computerprogramming.sh
  . $COMPUTERDIR/Computer_security/ComputerSecurity.sh
  . $COMPUTERDIR/Computer_hardware/Computerhardware.sh
  . $COMPUTERDIR/Computer_manufacturers/Manufacturers.sh
  . $COMPUTERDIR/Computer_networking/Computernetworking.sh
  . $COMPUTERDIR/Internet/Internet.sh
  . $COMPUTERDIR/Software/Software.sh #KEYWORDS_SOFTWARE_ALL
  . $COMPUTERDIR/Tablets/Tablets.sh

  debug_end "Computers"

else #Export variables only

  . $COMPUTERDIR/Computer_programming/Computerprogramming.sh norun
  . $COMPUTERDIR/Computer_security/ComputerSecurity.sh norun
  . $COMPUTERDIR/Computer_hardware/Computerhardware.sh norun
  . $COMPUTERDIR/Computer_manufacturers/Manufacturers.sh norun
  . $COMPUTERDIR/Computer_networking/Computernetworking.sh norun
  . $COMPUTERDIR/Software/Software.sh norun #KEYWORDS_SOFTWARE_ALL
  . $COMPUTERDIR/Tablets/Tablets.sh norun
fi


text:
package com.badlogic.gdx.ai.btree.decorator;

import com.badlogic.gdx.ai.btree.Decorator;
import com.badlogic.gdx.ai.btree.Task;
import com.badlogic.gdx.ai.btree.TaskCloneException;
import com.badlogic.gdx.ai.btree.annotation.TaskAttribute;
import com.badlogic.gdx.ai.btree.annotation.TaskConstraint;
import com.badlogic.gdx.ai.btree.utils.BehaviorTreeLibraryManager;

/** An {@code Include} decorator grafts a subtree. When the subtree is grafted depends on the value of the {@link #lazy} parameter:
 * at clone-time if is {@code false}, at run-time if is {@code true}.
 *
 * @param <E> type of the blackboard object that tasks use to read or modify game state
 *
 * @author davebaol
 * @author implicit-invocation */
@TaskConstraint(minChildren=0, maxChildren=0)
public class Include<E> extends Decorator<E> {

	/** The path of the subtree we're referencing to. */
	@TaskAttribute(required=true)
	public String subtree;

	/** Whether the subtree should be included at clone-time ({@code false}, the default) or at run-time ({@code true}). */
	@TaskAttribute
	public boolean lazy;

	/** Creates a non-lazy {@code Include} decorator without specifying the subtree. */
	public Include () {
	}

	/** Creates a non-lazy {@code Include} decorator for the specified subtree.
	 * @param subtree the subtree reference, usually a path */
	public Include (String subtree) {
		this.subtree = subtree;
	}

	/** Creates an eager or lazy {@code Include} decorator for the specified subtree.
	 * @param subtree the subtree reference, usually a path
	 * @param lazy whether inclusion should happen at clone-time (false) or at run-time (true) */
	public Include (String subtree, boolean lazy) {
		this.subtree = subtree;
		this.lazy = lazy;
	}

	/** The first call of this method lazily sets its child to the referenced subtree created through the
	 * {@link BehaviorTreeLibraryManager}, then invoke the same method of the superclass. Subsequent calls invoke the same method
	 * of the superclass directly since the child has already been set. A {@link UnsupportedOperationException} is thrown if this
	 * {@code Include} is eager.
	 *
	 * @param control the parent task
	 * @throws UnsupportedOperationException if this {@code Include} is eager */
	@Override
	public void setControl (Task<E> control) {
		if (!lazy)
			throw new UnsupportedOperationException("A non-lazy " + Include.class.getSimpleName() + " isn't meant to be run!");

		if (child == null) {
			// Lazy include is grafted at run-time
			child = createSubtreeRootTask();
		}

		super.setControl(control);
	}

	/** Returns a clone of the referenced subtree if this {@code Import} is eager; otherwise returns a clone of itself. */
	public Task<E> cloneTask () {
		if (lazy) return super.cloneTask();

		// Non lazy include is grafted at clone-time
		return createSubtreeRootTask();
	}

	/** Copies this {@code Include} to the given task. A {@link TaskCloneException} is thrown if this {@code Include} is eager.
	 * @param task the task to be filled
	 * @return the given task for chaining
	 * @throws TaskCloneException if this {@code Include} is eager. */
	@Override
	protected Task<E> copyTo (Task<E> task) {
		if (!lazy) throw new TaskCloneException("A non-lazy " + getClass().getSimpleName() + " should never be copied.");

		Include<E> include = (Include<E>)task;
		include.subtree = subtree;
		include.lazy = lazy;

		return task;
	}

	private Task<E> createSubtreeRootTask () {
		return BehaviorTreeLibraryManager.getInstance().createRootTask(subtree);
	}
}


text:
package org.wso2.carbon.cassandra.search.session;

import org.apache.axis2.context.MessageContext;
import org.apache.axis2.context.ServiceContext;

public class SearchSessionManager {

    public static void setSessionObject(String name, Object obj) {
        MessageContext messageContext = MessageContext.getCurrentMessageContext();
        if (messageContext != null) {
            ServiceContext serviceContext = messageContext.getServiceContext();
            if (serviceContext != null) {
                serviceContext.setProperty(name, obj);
            }
        }
    }

    public static Object getSessionObject(String name) {
        MessageContext messageContext = MessageContext.getCurrentMessageContext();
        if (messageContext != null) {
            ServiceContext serviceContext = messageContext.getServiceContext();
            if (serviceContext != null) {
                return serviceContext.getProperty(name);
            }
        }
        return null;
    }
}


text:
module Fog
  module Compute
    class Joyent

      class Mock
        def delete_key(keyname)
          if self.data[:keys].delete(keyname)
            response = Excon::Response.new
            response.status = 204
            response
          else
            raise Excon::Errors::NotFound, "Not Found"
          end
        end
      end

      class Real
        def delete_key(name)
          request(
            :method => "DELETE",
            :path => "/my/keys/#{name}",
            :expects => 204
          )
        end
      end # Real

    end
  end
end


text:
#ifndef WebPrescientNetworking_h
#define WebPrescientNetworking_h

#include "WebCommon.h"
#include "WebString.h"
#include "WebURL.h"

namespace blink {

class WebPrescientNetworking {
public:
    virtual ~WebPrescientNetworking() { }

    // When a page navigation is speculated, DNS prefetch is triggered to hide
    // the host resolution latency.
    virtual void prefetchDNS(const WebString& hostname) { }

    virtual void preconnect(const WebURL& url, const bool allowCredentials) { }
};

} // namespace blink

#endif // WebPrescientNetworking_h


text:
package tlc2.tool.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import tla2sany.modanalyzer.ModulePointer;
import tla2sany.modanalyzer.ParseUnit;
import tla2sany.modanalyzer.SpecObj;
import tla2sany.semantic.AbortException;
import tla2sany.semantic.Errors;
import tla2sany.semantic.ExprNode;
import tla2sany.semantic.ExternalModuleTable;
import tla2sany.semantic.ModuleNode;
import tla2sany.semantic.OpDefNode;
import tlc2.tool.Action;
import tlc2.util.Context;
import tlc2.value.impl.StringValue;
import util.FilenameToStream;

public class ParameterizedSpecObj extends SpecObj {

	public static final String POST_CONDITIONS = "POST_CONDITIONS";
	public static final String INVARIANT = "INVARIANT";

	private final Spec spec;
	private final Map<String, Object> params;

	public ParameterizedSpecObj(final Spec spec, final FilenameToStream resolver, final Map<String, Object> params) {
		super(spec.rootFile, resolver);
		this.spec = spec;
		this.params = params;
	}

	@Override
	protected final ParseUnit findOrCreateParsedUnit(final String name, final Errors errors, final boolean firstCall)
			throws AbortException {
		final ParseUnit pu = super.findOrCreateParsedUnit(name, errors, firstCall);
		if (firstCall && params.containsKey(POST_CONDITIONS)) {
			final ModulePointer rootModule = pu.getRootModule();

			@SuppressWarnings("unchecked")
			final List<PostCondition> pcs = (List<PostCondition>) params.get(POST_CONDITIONS);
			for (PostCondition pc : pcs) {
				rootModule.getRelatives().addExtendee(pc.module);
			}
		}
		if (firstCall && params.containsKey(INVARIANT)) {
			final ModulePointer rootModule = pu.getRootModule();

			@SuppressWarnings("unchecked")
			final List<Invariant> invs = (List<Invariant>) params.get(INVARIANT);
			for (Invariant inv : invs) {
				rootModule.getRelatives().addExtendee(inv.module);
			}
		}
		return pu;
	}

	@Override
	public List<ExprNode> getPostConditionSpecs() {
		final List<ExprNode> res = new ArrayList<>();

		@SuppressWarnings("unchecked")
		final List<PostCondition> pcs = (List<PostCondition>) params.getOrDefault(POST_CONDITIONS, new ArrayList<>());
		for (PostCondition pc : pcs) {

			final ExternalModuleTable mt = getExternalModuleTable();
			final ModuleNode moduleNode = mt.getModuleNode(pc.module);
			final OpDefNode opDef = moduleNode.getOpDef(pc.operator);

			for (Map.Entry<String, String> entry : pc.redefinitions.entrySet()) {
				final OpDefNode redefined = moduleNode.getOpDef(entry.getKey());
				redefined.setToolObject(spec.getId(), new StringValue(entry.getValue()));
			}

			res.add(opDef.getBody());
		}
		return res;
	}

	public static class PostCondition {
		public final String module;
		public final String operator;
		public final Map<String, String> redefinitions;

		public PostCondition(String moduleBangOp) {
			this(moduleBangOp.split("!")[0], moduleBangOp.split("!")[1]);
		}

		public PostCondition(String module, String operator) {
			this(module, operator, new HashMap<>());
		}

		public PostCondition(final String module, final String operator, final String def, final String redef) {
			this(module, operator);
			this.redefinitions.put(def, redef);
		}

		public PostCondition(String module, String operator, Map<String, String> redefinitions) {
			super();
			this.module = module;
			this.operator = operator;
			this.redefinitions = redefinitions;
		}
	}

	public static class Invariant {
		public final String module;
		public final String operator;

		public Invariant(String module, String operator) {
			super();
			this.module = module;
			this.operator = operator;
		}
	}

	@Override
	public List<Action> getInvariants() {
		final List<Action> res = new ArrayList<>();

		@SuppressWarnings("unchecked")
		final List<Invariant> invs = (List<Invariant>) params.getOrDefault(INVARIANT, new ArrayList<>());
		for (Invariant inv : invs) {

			final ExternalModuleTable mt = getExternalModuleTable();
			final ModuleNode moduleNode = mt.getModuleNode(inv.module);
			final OpDefNode opDef = moduleNode.getOpDef(inv.operator);

			res.add(new Action(opDef.getBody(), Context.Empty, opDef, false, true));
		}
		return res;
	}
}


text:
import React from 'react'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
import {selectToken} from '@inab/shared'
import {LoginScreen} from './LoginScreen'
import {MainTabNavigator} from './MainTabNavigator'

const mapStateToProps = state => ({
  token: selectToken(state),
})

@connect(mapStateToProps)
export class LoginDispatcher extends React.Component {
  static propTypes = {
    token: PropTypes.string,
  }

  render() {
    if (this.props.token) {
      return <MainTabNavigator />
    }
    return <LoginScreen />
  }
}


text:
package br.com.swconsultoria.nfe.schema.retEnvEpec;

import javax.xml.bind.annotation.*;

/**
 * Tipo procEvento
 *
 *
Classe Java de TProcEvento complex type.
 *
 *
O seguinte fragmento do esquema especifica o contedo esperado contido dentro desta classe.
 *
 *

 * <complexType name="TProcEvento">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="evento" type="{http://www.portalfiscal.inf.br/nfe}TEvento"/>
 *         <element name="retEvento" type="{http://www.portalfiscal.inf.br/nfe}TRetEvento"/>
 *       </sequence>
 *       <attribute name="versao" use="required" type="{http://www.portalfiscal.inf.br/nfe}TVerEvento" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TProcEvento", namespace = "http://www.portalfiscal.inf.br/nfe", propOrder = {
        "evento",
        "retEvento"
})
public class TProcEvento {

    @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
    protected TEvento evento;
    @XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
    protected TRetEvento retEvento;
    @XmlAttribute(name = "versao", required = true)
    protected String versao;

    /**
     * Obtm o valor da propriedade evento.
     *
     * @return possible object is
     * {@link TEvento }
     */
    public TEvento getEvento() {
        return evento;
    }

    /**
     * Define o valor da propriedade evento.
     *
     * @param value allowed object is
     *              {@link TEvento }
     */
    public void setEvento(TEvento value) {
        this.evento = value;
    }

    /**
     * Obtm o valor da propriedade retEvento.
     *
     * @return possible object is
     * {@link TRetEvento }
     */
    public TRetEvento getRetEvento() {
        return retEvento;
    }

    /**
     * Define o valor da propriedade retEvento.
     *
     * @param value allowed object is
     *              {@link TRetEvento }
     */
    public void setRetEvento(TRetEvento value) {
        this.retEvento = value;
    }

    /**
     * Obtm o valor da propriedade versao.
     *
     * @return possible object is
     * {@link String }
     */
    public String getVersao() {
        return versao;
    }

    /**
     * Define o valor da propriedade versao.
     *
     * @param value allowed object is
     *              {@link String }
     */
    public void setVersao(String value) {
        this.versao = value;
    }

}


text:
START_ATF_NAMESPACE
    struct _PROFILE_ELMENT
    {
        char mName[32];
        unsigned __int64 m_qwStartTicks;
        float m_TotalTime;
        float m_LoopTime;
    };
END_ATF_NAMESPACE


text:
<?xml version="1.0"?>
<project name="org.strategoxt.StrategoXT.atermfront" default="all">
	<!-- Import Stratego/XT Ant contributions -->
	<taskdef resource="org/strategoxt/antcontrib/strategoxt-antlib.xml" />

	<!-- Import Ant contrib -->
	<taskdef resource="net/sf/antcontrib/antlib.xml" />

	<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter" />

	<!-- Build configuration. Overwrite these from importer -->
	<property name="sdf2bundle" value="${user.home}/.nix-profile" />
	<property name="nativepath" value="${sdf2bundle}/bin/" />
	<property name="install-prefix" location="dist" />
	<property name="install-location" location="${install-prefix}/share/strategoxt/aterm-front" />

	<property name="syn" value="syn" />
	<property name="bin" value="bin" />

	<target name="all" depends="build, install" />

	<target name="build" depends="build-syntax" />

	<target name="build-syntax">
		<mkdir dir="${bin}/${syn}" />

		<sdf2generated base="${syn}/ATerms" main="ATerms" output="${bin}">
			<includeargs>
				<args>
					<arg value="-I" />
					<arg value="${sdf2bundle}/share/sdf-library/library" />
				</args>
			</includeargs>
		</sdf2generated>
	</target>

	<target name="install">
		<mkdir dir="${install-location}" />
		<copy todir="${install-location}">
			<fileset dir="${bin}" includes="ATerms.str, ATerms.rtg, ATerms.pp*" />
		</copy>

		<mkdir dir="${install-location}/sdf" />
		<copy todir="${install-location}/sdf">
			<fileset dir="${bin}" includes="ATerms.def, ATerms.tbl" />
		</copy>
	</target>

	<target name="clean">
		<delete dir="${bin}" />
		<delete dir="${install-location}" />
	</target>
</project>


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.7/15.7.3/15.7.3.1/15.7.3.1-2.js
 * @description Number.prototype, initial value is the Number prototype object
 */

function testcase() {
  // assume that Number.prototype has not been modified.
  return Object.getPrototypeOf(new Number(42))===Number.prototype;
 }
runTestCase(testcase);


text:
package org.globus.gsi.bc;

import java.io.IOException;

import org.bouncycastle.asn1.DEREncodable;

import org.globus.gsi.X509Extension;

/**
 * A convenience class for creating X.509 extensions from
 * DEREncodable objects.
 */
public class BouncyCastleX509Extension extends X509Extension {

    public BouncyCastleX509Extension(String oid) {
	this(oid, false, null);
    }

    public BouncyCastleX509Extension(String oid, DEREncodable value) {
	this(oid, false, value);
    }

    public BouncyCastleX509Extension(String oid, boolean critical,
				     DEREncodable value) {
	super(oid, critical, null);
	setValue(value);
    }

    protected void setValue(DEREncodable value) {
	if (value == null) {
	    return;
	}
    	try {
	    setValue(BouncyCastleUtil.toByteArray(value.getDERObject()));
	} catch (IOException e) {
	    throw new RuntimeException("Failed to convert to byte array: " +
				       e.getMessage());
	}
    }
}


text:
#ifndef UVW_REQUEST_INCLUDE_H
#define UVW_REQUEST_INCLUDE_H

#include <memory>
#include <type_traits>
#include <utility>
#include <uv.h>
#include "resource.hpp"

namespace uvw {

/**
 * @brief Request base class.
 *
 * Base type for all `uvw` request types.
 */
template<typename T, typename U>
class Request: public Resource<T, U> {
protected:
    static auto reserve(U *req) {
        auto ptr = static_cast<T *>(req->data)->shared_from_this();
        ptr->reset();
        return ptr;
    }

    template<typename E>
    static void defaultCallback(U *req, int status) {
        if(auto ptr = reserve(req); status) {
            ptr->publish(ErrorEvent{status});
        } else {
            ptr->publish(E{});
        }
    }

    template<typename F, typename... Args>
    auto invoke(F &&f, Args &&...args) {
        if constexpr(std::is_void_v<std::invoke_result_t<F, Args...>>) {
            std::forward<F>(f)(std::forward<Args>(args)...);
            this->leak();
        } else {
            if(auto err = std::forward<F>(f)(std::forward<Args>(args)...); err) {
                Emitter<T>::publish(ErrorEvent{err});
            } else {
                this->leak();
            }
        }
    }

public:
    using Resource<T, U>::Resource;

    /**
     * @brief Cancels a pending request.
     *
     * This method fails if the request is executing or has finished
     * executing.<br/>
     * It can emit an ErrorEvent event in case of errors.
     *
     * See the official
     * [documentation](http://docs.libuv.org/en/v1.x/request.html#c.uv_cancel)
     * for further details.
     *
     * @return True in case of success, false otherwise.
     */
    bool cancel() {
        return (0 == uv_cancel(this->template get<uv_req_t>()));
    }

    /**
     * @brief Returns the size of the underlying request type.
     * @return The size of the underlying request type.
     */
    std::size_t size() const noexcept {
        return uv_req_size(this->template get<uv_req_t>()->type);
    }
};

} // namespace uvw

#endif // UVW_REQUEST_INCLUDE_H


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/** @suppress {duplicate} */
var remoting = remoting || {};

/** @constructor */
remoting.MessageWindowOptions = function() {
  /** @type {string} */
  this.title = '';

  /** @type {string} */
  this.message = '';

  /** @type {string} */
  this.buttonLabel = '';

  /** @type {string} */
  this.cancelButtonLabel = '';

  /** @type {function(number):void} */
  this.onResult = function() {};

  /** @type {number} */
  this.duration = 0;

  /** @type {string} */
  this.infobox = '';

  /** @type {?function():void} */
  this.onTimeout = function() {};
};

/**
 * Create a new message window.
 *
 * @param {remoting.MessageWindowOptions} options Message window create options
 * @constructor
 */
remoting.MessageWindow = function(options) {
  var title = options.title;
  var message = options.message;
  var okButtonLabel = options.buttonLabel;
  var cancelButtonLabel = options.cancelButtonLabel;
  var onResult = options.onResult;
  var duration = 0;
  if (options.duration) {
    duration = options.duration;
  }
  var infobox = '';
  if (options.infobox) {
    infobox = options.infobox;
  }
  var onTimeout = options.onTimeout;

  /** @type {number} */
  this.id_ = remoting.MessageWindowManager.addMessageWindow(this);

  /** @type {?function(number):void} */
  this.onResult_ = onResult;

  /** @type {Window} */
  this.window_ = null;

  /** @type {number} */
  this.timer_ = 0;

  /** @type {Array<function():void>} */
  this.pendingWindowOperations_ = [];

  /**
   * Callback to call when the timeout expires.
   * @type {?function():void}
   */
  this.onTimeout_ = onTimeout;

  var message_struct = {
    command: 'show',
    id: this.id_,
    title: title,
    message: message,
    infobox: infobox,
    buttonLabel: okButtonLabel,
    cancelButtonLabel: cancelButtonLabel,
    showSpinner: (duration != 0)
  };

  var windowAttributes = {
    bounds: {
      width: 400,
      height: 100
    },
    resizable: false
  };

  /** @type {remoting.MessageWindow} */
  var that = this;

  /** @param {AppWindow} appWindow */
  var onCreate = function(appWindow) {
    that.setWindow_(/** @type {Window} */(appWindow.contentWindow));
    var onLoad = function() {
      appWindow.contentWindow.postMessage(message_struct, '*');
    };
    appWindow.contentWindow.addEventListener('load', onLoad, false);
  };

  chrome.app.window.create('message_window.html', windowAttributes, onCreate);

  if (duration != 0) {
    this.timer_ = window.setTimeout(this.onTimeoutHandler_.bind(this),
                                    duration);
  }
};

/**
 * Called when the timer runs out. This in turn calls the window's
 * timeout handler (if any).
 */
remoting.MessageWindow.prototype.onTimeoutHandler_ = function() {
  this.close();
  if (this.onTimeout_) {
    this.onTimeout_();
  }
};

/**
 * Update the message being shown in the window. This should only be called
 * after the window has been shown.
 *
 * @param {string} message The message.
 */
remoting.MessageWindow.prototype.updateMessage = function(message) {
  if (!this.window_) {
    this.pendingWindowOperations_.push(this.updateMessage.bind(this, message));
    return;
  }

  var message_struct = {
    command: 'update_message',
    message: message
  };
  this.window_.postMessage(message_struct, '*');
};

/**
 * Close the message box and unregister it with the window manager.
 */
remoting.MessageWindow.prototype.close = function() {
  if (!this.window_) {
    this.pendingWindowOperations_.push(this.close.bind(this));
    return;
  }

  if (this.timer_) {
    window.clearTimeout(this.timer_);
  }
  this.timer_ = 0;

  // Unregister the window with the window manager.
  // After this call, events sent to this window will no longer trigger the
  // onResult callback.
  remoting.MessageWindowManager.deleteMessageWindow(this.id_);
  this.window_.close();
  this.window_ = null;
};

/**
 * Dispatch a message box result to the registered callback.
 *
 * @param {number} result The dialog result.
 */
remoting.MessageWindow.prototype.handleResult = function(result) {
  if (this.onResult_) {
    this.onResult_(result);
  }
}

/**
 * Set the window handle and run any pending operations that require it.
 *
 * @param {Window} window
 * @private
 */
remoting.MessageWindow.prototype.setWindow_ = function(window) {
  base.debug.assert(this.window_ == null);
  this.window_ = window;
  for (var i = 0; i < this.pendingWindowOperations_.length; ++i) {
    var pendingOperation = this.pendingWindowOperations_[i];
    pendingOperation();
  }
  this.pendingWindowOperations_ = [];
};

/**
 * Static method to create and show a confirm message box.
 *
 * @param {string} title The title of the message box.
 * @param {string} message The message.
 * @param {string} okButtonLabel The text for the primary button.
 * @param {string} cancelButtonLabel The text for the secondary button.
 * @param {function(number):void} onResult The callback to invoke when the
 *     user closes the message window.
 * @return {remoting.MessageWindow}
 */
remoting.MessageWindow.showConfirmWindow = function(
    title, message, okButtonLabel, cancelButtonLabel, onResult) {
  var options = /** @type {remoting.MessageWindowOptions} */ ({
    title: title,
    message: message,
    buttonLabel: okButtonLabel,
    cancelButtonLabel: cancelButtonLabel,
    onResult: onResult
  });
  return new remoting.MessageWindow(options);
};

/**
 * Static method to create and show a simple message box.
 *
 * @param {string} title The title of the message box.
 * @param {string} message The message.
 * @param {string} buttonLabel The text for the primary button.
 * @param {function(number):void} onResult The callback to invoke when the
 *     user closes the message window.
 * @return {remoting.MessageWindow}
 */
remoting.MessageWindow.showMessageWindow = function(
    title, message, buttonLabel, onResult) {
  var options = /** @type {remoting.MessageWindowOptions} */ ({
    title: title,
    message: message,
    buttonLabel: buttonLabel,
    onResult: onResult
  });
  return new remoting.MessageWindow(options);
};

/**
 * Static method to create and show an error message box with an "OK" button.
 * The app will close when the user dismisses the message window.
 *
 * @param {string} title The title of the message box.
 * @param {string} message The message.
 * @return {remoting.MessageWindow}
 */
remoting.MessageWindow.showErrorMessage = function(title, message) {
  var options = /** @type {remoting.MessageWindowOptions} */ ({
    title: title,
    message: message,
    buttonLabel: chrome.i18n.getMessage(/*i18n-content*/'OK'),
    onResult: remoting.MessageWindow.quitApp
  });
  return new remoting.MessageWindow(options);
};

/**
 * Static method to create and show a timed message box.
 *
 * @param {string} title The title of the message box.
 * @param {string} message The message.
 * @param {string} infobox Additional information to be displayed in an infobox,
 *     or the empty string if there is no additional information.
 * @param {string} buttonLabel The text for the primary button.
 * @param {function(number):void} onResult The callback to invoke when the
 *     user closes the message window.
 * @param {number} duration Time for wait before calling onTime
 * @param {?function():void} onTimeout Callback function.
 * @return {remoting.MessageWindow}
 */
remoting.MessageWindow.showTimedMessageWindow = function(
    title, message, infobox, buttonLabel, onResult, duration, onTimeout) {
  var options = /** @type {remoting.MessageWindowOptions} */ ({
    title: title,
    message: message,
    infobox: infobox,
    buttonLabel: buttonLabel,
    onResult: onResult,
    duration: duration,
    onTimeout: onTimeout
  });
  return new remoting.MessageWindow(options);
};

/**
 * Cancel the current connection and close all app windows.
 *
 * @param {number} result The dialog result.
 */
remoting.MessageWindow.quitApp = function(result) {
  remoting.MessageWindowManager.closeAllMessageWindows();
  window.close();
};


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Tic-Tac-Toe</title>

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

Tic-Tac-Toe

      <button type="button" class="ticTacToe"></button>
      <button type="button" class="ticTacToe"></button>
      <button type="button" class="ticTacToe"></button>
      <button type="button" class="ticTacToe"></button>
      <button type="button" class="ticTacToe"></button>
      <button type="button" class="ticTacToe"></button>
      <button type="button" class="ticTacToe"></button>
      <button type="button" class="ticTacToe"></button>
      <button type="button" class="ticTacToe"></button>

Player: Player 1


text:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Misc } from '../../components';

class MiscContainer extends Component {
  render() {
    return <Misc {...this.props} />;
  }
}

function mapStateToProps(state) {
  return {
    emojis: state.shared.emojis,
    gitignoreTemplates: state.shared.gitignoreTemplates
  };
}

export default connect(mapStateToProps)(MiscContainer);


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!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/html; charset=UTF-8" />
    <title>Preface</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.62.4" />
    <link rel="home" href="index.html" title="Berkeley DB Collections Tutorial" />
    <link rel="up" href="index.html" title="Berkeley DB Collections Tutorial" />
    <link rel="previous" href="index.html" title="Berkeley DB Collections Tutorial" />
    <link rel="next" href="moreinfo.html" title="For More Information" />

          Preface

          Prev

           Next

Preface

          Table of Contents

              Conventions Used in this Book

              For More Information

        Welcome to the Berkeley DB (DB) Collections API.  This document
        provides a tutorial that introduces the collections API.
        The goal of this document is to provide you with an efficient mechanism
        with which you can quickly become efficient with this API. As such, this document is
        intended for Java developers and senior software architects who are
        looking for transactionally-protected backing of their Java collections.
        No prior experience with DB technologies is expected or required.

Conventions Used in this Book

        The following typographical conventions are used within in this manual:

        Class names are represented in <tt class="classname">monospaced font</tt>, as are <tt class="methodname">method
        names</tt>. For example: "The <tt class="methodname">Environment.openDatabase()</tt> method
		returns a <tt class="classname">Database</tt> class object."

        Variable or non-literal text is presented in italics. For example: "Go to your
         DB_INSTALLATION_HOME directory."

        Program examples are displayed in a monospaced font on a shaded background. For example:

import com.sleepycat.db.Environment;
import com.sleepycat.db.EnvironmentConfig;
import java.io.File;

...

// Open the environment. Allow it to be created if it does not already exist.
Environment myDbEnvironment;

        In situations in this book, programming examples are updated from one chapter to the next in this book. When
        this occurs, the new code is presented in <tt>monospaced bold</tt> font. For example:

import com.sleepycat.db.Environment;
import com.sleepycat.db.EnvironmentConfig;
import java.io.File;

...

// Open the environment. Allow it to be created if it does not already exist.
<tt>Environment myDbEnv;
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
myDbEnv = new Environment(new File("/export/dbEnv"), envConfig);</tt>

          Prev

            Up

           Next

          Berkeley DB Collections Tutorial

            Home

           For More Information


text:
module Geni
  class Document < Base
    has_fetchable_attributes %w[
      title url date date_parts content_type description sizes
    ]

    include Taggable
  end
end


text:
var blockChainInfoWs = require("blockchain"),
    fs = require("fs"),
    sql = require("sql"),
    pg = require("pg");

// Configuration
var dbConfigFile = __dirname + "/.pgpass";

// Parse DB Credentials
var config = (fs.readFileSync(dbConfigFile, { encoding : "ascii" })).trim().split(":"),
    hostname = config[0],
    port = config[1],
    database = config[2],
    username = config[3],
    password = config[4],
    dbUrl = "postgres://" + username + ":" + password + "@" + hostname + ":" + port + "/" + database;

// Create function that will handle loading of PostgreSQL data (asynchronously)
var pgload = function(dbUrl, tableName, insertFields, data, callback) {
    pg.connect(dbUrl, function(err, client, done) { // Connect!
        if(err) {
            // console.log("Could not connect to database.");
            callback(err);
        }

        var table = sql.define({ name : tableName, columns: insertFields});
        client.query(table.insert(data).toString(), function(err, result) {
            done();
            if(err) {
                return callback(err);
            } else {
                return callback(null,true);
            }
        });
    });
};

// Establish socket and attempt to reconnect if broken
var socket = new blockChainInfoWs();
socket.on("disconnect", function() {
    console.log("Experienced a disconnection @ " + (new Date()).toISOString());
    console.log("Attempting to reconnect...");
    socket.connect();
});

// Subscribe to the unconfirmed transaction feed and load relevant details on reception
socket.subscribeUnconfirmed( function(message) {
    // console.log("Received the following transaction broadcast: %o", message);
    var broadcastData = [{
        hash : message.hash,
        tx_index : message.tx_index,
        relayed_by : message.relayed_by,
        posted_time : (new Date(message.time*1000)).toISOString().replace("T",' ').replace(".000Z","+00"),
        receipt_time : (new Date()).toISOString().slice(0,-5).replace("T",' ') + "+00"
    }];
    pgload(dbUrl, 'tx', ['hash','tx_index','relayed_by','posted_time', 'receipt_time'], broadcastData, function(err, result) {
        if(err) {
            console.log("Could not load the following data: %o", broadcastData);
            console.log("Error message is as follows: %s", err.message);
        }
    });
});

// Subscribe to the block feed and load relevant details on receipt of messages
socket.subscribeBlocks( function(message) {
    // console.log("Received the following block broadcast: %o", message);
    var broadcastData = [{
        hash : message.hash,
        mrkl_root : message.mrklRoot,
        height : message.height,
        block_index : message.blockIndex,
        prev_block_index : message.prevBlockIndex,
        posted_time : (new Date(message.time*1000)).toISOString().replace("T",' ').replace(".000Z","+00"),
        receipt_time : (new Date()).toISOString().slice(0,-5).replace("T",' ') + "+00"
    }];
    pgload(dbUrl, 'block', ['hash','mrkl_root', 'height', 'block_index','prev_block_index','posted_time','receipt_time'], broadcastData, function(err, result) {
        if(err) {
            console.log("Could not load the following data: %o", broadcastData);
            console.log("Error message is as follows: %s", err.message);
        }
    });
});


text:
package org.auraframework.impl.css.flavor;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.auraframework.def.AttributeDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.FlavorBundleDef;
import org.auraframework.def.RegisterEventDef;
import org.auraframework.def.RequiredVersionDef;
import org.auraframework.def.RootDefinition;
import org.auraframework.impl.root.RootDefinitionImpl;
import org.auraframework.throwable.quickfix.QuickFixException;
import org.auraframework.util.json.Json;

public class FlavorBundleDefImpl extends RootDefinitionImpl<FlavorBundleDef> implements FlavorBundleDef {

    private static final long serialVersionUID = 7895713566349526564L;

    protected FlavorBundleDefImpl(Builder builder) {
        super(builder);
    }

    @Override
    public Map<String, RegisterEventDef> getRegisterEventDefs() throws QuickFixException {
        return null;
    }

    @Override
    public boolean isInstanceOf(DefDescriptor<? extends RootDefinition> other) throws QuickFixException {
        return false;
    }

    @Override
    public List<DefDescriptor<?>> getBundle() {
        return null;
    }

    @Override
    public void serialize(Json json) throws IOException {
    }

    @Override
    public Map<DefDescriptor<AttributeDef>, AttributeDef> getAttributeDefs() throws QuickFixException {
        return null;
    }

    @Override
    public Map<DefDescriptor<RequiredVersionDef>, RequiredVersionDef> getRequiredVersionDefs() {
        return null;
    }

    public static class Builder extends RootDefinitionImpl.Builder<FlavorBundleDef> {
        public Builder() {
            super(FlavorBundleDef.class);
        }

        @Override
        public FlavorBundleDef build() throws QuickFixException {
            return new FlavorBundleDefImpl(this);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.bugtrack.entity.permission" table="permission">
        <id column="permissionid" name="id" type="java.lang.Integer">
            <generator class="increment"/>
        </id>
        <property column="name" name="name" type="java.lang.String"/>
        <property column="description" name="description" type="java.lang.String"/>
    </class>
</hibernate-mapping>


text:
<oobe-adaptive-dialog
  hidden="[[!checkingForUpdate]]"
  aria-live="polite"
  id="checking-for-updates-dialog"
  footer-shrinkable
>
  <iron-icon slot="icon" icon="oobe-32:googleg"></iron-icon>

[[i18nDynamic(locale, 'checkingForUpdates')]]

    [[i18nDynamic(locale, checkingForUpdatesKey)]]

    [[i18nDynamic(locale, 'cancelUpdateHint')]]

  <paper-progress
    slot="progress"
    id="checking-progress"
    indeterminate="[[checkingForUpdate]]"
  >
  </paper-progress>

    <oobe-cr-lottie
      id="checkingAnimation"
      animation-url="animations/checking_for_update.json"
    >
    </oobe-cr-lottie>

</oobe-adaptive-dialog>

<oobe-adaptive-dialog
  footer-shrinkable
  id="updating-dialog"
  hidden="[[isCheckingOrUpdateCompleted_(checkingForUpdate,
                                               updateCompleted)]]"
  aria-live="polite"
>
  <iron-icon slot="icon" icon="oobe-32:googleg"></iron-icon>

[[i18nDynamic(locale, 'updatingTitle')]]

[[i18nDynamic(locale, downloadingUpdatesKey)]]

      [[i18nDynamic(locale, 'cancelUpdateHint')]]

      [[progressMessage_]]

  <paper-progress
    id="updating-progress"
    slot="progress"
    min="0"
    max="100"
    value="[[progressValue]]"
  >
  </paper-progress>

</oobe-adaptive-dialog>

<oobe-adaptive-dialog
  footer-shrinkable
  id="update-complete-dialog"
  hidden="[[!updateCompleted]]"
  aria-live="polite"
>
  <iron-icon slot="icon" icon="oobe-32:googleg"></iron-icon>

[[i18nDynamic(locale, 'updateCompeletedMsg')]]

</oobe-adaptive-dialog>


text:
#ifndef BOOST_HANA_FUNCTIONAL_REVERSE_PARTIAL_HPP
#define BOOST_HANA_FUNCTIONAL_REVERSE_PARTIAL_HPP

#include <hana/basic_tuple.hpp>
#include <hana/config.hpp>
#include <hana/detail/decay.hpp>

#include <cstddef>
#include <utility>

BOOST_HANA_NAMESPACE_BEGIN
    //! @ingroup group-functional
    //! Partially apply a function to some arguments.
    //!
    //! Given a function `f` and some arguments, `reverse_partial` returns a
    //! new function corresponding to `f` whose last arguments are partially
    //! applied. Specifically, `reverse_partial(f, x...)` is a function such
    //! that
    //! @code
    //!     reverse_partial(f, x...)(y...) == f(y..., x...)
    //! @endcode
    //!
    //! @note
    //! The arity of `f` must match the total number of arguments passed to
    //! it, i.e. `sizeof...(x) + sizeof...(y)`.
    //!
    //!
    //! Example
    //! -------
    //! @include example/functional/reverse_partial.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
    constexpr auto reverse_partial = [](auto&& f, auto&& ...x) {
        return [perfect-capture](auto&& ...y) -> decltype(auto) {
            return forwarded(f)(forwarded(y)..., forwarded(x)...);
        };
    };
#else
    template <typename Indices, typename F, typename ...X>
    struct reverse_partial_t;

    struct make_reverse_partial_t {
        struct secret { };
        template <typename F, typename ...X>
        constexpr reverse_partial_t<
            std::make_index_sequence<sizeof...(X)>,
            typename detail::decay<F>::type,
            typename detail::decay<X>::type...
        > operator()(F&& f, X&& ...x) const {
            return {secret{}, static_cast<F&&>(f), static_cast<X&&>(x)...};
        }
    };

    template <std::size_t ...n, typename F, typename ...X>
    struct reverse_partial_t<std::index_sequence<n...>, F, X...> {
        reverse_partial_t() = default;

        template <typename ...T>
        constexpr reverse_partial_t(make_reverse_partial_t::secret, T&& ...t)
            : storage_{static_cast<T&&>(t)...}
        { }

        basic_tuple<F, X...> storage_;

        template <typename ...Y>
        constexpr decltype(auto) operator()(Y&& ...y) const& {
            return hana::get_impl<0>(storage_)(
                static_cast<Y&&>(y)...,
                hana::get_impl<n+1>(storage_)...
            );
        }

        template <typename ...Y>
        constexpr decltype(auto) operator()(Y&& ...y) & {
            return hana::get_impl<0>(storage_)(
                static_cast<Y&&>(y)...,
                hana::get_impl<n+1>(storage_)...
            );
        }

        template <typename ...Y>
        constexpr decltype(auto) operator()(Y&& ...y) && {
            return static_cast<F&&>(hana::get_impl<0>(storage_))(
                static_cast<Y&&>(y)...,
                static_cast<X&&>(hana::get_impl<n+1>(storage_))...
            );
        }
    };

    constexpr make_reverse_partial_t reverse_partial{};
#endif
BOOST_HANA_NAMESPACE_END

#endif // !BOOST_HANA_FUNCTIONAL_REVERSE_PARTIAL_HPP