text:
namespace MatchMaker.Tool;

using System;
using System.Diagnostics;

using CommandLine;

/// <summary>
/// Defines the <see cref="Program" />
/// </summary>
internal class Program
{
    /// <summary>
    /// Gets the option types
    /// </summary>
    private static Type[] OptionTypes => new[] { typeof(ReportingOptions), typeof(SummaryOptions), typeof(ScheduleOptions) };

    /// <summary>
    /// The main program entry point
    /// </summary>
    /// <param name="args">The program arguments</param>
    private static void Main(string[] args)
    {
        try
        {
            Parser.Default.ParseArguments(args, OptionTypes)
                .WithParsed<BaseOptions>(ProcessBaseOptions)
                .MapResult(
                    (ReportingOptions options) => Reporting.Process(options),
                    (SummaryOptions options) => Reporting.Process(options),
                    (ScheduleOptions options) => Scheduling.Process(options),
                    errors => false);
        }
        catch (Exception e)
        {
            Trace.TraceError(e.ToString());
        }
    }

    /// <summary>
    /// Processes the base options.
    /// </summary>
    /// <param name="options">The options<see cref="BaseOptions"/></param>
    private static void ProcessBaseOptions(BaseOptions options)
    {
        if (options.Verbose)
        {
            Trace.Listeners.Add(new ConsoleTraceListener());
            Trace.IndentSize = 2;
        }
    }
}


text:
import gym
from gym import wrappers
import pickle
import argparse
import numpy as np
from tqdm import trange
from joblib import Parallel, delayed
import collections
from sklearn.neural_network import MLPRegressor

from matplotlib import pyplot as plt

plt.style.use("ggplot")

def plot_unimetric(history, metric, save_dir):
    plt.figure()
    plt.plot(history[metric])
    plt.title('model {}'.format(metric))
    plt.ylabel(metric)
    plt.xlabel('epoch')
    plt.savefig("{}/{}.png".format(save_dir, metric),
                format='png', dpi=300)

def generate_session(env, agent, t_max=int(1e5), step_penalty=0.01):
    states, actions = [], []
    total_reward = 0

    s = env.reset()

    for t in range(t_max):
        a = agent.predict([s])[0]
        a = np.array(list(map(
            lambda x: min(
                max(x[1], env.action_space.low[x[0]]),
                env.action_space.high[x[0]]),
            enumerate(a))))

        new_s, r, done, info = env.step(a)

        # record sessions like you did before
        states.append(s)
        actions.append(a)
        total_reward += r

        s = new_s
        if done:
            break

    total_reward -= t * step_penalty

    return states, actions, total_reward, t

glob_env = None
glob_agent = None

def generate_parallel_session(t_max=int(1e5), step_penalty=0.01):
    states, actions = [], []
    total_reward = 0

    s = glob_env.reset()

    for t in range(t_max):
        a = glob_agent.predict([s])[0]
        a = np.array(list(map(
            lambda x: min(
                max(x[1], glob_env.action_space.low[x[0]]),
                glob_env.action_space.high[x[0]]),
            enumerate(a))))

        new_s, r, done, info = glob_env.step(a)

        # record sessions like you did before
        states.append(s)
        actions.append(a)
        total_reward += r

        s = new_s
        if done:
            break

    total_reward -= t * step_penalty

    return states, actions, total_reward, t

def generate_parallel_sessions(n, t_max, step_penalty, n_jobs=-1):
    return Parallel(n_jobs)(n * [delayed(generate_parallel_session)(t_max, step_penalty)])

def cem(env, agent, num_episodes, max_steps=int(1e6), step_penalty=0.01,
        n_samples=200, percentile=50, n_jobs=-1, verbose=False):
    global glob_env, glob_agent
    init_n_samples = n_samples
    final_n_samples = n_samples // 5
    plays_to_decay = num_episodes // 2

    states_deque = collections.deque(maxlen=int(init_n_samples * 2))
    actions_deque = collections.deque(maxlen=int(init_n_samples * 2))
    rewards_deque = collections.deque(maxlen=int(init_n_samples * 2))

    glob_env = env  # NEVER DO LIKE THIS PLEASE!
    glob_agent = agent

    # Keeps track of useful statistics
    history = {
        "threshold": np.zeros(num_episodes),
        "reward": np.zeros(num_episodes),
        "n_steps": np.zeros(num_episodes),
    }

    tr = trange(
        num_episodes,
        desc="mean reward = {:.3f}\tthreshold = {:.3f}\tmean n_steps = {:.3f}".format(0.0, 0.0,
                                                                                0.0),
        leave=True)

    for i in tr:
        # generate new sessions
        # sessions = [
        #     generate_session(env, agent, max_steps, step_penalty)
        #     for _ in range(n_samples)]
        sessions = generate_parallel_sessions(n_samples, max_steps, step_penalty, n_jobs)
        if i < plays_to_decay:
            n_samples -= (init_n_samples - final_n_samples) // plays_to_decay

        batch_states, batch_actions, batch_rewards, batch_steps = map(np.array, zip(*sessions))
        # batch_states: a list of lists of states in each session
        # batch_actions: a list of lists of actions in each session
        # batch_rewards: a list of floats - total rewards at each session
        states_deque.extend(batch_states)
        actions_deque.extend(batch_actions)
        rewards_deque.extend(batch_rewards)

        batch_states = np.array(states_deque)
        batch_actions = np.array(actions_deque)
        batch_rewards = np.array(rewards_deque)

        threshold = np.percentile(batch_rewards, percentile)

        history["threshold"][i] = threshold
        history["reward"][i] = np.mean(batch_rewards)
        history["n_steps"][i] = np.mean(batch_steps)

        # look like > better, cause >= refer to reuse of bad examples
        if i < plays_to_decay:
            elite_states = batch_states[batch_rewards > threshold]
            elite_actions = batch_actions[batch_rewards > threshold]
        else:
            elite_states = batch_states[batch_rewards >= threshold]
            elite_actions = batch_actions[batch_rewards >= threshold]

        if len(elite_actions) > 0:
            elite_states, elite_actions = map(np.concatenate, [elite_states, elite_actions])
            # elite_states: a list of states from top games
            # elite_actions: a list of actions from top games
            try:
                agent.fit(elite_states, elite_actions)
            except:
                # just a hack
                addition = np.array([env.reset()] * env.action_space.n)
                elite_states = np.vstack((elite_states, addition))
                elite_actions = np.hstack((elite_actions, list(range(env.action_space.n))))
                agent.fit(elite_states, elite_actions)

        tr.set_description(
            "mean reward = {:.3f}\tthreshold = {:.3f}\tmean n_steps = {:.3f}".format(
                np.mean(batch_rewards) + step_penalty * np.mean(batch_steps),
                threshold, np.mean(batch_steps)))

    return history

def _parse_args():
    parser = argparse.ArgumentParser(description='Policy iteration example')
    parser.add_argument(
        '--env',
        type=str,
        default='MountainCarContinuous-v0',  # MountainCar-v0, LunarLander-v2
        help='The environment to use')
    parser.add_argument(
        '--num_episodes',
        type=int,
        default=200,
        help='Number of episodes')
    parser.add_argument(
        '--max_steps',
        type=int,
        default=int(1e5),
        help='Number of steps per episode')
    parser.add_argument(
        '--n_samples',
        type=int,
        default=1000,
        help='Games per epoch')
    parser.add_argument(
        '--step_penalty',
        type=float,
        default=0.01)
    parser.add_argument(
        '--percentile',
        type=int,
        default=80,
        help='percentile')
    parser.add_argument(
        '--verbose',
        action='store_true',
        default=False)
    parser.add_argument(
        '--plot_stats',
        action='store_true',
        default=False)
    parser.add_argument(
        '--layers',
        type=str,
        default=None)
    parser.add_argument(
        '--api_key',
        type=str,
        default=None)
    parser.add_argument(
        '--n_jobs',
        type=int,
        default=-1)
    parser.add_argument(
        '--seed',
        type=int,
        default=42)
    parser.add_argument(
        '--resume',
        action='store_true',
        default=False)

    args, _ = parser.parse_known_args()
    return args

def save_stats(stats, save_dir="./"):
    for key in stats:
        plot_unimetric(stats, key, save_dir)

def run(env, n_episodes=200, max_steps=int(1e5), n_samples=1000, step_penalty=0.01,
        percentile=80, layers=None,
        verbose=False, plot_stats=False, api_key=None, n_jobs=-1, seed=42, resume=False):
    env_name = env
    if env_name == "MountainCarContinuous-v0":
        env = gym.make(env).env
    else:
        env = gym.make(env)
    layers = layers or (256, 256, 128)

    agent = MLPRegressor(
        hidden_layer_sizes=layers,
        activation='tanh',
        warm_start=True,
        max_iter=1)
    agent.fit(
        np.zeros(env.observation_space.shape).reshape(1, -1),
        np.zeros(env.action_space.shape).reshape(1, -1))

    if resume:
        agent = pickle.load(open("agent.pkl", "rb"))

    env.seed(seed)
    np.random.seed(seed)

    stats = cem(env, agent, n_episodes,
                max_steps=max_steps, step_penalty=step_penalty,
                n_samples=n_samples, percentile=percentile,
                n_jobs=n_jobs, verbose=verbose)
    if plot_stats:
        save_stats(stats)

    pickle.dump(agent, open("agent.pkl", "wb"))

    if api_key is not None:
        env = gym.wrappers.Monitor(env, "/tmp/" + env_name, force=True)
        sessions = [generate_session(env, agent, int(1e10), 0.0) for _ in range(300)]
        env.close()
        gym.upload("/tmp/" + env_name, api_key=api_key)

