text:
title: "Checks"
description: "Reference documentation for Sensu Checks."
product: "Sensu Core"
version: "1.8"
weight: 3
menu:
  sensu-core-1.8:
    parent: reference
---

## Reference documentation

- [What is a Sensu check?](#what-is-a-sensu-check)
  - [Sensu check specification](#sensu-check-specification)
- [Check commands](#check-commands)
  - [What is a check command?](#what-is-a-check-command)
  - [Check command arguments](#check-command-arguments)
  - [How and where are check commands executed?](#how-and-where-are-check-commands-executed)
- [Check execution platform](#check-execution-platform)
  - [How are checks scheduled?](#how-are-checks-scheduled)
    - [Subscription checks](#subscription-checks)
    - [Standalone checks](#standalone-checks)
- [Check results](#check-results)
  - [What is a check result?](#what-is-a-check-result)
  - [Example check result output](#example-check-result-output)
- [Check token substitution](#check-token-substitution)
  - [What is check token substitution?](#what-is-check-token-substitution)
  - [Example check tokens](#example-check-tokens)
  - [Check token specification](#check-token-specification)
- [Check hooks](#check-hooks)
  - [What are check hooks?](#what-are-check-hooks)
  - [Example check hooks](#example-check-hooks)
- [Managing checks](#managing-checks)
- [Check configuration](#check-configuration)
  - [Example check definition](#example-check-definition)
  - [Check definition specification](#check-definition-specification)
    - [Check naming](#check-names)
    - [`CHECK` attributes](#check-attributes)
    - [`subdue` attributes](#subdue-attributes)
    - [`influxdb` attributes](#influxdb-attributes)
    - [`opsgenie` attributes](#opsgenie-attributes)
    - [`hooks` attributes](#hooks-attributes)
    - [Custom attributes](#custom-attributes)
  - [Check result specification](#check-result-specification)
    - [`check` attributes](#check-result-check-attributes)
    - [`client` attributes](#check-result-client-attributes)

## What is a Sensu check?

Sensu checks are commands executed by the [Sensu client][1] which monitor a
condition (e.g. is Nginx running?) or collect measurements (e.g. how much disk
space do I have left?). Although the Sensu client will attempt to execute any
command defined for a check, successful processing of check results requires
adherence to a simple specification.

### Sensu check specification

* Result data is output to [STDOUT or STDERR][2]
  * For standard checks this output is typically a human-readable message
  * For metrics checks this output contains the measurements gathered by the
    check
* Exit status code indicates state
  * `0` indicates "OK"
  * `1` indicates "WARNING"
  * `2` indicates "CRITICAL"
  * exit status codes other than `0`, `1`, or `2` indicate an "UNKNOWN" or
    custom status

_PRO TIP: Those familiar with the [Nagios][3] monitoring system may recognize
this specification, as it is the same one used by Nagios plugins. As a result,
Nagios plugins can be used with Sensu without any modification._

At every execution of a check command – regardless of success or failure
– the Sensu client publishes the check's [result][4] for eventual handling
by the [event processor][5] (i.e. the [Sensu server][6].

## Check commands

### What is a check command?

Each [Sensu check definition][7] defines a `command` and the interval at which
it  should be executed. Check commands are literally executable commands which
will be executed on the [Sensu client][1], run as the `sensu` user. Most check
commands are provided by [Sensu check plugins][8].

### Check command arguments

Sensu check `command` attributes may include command line arguments for
controlling the behavior of the command executable. Most [Sensu check
plugins][8] provide support for command line arguments for reusability.

### How and where are check commands executed?

As mentioned above, all check commands are executed by [Sensu clients][1] as the
`sensu` user. Commands must be executable files that are discoverable on the
Sensu client system (i.e. installed in a system [`$PATH` directory][9]).

_NOTE: By default, the Sensu installer packages will modify the system `$PATH`
for the Sensu processes to include `/etc/sensu/plugins`. As a result, executable
scripts (e.g. plugins) located in `/etc/sensu/plugins` will be valid commands.
This allows `command` attributes to use "relative paths" for Sensu plugin
commands;

e.g.: `"command": "check-http.rb -u https://sensuapp.org"`_

## Check execution platform

### How are checks scheduled?

Sensu offers two distinct check execution schedulers: the [Sensu
server](../server), and the [Sensu client][10] (monitoring agent).
The Sensu server schedules and publishes check execution requests to client
subscriptions via a [Publish/Subscribe model][11] (i.e. [subscription
checks](#subscription-checks)). The Sensu client (monitoring agent) schedules and
executes [standalone checks][12] (on the local system only).
Because Sensu's execution schedulers are not mutually
exclusive, any Sensu client may be configured to both schedule and
execute it's own standalone checks as well as execute subscription checks
scheduled by the Sensu server.

#### Subscription checks

Sensu checks which are centrally defined and scheduled by the [Sensu server][6]
are called "subscription checks". Sensu's use of a [message bus (transport)][13]
for communication enables [topic-based communication][14] — where messages
are published to a specific "topic", and consumers _subscribe_ to one or more
specific topics. This form of communication is commonly referred to as the
["publish-subscribe pattern"][11], or "pubsub" for short.

Subscription checks have a defined set of [subscribers][15], a list of
[transport][13] [topics][14] that check requests will be published to. Sensu
clients become subscribers to these topics (i.e. subscriptions) via their
individual [client definition][16] `subscriptions` attribute. In practice,
subscriptions will typically correspond to a specific role and/or responsibility
(e.g. a webserver, database, etc).

Subscriptions are a powerful primitives in the monitoring context because they
allow you to effectively monitor for specific behaviors or characteristics
corresponding to the function being provided by a particular system. For
example, disk capacity thresholds might be more important (or at least
different) on a database server as opposed to a webserver; conversely, CPU
and/or memory usage thresholds might be more important on a caching system than
on a file server. Subscriptions also allow you to configure check requests for
an entire group or subgroup of systems rather than require a traditional 1:1
mapping.

#### Standalone checks

Sensu checks which are defined on a [Sensu client][1] with the [check definition
attribute][17] `standalone` set to `true` are called "standalone checks". The
Sensu client provides its own [scheduler][10] for scheduling standalone checks
which ensures scheduling
consistency between Sensu clients with identical check definitions
(assuming that system clocks are synchronized via [NTP][18]).

Standalone checks are an important complement to [subscription checks][19]
because they provide a de-centralized management alternative for Sensu.

## Check results

### What is a check result?

A check result is a [JSON][20] document published as a message on the [Sensu
transport][13] by the Sensu client upon completion of a check execution. Sensu
check results include the [check definition attributes][17] (e.g. `command`,
`subscribers`, `interval`, `name`, etc; including [custom attributes][21]), the
client name the result was submitted from, and the `output` of the check.

### Example check result output

{{}}
{
  "check": {
    "status": 0,
    "command": "check-http.rb -u https://sensuapp.org",
    "subscribers": [
      "demo"
    ],
    "interval": 60,
    "name": "sensu-website",
    "issued": 1458934742,
    "executed": 1458934742,
    "duration": 0.637,
    "output": "CheckHttp OK: 200, 78572 bytes\n"
  },
  "client": "sensu-docs"
}
{{}}

_NOTE: please refer to the [check result specification][38] (below) for more
information about check results._

## Check token substitution

### What is check token substitution?

Sensu [check definitions][17] may include attributes that you may wish to
override on a client-by-client basis. For example, [check commands][23] –
which may include [command line arguments][23] for controlling the behavior of
the check command – may benefit from client-specific thresholds, etc.
Sensu check tokens are check definition placeholders that will be replaced by
the Sensu client with the corresponding [client definition attribute][16] values
(including [custom attributes][24]).

_NOTE: Sensu check tokens were formerly known as "check command tokens"
(which limited token substitution to the check `command` attribute); command
tokens were also sometimes referred to as **"Sensu client overrides"**; a
reference to the fact that command tokens allowed client attributes to
"override" [check command arguments][23]._

_NOTE: Check tokens are processed before check execution, therefore token
substitution will not apply to check data delivered via the local [client
socket input][46]._

### Example check tokens

The following is an example Sensu [check definition][17] using three check
tokens for [check command arguments][23]. In this example, the
`check-disk-usage.rb` command accepts `-w` (warning) and `-c` (critical)
arguments to indicate the thresholds (as percentages) for creating warning or
critical events. As configured, this check will create a warning event at 80%
disk capacity, unless a different threshold is provided by the client definition
(i.e. `:::disk.warning|80:::`); and a critical event will be created if disk
capacity reaches 90%, unless a different threshold is provided by the client
definition (i.e. `:::disk.critical|90:::`). This example also creates a custom
check definition attribute called `environment`, which will default to a value
of `production`, unless a different value is provided by the client definition
(i.e. `:::environment|production:::`).

{{}}
{
  "checks": {
    "check_disk_usage": {
      "command": "check-disk-usage.rb -w :::disk.warning|80::: -c :::disk.critical|90:::",
      "subscribers": [
        "production"
      ],
      "interval": 60,
      "environment": ":::environment|production:::"
    }
  }
}
{{}}

The following example [Sensu client definition][16] would provide the necessary
attributes to override the `disk.warning`, `disk.critical`, and `environment`
tokens declared above.

{{}}
{
  "client": {
    "name": "i-424242",
    "address": "10.0.2.100",
    "subscriptions": [
      "production",
      "webserver",
      "mysql"
    ],
    "disk": {
      "warning": 75,
      "critical": 85
    },
    "environment": "development"
  }
}
{{}}

### Check token specification

#### Token substitution syntax

Check tokens are invoked by wrapping references to client attributes with
"triple colons" (i.e. three colon characters, i.e. `:::`). Nested Sensu [client
definition attributes][16] can be accessed via "dot notation" (e.g.
`disk.warning`).

- `:::address:::` would be replaced with the [client `address` attribute][26]
- `:::url:::` would be replaced with a [custom attribute][24] called `url`
- `:::disk.warning:::` would be replaced with a [custom attribute][24] called
  `warning` nested inside of a JSON hash called `disk`

#### Token substitution default values {#check-token-default-values}

Check token default values can be used as a fallback in the event that an
attribute is not provided by the [client definition][16]. Check token default
values are separated by a pipe character (`|`), and can be used to provide a
"fallback value" for clients that are missing the declared token attribute.

- `:::url|https://sensuapp.org:::` would be replaced with a [custom
  attribute][24] called `url`. If no such attribute called `url` is included in
  the client definition, the default (or fallback) value of
  `https://sensuapp.org` will be used.

#### Unmatched tokens

If a [token substitution default value][25] is not provided (i.e. as a fallback
value), _and_ the Sensu client definition does not have a matching definition
attribute, a [check result][4] indicating "unmatched tokens" will be published
for the check execution (e.g.: `"Unmatched check token(s): disk.warning"`).

#### Token data type limitations

As part of the substitution process, Sensu converts all tokens to strings.
This means that tokens cannot be used for bare integer values or to access individual list items.

For example, token substitution **cannot** be used for specifying a check interval because the interval attribute requires an _integer_ value. But token substitution **can** be used for alerting thresholds since those values are included within the command _string_.

**Invalid use of token substitution:**

The resulting interval value is a string (`"60"`) instead of an integer (`60`), causing an invalid check request.

{{}}
{
  "checks": {
    "check_disk_usage": {
      "command": "check-disk-usage.rb -w 80 -c 90",
      "interval": ":::interval|60:::"
    }
  }
}
{{}}

**Valid use of token substitution:**

The resulting tokens are included within the command string, producing a valid check request.

{{}}
{
  "checks": {
    "check_disk_usage": {
      "command": "check-disk-usage.rb -w :::disk.warning|80::: -c :::disk.critical|90:::",
      "interval": 60
    }
  }
}
{{}}

When accessing a list using token substitution, Sensu returns the list in a fixed format.
For example, for the following check definition executed on a client with the subscriptions `["sensu", "rhel", "all"]`:

{{}}
{
  "checks": {
    "token_test": {
      "command": "echo ':::subscriptions:::'",
      "standalone": true,
      "interval": 15
    }
  }
}
{{}}

The resulting command output would be:

{{}}
[\"sensu\", \"rhel\", \"all\"]
{{}}

## Check hooks

### What are check hooks? {#what-are-check-hooks}

Check hooks are commands run by the Sensu client in response to the result of check command execution. The Sensu client will execute the appropriate configured hook command, depending on the check execution status (e.g. 1). Valid hook names include (in order of precedence): "1"-"255", "ok", "warning", "critical", "unknown", and "non-zero". The check hook command output, status, executed timestamp, and duration are captured and published in the check result. Check hook commands can optionally receive JSON serialized Sensu client and check definition data via STDIN.

### Example check hooks

Check hooks can be used for automated data gathering for incident triage, for example, a check hook could be used to capture the process tree when a process has been determined to be not running etc.

{{}}
{
  "checks": {
    "nginx_process": {
      "command": "check-process.rb -p nginx",
      "subscribers": [
        "proxy"
      ],
      "interval": 60,
      "hooks": {
        "non-zero": {"command": "ps aux"}
      }
    }
  }
}
{{}}

Check hooks can also be used to add context to a check result, for example,
outputting the last 100 lines of an error log.

{{}}
{
  "checks": {
    "nginx_process": {
      "command": "check-process.rb -p nginx",
      "subscribers": [
        "proxy"
      ],
      "interval": 60,
      "hooks": {
        "critical": {"command": "tail -n 100 /var/log/nginx/error.log"}
      }
    }
  }
}
{{}}

## Managing checks

### Delete a check

To delete a check from Sensu, remove the configuration file for the check, then restart the Sensu server and API.
The following example deletes a check named `check-sensu-website`:

{{}}
# Delete the configuration file
sudo rm /etc/sensu/conf.d/check-sensu-website.json
# Restart the Sensu server and API
sudo systemctl restart sensu-{server,api}
{{}}

_NOTE: On Ubuntu 14.04, CentOS 6, and RHEL 6, use `sudo service sensu-{server,api} restart` to restart the Sensu server and API._

While removing the configuration file removes the check from the registry, it doesn't affect the history of the check or any existing check results.
To remove a deleted check's results and history from Sensu, use the [Checks API DELETE endpoint][66].
The following example deletes all check results and check history for a check named `check-sensu-website`:

{{}}
# Delete check results and check history
curl -s -i -X DELETE http://127.0.0.1:4567/checks/check-sensu-website
{{}}

### Rename a check

To rename a check, modify the [check name](#check-names) in the check configuration, then restart the Sensu server and API and use the [Checks API DELETE endpoint][66] to remove the history and check results tied to the former name.

## Check configuration

### Example check definition

The following is an example Sensu check definition, a JSON configuration file
located at `/etc/sensu/conf.d/check-sensu-website.json`. This check definition
uses a [Sensu plugin][27] named [`check-http.rb`][28] to ensure that the Sensu
website is still available. The check is named `sensu-website` and it runs on
Sensu clients with the `production` [subscription][15], at an `interval` of 60
seconds.

{{}}
{
  "checks": {
    "sensu-website": {
      "command": "check-http.rb -u https://sensuapp.org",
      "subscribers": [
        "production"
      ],
      "interval": 60,
      "contact": "ops"
    }
  }
}
{{}}

### Check definition specification

#### Check naming {#check-names}

Each check definition has a unique check name, used for the definition key.
Every check definition is within the `"checks": {}` [configuration scope][29].

- A unique string used to name/identify the check
- Cannot contain special characters or spaces
- Validated with [Ruby regex][30] `/^[\w\.-]+$/.match("check-name")`

#### `CHECK` attributes

The following attributes are configured within the `{"checks": { "CHECK": {} }
}` [configuration scope][29] (where `CHECK` is a valid [check name][41]).

type            |
----------------|------
description     | The check type, either `standard` or `metric`. Setting type to `metric` will cause OK (exit 0) check results to create events.
required        | false
type            | String
allowed values  | `standard`, `metric`
default         | `standard`
example         | {{}}"type": "metric"{{}}

command      |
-------------|------
description  | The check command to be executed.
required     | true (unless `extension` is configured)
type         | String
example      | {{}}"command": "/etc/sensu/plugins/check-chef-client.rb"{{}}

extension    |
-------------|------
description  | The name of a Sensu check extension to run instead of a command. This is an _advanced feature_ and is not commonly used.
required     | true (unless `command` is configured)
type         | String
example      | {{}}"extension": "system_profile"{{}}

standalone   |
-------------|------
description  | If the check is scheduled by the local Sensu client instead of the Sensu server (standalone mode).
required     | false
type         | Boolean
default      | false
example      | {{}}"standalone": true{{}}

subscribers  |
-------------|------
description  | An array of Sensu client subscriptions that check requests will be sent to. The array cannot be empty and its items must each be a string.
required     | true (unless `standalone` is `true`)
type         | Array
example      | {{}}"subscribers": ["production"]{{}}

publish      |
-------------|------
description  | If check requests are published for the check. If `standalone` is `true`, setting `publish` to `false` prevents the Sensu client from scheduling the check automatically.
required     | false
type         | Boolean
default      | true
example      | {{}}"publish": false{{}}

interval     |
-------------|------
description  | The frequency in seconds the check is executed.
required     | true (unless `publish` is `false` or `cron` is configured)
type         | Integer
example      | {{}}"interval": 60{{}}

cron         |
-------------|------
description  | When the check should be executed, using the [Cron syntax][47].
required     | true (unless `publish` is `false` or `interval` is configured)
type         | String
example      | {{}}"cron": "0 0 * * *"{{}}

timeout      |
-------------|------
description  | The check execution duration timeout in seconds (hard stop).
required     | false
type         | Integer
example      | {{}}"timeout": 30{{}}

stdin        |
-------------|------
description  | If the Sensu client writes JSON serialized Sensu client and check data to the command process' STDIN. The command must expect the JSON data via STDIN, read it, and close STDIN. This attribute cannot be used with existing Sensu check plugins, nor Nagios plugins etc, as the Sensu client will wait indefinitely for the check process to read and close STDIN.
required     | false
type         | boolean
example      | {{}}"stdin": true{{}}

ttl          |
-------------|------
description  | The time to live (TTL) in seconds until check results are considered stale. If a client stops publishing results for the check, and the TTL expires, an event will be created for the client. The check `ttl` must be greater than the check `interval`, and should accommodate time for the check execution and result processing to complete. For example, if a check has an `interval` of `60` (seconds) and a `timeout` of `30` (seconds), an appropriate `ttl` would be a minimum of `90` (seconds). _**NOTE**: Adding TTLs to checks adds overhead, so use the `ttl` attribute sparingly._
required     | false
type         | Integer
example      | {{}}"ttl": 100{{}}

ttl_status   |
-------------|------
description  | The exit code that a check with the `ttl` attribute should return.
required     | false
type         | Integer
default      | 1
example      | {{}}"ttl_status": 2{{}}

auto_resolve |
-------------|------
description  | When a check in a `WARNING` or `CRITICAL` state returns to an `OK` state, the event generated by the `WARNING` or `CRITICAL` state will be automatically resolved. Setting `auto_resolve` to `false` will prevent this automatic event resolution from occurring. This is useful in situations where you want to explicitly require manual resolution of an event, e.g. via the API or a dashboard.
required     | false
type         | Boolean
default      | true
example      | {{}}"auto_resolve": false{{}}

force_resolve |
--------------|------
description   | Setting `force_resolve` to `true` on a check result ensures that the event is resolved and removed from the registry, regardless of the current event action. This attribute is used internally by [Sensu's `/resolve` API][45].
required      | false
type          | Boolean
default       | false
example       | {{}}"force_resolve": true{{}}

handle       |
-------------|------
description  | If events created by the check should be handled.
required     | false
type         | Boolean
default      | true
example      | {{}}"handle": false{{}}

handler      |
-------------|------
description  | The Sensu event handler (name) to use for events created by the check.
required     | false
type         | String
example      | {{}}"handler": "pagerduty"{{}}

handlers     |
-------------|------
description  | An array of Sensu event handlers (names) to use for events created by the check. Each array item must be a string.
required     | false
type         | Array
example      | {{}}"handlers": ["pagerduty", "email"]{{}}

low_flap_threshold |
-------------------|------
description        | The flap detection low threshold (% state change) for the check. Sensu uses the same [flap detection algorithm as Nagios][31].
required           | false
type               | Integer
example            | {{}}"low_flap_threshold": 20{{}}

high_flap_threshold |
--------------------|------
description         | The flap detection high threshold (% state change) for the check. Sensu uses the same [flap detection algorithm as Nagios][31].
required            | true (if `low_flap_threshold` is configured)
type                | Integer
example             | {{}}"high_flap_threshold": 60{{}}

source       |
-------------|------
description  | The check source, used to create a [proxy client][32] for an external resource (e.g. a network switch).
required     | false
type         | String
validated    | `/^[\w\.-]+$/`
example      | {{}}"source": "switch-dc-01"{{}}

truncate_output |
----------------|------
description     | If check output will be truncated for storage. Output truncation is automatically set to `true` for checks with type set to `"metric"` unless configured to `false`.
required        | false
type            | Boolean
default         | false
example         | {{}}"truncate_output": true{{}}

truncate_output_length |
-----------------------|------
description            |The output truncation length, the maximum number of characters.
required               | false
type                   | Integer
default                | 255
example                | {{}}"truncate_output_length": 1024{{}}

aggregate    |
-------------|------
description  | Create a named aggregate for the check. Check result data will be aggregated and exposed via the [Sensu Aggregates API][33]. _NOTE: named aggregates are new to [Sensu version 0.24][43], now being defined with a String data type rather than a Boolean (i.e. `true` or `false`). Legacy check definitions with `"aggregate": true` attributes will default to using the check name as the aggregate name._
required     | false
type         | String
example      | {{}}"aggregate": "proxy_servers"{{}}

aggregates   |
-------------|------
description  | An array of strings defining one or more named aggregates (described above).
required     | false
type         | Array
example      | {{}}"aggregates": [ "webservers", "production" ]{{}}

subdue       |
-------------|------
description  | The [`subdue` definition scope][42], used to determine when a check is subdued.
required     | false
type         | Hash
example      | {{}}"subdue": {}{{}}

hooks        |
-------------|------
description  | The `hooks` definition scope, commands run by the Sensu client in response to the result of the check command execution
required     | false
type         |  Hash
example      | {{}}"hooks": {}{{}}

contact      |
-------------|------
description  | A contact name to use for the check.
**ENTERPRISE: This configuration is provided for using [Contact Routing][44].**
required     | false
type         | String
example      | {{}}"contact": "ops"{{}}

contacts     |
-------------|------
description  | An array of contact names to use for the check. Each array item (name) must be a string.
**ENTERPRISE: This configuration is provided for using [Contact Routing][44].**
required     | false
type         | Array
example      | {{}}"contacts": ["ops"]{{}}

proxy_requests |
---------------|------
description    | The [`proxy_requests` definition scope][48], used to create proxy check requests.
required       | false
type           | Hash
example        | {{}}"proxy_requests": {}{{}}

occurrences  |
-------------|------
description  | The number of event occurrences that must occur before an event is handled for the check. _NOTE: For this attribute to take effect, the `occurrences` filter must be explicitly configured in your handler definition._
required     | false
type         | Integer
default      | `1`
example      | {{}}"occurrences": 3{{}}

refresh      |
-------------|------
description  | Time in seconds until the event occurrence count is considered reset for the purpose of counting `occurrences`, to allow an event for the check to be handled again. For example, a check with a refresh of `1800` will have its events (recurrences) handled every 30 minutes, to remind users of the issue. _NOTE: For this attribute to take effect, the `occurrences` filter must be explicitly configured in your handler definition._
required     | false
type         | Integer
default      | `1800`
example      | {{}}"refresh": 3600{{}}

dependencies |
-------------|------
description  | An array of check dependencies. Events for the check will not be handled if events exist for one or more of the check dependencies. A check dependency can be a check executed by the same Sensu client (eg. `check_app`), or a client/check pair (eg.`db-01/check_mysql`). _NOTE: For this attribute to take effect, the `check_dependencies` filter must be explicitly configured in your handler definition._
required     | false
type         | Array
example      | {{}}"dependencies": [
  "check_app",
  "db-01/check_mysql"
]
{{}}

notification |
-------------|------
description  | The notification message used for events created by the check, instead of the commonly used check output. This attribute is used by most notification event handlers that use the sensu-plugin library.
required     | false
type         | String
example      | {{}}"notification": "the shopping cart application is not responding to requests"{{}}

influxdb     |
-------------|------
description  | The [`influxdb` definition scope][61], used to configure the [Sensu Enterprise InfluxDB integration][62] ([Sensu Enterprise][60] users only).
required     | false
type         | Hash
example      | {{}}"influxdb": {}{{}}

opsgenie     |
-------------|------
description  | The [`opsgenie` definition scope][63], used to configure the [Sensu Enterprise OpsGenie integration][64] ([Sensu Enterprise][60] users only).
required     | false
type         | Hash
example      | {{}}"opsgenie": {}{{}}

#### `subdue` attributes

The following attributes are configured within the `{"checks": { "CHECK": {
"subdue": {} } } }` [configuration scope][29] (where `CHECK` is a valid [check
name][41]).

##### EXAMPLE {#subdue-attributes-example}

{{}}
{
  "checks": {
    "check-printer": {
      "...": "...",
      "subdue": {
        "days": {
          "all": [
            {
              "begin": "5:00 PM",
              "end": "8:00 AM"
            }
          ]
        }
      }
    }
  }
}
{{}}

##### ATTRIBUTES {#subdue-attributes-specification}

days         |
-------------|------
description  | A hash of days of the week or 'all', each day specified must define one or more time windows in which the check is not scheduled to be executed.
required     | false (unless `subdue` is configured)
type         | Hash
example      | {{}}"days": {
  "all": [
    {
      "begin": "5:00 PM",
      "end": "8:00 AM"
    }
  ],
  "friday": [
    {
      "begin": "12:00 PM",
      "end": "5:00 PM"
    }
  ]
}
{{}}

#### `influxdb` attributes

The following attributes are configured within the `{ "check": { "influxdb": {} }
}` [configuration scope][29].

**ENTERPRISE: This configuration is provided for using the built-in [Sensu
Enterprise InfluxDB integration][62].**

##### EXAMPLE {#influxdb-attributes-example}

{{}}
{
  "check": {
    "name": "nginx_process",
    "...": "...",
    "influxdb": {
      "tags": {
        "dc": "us-central-1"
      }
    }
  }
}
{{}}

##### ATTRIBUTES {#influxdb-attributes-specification}

tags           |
---------------|------
description    | Custom tags (key/value pairs) to add to every InfluxDB measurement. Check tags will override any [InfluxDB integration tags][62] with the same key.
required       | false
type           | Hash
default        | {{}}{}{{}}
example        | {{}}
"tags": {
  "dc": "us-central-1"
}
{{}}

#### `opsgenie` attributes

The following attributes are configured within the `{ "check": { "opsgenie": {} }
}` [configuration scope][29].

**ENTERPRISE: This configuration is provided for using the built-in [Sensu
Enterprise OpsGenie integration][64].**

##### EXAMPLE {#opsgenie-attributes-example}

{{}}
{
  "check": {
    "name": "nginx_process",
    "...": "...",
    "opsgenie": {
      "tags": ["production"]
    }
  }
}
{{}}

##### ATTRIBUTES {#opsgenie-attributes-specification}

tags         |
-------------|------
description  | An array of OpsGenie alert tags that will be added to created alerts.
required     | false
type         | Array
default      | `[]`
example      | {{}}"tags": ["production"]{{}}

#### `hooks` attributes {#hooks-attributes}

The following attributes are configured within the `{"checks": { "CHECK": { "hooks": {} } } }` [configuration scope][29] (where `CHECK` is a valid [check name][41]).

##### ATTRIBUTES {#hooks-attributes-specification}

command      |
-------------|------
description  | The hook command to be executed.
required     | true
type         | String
example      | {{}}"command": "ps aux"{{}}

timeout      |
-------------|------
description  | The hook command execution duration timeout in seconds (hard stop).
required     | false
type         | Integer
default      | 60
example      | {{}}"timeout": 30{{}}

stdin        |
-------------|------
description  | If the Sensu client writes JSON serialized Sensu client and check data to the hook command process' STDIN. The hook command must expect the JSON data via STDIN, read it and close STDIN.
required     | false
type         | Boolean
default      | false
example      | {{}}"stdin": true{{}}

##### Hook naming {#hook-names}

Each check hook has a unique hook name. Valid hook names include (in order of precedence): "1"-"255", "ok", "warning", "critical", "unknown", and "non-zero". The check hook name is used to determine the appropriate hook command to execute, depending on the check execution status (e.g. 1).

##### `HOOK` attributes {#hook-attributes}

The following attributes are configured within the {"checks": { "CHECK": { "hooks": { "HOOK": {}} } } } [configuration scope][29] (where CHECK is a valid [check name][41] and HOOK is a valid [hook name](#hook-names)).

##### EXAMPLE {#hooks-attributes-example}

{{}}
{
  "checks": {
    "nginx_process": {
      "command": "check-process.rb -p nginx",
      "subscribers": [
        "proxy"
      ],
      "interval": 60,
      "hooks": {
        "non-zero": {
          "command": "ps aux",
          "timeout": 10
        }
      }
    }
  }
}
{{}}

#### `proxy_requests` attributes {#proxy-requests-attributes}

The following attributes are configured within the `{"checks": {
"CHECK": { "proxy_requests": {} } } }` [configuration scope][29]
(where `CHECK` is a valid [check name][41]).

##### EXAMPLE {#proxy-requests-attributes-example}

Publish a check request to the configured `subscribers` (e.g.
`["roundrobin:snmp_pollers"]`) for every Sensu client in the registry
that matches the configured client attributes in `client_attributes`
on the configured `interval` (e.g. `60`). Client tokens in the check
definition (e.g. `"check-snmp-if.rb -h :::address::: -i eth0"`) are
substituted prior to publishing the check request. The check request
check `source` is set to the client `name`.

{{}}
{
  "checks": {
    "check_arista_eth0": {
      "command": "check-snmp-if.rb -h :::address::: -i eth0",
      "subscribers": [
        "roundrobin:snmp_pollers"
      ],
      "interval": 60,
      "proxy_requests": {
        "client_attributes": {
          "keepalives": false,
          "device_type": "router",
          "device_manufacturer": "arista"
        }
      }
    }
  }
}
{{}}

##### ATTRIBUTES {#proxy-requests-attributes-specification}

client_attributes |
------------------|------
description       | Sensu client attributes to match clients in the registry.
required          | true
type              | Hash
example           | {{}}"client_attributes": {
  "keepalive": false,
  "device_type": "router",
  "device_manufacturer": "arista",
  "subscriptions": "eval: value.include?('dc-01')"
}
{{}}

splay       |
------------|------
description | If proxy check requests should be splayed, published evenly over a window of time, determined by the check interval and a configurable splay coverage percentage. For example, if a check has an interval of 60s and a configured splay coverage of 90%, its proxy check requests would be splayed evenly over a time window of 60s * 90%, 54s, leaving 6s for the last proxy check execution before the the next round of proxy check requests for the same check.
required    | false
type        | Boolean
default     | false
example     | {{}}"splay": true{{}}

splay_coverage |
---------------|------
description    | If proxy check requests should be splayed, published evenly over a window of time, determined by the check interval and a configurable splay coverage percentage. For example, if a check has an interval of 60s and a configured splay coverage of 90%, its proxy check requests would be splayed evenly over a time window of 60s * 90%, 54s, leaving 6s for the last proxy check execution before the the next round of proxy check requests for the same check.
required       | false
type           | Integer
default        | 90
example        | {{}}"splay_coverage": 65{{}}

You can, as above, also use `eval` to perform more complicated filtering with Ruby on the available `value`, such as finding clients with particular subscriptions.

For a more general introduction to using this style of check, check out the [guide on using proxy checks][49] or the [guide on adding a proxy client][50].

#### Custom attributes

Because Sensu configuration is simply JSON data, it is possible to define
configuration attributes that are not part of the Sensu [check definition
specification][17]. These custom check attributes are included in
[check results][4] and [event data][40], providing additional context
about the check. Some great example use cases for custom check
definition attributes are links to playbook documentation
(i.e. "here's a link to some instructions for how to fix this if it's
broken"), [contact routing][36], and metric graph image URLs.

##### EXAMPLE

The following is an example Sensu check definition that a custom definition
attribute, `"playbook"`, a URL for documentation to aid in the resolution of
events for the check. The playbook URL will be available in [event data][34] and
thus able to be included in event notifications (e.g. email).

{{}}
{
  "checks": {
    "check_mysql_replication": {
      "command": "check-mysql-replication-status.rb --user sensu --password secret",
      "subscribers": [
        "mysql"
      ],
      "interval": 30,
      "playbook": "http://docs.example.com/wiki/mysql-replication-playbook"
    }
  }
}
{{}}

### Check result specification

See [check results][4] (above) for more information about check results,
including an [example check result][37].

Required attributes below are the minimum for check results submitted
via the [client socket input][46]. Additional attributes are
automatically added by the client to build a complete check result.

#### `check` attributes {#check-result-check-attributes}

status       |
-------------|------
description  | The check execution exit status code. An exit status code of `0` (zero) indicates `OK`, `1` indicates `WARNING`, and `2` indicates `CRITICAL`; exit status codes other than `0`, `1`, or `2` indicate an `UNKNOWN` or custom status.
required     | true
type         | Integer
example      | {{}}"status": 0{{}}

command      |
-------------|------
description  | The command as [provided by the check definition][17].
required     | false
type         | String
example      | {{}}"command": "check-http.rb -u https://sensuapp.org"{{}}

subscribers  |
-------------|------
description  | The check subscribers as [provided by the check definition][17].
required     | false
type         | Array
example      | {{}}"subscribers": ["database_servers"]{{}}

interval     |
-------------|------
description  | The check interval in seconds, as [provided by the check definition][17]
required     | false
type         | Integer
example      | {{}}"interval": 60{{}}

name         |
-------------|------
description  | The check name, as [provided by the check definition][17]
required     | true
type         | String
example      | {{}}"name": "sensu-website"{{}}

issued       |
-------------|------
description  | The time the check request was issued (by the [Sensu server][6] or [client][1]), stored as an integer (i.e. `Time.now.to_i`)
required     | false
type         | Integer
example      | {{}}"issued": 1458934742{{}}

executed     |
-------------|------
description  | The time the check request was executed by the [Sensu client][1], stored as and integer (i.e. `Time.now.to_i`).
required     | false
type         | Integer
example      | {{}}"executed": 1458934742{{}}

duration     |
-------------|------
description  | The amount of time (in seconds) it took for the [Sensu client][1] to execute the check.
required     | false
type         | Float
example      | {{}}"duration": 0.637{{}}

output       |
-------------|------
description  | The output produced by the check `command`.
required     | true
type         | String
example      | {{}}"output": "CheckHttp OK: 200, 78572 bytes\n"{{}}

#### `client` attributes {#check-result-client-attributes}

name         |
-------------|------
description  | The name of the [Sensu client][1] that generated the check result. The Sensu server will use the client `name` value to fetch the corresponding client attributes from the [Clients API][39] and add them to the resulting [Sensu event][34] for context.
type         | String
example      | {{}}"client": { "name": "i-424242" }{{}}

[?]:  #
[1]:  ../clients/
[2]:  https://en.wikipedia.org/wiki/Standard_streams
[3]:  https://www.nagios.org/
[4]:  #check-results
[5]:  ../../overview/architecture/#event-processor
[6]:  ../server/
[7]:  #check-configuration
[8]:  ../plugins/#check-plugins
[9]:  https://en.wikipedia.org/wiki/PATH_(variable)
[10]: ../clients/#standalone-check-execution-scheduler
[11]: https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern
[12]: #standalone-checks
[13]: ../transport/
[14]: https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern#Message_filtering
[15]: ../clients/#client-subscriptions
[16]: ../clients/#client-definition-specification
[17]: #check-definition-specification
[18]: http://www.ntp.org/
[19]: #subscription-checks
[20]: http://www.json.org/
[21]: #custom-attributes
[22]: #check-commands
[23]: #check-command-arguments
[24]: ../clients#custom-attributes
[25]: #check-token-default-values
[26]: ../clients#client-attributes
[27]: ../plugins
[28]: https://github.com/sensu-plugins/sensu-plugins-http
[29]: ../configuration/#configuration-scopes
[30]: http://ruby-doc.org/core-2.2.0/Regexp.html
[31]: https://assets.nagios.com/downloads/nagioscore/docs/nagioscore/3/en/flapping.html
[32]: ../clients#proxy-clients
[33]: ../../api/aggregates/
[34]: ../events/
[35]: ../handlers/
[36]: /sensu-enterprise/latest/contact-routing
[37]: #example-check-result-output
[38]: #check-result-specification
[39]: ../../api/clients/
[40]: ../events#event-data
[41]: #check-names
[42]: #subdue-attributes
[43]: ../../changelog/
[44]: /sensu-enterprise/latest/contact-routing
[45]: ../../api/events#the-resolve-api-endpoint
[46]: ../clients#client-socket-input
[47]: https://en.wikipedia.org/wiki/Cron#CRON_expression
[48]: #proxy-requests-attributes
[49]: ../../guides/intro-to-checks/#proxy-clients
[50]: ../../guides/adding-a-client/#proxy-clients
[60]: /sensu-enterprise/latest
[61]: #influxdb-attributes
[62]: /sensu-enterprise/latest/integrations/influxdb
[63]: #opsgenie-attributes
[64]: /sensu-enterprise/latest/integrations/opsgenie
[65]: ../configuration#configuration-scopes
[66]: ../../api/checks#checkscheck-delete


text:
function maxNSE = getMaxNSample( obj, nS )
% GETMAXNSAMPLE  Get maximum allowable number of samples in an array of nlsaEmbeddedComponent objects after emedding source data with nS samples
%
% Modified 2013/12/10

if any( size( obj ) ~= size( nS ) )
    error( 'Incompatible source sample array' )
end

maxNSE = min( nS - getOrigin( obj ) ) + 1;

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Mortgage rates and the Fed Funds rate · Len Kiefer</title>
        <meta name="description" content="YESTERDAY THE FEDERAL RESERVE RELEASED minutes from their last Federal Open Market Committee (FOMC) meeting in April. The big news was that the FOMC still considered a June rate hike a possibility. How much does Fed policy impact mortgage rates? I put together a few gifs comparing the history of the 30-year mortgage rate, the Fed Funds rate and the 10-year constant maturity Treasury.
{% include JB/setup %}">
        <meta name="HandheldFriendly" content="True">
        <meta name="MobileOptimized" content="320">
        <meta name="generator" content="Hugo 0.27.1" />
        <meta name="robots" content="index,follow">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="/dist/styles.css">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,400,600,700,300&subset=latin,cyrillic-ext,latin-ext,cyrillic">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

                                Len Kiefer

        Blog

        Topics

        Projects

        About

        Contact

Mortgage rates and the Fed Funds rate

        Published <time datetime="0001-01-01" itemprop="datePublished">Mon, Jan 1, 0001</time>
        by

                Len Kiefer

YESTERDAY THE FEDERAL RESERVE RELEASED minutes from their last Federal Open Market Committee (FOMC) meeting in April.  The big news was that the FOMC still considered a June rate hike a possibility.  How much does Fed policy impact mortgage rates? I put together a few gifs comparing the history of the 30-year mortgage rate, the Fed Funds rate and the 10-year constant maturity Treasury.

{% include JB/setup %}

            Tagged:

                dataviz,

                animation

                Twitter

                Facebook

                Google+

               LinkedIn

                        Len Kiefer

                    © Len Kiefer 2017 / Powered by Hugo

                    Ghostwriter theme By JollyGoodThemes
                    / Ported to Hugo By jbub


text:
kafka producer and consumer example in scala and java

you can test with local server.

### start zookeeper
if you have installed zookeeper, start it, or
run the command:
``` sh
bin/zookeeper-server-start.sh config/zookeeper.properties
```

### start kafka with default configuration
``` sh
> bin/kafka-server-start.sh config/server.properties
```

### create a topic
``` sh
> bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 10 --topic test_topic
```

### package this example
``` sh
mvn clean package
```

it will package compiled classes and its dependencies into a jar.

### run the consumer
This example contains two consumers written in Java and in scala.
You can run this for java:
``` sh
java -cp kafka_example-0.1.0-SNAPSHOT.jar com.colobu.kafka.ConsumerExample localhost:2181 group1 test_topic 10 0
```

or this for scala:
``` sh
java -cp kafka_example-0.1.0-SNAPSHOT.jar com.colobu.kafka.ScalaConsumerExample localhost:2181 group1 test_topic 10 0
```

### run the consumer
This example also contains two producers written in Java and in scala.
you can run this for java:
``` sh
java -cp kafka_example-0.1.0-SNAPSHOT.jar com.colobu.kafka.ProducerExample 10000 colobu localhost:9092
```
or this for scala
``` sh
java -cp kafka_example-0.1.0-SNAPSHOT.jar com.colobu.kafka.ScalaProducerExample 10000 colobu localhost:9092
```


text:
Fixing Reset-on-Connect Issue / Broken Reset Circuits
=====================================================

Regarding to Issue #14

Build-In Reset Circuit
----------------------

The original [NodeMCU DEVKIT](https://github.com/nodemcu/nodemcu-devkit-v1.0) includes a build-in circuit to pull down the reset (RST) and/or flash (GPIO0) pins via the serial connection using the DTR/RTS lines.
This allows the user to execute a hard-reset or flash command via software.

**Reset Circuit** (from [NodeMCU DEVKIT Schematics](https://github.com/nodemcu/nodemcu-devkit-v1.0/blob/master/NODEMCU_DEVKIT_V1.0.PDF))

![Reset Circuit of NodeMCU DEVKIT](../assets/nodemcu-reset-circuit.jpg)

The Issue
---------------------
It's a very useful feature, but on some modules these circuits cause a **reset on connect** which make the module inaccessible with NodeMCU-Tool:
on opening the serial connection software side, the module will be reset immediately and it reboots. Directly after reboot, the **auto-baudrate** detection of NodeMCU is capturing the serial input to determinate the used baudrate.
And this is the issue: NodeMCU-Tool sends a few hearbeat messages to the module to check its state, but these messages are lost because of the auto-baudrate detection. Therefore the module is threatened as unavailable and a error message is raised.

This behaviour can be caused by a hardware issue: wrong transistors, wrong series-resistors **or** a usb driver failure, which invokes the DTR/RTS lines asynchronous

**Timeline**

1. **NodeMCU-Tool** is establishing the serial connection
2. DTR/RTS lines are invoked
3. NodeMCU will do a hard-reset or go into flash mode
4. **NodeMCU-Tool** sends heartbeat sequence
5. NodeMCU Auto-Baudrate Detection is capturing the input or the module is not ready yet the receive incoming data
6. **NodeMCU-Tool** will not receive the hearbeat response - the module is threatened as unavailable

How to fix it
---------------------

NodeMCU-Tool v2.0.0 includes a special delay flag `--connection-delay N` which waits **N** milliseconds after establishing the connection and sends additional dummy sequences to trigger the auto-baudrate detection.

**Timeline**

1. **NodeMCU-Tool** establishes the serial connection
2. **NodeMCU-Tool** is waiting **N** milliseconds until the hard-reset/reboot is done
3. **NodeMCU** becomes ready and starts the auto-baudrate detection
4. **NodeMCU-Tool** sends dummy sequence 1 to trigger the auto-baudrate detection
5. **NodeMCU-Tool** is waiting **N** milliseconds for baudrate detection
6. **NodeMCU-Tool** sends dummy sequence 2 to trigger the auto-baudrate detection
7. **NodeMCU-Tool** is waiting **N** milliseconds for baudrate detection
8. **NodeMCU** set its baudrate based on the previous dummy sequences
9. **NodeMCU-Tool** starts the regular heartbeat detection

The connection delay is applied 3 times, between each step. A value between **300...500ms** has been approved as best option.

**Example 1**
```bash
$ ./nodemcu-tool upload helloworld.lua --connection-delay 300 --baud 115200
```


text:
from BaseModel import BaseModel
from Defintions import Defintions
import DatabaseLayer

class StoryModels(BaseModel):
  """
    This will be the base class for all of models that are used as parts of
    other models. Maily, this will refer to Zone and Monster.

    Do not try to use this class directly. Only use its subclasses
  """

  @classmethod
  def construct_model_from_dict(cls,dict):
    """
      args:
        dict:
          loads the properties of the model from the dict.

      return: an instance of the model on which this is called

    """
    obj = cls(None)
    obj.dict = dict
    return obj

  def __init__(self,definitionKey):
    """
      args:
        definitionKey:
          a string dictionary key used with one the definition classes. The hashed value
          is a sub-dict that contains the definition info

    """
    super().__init__()
    self._definition = None
    if not definitionKey:
      return
    self.definitionKey = definitionKey

  def set_common_story_property(self,key,value):
    """
      I noticed that I was using the same two lines all over my setters.
      So, I decided to just centralize it here.
    """
    self.dict[key] = value
    self._changes[self.get_dbFields().OWNER_PROPERTY + "." +key] = value


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3: 448 (1898)

#### Original name
Helotium collinum Speg.

### Remarks
null


text:
<?php

$path_extra = dirname(dirname(dirname(__FILE__)));
$path = ini_get('include_path');
$path = $path_extra . PATH_SEPARATOR . $path;
ini_set('include_path', $path);

$try_include = @include 'config.php';

if (!$try_include) {
    header("Location: setup.php");
}

header('Cache-Control: no-cache');
header('Pragma: no-cache');

if (function_exists('getOpenIDStore')) {
    require_once 'lib/session.php';
    require_once 'lib/actions.php';

    init();

    $action = getAction();
    if (!function_exists($action)) {
        $action = 'action_default';
    }

    $resp = $action();

    writeResponse($resp);
} else {
?>

    <title>PHP OpenID Server</title>

PHP OpenID Server

        This server needs to be configured before it can be used. Edit
        config.php to reflect your server's setup, then
        load this page again.

<?php
}
?>


text:
Instagram Popup Login
=====================

Log into Instagram via a Pop-Up window with Javascript. After authentication you receive the acccess token, that can be used to make API endpoint calls.

You can view a demo [here](http://github.radykal.de/instagram-popup-login/).

## Setup

1. Download index.php and instagram_auth.php.
2. [Get a Client ID](http://instagram.com/developer/clients/manage/).
2. Keep "Disable implicit OAuth" and "Enforce signed header" disabled.
3. Copy Client ID and OAuth redirect_uri.
4. Paste both values in the authenticateInstagram() function:
```
authenticateInstagram(
	'your_client_id', //instagram client ID
	'your_redirect_uri', //instagram redirect URI
	login_callback //optional - a callback function
);
```

## Live Usage

I am using this method in my [Fancy Product Designer plugin](http://fancyproductdesigner.com/jquery-plugin/) to load users feed and recent images.


text:
package unit.com.bitdubai.fermat_ccp_plugin.layer.middleware.wallet_contacts.developer.bitdubai.version_1.WalletContactsMiddlewarePluginRoot;

import com.bitdubai.fermat_api.layer.all_definition.crypto.asymmetric.ECCKeyPair;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabaseTable;
import com.bitdubai.fermat_api.layer.dmp_identity.intra_user.exceptions.CantCreateNewIntraUserException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;
import com.bitdubai.fermat_api.layer.osa_android.file_system.PluginFileSystem;
import com.bitdubai.fermat_api.layer.osa_android.logger_system.LogLevel;
import com.bitdubai.fermat_ccp_plugin.layer.middleware.wallet_contacts.developer.bitdubai.version_1.WalletContactsMiddlewarePluginRoot;
import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.ErrorManager;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

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

import static org.mockito.Matchers.any;

/**
 * Created by natalia on 10/09/15.
 */

@RunWith(MockitoJUnitRunner.class)
public class SetLoggingLevelPerClassTest {

    @Mock
    private Database mockDatabase;

    @Mock
    private PluginDatabaseSystem mockPluginDatabaseSystem;

    @Mock
    private PluginFileSystem mockPluginFileSystem;

    @Mock
    private DeveloperDatabaseTable developerDatabaseTable;

    @Mock
    private ErrorManager errorManager;

    private WalletContactsMiddlewarePluginRoot pluginRoot;

    @Test
    public void setLoggingLevelPerClassTest() throws CantOpenDatabaseException, DatabaseNotFoundException, CantCreateNewIntraUserException {
        UUID testOwnerId = UUID.randomUUID();

        pluginRoot = new WalletContactsMiddlewarePluginRoot();

        pluginRoot.setPluginDatabaseSystem(mockPluginDatabaseSystem);

        pluginRoot.setId(testOwnerId);
        pluginRoot.setErrorManager(errorManager);

        ECCKeyPair eccKeyPair = new ECCKeyPair();
        Map<String, LogLevel> newLoggingLevel = new HashMap<String, LogLevel>();
        newLoggingLevel.put(eccKeyPair.getPrivateKey(), LogLevel.AGGRESSIVE_LOGGING);

        pluginRoot.setLoggingLevelPerClass(newLoggingLevel);

    }
}


text:
{% load static people_tags %}

{% with event.content_object as object %}
{% if event.date_field == "started" %}
  {% if object.group.romanized_name == "Soloist" %}

    {{ object.idol }} becomes a soloist
    {% if event.items.exists %}{% include "correlations/partials/happenings_news.html" %}{% endif %}

{% if object.idol.image %}{% endif %}

  {% elif object.started != object.group.started %}

    {{ object.idol }} joins {{ object.group }}
    {% if event.items.exists %}{% include "correlations/partials/happenings_news.html" %}{% endif %}

{% if object.idol.image %}{% endif %}

{% if object.group.image %}{% endif %}

  {% endif %}
{% endif %}
{% if event.date_field == "ended" %}
  {% if object.group.romanized_name == "Soloist" %}

    {{ object.idol }} discontinues soloist work
    {% if event.items.exists %}{% include "correlations/partials/happenings_news.html" %}{% endif %}

{% if object.idol.image %}{% endif %}

  {% else %}

    {{ object.idol }} leaves {{ object.group }}
    {% if event.items.exists %}{% include "correlations/partials/happenings_news.html" %}{% endif %}

{% if object.idol.image %}{% endif %}

{% if object.group.image %}{% endif %}

  {% endif %}
{% endif %}
{% if event.date_field == "leadership_started" %}

  {{ object.idol }} becomes leader of {% romanized_designation_for target=object.group target_date=object.leadership_started %}
  {% if event.items.exists %}{% include "correlations/partials/happenings_news.html" %}{% endif %}

{% if object.idol.image %}{% endif %}

{% if object.group.image %}{% endif %}

{% endif %}
{% if event.date_field == "leadership_ended" %}

  {{ object.idol }} steps down as leader of {% romanized_designation_for target=object.group target_date=object.leadership_ended %}
  {% if event.items.exists %}{% include "correlations/partials/happenings_news.html" %}{% endif %}

{% if object.idol.image %}{% endif %}

{% if object.group.image %}{% endif %}

{% endif %}
{% endwith %}


text:
BUILDDIR="/home/kzv/SmailCoin"
EXEEXT=".exe"

# These will turn into comments if they were disabled when configuring.
ENABLE_WALLET=1
ENABLE_UTILS=1
ENABLE_BITCOIND=1
#ENABLE_ZMQ=1


text:
package org.elasticsearch.index.mapper.core;

import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.NumericRangeFilter;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.NumericUtils;
import org.elasticsearch.ElasticSearchIllegalArgumentException;
import org.elasticsearch.common.Explicit;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Numbers;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.joda.DateMathParser;
import org.elasticsearch.common.joda.FormatDateTimeFormatter;
import org.elasticsearch.common.joda.Joda;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.analysis.NamedAnalyzer;
import org.elasticsearch.index.analysis.NumericDateAnalyzer;
import org.elasticsearch.index.codec.postingsformat.PostingsFormatProvider;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.fielddata.IndexFieldDataService;
import org.elasticsearch.index.fielddata.IndexNumericFieldData;
import org.elasticsearch.index.mapper.*;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.search.NumericRangeFieldDataFilter;
import org.elasticsearch.index.similarity.SimilarityProvider;

import java.io.IOException;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static org.elasticsearch.index.mapper.MapperBuilders.dateField;
import static org.elasticsearch.index.mapper.core.TypeParsers.parseDateTimeFormatter;
import static org.elasticsearch.index.mapper.core.TypeParsers.parseNumberField;

/**
 *
 */
public class DateFieldMapper extends NumberFieldMapper<Long> {

    public static final String CONTENT_TYPE = "date";

    public static class Defaults extends NumberFieldMapper.Defaults {
        public static final FormatDateTimeFormatter DATE_TIME_FORMATTER = Joda.forPattern("dateOptionalTime");

        public static final FieldType FIELD_TYPE = new FieldType(NumberFieldMapper.Defaults.FIELD_TYPE);

        static {
            FIELD_TYPE.freeze();
        }

        public static final String NULL_VALUE = null;

        public static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
        public static final boolean PARSE_UPPER_INCLUSIVE = true;
    }

    public static class Builder extends NumberFieldMapper.Builder<Builder, DateFieldMapper> {

        protected TimeUnit timeUnit = Defaults.TIME_UNIT;

        protected String nullValue = Defaults.NULL_VALUE;

        protected FormatDateTimeFormatter dateTimeFormatter = Defaults.DATE_TIME_FORMATTER;

        private Locale locale;

        public Builder(String name) {
            super(name, new FieldType(Defaults.FIELD_TYPE));
            builder = this;
        }

        public Builder timeUnit(TimeUnit timeUnit) {
            this.timeUnit = timeUnit;
            return this;
        }

        public Builder nullValue(String nullValue) {
            this.nullValue = nullValue;
            return this;
        }

        public Builder dateTimeFormatter(FormatDateTimeFormatter dateTimeFormatter) {
            this.dateTimeFormatter = dateTimeFormatter;
            return this;
        }

        @Override
        public DateFieldMapper build(BuilderContext context) {
            boolean parseUpperInclusive = Defaults.PARSE_UPPER_INCLUSIVE;
            if (context.indexSettings() != null) {
                parseUpperInclusive = context.indexSettings().getAsBoolean("index.mapping.date.parse_upper_inclusive", Defaults.PARSE_UPPER_INCLUSIVE);
            }
            fieldType.setOmitNorms(fieldType.omitNorms() && boost == 1.0f);
            if (locale != null && !locale.equals(dateTimeFormatter.locale())) {
                // this sucks we should use the root local by default and not be dependent on the node if it is null?
                dateTimeFormatter = new FormatDateTimeFormatter(dateTimeFormatter.format(), dateTimeFormatter.parser(), dateTimeFormatter.printer(), locale);
            }
            DateFieldMapper fieldMapper = new DateFieldMapper(buildNames(context), dateTimeFormatter,
                    precisionStep, boost, fieldType, nullValue,
                    timeUnit, parseUpperInclusive, ignoreMalformed(context), provider, similarity, fieldDataSettings);
            fieldMapper.includeInAll(includeInAll);
            return fieldMapper;
        }

        public Builder locale(Locale locale) {
            this.locale = locale;
            return this;
        }
    }

    public static class TypeParser implements Mapper.TypeParser {
        @Override
        public Mapper.Builder<?, ?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
            DateFieldMapper.Builder builder = dateField(name);
            parseNumberField(builder, name, node, parserContext);
            for (Map.Entry<String, Object> entry : node.entrySet()) {
                String propName = Strings.toUnderscoreCase(entry.getKey());
                Object propNode = entry.getValue();
                if (propName.equals("null_value")) {
                    builder.nullValue(propNode.toString());
                } else if (propName.equals("format")) {
                    builder.dateTimeFormatter(parseDateTimeFormatter(propName, propNode));
                } else if (propName.equals("numeric_resolution")) {
                    builder.timeUnit(TimeUnit.valueOf(propNode.toString().toUpperCase(Locale.ROOT)));
                } else if (propName.equals("locale")) {
                    builder.locale(parseLocale(propNode.toString()));
                }
            }
            return builder;
        }
    }

    // public for test
    public static Locale parseLocale(String locale) {
        final String[] parts = locale.split("_", -1);
        switch (parts.length) {
            case 3:
                // lang_country_variant
                return new Locale(parts[0], parts[1], parts[2]);
            case 2:
                // lang_country
                return new Locale(parts[0], parts[1]);
            case 1:
                if ("ROOT".equalsIgnoreCase(parts[0])) {
                    return Locale.ROOT;
                }
                // lang
                return new Locale(parts[0]);
            default:
                throw new ElasticSearchIllegalArgumentException("Can't parse locale: [" + locale + "]");
        }
    }

    protected final FormatDateTimeFormatter dateTimeFormatter;

    private final boolean parseUpperInclusive;

    private final DateMathParser dateMathParser;

    private String nullValue;

    protected final TimeUnit timeUnit;

    protected DateFieldMapper(Names names, FormatDateTimeFormatter dateTimeFormatter, int precisionStep, float boost, FieldType fieldType,
                              String nullValue, TimeUnit timeUnit, boolean parseUpperInclusive, Explicit<Boolean> ignoreMalformed,
                              PostingsFormatProvider provider, SimilarityProvider similarity, @Nullable Settings fieldDataSettings) {
        super(names, precisionStep, boost, fieldType,
                ignoreMalformed, new NamedAnalyzer("_date/" + precisionStep,
                new NumericDateAnalyzer(precisionStep, dateTimeFormatter.parser())),
                new NamedAnalyzer("_date/max", new NumericDateAnalyzer(Integer.MAX_VALUE, dateTimeFormatter.parser())),
                provider, similarity, fieldDataSettings);
        this.dateTimeFormatter = dateTimeFormatter;
        this.nullValue = nullValue;
        this.timeUnit = timeUnit;
        this.parseUpperInclusive = parseUpperInclusive;
        this.dateMathParser = new DateMathParser(dateTimeFormatter, timeUnit);
    }

    @Override
    public FieldType defaultFieldType() {
        return Defaults.FIELD_TYPE;
    }

    @Override
    public FieldDataType defaultFieldDataType() {
        return new FieldDataType("long");
    }

    @Override
    protected int maxPrecisionStep() {
        return 64;
    }

    @Override
    public Long value(Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        if (value instanceof BytesRef) {
            return Numbers.bytesToLong((BytesRef) value);
        }
        return parseStringValue(value.toString());
    }

    /**
     * Dates should return as a string.
     */
    @Override
    public Object valueForSearch(Object value) {
        if (value instanceof String) {
            // assume its the string that was indexed, just return it... (for example, with get)
            return value;
        }
        Long val = value(value);
        if (val == null) {
            return null;
        }
        return dateTimeFormatter.printer().print(val);
    }

    @Override
    public BytesRef indexedValueForSearch(Object value) {
        BytesRef bytesRef = new BytesRef();
        NumericUtils.longToPrefixCoded(parseValue(value), 0, bytesRef); // 0 because of exact match
        return bytesRef;
    }

    private long parseValue(Object value) {
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        if (value instanceof BytesRef) {
            return dateTimeFormatter.parser().parseMillis(((BytesRef) value).utf8ToString());
        }
        return dateTimeFormatter.parser().parseMillis(value.toString());
    }

    private String convertToString(Object value) {
        if (value instanceof BytesRef) {
            return ((BytesRef) value).utf8ToString();
        }
        return value.toString();
    }

    @Override
    public Query fuzzyQuery(String value, String minSim, int prefixLength, int maxExpansions, boolean transpositions) {
        long iValue = dateMathParser.parse(value, System.currentTimeMillis());
        long iSim;
        try {
            iSim = TimeValue.parseTimeValue(minSim, null).millis();
        } catch (Exception e) {
            // not a time format
            iSim = (long) Double.parseDouble(minSim);
        }
        return NumericRangeQuery.newLongRange(names.indexName(), precisionStep,
                iValue - iSim,
                iValue + iSim,
                true, true);
    }

    @Override
    public Query termQuery(Object value, @Nullable QueryParseContext context) {
        long now = context == null ? System.currentTimeMillis() : context.nowInMillis();
        long lValue = dateMathParser.parse(convertToString(value), now);
        return NumericRangeQuery.newLongRange(names.indexName(), precisionStep,
                lValue, lValue, true, true);
    }

    @Override
    public Filter termFilter(Object value, @Nullable QueryParseContext context) {
        long now = context == null ? System.currentTimeMillis() : context.nowInMillis();
        long lValue = dateMathParser.parse(convertToString(value), now);
        return NumericRangeFilter.newLongRange(names.indexName(), precisionStep,
                lValue, lValue, true, true);
    }

    @Override
    public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
        long now = context == null ? System.currentTimeMillis() : context.nowInMillis();
        return NumericRangeQuery.newLongRange(names.indexName(), precisionStep,
                lowerTerm == null ? null : dateMathParser.parse(convertToString(lowerTerm), now),
                upperTerm == null ? null : (includeUpper && parseUpperInclusive) ? dateMathParser.parseUpperInclusive(convertToString(upperTerm), now) : dateMathParser.parse(convertToString(upperTerm), now),
                includeLower, includeUpper);
    }

    @Override
    public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
        long now = context == null ? System.currentTimeMillis() : context.nowInMillis();
        return NumericRangeFilter.newLongRange(names.indexName(), precisionStep,
                lowerTerm == null ? null : dateMathParser.parse(convertToString(lowerTerm), now),
                upperTerm == null ? null : (includeUpper && parseUpperInclusive) ? dateMathParser.parseUpperInclusive(convertToString(upperTerm), now) : dateMathParser.parse(convertToString(upperTerm), now),
                includeLower, includeUpper);
    }

    @Override
    public Filter rangeFilter(IndexFieldDataService fieldData, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
        long now = context == null ? System.currentTimeMillis() : context.nowInMillis();
        return NumericRangeFieldDataFilter.newLongRange((IndexNumericFieldData) fieldData.getForField(this),
                lowerTerm == null ? null : dateMathParser.parse(convertToString(lowerTerm), now),
                upperTerm == null ? null : (includeUpper && parseUpperInclusive) ? dateMathParser.parseUpperInclusive(convertToString(upperTerm), now) : dateMathParser.parse(convertToString(upperTerm), now),
                includeLower, includeUpper);
    }

    @Override
    public Filter nullValueFilter() {
        if (nullValue == null) {
            return null;
        }
        long value = parseStringValue(nullValue);
        return NumericRangeFilter.newLongRange(names.indexName(), precisionStep,
                value,
                value,
                true, true);
    }

    @Override
    protected boolean customBoost() {
        return true;
    }

    @Override
    protected Field innerParseCreateField(ParseContext context) throws IOException {
        String dateAsString = null;
        Long value = null;
        float boost = this.boost;
        if (context.externalValueSet()) {
            Object externalValue = context.externalValue();
            if (externalValue instanceof Number) {
                value = ((Number) externalValue).longValue();
            } else {
                dateAsString = (String) externalValue;
                if (dateAsString == null) {
                    dateAsString = nullValue;
                }
            }
        } else {
            XContentParser parser = context.parser();
            XContentParser.Token token = parser.currentToken();
            if (token == XContentParser.Token.VALUE_NULL) {
                dateAsString = nullValue;
            } else if (token == XContentParser.Token.VALUE_NUMBER) {
                value = parser.longValue();
            } else if (token == XContentParser.Token.START_OBJECT) {
                String currentFieldName = null;
                while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                    if (token == XContentParser.Token.FIELD_NAME) {
                        currentFieldName = parser.currentName();
                    } else {
                        if ("value".equals(currentFieldName) || "_value".equals(currentFieldName)) {
                            if (token == XContentParser.Token.VALUE_NULL) {
                                dateAsString = nullValue;
                            } else if (token == XContentParser.Token.VALUE_NUMBER) {
                                value = parser.longValue();
                            } else {
                                dateAsString = parser.text();
                            }
                        } else if ("boost".equals(currentFieldName) || "_boost".equals(currentFieldName)) {
                            boost = parser.floatValue();
                        } else {
                            throw new ElasticSearchIllegalArgumentException("unknown property [" + currentFieldName + "]");
                        }
                    }
                }
            } else {
                dateAsString = parser.text();
            }
        }

        if (value != null) {
            LongFieldMapper.CustomLongNumericField field = new LongFieldMapper.CustomLongNumericField(this, timeUnit.toMillis(value), fieldType);
            field.setBoost(boost);
            return field;
        }

        if (dateAsString == null) {
            return null;
        }
        if (context.includeInAll(includeInAll, this)) {
            context.allEntries().addText(names.fullName(), dateAsString, boost);
        }

        value = parseStringValue(dateAsString);
        LongFieldMapper.CustomLongNumericField field = new LongFieldMapper.CustomLongNumericField(this, value, fieldType);
        field.setBoost(boost);
        return field;
    }

    @Override
    protected String contentType() {
        return CONTENT_TYPE;
    }

    @Override
    public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException {
        super.merge(mergeWith, mergeContext);
        if (!this.getClass().equals(mergeWith.getClass())) {
            return;
        }
        if (!mergeContext.mergeFlags().simulate()) {
            this.nullValue = ((DateFieldMapper) mergeWith).nullValue;
        }
    }

    @Override
    protected void doXContentBody(XContentBuilder builder) throws IOException {
        super.doXContentBody(builder);
        if (precisionStep != Defaults.PRECISION_STEP) {
            builder.field("precision_step", precisionStep);
        }
        builder.field("format", dateTimeFormatter.format());
        if (nullValue != null) {
            builder.field("null_value", nullValue);
        }
        if (includeInAll != null) {
            builder.field("include_in_all", includeInAll);
        }
        if (timeUnit != Defaults.TIME_UNIT) {
            builder.field("numeric_resolution", timeUnit.name().toLowerCase(Locale.ROOT));
        }
        // only serialize locale if needed, ROOT is the default, so no need to serialize that case as well...
        if (dateTimeFormatter.locale() != null && dateTimeFormatter.locale() != Locale.ROOT) {
            builder.field("locale", dateTimeFormatter.locale());
        }
    }

    private long parseStringValue(String value) {
        try {
            return dateTimeFormatter.parser().parseMillis(value);
        } catch (RuntimeException e) {
            try {
                long time = Long.parseLong(value);
                return timeUnit.toMillis(time);
            } catch (NumberFormatException e1) {
                throw new MapperParsingException("failed to parse date field [" + value + "], tried both date format [" + dateTimeFormatter.format() + "], and timestamp number with locale [" + dateTimeFormatter.locale() + "]", e);
            }
        }
    }
}


text:
module Main where
  import GHC.IO.Encoding

  import JVM.ClassFile
  import Java.JAR
  -- import Runtime.Environment
  import System.Environment
  import Data.Char
  import Data.List
  import Data.List.Split
  import qualified Data.ByteString.Lazy as B
  import qualified Data.ByteString.Lazy.Char8 as C8
  import Control.Monad

  import LLVMFrontend.CFG

  import MateVMRuntime.ClassPool
  import MateVMRuntime.MethodPool

  import MateVMRuntime.Types
  import MateVMRuntime.Debug
  import MateVMRuntime.RtsOptions

  import MateVMRuntime.Utilities

  import Mate.GC.Boehm

  import Misc.Logger

  bootstrapMethod :: String
  bootstrapMethod = "RunMe"

  main ::  IO ()
  main = do
    time "main" $ do
      args <- getArgs
      parseArgs args False
    printCompileTime

  parseArgs :: [String] -> Bool -> IO ()
  parseArgs ("-jar":jarpath:_) stdcp = do
    unless stdcp $ addClassPath "./"
    addClassPathJAR jarpath
    res <- readMainClass jarpath
    case res of
      Nothing -> error "JAR: no MainClass entry found. Try to pass the jar file via -cp instead."
      Just mc -> do
        let bclspath = B.pack . map (fromIntegral . ord) $ mc
        cls <- getClassFile bclspath
        executeMain bclspath cls

  parseArgs ("-cp":cps) cpset = parseArgs ("-classpath":cps) cpset
  parseArgs ("-classpath":cps:xs) False = do
    mapM_ addStuff $ splitOn ":" cps
    parseArgs xs True
      where
        addStuff :: String -> IO ()
        addStuff x
          | ".jar" `isSuffixOf` x = addClassPathJAR x
          | otherwise = addClassPath $ x ++ "/"
  parseArgs ("-classpath":xs) _ = parseArgs ("-":xs) True -- usage
  parseArgs (('-':_):_) _ = error "Usage: mate [-cp|-classpath <cp1:cp2:..>] [<class-file> | -jar <jar-file>]"
  -- first argument which isn't prefixed by '-' should be a class file
  parseArgs (clspath:_) stdcp = do
    unless stdcp $ addClassPath "./"
    let bclspath = B.pack . map (fromIntegral . ord) $ clspath
    cls <- getClassFile bclspath
    executeMain bclspath cls
  parseArgs _ _ = parseArgs ["-"] False

  executeMain :: B.ByteString -> Class Direct -> IO ()
  executeMain bclspath cls = do
    --required on some platforms, initializes boehmgc. [todo bernhard: maybe this should be moved somewhere else - maybe at a global place where vm initialization takes place]
    unless usePreciseGC initGC

    case find ((==) (C8.pack bootstrapMethod) . methodName) (classMethods cls) of
      Just m -> do
        let mi = MethodInfo (C8.pack bootstrapMethod) bclspath $ methodSignature m
        entry <- lookupMethodEntry mi
        printfInfo $ "executing '" ++ bootstrapMethod ++ "' now:\n"
        executeFuncPtr (fromIntegral entry)
        printfInfo "Well, goodbye Sir!\n"
      Nothing -> error $ bootstrapMethod ++ " not found"


text:
package org.apache.camel.component.netty4;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadFactory;

import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.impl.UriEndpointComponent;
import org.apache.camel.util.IntrospectionSupport;
import org.apache.camel.util.concurrent.CamelThreadFactory;

public class NettyComponent extends UriEndpointComponent {
    private NettyConfiguration configuration;
    private volatile EventExecutorGroup executorService;

    public NettyComponent() {
        super(NettyEndpoint.class);
    }

    public NettyComponent(Class<? extends Endpoint> endpointClass) {
        super(endpointClass);
    }

    public NettyComponent(CamelContext context) {
        super(context, NettyEndpoint.class);
    }

    @Override
    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
        NettyConfiguration config;
        if (configuration != null) {
            config = configuration.copy();
        } else {
            config = new NettyConfiguration();
        }
        config = parseConfiguration(config, remaining, parameters);

        // merge any custom bootstrap configuration on the config
        NettyServerBootstrapConfiguration bootstrapConfiguration = resolveAndRemoveReferenceParameter(parameters, "bootstrapConfiguration", NettyServerBootstrapConfiguration.class);
        if (bootstrapConfiguration != null) {
            Map<String, Object> options = new HashMap<String, Object>();
            if (IntrospectionSupport.getProperties(bootstrapConfiguration, options, null, false)) {
                IntrospectionSupport.setProperties(getCamelContext().getTypeConverter(), config, options);
            }
        }

        // validate config
        config.validateConfiguration();

        NettyEndpoint nettyEndpoint = new NettyEndpoint(remaining, this, config);
        setProperties(nettyEndpoint.getConfiguration(), parameters);
        return nettyEndpoint;
    }

    /**
     * Parses the configuration
     *
     * @return the parsed and valid configuration to use
     */
    protected NettyConfiguration parseConfiguration(NettyConfiguration configuration, String remaining, Map<String, Object> parameters) throws Exception {
        configuration.parseURI(new URI(remaining), parameters, this, "tcp", "udp");
        return configuration;
    }

    public NettyConfiguration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(NettyConfiguration configuration) {
        this.configuration = configuration;
    }

    public void setExecutorService(EventExecutorGroup executorServcie) {
        this.executorService = executorService;
    }

    public synchronized EventExecutorGroup getExecutorService() {
        if (executorService == null) {
            executorService = createExecutorService();
        }
        return executorService;
    }

    @Override
    protected void doStart() throws Exception {

        if (configuration == null) {
            configuration = new NettyConfiguration();
        }

        if (configuration.isUsingExecutorService() && executorService == null) {
            executorService = createExecutorService();
        }

        super.doStart();
    }

    protected EventExecutorGroup createExecutorService() {
        // Provide the executor service for the application
        // and use a Camel thread factory so we have consistent thread namings
        // we should use a shared thread pool as recommended by Netty
        String pattern = getCamelContext().getExecutorServiceManager().getThreadNamePattern();
        ThreadFactory factory = new CamelThreadFactory(pattern, "NettyEventExecutorGroup", true);
        return new DefaultEventExecutorGroup(configuration.getMaximumPoolSize(), factory);
    }

    @Override
    protected void doStop() throws Exception {

        if (executorService != null) {
            getCamelContext().getExecutorServiceManager().shutdownNow(executorService);
            executorService = null;
        }

        super.doStop();
    }

}


text:
package neo4jgo

import (
	"bytes"
	"encoding/base64"
	"net/http"
	"strconv"
	"strings"
)

type neo4jInfo struct {
	url  string
	auth string
}

type Executer interface {
	Execute(string, map[string]interface{}) string
}

func NewExecuter(host string, user string, password string) Executer {
	return &neo4jInfo{"http://" + host + "/db/data/transaction/commit", auth(user, password)}
}

func valueToString(value interface{}) string {
	switch t := value.(type) {
	case string:
		return "\"" + t + "\""
	case int:
		return strconv.FormatInt(int64(t), 10)
	case []int:
		res := ""
		for _, v := range t {
			if res != "" {
				res = res + ", "
			}
			res = res + valueToString(v)
		}
		return "[" + res + "]"
	case []string:
		res := ""
		for _, v := range t {
			if res != "" {
				res = res + ", "
			}
			res = res + valueToString(v)
		}
		return "[" + res + "]"
	}
	return "err"
}

func paramsToJson(params map[string]interface{}) string {
	res := ""
	for key, value := range params {
		if res != "" {
			res = res + ", "
		}
		res = res + "\"" + key + "\": " + valueToString(value)
	}
	return "{" + res + "}"
}

func createBody(stmt string, params map[string]interface{}) string {
	c := stmt
	p := paramsToJson(params)
	res := `{"statements": [{"statement": "` + c + `", "parameters": ` + p + `}]}`
	return res
}

func (con *neo4jInfo) Execute(stmt string, params map[string]interface{}) string {
	client := new(http.Client)
	body := createBody(stmt, params)
	req, err := http.NewRequest("POST", con.url, strings.NewReader(body))
	if err != nil {
		panic(err)
	}
	req.Header.Add("Accept", "application/json")
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Authorization", "Basic "+con.auth)
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	buf := new(bytes.Buffer)
	buf.ReadFrom(resp.Body)
	return buf.String()
}

func auth(user string, password string) string {
	e := base64.StdEncoding
	return e.EncodeToString([]byte(user + ":" + password))
}


text:
class Specinfra::Helper::DetectOs::Esxi < Specinfra::Helper::DetectOs
  def detect
    if run_command('vmware -v').success?
      line = run_command('vmware -v').stdout
      if line =~ /VMware ESXi (.*)/
        { :family => 'esxi', :release => $1 }
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="http://schemas.android.com/apk/res-auto">

    <!--
         Used in Action Bar, and in AndroidManifest to tell the device the name of this app.
         It's to keep this short, so your launcher icon isn't displayed with "The greatest Wea"
         or something similar.
    -->
    <string name="app_name">Food Recipes</string>

    <!--
         By convention, "action" denotes that this String will be used as the label for an Action,
         typically from the action bar.  The ActionBar is limited real estate, so shorter is better.
    -->

    <string name="content_authority" translatable="false">com.example.android.foodrecipes.app</string>

    <string name="action_settings">Settings</string>
    <string name="action_favourites">Favourite recipes</string>
    <string name="action_default_recipes">Show default recipes</string>
    <string name="action_share">Share</string>

    <string name="title_activity_favorite_recipes">Favorite Recipes</string>
    <string name="title_activity_detail">Details</string>
    <string name="title_activity_settings">Settings</string>

    <!-- Label for storing default recipe query that is shown on startup -->
    <string name="pref_default_recipe_query_label">Your favourite ingredients</string>

    <!-- Default recipe query that is shown on the first run (or before user types something) -->
    <string name="pref_recipe_query_default" translatable="false">Chicken,Mayo,Tomato,Jalapeno</string>

	<string name="prefs_category_storage" translatable="false">Favorite recipes storage options</string>
	<string name="prefs_save_images_key" translatable="false">save_recipe_images</string>
	<string name="prefs_save_images_summary" translatable="false">Your favorite recipe images will be available when you are offline, however extra space will be taken for storage</string>
	<string name="prefs_save_images_title" translatable="false">Save images for favorite recipes</string>

    <string name="recipe_query_placeholder_text">What ingredients do you have?</string>

    <string name="text_loading_best_recipes">Loading best recipes for you</string>
    <string name="text_please_wait">Please wait</string>
    <string name="text_saving_in_favorites">Saving recipe in favorites</string>
    <string name="text_removing_from_favorites">Removing recipe from favorites</string>

    <string name="recipe_share_text">Try <xliff:g id="title">%1$s</xliff:g>! Find more details at <xliff:g id="url">%2$s</xliff:g>!</string>

	<string name="recipe_loading_error_text">Cannot load recipes!</string>
	<string name="connection_problems">Please check internet connection!</string>

    <string name="recipe_details_save_in_favourites">Save in favorites</string>
    <string name="recipe_details_remove_from_favorites">Remove from favorites</string>
    <string name="recipe_details_show_in_browser">Open in browser</string>

    <string name="no_recipes_found">No recipes found</string>

    <string name="recipe_saved_in_favorites">Recipe saved in favourites</string>
    <string name="recipe_removed_from_favorites">Recipe removed from favourites</string>

</resources>


text:
"""Helped functions to concatenate subset of noisy images to batch."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow.compat.v1 as tf
from tensorflow.compat.v2 import summary

IMG_SUMMARY_PREFIX = '_img_'

def format_tensors(*dicts):
  """Format metrics to be callable as tf.summary scalars on tpu's.

  Args:
    *dicts: A set of metric dictionaries, containing metric name + value tensor.

  Returns:
    A single formatted dictionary that holds all tensors.

  Raises:
   ValueError: if any tensor is not a scalar.
  """
  merged_summaries = {}
  for d in dicts:
    for metric_name, value in d.items():
      shape = value.shape.as_list()
      if metric_name.startswith(IMG_SUMMARY_PREFIX):
        # If image, shape it into 2d.
        merged_summaries[metric_name] = tf.reshape(value,
                                                   (1, -1, value.shape[-1], 1))
      elif not shape:
        merged_summaries[metric_name] = tf.expand_dims(value, axis=0)
      elif shape == [1]:
        merged_summaries[metric_name] = value
      else:
        raise ValueError(
            'Metric {} has value {} that is not reconciliable'.format(
                metric_name, value))
  return merged_summaries

def host_call_fn(model_dir, **kwargs):
  """host_call function used for creating training summaries when using TPU.

  Args:
    model_dir: String indicating the output_dir to save summaries in.
    **kwargs: Set of metric names and tensor values for all desired summaries.

  Returns:
    Summary op to be passed to the host_call arg of the estimator function.
  """
  gs = kwargs.pop('global_step')[0]
  with summary.create_file_writer(model_dir).as_default():
    # Always record summaries.
    with summary.record_if(True):
      for name, tensor in kwargs.items():
        if name.startswith(IMG_SUMMARY_PREFIX):
          summary.image(name.replace(IMG_SUMMARY_PREFIX, ''), tensor,
                        max_images=1)
        else:
          summary.scalar(name, tensor[0], step=gs)
      # Following function is under tf:1x, so we use it.
      return tf.summary.all_v2_summary_ops()

def mask_summaries(masks, with_img=False):
  metrics = {}
  for mask in masks:
    metrics['pruning/{}/sparsity'.format(
        mask.op.name)] = tf.nn.zero_fraction(mask)
    if with_img:
      metrics[IMG_SUMMARY_PREFIX + 'mask/' + mask.op.name] = mask
  return metrics

def initialize_parameters_from_ckpt(ckpt_path, model_dir, param_suffixes):
  """Load parameters from an existing checkpoint.

  Args:
    ckpt_path: str, loads the mask variables from this checkpoint.
    model_dir: str, if checkpoint exists in this folder no-op.
    param_suffixes: list or str, suffix of parameters to be load from
      checkpoint.
  """
  already_has_ckpt = model_dir and tf.train.latest_checkpoint(
      model_dir) is not None
  if already_has_ckpt:
    tf.logging.info(
        'Training already started on this model, not loading masks from'
        'previously trained model')
    return

  reader = tf.train.NewCheckpointReader(ckpt_path)
  param_names = reader.get_variable_to_shape_map().keys()
  param_names = [x for x in param_names if x.endswith(param_suffixes)]

  variable_map = {}
  for var in tf.global_variables():
    var_name = var.name.split(':')[0]
    if var_name in param_names:
      tf.logging.info('Loading parameter variable from checkpoint: %s',
                      var_name)
      variable_map[var_name] = var
    elif var_name.endswith(param_suffixes):
      tf.logging.info(
          'Cannot find parameter variable in checkpoint, skipping: %s',
          var_name)
  tf.train.init_from_checkpoint(ckpt_path, variable_map)


text:
package org.springframework.security.config.http;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import org.springframework.beans.factory.xml.ParserContext;

import static org.mockito.Mockito.verifyZeroInteractions;

@RunWith(PowerMockRunner.class)
@PrepareOnlyThisForTest(ParserContext.class)
public class WebConfigUtilsTests {

	public static final String URL = "/url";

	@Mock
	private ParserContext parserContext;

	// SEC-1980
	@Test
	public void validateHttpRedirectSpELNoParserWarning() {
		WebConfigUtils.validateHttpRedirect("#{T(org.springframework.security.config.http.WebConfigUtilsTest).URL}",
				this.parserContext, "fakeSource");
		verifyZeroInteractions(this.parserContext);
	}

}


text:
<?php

namespace Google\Service\SearchConsole;

class SitesListResponse extends \Google\Collection
{
  protected $collection_key = 'siteEntry';
  protected $siteEntryType = WmxSite::class;
  protected $siteEntryDataType = 'array';

  /**
   * @param WmxSite[]
   */
  public function setSiteEntry($siteEntry)
  {
    $this->siteEntry = $siteEntry;
  }
  /**
   * @return WmxSite[]
   */
  public function getSiteEntry()
  {
    return $this->siteEntry;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(SitesListResponse::class, 'Google_Service_SearchConsole_SitesListResponse');


text:
<?php
Atomik::needed('Aircraft.class');
Atomik::needed('Project.class');
Atomik::needed('Company.class');
Atomik::needed("Tool.class");

Atomik::set('tab_select','admin');
$fill = false;
$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
$limite = isset($_REQUEST['limite']) ? $_REQUEST['limite'] : 8;
$context_array['company_id']= Atomik::has('session/company_id')?Atomik::get('session/company_id'):"";
$context_array['aircraft_id']= Atomik::get('session/current_aircraft_id');
if ($context_array['company_id'] == ""){
	$aircraft = Aircraft::getAircraft($context_array['aircraft_id']);
	$context_array['company_id'] = $aircraft['company_id'];
}
$context_array['project_id']= Atomik::get('session/project_id');
$context_array['sub_project_id']= "";

$project = new Project($context_array);
$list_data = $project->getSubProjectList();
/* menu company */
$html=  '<form method="POST" action="'.Atomik::url('list_eqpt', false).'">';
$html.= '<fieldset class="medium">';
$html.= Company::getSelectCompany($context_array['company_id'],"active");
$html.= '</fieldset >';
$html.= '</form>';

/* menu aircraft */
$html.=  '<form method="POST" action="'.Atomik::url('list_eqpt', false).'">';
$html.= '<fieldset class="medium">';
$html.= Project::getSelectAircraft($context_array['company_id'],
                                    $context_array['aircraft_id'],
                                    "active");
$html.= '</fieldset >';
$html.= '</form>';

/* menu project */
$html.= '<form method="POST" action="'.Atomik::url('list_eqpt', false).'">';
$html.= '<fieldset class="medium">';
$html.= Project::getSelectProject($context_array['project_id'],"active",$context_array['aircraft_id'],$context_array['company_id']);
$html.= '</fieldset >';
$html.= '</form>';
$html .='
Back
';

Atomik::set('title',"Items");
Atomik::set('css_title',"hardware");
Atomik::set('css_reset',"no_show");
Atomik::set('url',"list_eqpt");
Atomik::set('url_add',Atomik::url('edit_eqpt'));
Atomik::set('title_add',"Add an item");
Atomik::set('page',$page);
Atomik::set('limite',$limite);
Atomik::set('css_page_previous','no_show');
Atomik::set('css_page_next','no_show');
Atomik::set('css_page',"no_show");
Atomik::set('select_menu',$html);


text:
<?php
/**
 * Jetpack Compatibility File
 * See: http://jetpack.me/
 *
 * @package sparkling
 */

/**
 * Add theme support for Infinite Scroll.
 * See: http://jetpack.me/support/infinite-scroll/
 */
function sparkling_jetpack_setup() {
	add_theme_support( 'infinite-scroll', array(
		'type'      => 'click',
		'container' => 'main',
		'footer'    => 'page',
	) );
}
add_action( 'after_setup_theme', 'sparkling_jetpack_setup' );


text:
class IEntity
{
	public:
		virtual ~IEntity() {};
		virtual void PrimaryXMove(float movementVal) = 0;
		virtual void PrimaryYMove(float movementVal) = 0;
		virtual void SecondaryXMove(float movementVal) = 0;
		virtual void SecondaryYMove(float movementVal) = 0;
		virtual void Trigger1() = 0;
		virtual void Trigger2() = 0;
};


text:
import * as React from 'react';
import { Palette } from './createPalette';

export type TextStyle =
  | 'display1'
  | 'display2'
  | 'display3'
  | 'display4'
  | 'headline'
  | 'title'
  | 'subheading'
  | 'body1'
  | 'body2'
  | 'caption';

export type Style = TextStyle | 'button';

export interface FontStyle {
  fontFamily: React.CSSProperties['fontFamily'];
  fontSize: React.CSSProperties['fontSize'];
  fontWeightLight: number | string;
  fontWeightRegular: number | string;
  fontWeightMedium: number | string;
}

export interface TypographyStyle {
  color: React.CSSProperties['color'];
  fontFamily: React.CSSProperties['fontFamily'];
  fontSize: React.CSSProperties['fontSize'];
  fontWeight: React.CSSProperties['fontWeight'];
  letterSpacing: React.CSSProperties['letterSpacing'];
  lineHeight: React.CSSProperties['lineHeight'];
}

export type Typography = { [type in Style]: TypographyStyle } & FontStyle;

export default function createTypography(
  palette: Palette,
  constants?: FontStyle
): Typography;