def main():
    args = _parse_args()
    try:
        layers = tuple(map(int, args.layers.split("-")))
    except:
        layers = None
    run(args.env, args.num_episodes, args.max_steps, args.n_samples, args.step_penalty,
        args.percentile, layers,
        args.verbose, args.plot_stats, args.api_key, args.n_jobs, args.seed, args.resume)

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaGithub


text:
function Add-VSBackupBackupPlanBackupRuleResourceType {
    <#
    .SYNOPSIS
        Adds an AWS::Backup::BackupPlan.BackupRuleResourceType resource property to the template. Specifies an object containing properties used to schedule a task to back up a selection of resources.

    .DESCRIPTION
        Adds an AWS::Backup::BackupPlan.BackupRuleResourceType resource property to the template.
Specifies an object containing properties used to schedule a task to back up a selection of resources.

    .LINK
        http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-backup-backupplan-backupruleresourcetype.html

    .PARAMETER CompletionWindowMinutes
        A value in minutes after a backup job is successfully started before it must be completed or it is canceled by AWS Backup.

        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-backup-backupplan-backupruleresourcetype.html#cfn-backup-backupplan-backupruleresourcetype-completionwindowminutes
        PrimitiveType: Double
        UpdateType: Mutable

    .PARAMETER ScheduleExpression
        A CRON expression specifying when AWS Backup initiates a backup job.

        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-backup-backupplan-backupruleresourcetype.html#cfn-backup-backupplan-backupruleresourcetype-scheduleexpression
        PrimitiveType: String
        UpdateType: Mutable

    .PARAMETER RecoveryPointTags
        To help organize your resources, you can assign your own metadata to the resources that you create. Each tag is a key-value pair.

        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-backup-backupplan-backupruleresourcetype.html#cfn-backup-backupplan-backupruleresourcetype-recoverypointtags
        PrimitiveType: Json
        UpdateType: Mutable

    .PARAMETER CopyActions
        Not currently supported by AWS CloudFormation.

        Type: List
        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-backup-backupplan-backupruleresourcetype.html#cfn-backup-backupplan-backupruleresourcetype-copyactions
        ItemType: CopyActionResourceType
        UpdateType: Mutable

    .PARAMETER Lifecycle
        The lifecycle defines when a protected resource is transitioned to cold storage and when it expires. AWS Backup transitions and expires backups automatically according to the lifecycle that you define.

        Type: LifecycleResourceType
        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-backup-backupplan-backupruleresourcetype.html#cfn-backup-backupplan-backupruleresourcetype-lifecycle
        UpdateType: Mutable

    .PARAMETER TargetBackupVault
        The name of a logical container where backups are stored. Backup vaults are identified by names that are unique to the account used to create them and the AWS Region where they are created. They consist of lowercase letters, numbers, and hyphens.

        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-backup-backupplan-backupruleresourcetype.html#cfn-backup-backupplan-backupruleresourcetype-targetbackupvault
        PrimitiveType: String
        UpdateType: Mutable

    .PARAMETER StartWindowMinutes
        An optional value that specifies a period of time in minutes after a backup is scheduled before a job is canceled if it doesn't start successfully.

        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-backup-backupplan-backupruleresourcetype.html#cfn-backup-backupplan-backupruleresourcetype-startwindowminutes
        PrimitiveType: Double
        UpdateType: Mutable

    .PARAMETER RuleName
        A display name for a backup rule.

        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-backup-backupplan-backupruleresourcetype.html#cfn-backup-backupplan-backupruleresourcetype-rulename
        PrimitiveType: String
        UpdateType: Mutable

    .FUNCTIONALITY
        Vaporshell
    #>
    [OutputType('Vaporshell.Resource.Backup.BackupPlan.BackupRuleResourceType')]
    [cmdletbinding()]
    Param
    (
        [parameter(Mandatory = $false)]
        [ValidateScript( {
                $allowedTypes = "System.Double","Vaporshell.Function"
                if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
                    $true
                }
                else {
                    $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
                }
            })]
        $CompletionWindowMinutes,
        [parameter(Mandatory = $false)]
        [ValidateScript( {
                $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition"
                if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
                    $true
                }
                else {
                    $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
                }
            })]
        $ScheduleExpression,
        [parameter(Mandatory = $false)]
        [ValidateScript( {
                $allowedTypes = "System.String","System.Collections.Hashtable","System.Management.Automation.PSCustomObject"
                if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
                    $true
                }
                else {
                    $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
                }
            })]
        $RecoveryPointTags,
        [parameter(Mandatory = $false)]
        [ValidateScript( {
                $allowedTypes = "Vaporshell.Resource.Backup.BackupPlan.CopyActionResourceType"
                if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
                    $true
                }
                else {
                    $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
                }
            })]
        $CopyActions,
        [parameter(Mandatory = $false)]
        $Lifecycle,
        [parameter(Mandatory = $true)]
        [ValidateScript( {
                $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition"
                if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
                    $true
                }
                else {
                    $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
                }
            })]
        $TargetBackupVault,
        [parameter(Mandatory = $false)]
        [ValidateScript( {
                $allowedTypes = "System.Double","Vaporshell.Function"
                if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
                    $true
                }
                else {
                    $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
                }
            })]
        $StartWindowMinutes,
        [parameter(Mandatory = $true)]
        [ValidateScript( {
                $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition"
                if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
                    $true
                }
                else {
                    $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
                }
            })]
        $RuleName
    )
    Begin {
        $obj = [PSCustomObject]@{}
        $commonParams = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable')
    }
    Process {
        foreach ($key in $PSBoundParameters.Keys | Where-Object {$commonParams -notcontains $_}) {
            switch ($key) {
                RecoveryPointTags {
                    if (($PSBoundParameters[$key]).PSObject.TypeNames -contains "System.String"){
                        try {
                            $JSONObject = (ConvertFrom-Json -InputObject $PSBoundParameters[$key] -ErrorAction Stop)
                        }
                        catch {
                            $PSCmdlet.ThrowTerminatingError((New-VSError -String "Unable to convert parameter '$key' string value to PSObject! Please use a JSON string OR provide a Hashtable or PSCustomObject instead!"))
                        }
                    }
                    else {
                        $JSONObject = ([PSCustomObject]$PSBoundParameters[$key])
                    }
                    $obj | Add-Member -MemberType NoteProperty -Name $key -Value $JSONObject
                }
                Default {
                    $obj | Add-Member -MemberType NoteProperty -Name $key -Value $PSBoundParameters.$key
                }
            }
        }
    }
    End {
        $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.Backup.BackupPlan.BackupRuleResourceType'
        Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n"
    }
}


text:
The `ConfigAggregator` works by aggregating "config providers" passed to its
constructor.  Each provider should be a callable, returning a configuration
array (or a PHP generator) to be merged.

```php
$aggregator = new ConfigAggregator([
    function () {
        return ['foo' => 'bar'];
    },
    new PhpFileProvider('*.global.php'),
]);
var_dump($aggregator->getMergedConfig());
```

If the provider is a class name, the aggregator automatically instantiates it
before invoking it; as such, any class name you use as a config provider _must_
also define `__invoke()`, and that method _must_ return an array.

This can be used to mimic the Zend Framework module system: you can specify a
list of config providers from different packages, and aggregated configuration
will be available to your application.

As a library owner, you can distribute your own configuration providers that
provide default values for use with your library.

As an example:

```php
class ApplicationConfig
{
    public function __invoke()
    {
        return ['foo' => 'bar'];
    }
}

$aggregator = new ConfigAggregator([
    ApplicationConfig::class,
    new PhpFileProvider('*.global.php'),
]);
var_dump($aggregator->getMergedConfig());
```

Output from both examples will be the same:

```php
array(4) {
  'foo' =>
  string(3) "bar"
  'db' =>
  array(1) {
    'dsn' =>
    string(9) "mysql:..."
  }
  'cache_storage' =>
  string(5) "redis"
  'redis' =>
  array(0) {
  }
}
```

### Generators

Config providers can be written as generators. This way, a single callable can
provide multiple configurations:

```php
use Zend\ConfigAggregator\ConfigAggregator;
use Zend\Stdlib\Glob;

$aggregator = new ConfigAggregator([
    function () {
        foreach (Glob::glob('data/*.global.php', Glob::GLOB_BRACE) as $file) {
            yield include $file;
        }
    },
]);
var_dump($aggregator->getMergedConfig());
```

The `PhpFileProvider` is implemented as a generator.

## Available config providers

### PhpFileProvider

Loads configuration from PHP files returning arrays, such as this one:

```php
return [
    'db' => [
        'dsn' => 'mysql:...',
    ],
];
```

Wildcards are supported:

```php
use Zend\ConfigAggregator\ConfigAggregator;
use Zend\ConfigAggregator\PhpFileProvider;

$aggregator = new ConfigAggregator(
    [
        new PhpFileProvider('config/*.global.php'),
    ]
);
```

The example above will merge all matching files from the `config/` directory. If
you have files such as `app.global.php` or `database.global.php` in that
directory, they will be loaded using this above lines of code.

The provider also supports _globbing_.  Globbing defaults to PHP's `glob()`
function. However, if `Zend\Stdlib\Glob` is available, it will use that to allow
for cross-platform glob patterns, including brace notation:
`'config/autoload/{{,*.}global,{,*.}local}.php'`. Install
[zendframework/zend-stdlib](https://docs.zendframework.com/zend-stdlib) to
utilize this feature.

### ZendConfigProvider

Sometimes using plain PHP files may be not enough; you may want to build your
configuration from multiple files of different formats, such as INI, JSON, YAML,
or XML.  zend-config-aggregator allows you to do so via its
`ZendConfigProvider`. This feature requires first installing zend-config:

```bash
$ composer require zendframework/zend-config
```

Once installed, you may use as many `ZendConfigProvider` instances as you need:

```php
use Zend\ConfigAggregator\ConfigAggregator;
use Zend\ConfigAggregator\ZendConfigProvider;

$aggregator = new ConfigAggregator(
    [
        new ZendConfigProvider('*.global.json'),
        new ZendConfigProvider('database.local.ini'),
    ]
);
```

These could even be combined into a single glob statement:

```php
$aggregator = new ConfigAggregator(
    [
        new ZendConfigProvider('*.global.json,database.local.ini'),
    ]
);
```

`ZendConfigProvider` accepts wildcards and globs, and autodetects the config
type based on file extension.

Some config readers (in particular, YAML) may need additional dependencies;
please refer to [the zend-config manual](https://docs.zendframework.com/zend-config/reader/)
for more details.


text:
/**
 * Created by cmeyers on 8/25/16.
 */
import { assert } from 'chai';

import { buildRunDetailsUrl, buildRunDetailsUrlFromQueue } from '../../src/js/UrlBuilder';

const createObjectFromLink = (url) => (
    { _links: { self: { href: url } } }
);

describe('UrlBuilder', () => {
    describe('buildRunDetailsUrl', () => {
        describe('handling input', () => {
            it('handles an object', () => {
                const freestyle = createObjectFromLink(
                    '/blue/rest/organizations/jenkins/pipelines/freestyle-success-10m/runs/28/'
                );

                const url = buildRunDetailsUrl(freestyle);
                assert.equal(url, '/organizations/jenkins/freestyle-success-10m/detail/freestyle-success-10m/28/pipeline');
            });

            it('handles a URL', () => {
                const freestyle = '/blue/rest/organizations/jenkins/pipelines/freestyle-success-10m/runs/28/';
                const url = buildRunDetailsUrl(freestyle);
                assert.equal(url, '/organizations/jenkins/freestyle-success-10m/detail/freestyle-success-10m/28/pipeline');
            });

            it('throws sensible error for bogus object', () => {
                assert.throws(() => buildRunDetailsUrl({}), 'Could not find input URL');
            });

            it('throws sensible error for bad url', () => {
                assert.throws(() => buildRunDetailsUrl('/a/b/c/d'), 'Could not extract URI components');
            });

            it('throws sensible error for a string of chars', () => {
                assert.throws(() => buildRunDetailsUrl('abcdefghijklmnopqrstuvwxyz'), 'Could not extract URI components');
            });
        });

        describe('freestyle', () => {
            it('handles top-level job', () => {
                const freestyle = createObjectFromLink(
                    '/blue/rest/organizations/jenkins/pipelines/freestyle-success-10m/runs/28/'
                );

                const url = buildRunDetailsUrl(freestyle);
                assert.equal(url, '/organizations/jenkins/freestyle-success-10m/detail/freestyle-success-10m/28/pipeline');
            });

            it('handles nested job', () => {
                const freestyle = createObjectFromLink(
                    '/blue/rest/organizations/jenkins/pipelines/myfolder/pipelines/pipeline-2/runs/103/'
                );

                const url = buildRunDetailsUrl(freestyle);
                assert.equal(url, '/organizations/jenkins/myfolder%2Fpipeline-2/detail/pipeline-2/103/pipeline');
            });
        });

        describe('pipeline', () => {
            it('handles top-level job', () => {
                const pipeline = createObjectFromLink(
                    '/blue/rest/organizations/jenkins/pipelines/pipeline-failure-15s/runs/42/'
                );

                const url = buildRunDetailsUrl(pipeline);
                assert.equal(url, '/organizations/jenkins/pipeline-failure-15s/detail/pipeline-failure-15s/42/pipeline');
            });

            it('handles nested job', () => {
                const pipeline = createObjectFromLink(
                    '/blue/rest/organizations/jenkins/pipelines/pipeline-failure-15s/runs/42/'
                );

                const url = buildRunDetailsUrl(pipeline);
                assert.equal(url, '/organizations/jenkins/pipeline-failure-15s/detail/pipeline-failure-15s/42/pipeline');
            });
        });

        describe('multibranch pipeline', () => {
            it('handles top-level job', () => {
                const multibranch = createObjectFromLink(
                    '/blue/rest/organizations/jenkins/pipelines/jdl1/branches/experiment%252Fbuild-locally-docker/runs/41/'
                );

                const url = buildRunDetailsUrl(multibranch);
                assert.equal(url, '/organizations/jenkins/jdl1/detail/experiment%2Fbuild-locally-docker/41/pipeline');
            });

            it('handles nested job', () => {
                const multibranch = createObjectFromLink(
                    '/blue/rest/organizations/jenkins/pipelines/folder1/pipelines/folder2/pipelines/folder3/pipelines' +
                    '/jdl-2/branches/experiment%252Fbuild-locally-docker/runs/21/'
                );

                const url = buildRunDetailsUrl(multibranch);
                assert.equal(url, '/organizations/jenkins/folder1%2Ffolder2%2Ffolder3%2Fjdl-2/detail/experiment%2Fbuild-locally-docker/21/pipeline');
            });
        });
    });

    describe('buildRunDetailsUrlFromQueue', () => {
        describe('freestyle', () => {
            it('handles top-level job', () => {
                const freestyle = createObjectFromLink(
                    '/blue/rest/organizations/jenkins/pipelines/freestyle-success-10m/queue/28/'
                );

                const url = buildRunDetailsUrlFromQueue(freestyle, false, 20);
                assert.equal(url, '/organizations/jenkins/freestyle-success-10m/detail/freestyle-success-10m/20/pipeline');
            });

            it('handles nested job', () => {
                const freestyle = createObjectFromLink(
                    '/blue/rest/organizations/jenkins/pipelines/myfolder/pipelines/pipeline-2/queue/103/'
                );

                const url = buildRunDetailsUrlFromQueue(freestyle, false, 40);
                assert.equal(url, '/organizations/jenkins/myfolder%2Fpipeline-2/detail/pipeline-2/40/pipeline');
            });
        });

        describe('pipeline', () => {
            it('handles top-level job', () => {
                const pipeline = createObjectFromLink(
                    '/blue/rest/organizations/jenkins/pipelines/pipeline-failure-15s/queue/42/'
                );

                const url = buildRunDetailsUrlFromQueue(pipeline, false, 15);
                assert.equal(url, '/organizations/jenkins/pipeline-failure-15s/detail/pipeline-failure-15s/15/pipeline');
            });

            it('handles nested job', () => {
                const pipeline = createObjectFromLink(
                    '/blue/rest/organizations/jenkins/pipelines/simple-pipeline-jobs/pipelines/pipeline-failure-1m/queue/17/'
                );

                const url = buildRunDetailsUrlFromQueue(pipeline, false, 25);
                assert.equal(url, '/organizations/jenkins/simple-pipeline-jobs%2Fpipeline-failure-1m/detail/pipeline-failure-1m/25/pipeline');
            });
        });

        describe('multibranch pipeline', () => {
            it('handles top-level job', () => {
                const multibranch = createObjectFromLink(
                    '/blue/rest/organizations/jenkins/pipelines/jdl1/pipelines/experiment%252Fbuild-locally-docker/queue/42/'
                );

                const url = buildRunDetailsUrlFromQueue(multibranch, true, 55);
                assert.equal(url, '/organizations/jenkins/jdl1/detail/experiment%2Fbuild-locally-docker/55/pipeline');
            });

            it('handles nested job', () => {
                const multibranch = createObjectFromLink(
                    '/blue/rest/organizations/jenkins/pipelines/folder1/pipelines/folder2/pipelines/folder3/pipelines/jdl-2/pipelines/master/queue/31/'
                );

                const url = buildRunDetailsUrlFromQueue(multibranch, true, 11);
                assert.equal(url, '/organizations/jenkins/folder1%2Ffolder2%2Ffolder3%2Fjdl-2/detail/master/11/pipeline');
            });
        });
    });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

namespace StackExchange.Opserver.Data.HAProxy
{
    /// <summary>
    /// Represents the a single proxy instance in HAProxy including the Frontends, Servers, and Backends currently configured.
    /// </summary>
    public class Proxy : IMonitorStatus
    {
        [JsonIgnore]
        public HAProxyInstance Instance { get; internal set; }
        public string Name { get; internal set; }
        public string GroupName { get { return Instance.Group != null ? Instance.Group.Name : ""; } }
        public string GroupLinkName { get { return string.Concat(Instance.Group != null ? Instance.Group.Name + "-" : "", Name); } }
        public string InstanceLinkName { get { return string.Concat(Instance.Name, "-", Name); } }
        public Frontend Frontend { get; internal set; }
        public List<Server> Servers { get; internal set; }
        public Backend Backend { get; internal set; }
        public DateTime PollDate { get; internal set; }

        public IEnumerable<Item> AllStats
        {
            get
            {
                if(Frontend != null)
                    yield return Frontend;
                foreach (var s in Servers)
                    yield return s;
                if (Backend != null)
                    yield return Backend;
            }
        }

        public bool HasContent
        {
            get { return Frontend != null || Backend != null || (Servers != null && Servers.Count > 0); }
        }

        public bool HasFrontend { get { return Frontend != null; } }
        public bool HasServers { get { return Servers != null && Servers.Count > 0; } }
        public bool HasBackend { get { return Backend != null; } }

        public MonitorStatus MonitorStatus
        {
            get
            {
                if (Servers == null || Servers.Count == 0)
                    return MonitorStatus.Good;
                return Servers.GetWorstStatus();
            }
        }
        public string MonitorStatusReason
        {
            get
            {
                if(Servers == null || Servers.Count == 0) return null;
                var pieces = new List<string>();
                foreach(var g in Servers.WithIssues().GroupBy(s => s.ProxyServerStatus).OrderByDescending(g => g.Key))
                {
                    pieces.Add(string.Format("{0}: {1} {2}", NiceName, g.Count().ToComma(), g.Key.ShortDescription()));
                }
                return string.Join(", ", pieces);
            }
        }

        private Item Primary { get { return (Item)Frontend ?? Backend; } }

        public string Status { get { return Primary.Status; } }
        public int LastStatusChangeSecondsAgo { get { return Primary.LastStatusChangeSecondsAgo; } }
        public long BytesIn { get { return Primary.BytesIn; } }
        public long BytesOut { get { return Primary.BytesIn; } }

        public int Order
        {
            get { return Frontend != null ? 0 : HasServers ? 1 : 2; }
        }

        #region Display Properties

        public bool ShowQueue
        {
            get { return HasServers && Servers.Any(s => s.LimitSessions > 0 || s.LimitNewSessionPerSecond > 0); }
        }
        public bool ShowWarnings
        {
            get { return HasServers; }
        }
        public bool ShowServers
        {
            get { return HasServers; }
        }
        public bool ShowThrottle
        {
            get { return HasServers && Servers.Any(s => s.Throttle > 0); }
        }

        #endregion

        public string NiceName
        {
            get
            {
                string result;
                if (Current.Settings.HAProxy.Aliases.TryGetValue(Name, out result))
                    return result;
                return Name;
            }
        }

        public override string ToString()
        {
            return string.Concat(Instance.Group != null ? (Instance.Group.Name + ": ") : "", Instance.Name, ": ", Name);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="edu.cs4730.input"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="20" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)

require "codeclimate-test-reporter"
ENV['CODECLIMATE_REPO_TOKEN'] = '434d4cfa388ad2146c71bca82bf4cb9693336f208412c7378c2c099de8f81326'
CodeClimate::TestReporter.start

require 'simpack'
require 'byebug'


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:background="@color/app_color"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="60dp"
        android:gravity="center_horizontal"
        android:text="请选择登录类型"
        android:textColor="@android:color/white"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tv_no_account"
        style="@style/round_border_text"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginBottom="20dp"
        android:text="无账号" />

    <TextView
        android:id="@+id/tv_login_account"
        style="@style/round_border_text"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginTop="20dp"
        android:text="扇贝网账号" />

</LinearLayout>


text:
namespace Eurotrash.GrimDawn.WinFormsFrontEnd.Forms
{
    partial class ErrorForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ErrorForm));
            this.label1 = new System.Windows.Forms.Label();
            this._errorDetailsTextBox = new System.Windows.Forms.TextBox();
            this._closeButton = new System.Windows.Forms.Button();
            this._copyToClipboardButton = new System.Windows.Forms.Button();
            this._messageLabel = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this._exitButton = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 9);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(171, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "An unexpected error has occurred:";
            //
            // _errorDetailsTextBox
            //
            this._errorDetailsTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this._errorDetailsTextBox.Location = new System.Drawing.Point(12, 108);
            this._errorDetailsTextBox.Multiline = true;
            this._errorDetailsTextBox.Name = "_errorDetailsTextBox";
            this._errorDetailsTextBox.ReadOnly = true;
            this._errorDetailsTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this._errorDetailsTextBox.Size = new System.Drawing.Size(658, 190);
            this._errorDetailsTextBox.TabIndex = 1;
            //
            // _closeButton
            //
            this._closeButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this._closeButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this._closeButton.Location = new System.Drawing.Point(420, 304);
            this._closeButton.Name = "_closeButton";
            this._closeButton.Size = new System.Drawing.Size(122, 25);
            this._closeButton.TabIndex = 2;
            this._closeButton.Text = "Close and Continue";
            this._closeButton.UseVisualStyleBackColor = true;
            this._closeButton.Click += new System.EventHandler(this._closeButton_Click);
            //
            // _copyToClipboardButton
            //
            this._copyToClipboardButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this._copyToClipboardButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this._copyToClipboardButton.Location = new System.Drawing.Point(260, 304);
            this._copyToClipboardButton.Name = "_copyToClipboardButton";
            this._copyToClipboardButton.Size = new System.Drawing.Size(154, 25);
            this._copyToClipboardButton.TabIndex = 3;
            this._copyToClipboardButton.Text = "Copy Details to Clipboard";
            this._copyToClipboardButton.UseVisualStyleBackColor = true;
            this._copyToClipboardButton.Click += new System.EventHandler(this._copyToClipboardButton_Click);
            //
            // _messageLabel
            //
            this._messageLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this._messageLabel.Location = new System.Drawing.Point(50, 38);
            this._messageLabel.Name = "_messageLabel";
            this._messageLabel.Size = new System.Drawing.Size(608, 31);
            this._messageLabel.TabIndex = 4;
            this._messageLabel.Text = "[message]";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(12, 81);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(241, 13);
            this.label3.TabIndex = 5;
            this.label3.Text = "It is recommended that you restart the application.";
            //
            // _exitButton
            //
            this._exitButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this._exitButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this._exitButton.Location = new System.Drawing.Point(548, 304);
            this._exitButton.Name = "_exitButton";
            this._exitButton.Size = new System.Drawing.Size(122, 25);
            this._exitButton.TabIndex = 6;
            this._exitButton.Text = "Exit Application";
            this._exitButton.UseVisualStyleBackColor = true;
            this._exitButton.Click += new System.EventHandler(this._exitButton_Click);
            //
            // ErrorForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.CancelButton = this._exitButton;
            this.ClientSize = new System.Drawing.Size(682, 339);
            this.Controls.Add(this._exitButton);
            this.Controls.Add(this.label3);
            this.Controls.Add(this._messageLabel);
            this.Controls.Add(this._copyToClipboardButton);
            this.Controls.Add(this._closeButton);
            this.Controls.Add(this._errorDetailsTextBox);
            this.Controls.Add(this.label1);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "ErrorForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "An error has occurred...";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox _errorDetailsTextBox;
        private System.Windows.Forms.Button _closeButton;
        private System.Windows.Forms.Button _copyToClipboardButton;
        private System.Windows.Forms.Label _messageLabel;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Button _exitButton;
    }
}


text:
require 'spec_helper'

describe WorkshopsController, type: :controller do
  let(:workshop) { Fabricate(:sessions) }
  let(:member) { Fabricate(:member) }

  describe "POST #add" do
    it "Redirects to the login page if the user's logged out" do
      post :add, id: workshop.id
      expect(response).to redirect_to '/auth/github'
    end

    it "Adds a student to the attendees, if the user's a student and there's space" do
      login member
      post :add, {id: workshop.id, role: 'student'}
      expect(response).to redirect_to :added_workshop
    end

    it "Adds a student to the waiting list, if the user's a student and there's no space" do
      login member
      expect_any_instance_of(WorkshopPresenter).to receive(:student_spaces?).and_return(false)

      post :add, {id: workshop.id, role: 'student'}
      expect(response).to redirect_to :waitlisted_workshop
    end

    it "Adds a coach to the attendees, if the user's a coach and there's space" do
      login member

      post :add, {id: workshop.id, role: 'coach'}
      expect(response).to redirect_to :added_workshop
    end

    it "Adds a coach to the waiting list, if the user's a coach and there's no space" do
      login member
      expect_any_instance_of(WorkshopPresenter).to receive(:coach_spaces?).and_return(false)

      post :add, {id: workshop.id, role: 'coach'}
      expect(response).to redirect_to :waitlisted_workshop
    end

    it "Redirects back to the event page if we have no idea whether the user's a coach or a student" do
      login member

      post :add, {id: workshop.id}
      expect(response).to redirect_to :workshop
    end
  end

  describe "POST #remove" do
    it "Redirects to the login page if the user's logged out" do
      post :remove, id: workshop.id
      expect(response).to redirect_to '/auth/github'
    end

    it "Does nothing if the student has no invite or waiting list" do
      login member
      post :remove, id: workshop.id
      expect(response).to redirect_to removed_workshop_path(workshop)
    end

    it "Removes a student from the attendees, if the user's got an invite" do
      Fabricate(:student_session_invitation, member: member, sessions: workshop, attending: true)
      expect(workshop.attendee? member).to be true

      login member
      post :remove, id: workshop.id
      expect(workshop.attendee? member).to be false
    end

    it "Removes a coach from the attendees, if the user has an invite" do
      Fabricate(:coach_session_invitation, member: member, sessions: workshop, attending: true)
      expect(workshop.attendee? member).to be true

      login member
      post :remove, id: workshop.id
      expect(workshop.attendee? member).to be false
    end

    it "Removes a student from the waiting list, if the user's on the waiting list" do
      invite = Fabricate(:student_session_invitation, sessions: workshop, member: member)
      WaitingList.add(invite)
      expect(workshop.attendee? member).to be false
      expect(workshop.waitlisted? member).to be true

      login member
      post :remove, id: workshop.id
      expect(workshop.attendee? member).to be false
      expect(workshop.waitlisted? member).to be false
    end

    it "Removes both invites if the student has somehow got both a student and coach invite" do
      Fabricate(:student_session_invitation, member: member, sessions: workshop, attending: true)
      Fabricate(:coach_session_invitation, member: member, sessions: workshop, attending: true)
      expect(workshop.attendee? member).to be true

      login member
      post :remove, id: workshop.id
      expect(workshop.attendee? member).to be false
    end
  end
end


text:
package sm.search;

import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.io.InputStream;
import java.net.URL;

import sm.R;

public class RecipeInfoActivity extends AppCompatActivity {
    String name, link;
    int time;
    String[] ingredients;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe_info);

        if (getIntent().getExtras() != null) {
            name = getIntent().getExtras().getString("NAME");
            link = getIntent().getExtras().getString("IMAGE");
            ingredients = getIntent().getExtras().getStringArray("INGREDIENTS");
            time = getIntent().getExtras().getInt("TIME");
        }

        final TextView recipeName = (TextView)findViewById(R.id.recipeName);
        final TextView ingredientString = (TextView)findViewById(R.id.ingredients);
        final TextView cookTime = (TextView)findViewById(R.id.cookTime);
        final TextView recipeLink = (TextView)findViewById(R.id.link);
        final ImageView imageView = (ImageView)findViewById(R.id.recipeImage);

        new AsyncTask<Void,Void,Void>() {
            String newImageString;
            Drawable drawable;
            @Override
            protected Void doInBackground(Void... params) {

                drawable = LoadImageFromWebOperations(link);
                return null;
            }
            @Override
            protected void onPostExecute(Void result) {

                if (drawable != null) {

                    imageView.setImageDrawable(drawable);
                    recipeName.setText(name);
                    String ingredientList = "Ingredients: ";
                    for (int i = 0; i < ingredients.length; ++i) {
                        if (i == ingredients.length-1) {
                            ingredientList += ingredients[i];
                        } else {
                            ingredientList += ingredients[i] + ", ";
                        }
                    }
                    ingredientString.setText(ingredientList);
                    cookTime.setText("Time: ");
                    if (time <= 0 ) {
                        cookTime.setText(cookTime.getText() + "Not specified");
                    } else {
                        int temp_time = time;
                        int hours = temp_time/3600;
                        temp_time -= hours*3600;
                        int mins = temp_time/60;
                        temp_time -= mins*60;
                        int secs = temp_time;
                        String hourString = "" + hours;
                        String minString = "" + mins;
                        String secString = "" + secs;
                        if (hours != 0) {
                            cookTime.setText(cookTime.getText() + " " + hourString + " hours");
                        }
                        if (mins != 0) {
                            cookTime.setText(cookTime.getText() + " " + minString + " minutes");
                        }
                        if (secs != 0) {
                            cookTime.setText(cookTime.getText() + " " + secString + " seconds");
                        }
                    }
                    recipeLink.setText(link);

                } else {
                    throw new RuntimeException("Drawable is null!");
                }
            }
        }.execute();
    }

    public static Drawable LoadImageFromWebOperations(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "");
            return d;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}


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

import java.math.*;

import javax.annotation.Generated;

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

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

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

    public ScheduleKeyDeletionResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        ScheduleKeyDeletionResult scheduleKeyDeletionResult = new ScheduleKeyDeletionResult();

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

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

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

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("KeyId", targetDepth)) {
                    context.nextToken();
                    scheduleKeyDeletionResult.setKeyId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("DeletionDate", targetDepth)) {
                    context.nextToken();
                    scheduleKeyDeletionResult.setDeletionDate(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return scheduleKeyDeletionResult;
    }

    private static ScheduleKeyDeletionResultJsonUnmarshaller instance;

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


text:
package ro.pub.cs.systems.pdsd.lab07.landmarklister.views;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ro.pub.cs.systems.pdsd.lab07.earthquakelister.R;
import ro.pub.cs.systems.pdsd.lab07.landmarklister.controller.LandmarkInformationAdapter;
import ro.pub.cs.systems.pdsd.lab07.landmarklister.general.Constants;
import ro.pub.cs.systems.pdsd.lab07.landmarklister.model.LandmarkInformation;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class LandmarkListerActivity extends Activity {

	private EditText northEditText, southEditText, eastEditText, westEditText;

	private ListView landmarksListView;

	private ShowResultsButtonClickListener showResultsButtonClickListener = new ShowResultsButtonClickListener();
	private class ShowResultsButtonClickListener implements Button.OnClickListener {

		@Override
		public void onClick(View view) {
			String northString = northEditText.getText().toString();
			if (northString == null || northString.isEmpty()) {
				Toast.makeText(getApplication(), Constants.MISSING_INFORMATION_ERROR_MESSAGE, Toast.LENGTH_LONG).show();
				return;
			}
			String southString = southEditText.getText().toString();
			if (southString == null || southString.isEmpty()) {
				Toast.makeText(getApplication(), Constants.MISSING_INFORMATION_ERROR_MESSAGE, Toast.LENGTH_LONG).show();
				return;
			}
			String eastString = eastEditText.getText().toString();
			if (eastString == null || eastString.isEmpty()) {
				Toast.makeText(getApplication(), Constants.MISSING_INFORMATION_ERROR_MESSAGE, Toast.LENGTH_LONG).show();
				return;
			}
			String westString = westEditText.getText().toString();
			if (westString == null || westString.isEmpty()) {
				Toast.makeText(getApplication(), Constants.MISSING_INFORMATION_ERROR_MESSAGE, Toast.LENGTH_LONG).show();
				return;
			}

			new EarthquakeListerThread().start();
		}
	}

	private class EarthquakeListerThread extends Thread {

		@Override
		public void run() {
			String northString = northEditText.getText().toString();
			String southString = southEditText.getText().toString();
			String eastString = eastEditText.getText().toString();
			String westString = westEditText.getText().toString();

			HttpClient httpClient = new DefaultHttpClient();
			String url = Constants.LANDMARK_LISTER_WEB_SERVICE_INTERNET_ADDRESS +
					Constants.NORTH + northString +
					"&" + Constants.SOUTH + southString +
					"&" + Constants.EAST + eastString +
					"&" + Constants.WEST + westString +
					"&" + Constants.CREDENTIALS;
			HttpGet httpGet = new HttpGet(url);
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			try {
				String content = httpClient.execute(httpGet, responseHandler);
				final ArrayList<LandmarkInformation> landMarkInformationList = new ArrayList<LandmarkInformation>();
				JSONObject result = new JSONObject(content);
				JSONArray jsonArray = result.getJSONArray(Constants.GEONAMES);
				for (int k = 0; k < jsonArray.length(); k++) {
					JSONObject jsonObject = jsonArray.getJSONObject(k);
					landMarkInformationList.add(new LandmarkInformation(
							jsonObject.getDouble(Constants.LATITUDE),
							jsonObject.getDouble(Constants.LONGITUDE),
							jsonObject.getString(Constants.TOPONYM_NAME),
							jsonObject.getLong(Constants.POPULATION),
							jsonObject.getString(Constants.FCODE_NAME),
							jsonObject.getString(Constants.NAME),
							jsonObject.getString(Constants.WIKIPEDIA_WEB_PAGE_ADDRESS),
							jsonObject.getString(Constants.COUNTRY_CODE)));
				}
				landmarksListView.post(new Runnable() {
					@Override
					public void run() {
						landmarksListView.setAdapter(new LandmarkInformationAdapter(
								getBaseContext(),
								landMarkInformationList));
					}
				});
			} catch (JSONException jsonException) {
				Log.e(Constants.TAG, jsonException.getMessage());
				if (Constants.DEBUG) {
					jsonException.printStackTrace();
				}
			} catch (ClientProtocolException clientProtocolException) {
				Log.e(Constants.TAG, clientProtocolException.getMessage());
				if (Constants.DEBUG) {
					clientProtocolException.printStackTrace();
				}
			} catch (IOException ioException) {
				Log.e(Constants.TAG, ioException.getMessage());
				if (Constants.DEBUG) {
					ioException.printStackTrace();
				}
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_landmark_lister);

		northEditText = (EditText)findViewById(R.id.north_edit_text);
		southEditText = (EditText)findViewById(R.id.south_edit_text);
		eastEditText = (EditText)findViewById(R.id.east_edit_text);
		westEditText = (EditText)findViewById(R.id.west_edit_text);

		landmarksListView = (ListView)findViewById(R.id.landmarks_list_view);

		Button showResultsButton = (Button)findViewById(R.id.show_results_button);
		showResultsButton.setOnClickListener(showResultsButtonClickListener);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.landmark_lister, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}


text:
static NSString *const kTagStart = @"<";
static NSString *const kTagEnd = @">";
static const unichar kTagIgnore = '\01';
static NSString *const kIgnoredTagStart = @"\01<";

@implementation ZSWStringParser

extern NSString *ZSWEscapedStringForString(NSString *unescapedString) {
    return [unescapedString stringByReplacingOccurrencesOfString:kTagStart
                                                      withString:kIgnoredTagStart];
}

+ (void)appendString:(NSString *)string intoAttributedString:(NSMutableAttributedString *)attributedString {
    if (!string.length) {
        return;
    }

    [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:string]];
}

+ (id)stringWithTaggedString:(ZSWTaggedString *)taggedString
                     options:(ZSWTaggedStringOptions *)options
                 returnClass:(Class)returnClass
                       error:(NSError **)error {
    BOOL parseTagAttributes = [returnClass isEqual:[NSAttributedString class]];

    NSScanner *scanner = [NSScanner scannerWithString:taggedString.underlyingString];
    scanner.charactersToBeSkipped = nil;

    NSMutableAttributedString *pendingString = [[NSMutableAttributedString alloc] init];
    NSMutableArray *tagStack = [NSMutableArray array];
    NSMutableArray *finishedTags = [NSMutableArray array];

    NSCharacterSet *tagStartCharacterSet = [NSCharacterSet characterSetWithCharactersInString:kTagStart];
    NSCharacterSet *tagEndCharacterSet = [NSCharacterSet characterSetWithCharactersInString:kTagEnd];

    while (!scanner.isAtEnd) {
        NSString *scratchString;
        [scanner scanUpToCharactersFromSet:tagStartCharacterSet intoString:&scratchString];
        [self appendString:scratchString intoAttributedString:pendingString];

        if (scanner.isAtEnd) {
            // No tag were found; we're done.
            break;
        }

        // Eat the < nom nom nom
        [scanner scanCharactersFromSet:tagStartCharacterSet intoString:NULL];

        if ([scratchString characterAtIndex:(scratchString.length - 1)] == kTagIgnore) {
            // We found a tag start, but it's one that's been escaped. Skip it, and append the start tag we just gobbled up.
            [pendingString deleteCharactersInRange:NSMakeRange(pendingString.length - 1, 1)];
            [self appendString:kTagStart intoAttributedString:pendingString];
            continue;
        }

        scratchString = nil;
        [scanner scanUpToCharactersFromSet:tagEndCharacterSet intoString:&scratchString];
        if (scanner.isAtEnd) {
            [self appendString:scratchString intoAttributedString:pendingString];
            break;
        }

        // Eat the > nom nom nom
        [scanner scanCharactersFromSet:tagEndCharacterSet intoString:NULL];

        NSScanner *tagScanner = [NSScanner scannerWithString:scratchString];
        NSString *tagName;
        BOOL scannedSpace = [tagScanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString:&tagName];

        ZSWStringParserTag *tag = [[ZSWStringParserTag alloc] initWithTagName:tagName startLocation:pendingString.length];

        if (scannedSpace && parseTagAttributes) {
            [tagScanner scanCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString:NULL];
            [tag addRawTagAttributes:[tagScanner.string substringFromIndex:tagScanner.scanLocation]];
        }

        ZSWStringParserTag *lastTag = tagStack.lastObject;
        if ([lastTag isEndedByTag:tag]) {
            [lastTag updateWithTag:tag];
            [tagStack removeLastObject];

            // We want to apply the attributes from the outer-most tags first, so put them at the start.
            [finishedTags insertObject:lastTag atIndex:0];
        } else if (tag.isEndingTag) {
            if (error) {
                *error = [NSError errorWithDomain:ZSWTaggedStringErrorDomain
                                            code:ZSWTaggedStringErrorCodeInvalidTags
                                        userInfo:@{ @"developerError": [NSString stringWithFormat:@"String had ending tag %@ when we expected ending tag %@ or new tag", tag.tagName, lastTag.tagName] }];
            }

            return nil;
        } else {
            [tagStack addObject:tag];
        }
    }

    if (tagStack.count) {
        if (error) {
            *error = [NSError errorWithDomain:ZSWTaggedStringErrorDomain
                                         code:ZSWTaggedStringErrorCodeInvalidTags
                                     userInfo:@{ @"developerError": [NSString stringWithFormat:@"Reached end of string with %@ tags remaining (%@)", @(tagStack.count), [[tagStack valueForKey:@"tagName"] componentsJoinedByString:@", "]] }];
        }

        return nil;
    }

    if ([returnClass isEqual:[NSAttributedString class]]) {
        [options _private_updateAttributedString:pendingString updatedWithTags:finishedTags];
        return [pendingString copy];
    } else if ([returnClass isEqual:[NSString class]]) {
        return [pendingString.string copy];
    } else {
        [NSException raise:NSInternalInconsistencyException
                    format:@"Somehow asked for class type %@ for parsed string",
                                    NSStringFromClass(returnClass)];
        return nil;
    }
}

@end


text:
const dbus = require('../index');

var bus = dbus.systemBus();
bus.invoke({
  member: 'AddMatch',
  signature: 's',
  body: ["type='signal'"]
});
bus.invoke({
  member: 'AddMatch',
  signature: 's',
  body: ["type='method_call'"]
});
bus.invoke({
  member: 'AddMatch',
  signature: 's',
  body: ["type='method_return'"]
});


text:
from humansms.bean.Response import Response
from humansms.util.HumanHTTPHelper import HumanHTTPHelper
import http.client
import urllib.request, urllib.parse, urllib.error

class HumanConnectionHelper:

    def getResponse(self, response):

        responses = []
        is_array = lambda var: isinstance(var, (list, tuple))

        if (is_array(response) == False):
            response = str(response, encoding="utf-8").split("\n")

        for msg in response:
            parceMsg = self.parceResponse(msg)
            objResponse = Response()
            objResponse.setCode(parceMsg[0])
            objResponse.setDescription(parceMsg[2])

            if(parceMsg[0] != "") and (parceMsg[1] != ""):
                responses.append(objResponse)
        return responses

    def parceResponse(self, response):

        response = response.replace("[", "")
        response = response.replace("]", "")
        response = response.replace("\n", "")
        response = response.replace("\r", "")
        response = response.replace(",", "")
        arResponse = response.partition(" - ")
        return arResponse

    def pathEncode(self, pathToFile):
        pathToFile = pathToFile.replace('\r', '/r')
        pathToFile = pathToFile.replace('\a', '/a')
        pathToFile = pathToFile.replace('\t', '/t')
        pathToFile = pathToFile.replace('\d', '/d')
        pathToFile = pathToFile.replace('\w', '/w')
        pathToFile = pathToFile.replace('\s', '/s')
        pathToFile = pathToFile.replace('\n', '/n')
        pathToFile = pathToFile.replace('\f', '/f')
        pathToFile = pathToFile.replace('\\', '/')
        return pathToFile

    def csvDecode(self, csv):
        csv = csv.replace(",", ";")
        csv = csv.replace("[", "")
        csv = csv.replace("]", "")
        csv = csv.replace(" ", "")
        csv = csv.replace("'", "")
        return csv

    def sendRequest(self, params):

        help = HumanHTTPHelper()

        # Seta o cabeçalho http
        headers = {"Content-type": params["ContentType"], "Accept": params["Accept"]}

        # Abre uma conexão http
        conn = http.client.HTTPConnection(params["host"])

        param = urllib.parse.urlencode(params["data"])
        # Envia os dados
        conn.request(params["sendMethod"], params["uri"], param, headers)

        # Coleta a resposta do Gateway
        response = conn.getresponse()

        data = response.read()

        conn.close()

        return data


text:
/**
 * TODO JS
 *
 * Make sure your TODOs in JavaScript get done my making them throw exceptions!
 *
 * Inspired by https://github.com/andyw8/do_by
 *
 * Does not support alpha, beta,... versioning.  We will accept a pull request
 * that adds in this functionality.
 *
 * Usage:
 *
 * ```js
 * TODO.options( {
 *   ignore : [], // ['TODO', 'FIXME', 'XXX'] => ignore these functions
 *   log : false, // true => `console.log` instead of `throw new Error`
 *   currentVersion : 'v0.0.0' // 'v1.0.1' => Make sure it starts with a 'v'
 * } )
 *
 * TODO( 'Finish refactoring this code', 'December 25, 2015' );
 *
 * TODO( 'Dates can have time!', 'December 25, 2015 2:12 PM' );
 *
 * TODO( 'Implement email alerts', 'v1.0.2' );
 *
 * FIXME( 'Need to change the index', '12/15/2015' );
 *
 * XXX( 'This needs to be documented', 'v1.2' );
 * ```
 *
 * @author MantarayAR http://github.com/mantarayar
 * @author Ivan Montiel http://github.com/idmontie
 * @license MIT
 */

var that = this;

+function () {
  'use strict';
  var TODO, FIXME, XXX;

  /**
   * Return 1 if a > b
   * Return -1 if a < b
   * Return 0 if a == b
   * @author http://stackoverflow.com/questions/6832596/how-to-compare-software-version-number-using-js-only-number
   */
  var versionCheck = function ( a, b ) {
    if (a === b) {
      return 0;
    }

    var aComponent = a.split( '.' );
    var bComponent = b.split( '.' );

    var len = Math.min( aComponent.length, bComponent.length );

    // loop while the components are equal
    for ( var i = 0; i < len; i++ ) {
      // A bigger than B
      if ( aComponent[i] > bComponent[i] ) {
        return 1;
      }

      // B bigger than A
      if ( aComponent[i] < bComponent[i] ) {
        return -1;
      }
    }

    // If one's a prefix of the other, the longer one is greater.
    if ( aComponent.length > bComponent.length ) {
      return 1;
    }

    if ( aComponent.length < bComponent.length ) {
      return -1;
    }

    // Otherwise they are the same.
    return 0;
  }

  var itFailed = function ( message, by ) {
    var m = message + ' is past due! Should have been completed by ' + by + '. On line ' + (new Error).lineNumber;
    // only throw if not log
    if ( TODO.options().log ) {
      console.log( m );
    } else {
      throw new Error( m );
    }
  };

  var check = function ( message, by, level ) {
    if ( TODO.options().ignore.indexOf( level ) > -1) {
      // Ignore this check
      return;
    }

    // Determine what type of "by" we are checking: date or version
    if ( by.indexOf( 'v' ) === 0 ) {
      // Checking version
      if ( versionCheck( by, TODO.options().currentVersion ) === -1 ) {
        itFailed.call( this, message, by );
      }
    } else {
      // Checking date
      var timeToCheckAgainst = new Date();
      var date = new Date( Date.parse( by ) );

      // check for invalid date
      if ( 'Invalid Date' == date ) {
        throw new Error( 'Invalid Date! ' + by );
      }

      // only set the hours to zero if no time is provided in the TODO
      if ( date.getMinutes() == 0 && date.getHours() == 0 ) {
        timeToCheckAgainst.setHours( 0, 0, 0, 0 );
      }

      if ( date < timeToCheckAgainst ) {
        itFailed.call( this, message, by );
      }
    }
  };

  /**
   * @param message String
   * @param by String - date in a normal format or a version
   */
  TODO = function () {
    var message = arguments[0];
    var by = arguments[1] || false;

    check.call( this, message, by, 'TODO' );
  };

  /**
   * @param message String
   * @param by String - date in a normal format or a version
   */
  FIXME = function () {
    var message = arguments[0];
    var date = arguments[1] || false;

    check.call( this, message, date, 'FIXME' );
  };

  /**
   * @param message String
   * @param by String - date in a normal format or a version
   */
  XXX = function  () {
    var message = arguments[0];
    var date = arguments[1] || false;

    check.call( this, message, date, 'XXX' );
  };

  TODO._defaults = {
    ignore : [],
    log : false,
    currentVersion : 'v0.0.0'
  };

  TODO._options = false;

  /**
   * Options to set
   */
  TODO.options = function () {
    if ( arguments.length === 0 ) {
      return this._options || this._defaults;
    }

    var options = {};

    if ( typeof arguments === 'object' ) {
      for ( var property in this._defaults ) {
        if ( this._defaults.hasOwnProperty( property ) ) {
          options[property] = arguments[0][property] || this._defaults[property]
        }
      }
    }

    this._options = options;
  };

  TODO.options.reset = function () {
    TODO._options = TODO._defaults;
  }

  // Metoer support
  if ( typeof Meteor !== 'undefined' ) {
    that.TODO  = TODO;
    that.FIXME = FIXME;
    that.XXX   = XXX;
  }

  // support require modules
  if ( typeof module !== 'undefined' ) {
    module.exports = {
      TODO : TODO,
      FIXME : FIXME,
      XXX : XXX
    }
  }
}();


text:
package ptrman.Datastructures;

public interface IMap2d<Type>
{
    Type readAt(int x, int y);
    void setAt(int x, int y, Type value);

    int getWidth();
    int getLength();

    default boolean inBounds(Vector2d<Integer> position) {
        return inBounds(position.xInt(), position.yInt() );
        //return position.xInt() < getWidth() && position.yInt() < getLength();
    }

    default boolean inBounds(int x, int y) {
        return x>=0 && y >=0 && x < getWidth() && y < getLength();
    }

    void clear();

    IMap2d<Type> copy();
}


text:
#import <Foundation/Foundation.h>

#import "RTCMacros.h"
#import "RTCVideoCodecInfo.h"
#import "RTCVideoEncoder.h"

NS_ASSUME_NONNULL_BEGIN

/** RTCVideoEncoderFactory is an Objective-C version of
 webrtc::VideoEncoderFactory::VideoEncoderSelector.
 */
RTC_OBJC_EXPORT
@protocol RTC_OBJC_TYPE
(RTCVideoEncoderSelector)<NSObject>

    - (void)registerCurrentEncoderInfo : (RTC_OBJC_TYPE(RTCVideoCodecInfo) *)info;
- (nullable RTC_OBJC_TYPE(RTCVideoCodecInfo) *)encoderForBitrate:(NSInteger)bitrate;
- (nullable RTC_OBJC_TYPE(RTCVideoCodecInfo) *)encoderForBrokenEncoder;

@end

/** RTCVideoEncoderFactory is an Objective-C version of webrtc::VideoEncoderFactory.
 */
RTC_OBJC_EXPORT
@protocol RTC_OBJC_TYPE
(RTCVideoEncoderFactory)<NSObject>

    - (nullable id<RTC_OBJC_TYPE(RTCVideoEncoder)>)createEncoder
    : (RTC_OBJC_TYPE(RTCVideoCodecInfo) *)info;
- (NSArray<RTC_OBJC_TYPE(RTCVideoCodecInfo) *> *)
    supportedCodecs;  // TODO(andersc): "supportedFormats" instead?

@optional
- (NSArray<RTC_OBJC_TYPE(RTCVideoCodecInfo) *> *)implementations;
- (nullable id<RTC_OBJC_TYPE(RTCVideoEncoderSelector)>)encoderSelector;

@end

NS_ASSUME_NONNULL_END


text:
import {SpecialFiledProcess as process} from "./Core"

const defaultValues = {value: "special", count: 0};

export function SpecialField(targetPrototype: any, propertyKey: string): void;
export function SpecialField(args_: { value?: string; count?: number }): (targetPrototype: any, propertyKey: string) => void;
export function SpecialField(arg1: any, arg2?: string): any {
    if (typeof arg2 === 'string') {
        const args = defaultValues;
        const targetPrototype: any = arg1;
        const propertyKey = arg2;
        process(args, targetPrototype, propertyKey);
    } else {
        {
            const args = {...defaultValues, ...arg1};
            return (targetPrototype: any, propertyKey: string) => process(args, targetPrototype, propertyKey)
        }
    }
}


text:
class SPIReader {

public:
  SPIReader();
  ~SPIReader();
  void Open(int spiPort);
  void Close();
  bool Poll();
  bool FrameBufferReady;

  QImage Image;
  uint16_t FrameBuffer[FRAME_SIZE_UINT16];

protected:
  int GetSPIFileDescriptor();
  void OnFrameComplete();

private:
  int _spiPort;
  uint8_t rawdata[PACKET_SIZE * ROWS_PER_FRAME];

  int resets, restarts, row;
  bool is_big_endian;
};

#endif


text:
<?php

namespace Loo\Debug;

use Loo\Core\AbstractEnum;

/**
 * Enumeration with all different error levels.
 */
class LoggerLevel extends AbstractEnum
{
    /**
     * Detailed debug information.
     */
    const DEBUG = 100;

    /**
     * Interesting events.
     *
     * Examples: User logs in, SQL logs.
     */
    const INFO = 200;

    /**
     * Uncommon events.
     */
    const NOTICE = 250;

    /**
     * Exceptional occurrences that are not errors.
     *
     * Examples: Use of deprecated APIs, poor use of an API,
     * undesirable things that are not necessarily wrong.
     */
    const WARNING = 300;

    /**
     * Runtime errors.
     */
    const ERROR = 400;

    /**
     * Critical conditions.
     *
     * Example: Application component unavailable, unexpected exception.
     */
    const CRITICAL = 500;

    /**
     * Action must be taken immediately.
     *
     * Example: Entire website down, database unavailable, etc.
     * This should trigger the SMS alerts and wake you up.
     */
    const ALERT = 550;

    /**
     * Urgent alert.
     */
    const EMERGENCY = 600;
}


text:
Google Cloud Python Client
==========================

    Python idiomatic client for `Google Cloud Platform`_ services.

.. _Google Cloud Platform: https://cloud.google.com/

|pypi| |build| |coverage| |versions|

-  `Homepage`_
-  `API Documentation`_

.. _Homepage: https://googlecloudplatform.github.io/gcloud-python/
.. _API Documentation: http://googlecloudplatform.github.io/gcloud-python/stable/

This client supports the following Google Cloud Platform services:

-  `Google Cloud Datastore`_
-  `Google Cloud Storage`_
-  `Google Cloud Pub/Sub`_
-  `Google BigQuery`_
-  `Google Cloud Resource Manager`_

.. _Google Cloud Datastore: https://github.com/GoogleCloudPlatform/gcloud-python#google-cloud-datastore
.. _Google Cloud Storage: https://github.com/GoogleCloudPlatform/gcloud-python#google-cloud-storage
.. _Google Cloud Pub/Sub: https://github.com/GoogleCloudPlatform/gcloud-python#google-cloud-pubsub
.. _Google BigQuery: https://github.com/GoogleCloudPlatform/gcloud-python#google-bigquery
.. _Google Cloud Resource Manager: https://github.com/GoogleCloudPlatform/gcloud-python#google-cloud-resource-manager

If you need support for other Google APIs, check out the
`Google APIs Python Client library`_.

.. _Google APIs Python Client library: https://github.com/google/google-api-python-client

Quick Start
-----------

::

    $ pip install --upgrade gcloud

Example Applications
--------------------

-  `getting-started-python`_ - A sample and `tutorial`_ that demonstrates how to build a complete web application using Cloud Datastore, Cloud Storage, and Cloud Pub/Sub and deploy it to Google App Engine or Google Compute Engine.
-  `gcloud-python-expenses-demo`_ - A sample expenses demo using Cloud Datastore and Cloud Storage

.. _getting-started-python: https://github.com/GoogleCloudPlatform/getting-started-python
.. _tutorial: https://cloud.google.com/python
.. _gcloud-python-expenses-demo: https://github.com/GoogleCloudPlatform/gcloud-python-expenses-demo

Authentication
--------------

With ``gcloud-python`` we try to make authentication as painless as possible.
Check out the `Authentication section`_ in our documentation to learn more.
You may also find the `authentication document`_ shared by all the ``gcloud-*``
libraries to be helpful.

.. _Authentication section: http://gcloud-python.readthedocs.org/en/latest/gcloud-auth.html
.. _authentication document: https://github.com/GoogleCloudPlatform/gcloud-common/tree/master/authentication

Google Cloud Datastore
----------------------

Google `Cloud Datastore`_ (`Datastore API docs`_) is a fully managed, schemaless
database for storing non-relational data. Cloud Datastore automatically scales
with your users and supports ACID transactions, high availability of reads and
writes, strong consistency for reads and ancestor queries, and eventual
consistency for all other queries.

.. _Cloud Datastore: https://cloud.google.com/datastore/docs
.. _Datastore API docs: https://cloud.google.com/datastore/docs/apis/v1beta3/

See the ``gcloud-python`` API `datastore documentation`_ to learn how to
interact with the Cloud Datastore using this Client Library.

.. _datastore documentation: https://googlecloudplatform.github.io/gcloud-python/stable/datastore-client.html

See the `official Google Cloud Datastore documentation`_ for more details on how
to activate Cloud Datastore for your project.

.. _official Google Cloud Datastore documentation: https://cloud.google.com/datastore/docs/activate

.. code:: python

    from gcloud import datastore
    # Create, populate and persist an entity
    entity = datastore.Entity(key=datastore.Key('EntityKind'))
    entity.update({
        'foo': u'bar',
        'baz': 1337,
        'qux': False,
    })
    # Then query for entities
    query = datastore.Query(kind='EntityKind')
    for result in query.fetch():
        print result

Google Cloud Storage
--------------------

Google `Cloud Storage`_ (`Storage API docs`_) allows you to store data on Google
infrastructure with very high reliability, performance and availability, and can
be used to distribute large data objects to users via direct download.

.. _Cloud Storage: https://cloud.google.com/storage/docs
.. _Storage API docs: https://cloud.google.com/storage/docs/json_api/v1

See the ``gcloud-python`` API `storage documentation`_ to learn how to connect
to Cloud Storage using this Client Library.

.. _storage documentation: https://googlecloudplatform.github.io/gcloud-python/stable/storage-client.html

You need to create a Google Cloud Storage bucket to use this client library.
Follow along with the `official Google Cloud Storage documentation`_ to learn
how to create a bucket.

.. _official Google Cloud Storage documentation: https://cloud.google.com/storage/docs/cloud-console#_creatingbuckets

.. code:: python

    from gcloud import storage
    client = storage.Client()
    bucket = client.get_bucket('bucket-id-here')
    # Then do other things...
    blob = bucket.get_blob('/remote/path/to/file.txt')
    print blob.download_as_string()
    blob.upload_from_string('New contents!')
    blob2 = bucket.blob('/remote/path/storage.txt')
    blob2.upload_from_filename(filename='/local/path.txt')

Google Cloud Pub/Sub
--------------------

Google `Cloud Pub/Sub`_ (`Pub/Sub API docs`_) is designed to provide reliable,
many-to-many, asynchronous messaging between applications. Publisher
applications can send messages to a ``topic`` and other applications can
subscribe to that topic to receive the messages. By decoupling senders and
receivers, Google Cloud Pub/Sub allows developers to communicate between
independently written applications.

.. _Cloud Pub/Sub: https://cloud.google.com/pubsub/docs
.. _Pub/Sub API docs: https://cloud.google.com/pubsub/reference/rest/

See the ``gcloud-python`` API `Pub/Sub documentation`_ to learn how to connect
to Cloud Pub/Sub using this Client Library.

.. _Pub/Sub documentation: https://googlecloudplatform.github.io/gcloud-python/stable/pubsub-usage.html

To get started with this API, you'll need to create

.. code:: python

    from gcloud import pubsub

    client = pubsub.Client()
    topic = client.topic('topic_name')
    topic.create()

    topic.publish('this is the message_payload',
                  attr1='value1', attr2='value2')

Google BigQuery
---------------

Querying massive datasets can be time consuming and expensive without the
right hardware and infrastructure. Google `BigQuery`_ (`BigQuery API docs`_)
solves this problem by enabling super-fast, SQL-like queries against
append-only tables, using the processing power of Google's infrastructure.

.. _BigQuery: https://cloud.google.com/bigquery/what-is-bigquery
.. _BigQuery API docs: https://cloud.google.com/bigquery/docs/reference/v2/

This package is still being implemented, but it is almost complete!

See the ``gcloud-python`` API `BigQuery documentation`_ to learn how to connect
to BigQuery using this Client Library.

.. _BigQuery documentation: https://googlecloudplatform.github.io/gcloud-python/stable/bigquery-usage.html

Google Cloud Resource Manager
-----------------------------

The Cloud `Resource Manager`_ API (`Resource Manager API docs`_) provides
methods that you can use to programmatically manage your projects in the
Google Cloud Platform.

.. _Resource Manager: https://cloud.google.com/resource-manager/
.. _Resource Manager API docs: https://cloud.google.com/resource-manager/reference/rest/

See the ``gcloud-python`` API `Resource Manager documentation`_ to learn how to
manage projects using this Client Library.

.. _Resource Manager documentation: https://googlecloudplatform.github.io/gcloud-python/stable/resource-manager-api.html

Contributing
------------

Contributions to this library are always welcome and highly encouraged.

See `CONTRIBUTING`_ for more information on how to get started.

.. _CONTRIBUTING: https://github.com/GoogleCloudPlatform/gcloud-python/blob/master/CONTRIBUTING.rst

License
-------

Apache 2.0 - See `LICENSE`_ for more information.

.. _LICENSE: https://github.com/GoogleCloudPlatform/gcloud-python/blob/master/LICENSE

.. |build| image:: https://travis-ci.org/GoogleCloudPlatform/gcloud-python.svg?branch=master
   :target: https://travis-ci.org/GoogleCloudPlatform/gcloud-python
.. |coverage| image:: https://coveralls.io/repos/GoogleCloudPlatform/gcloud-python/badge.png?branch=master
   :target: https://coveralls.io/r/GoogleCloudPlatform/gcloud-python?branch=master
.. |pypi| image:: https://img.shields.io/pypi/v/gcloud.svg
   :target: https://pypi.python.org/pypi/gcloud
.. |versions| image:: https://img.shields.io/pypi/pyversions/gcloud.svg
   :target: https://pypi.python.org/pypi/gcloud


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

import java.math.*;

import javax.annotation.Generated;

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

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

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

    public DescribeHsmResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        DescribeHsmResult describeHsmResult = new DescribeHsmResult();

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

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

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

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("HsmArn", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setHsmArn(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Status", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("StatusDetails", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setStatusDetails(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("AvailabilityZone", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setAvailabilityZone(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("EniId", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setEniId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("EniIp", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setEniIp(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("SubscriptionType", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setSubscriptionType(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("SubscriptionStartDate", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setSubscriptionStartDate(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("SubscriptionEndDate", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setSubscriptionEndDate(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("VpcId", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setVpcId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("SubnetId", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setSubnetId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("IamRoleArn", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setIamRoleArn(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("SerialNumber", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setSerialNumber(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("VendorName", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setVendorName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("HsmType", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setHsmType(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("SoftwareVersion", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setSoftwareVersion(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("SshPublicKey", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setSshPublicKey(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("SshKeyLastUpdated", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setSshKeyLastUpdated(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("ServerCertUri", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setServerCertUri(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("ServerCertLastUpdated", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setServerCertLastUpdated(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Partitions", targetDepth)) {
                    context.nextToken();
                    describeHsmResult.setPartitions(new ListUnmarshaller<String>(context.getUnmarshaller(String.class)).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return describeHsmResult;
    }

    private static DescribeHsmResultJsonUnmarshaller instance;

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


text:
module Fleetctl
  class Options < Hashie::Mash
    def initialize(*)
      deep_merge!(Hashie::Mash.new(defaults))
      super
    end

    def defaults
      {
        global: {},
        executable: 'fleetctl',
        logger: Logger.new(STDOUT),
        runner_class: 'SSH',
        command_prefix: nil,
        discovery_url: nil,

        # for use with runner_class: 'SSH'
        # these aren't used wih a Shell runner
        fleet_host: nil,
        fleet_user: 'core',
        ssh_options: {},
        remote_temp_dir: '/tmp'
      }
    end

    def ssh_options
      self[:ssh_options].to_hash(symbolize_keys: true)
    end
  end
end


text:
#!/bin/bash
set -e # Exit with nonzero exit code if anything fails

SOURCE_BRANCH="master"
TARGET_BRANCH="gh-pages"

# Pull requests and commits to other branches shouldn't try to deploy, just build to verify
if [ "$TRAVIS_PULL_REQUEST" != "false" -o "$TRAVIS_BRANCH" != "$SOURCE_BRANCH" ]; then
    echo "Skipping deploy; just doing a build."
    exit 0
fi

# Save some useful information
REPO=`git config remote.origin.url`
SSH_REPO=${REPO/https:\/\/github.com\//git@github.com:}
SHA=`git rev-parse --verify HEAD`

# Clone the existing gh-pages for this repo into out/
# Create a new empty branch if gh-pages doesn't exist yet (should only happen on first deply)
rm -rf out || exit 0

git clone $REPO out
cd out
git checkout $TARGET_BRANCH || git checkout --orphan $TARGET_BRANCH
cd ..

# Clean out existing contents
rm -rf out/**/* || exit 0

# Copy generated documentation to the new directory
cp -a docs/build/html/. out/

cd out
git config user.name "Travis CI"
git config user.email "oneview-pythonsdk@hpe.com"

# If there are no changes (e.g. this is a README update) then just bail.
if [ $(git status --porcelain | wc -l) -lt 1 ]; then
    echo "No changes to the spec on this push; exiting."
    exit 0
fi

# Commit the "changes", i.e. the new version.
# The delta will show diffs between new and old versions.
git add -A .
git commit -m "Deploy to GitHub Pages: ${SHA}"

## Get the deploy key by using Travis's stored variables to decrypt deploy_key.enc
openssl aes-256-cbc -K $encrypted_207a3e71573a_key -iv $encrypted_207a3e71573a_iv -in deploy_key.enc -out deploy_key -d

chmod 600 deploy_key

eval `ssh-agent -s`

ssh-add deploy_key

## Now that we're all set up, we can push.
git push $SSH_REPO $TARGET_BRANCH

echo "Documentation pushed to gh-pages ................................"
cd ..
rm -rf out || exit 0

echo "Documentation deploy finished ..................................."