text:
app.controller('EditProjectController', ['ProjectServices', 'UserServices', '$location', '$routeParams', function (ProjectServices, UserServices, $location, $routeParams) {
    var ctrl = this;
    ctrl.edit = edit;
    ctrl.users = [];
    var id = $routeParams.id;
    ctrl.old = {};
    ctrl.project = {};

    UserServices.GetAll().then(function(response) {
        ctrl.users = response.data;
    });

    ProjectServices.GetById(id).then(function(response) {
        ctrl.old = response.data;
        ctrl.project.name = ctrl.old.Name;
        ctrl.project.description = ctrl.old.Description;
        ctrl.project.leader = ctrl.old.Lead.Id;
        ctrl.project.key = ctrl.old.ProjectKey;
        ctrl.project.labelsString = getLabelsString(ctrl.old.Labels);
        ctrl.project.prioritiesString = getPrioritiesString(ctrl.old.Priorities);

        if (sessionStorage.getItem('isAdmin') !== 'true' && ctrl.old.Lead.Id !== sessionStorage.getItem('id')) {
            $location.path('/projects/' + ctrl.old.Id);
        }
    });

    function edit() {
        ctrl.dataLoading = true;
        var name = ctrl.project.name;

        var projectForAdding = {
            Name: name,
            Description: ctrl.project.description,
            ProjectKey: ctrl.project.key,
            LeadId: ctrl.project.leader
        };

        var labelsSplit = ctrl.project.labelsString.split(' ');
        projectForAdding.labels = [];

        for (var i = 0; i < labelsSplit.length; i++) {
            if (labelsSplit[i] !== '') {
                projectForAdding.labels.push({Name: labelsSplit[i]});
            }
        }

        var prioritiesSplit = ctrl.project.prioritiesString.split(' ');
        projectForAdding.priorities = [];

        for (var e = 0; e < prioritiesSplit.length; e++) {
            if (prioritiesSplit[e] !== '') {
                projectForAdding.priorities.push({Name: prioritiesSplit[e]});
            }
        }

        ProjectServices.Edit(id, projectForAdding).then(function() {
            $location.path('/projects/' + id);
        });
    }

    function getLabelsString(labels) {
        var labelsString = '';

        for (var i = 0; i < labels.length; i++) {
            labelsString += labels[i].Name + ' ';
        }

        return labelsString;
    }

    function getPrioritiesString(priorities) {
        var prioritiesString = '';

        for (var i = 0; i < priorities.length; i++) {
            prioritiesString += priorities[i].Name + ' ';
        }

        return prioritiesString;
    }
}]);


text:
namespace ExoMail.Smtp.Utilities
{
    /// <summary>
    /// Helps to get number of bytes in byte unit prefix.
    /// </summary>
    public static class ByteSizeHelper
    {
        public const int KILOBYTE = 1024;
        public const int MEGABYTE = KILOBYTE * 1024;
        public const int GIGABYTE = MEGABYTE * 1024;

        /// <summary>
        /// Get the number of bytes in the specified prefix.
        /// </summary>
        /// <param name="kilobytes">The number of Kilobytes to conver.t</param>
        /// <returns>An integer for the number of bytes.</returns>
        public static int FromKiloBytes(int kilobytes)
        {
            return KILOBYTE * kilobytes;
        }

        /// <summary>
        /// Get the number of bytes in the specified prefix.
        /// </summary>
        /// <param name="megabytes">The number of megabytes to convert.</param>
        /// <returns>An integer for the number of bytes.</returns>
        public static int FromMegaBytes(int megabytes)
        {
            return MEGABYTE * megabytes;
        }

        /// <summary>
        /// Get the number of bytes in the specified prefix.
        /// </summary>
        /// <param name="gigabytes">The number of gigabytes to convert.</param>
        /// <returns>An integer for the number of bytes.</returns>
        public static int FromGigaBytes(int gigabytes)
        {
            return GIGABYTE * gigabytes;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
module LokalebasenApi
  VERSION = "0.0.2"
end


text:
//
// A class that transforms a texture into a grid
//

#import "FastGrid.h"

@interface FastGrid (Private)

-(void)calculateVertexPoints;

@end

@implementation FastGrid

+(id) gridWithTexture:(CCTexture2D*)texture
{
	return [[[self alloc] initWithTexture:texture] autorelease];
}

-(id)initWithTexture:(CCTexture2D*)texture
{
	if ( (self = [super init] ) )
	{
		self.texture = texture;
		sprite_ = [[CCSprite alloc] initWithTexture:texture];
	}

	return self;
}

- (void) dealloc
{
	[sprite_ release];
	[texture_ release];
	[fastGrid_ release];

	[super dealloc];
}

-(void)draw
{
	if( fastGrid_ && fastGrid_.active ) {

		ccGLBindTexture2D( [texture_ name]);

		[fastGrid_ blit];

	} else {
		[sprite_ draw];
	}
}

// override "slow grid"
-(CCGridBase*) grid
{
	return fastGrid_;
}

-(void) setGrid:(CCGridBase*)grid
{
	[grid setIsTextureFlipped:YES];
	[fastGrid_ release];
	fastGrid_ = [grid retain];
	[fastGrid_ setTexture:texture_];
}

// set texture into fastgrid if a new texture is set
-(void) setTexture:(CCTexture2D*) texture
{
	[texture_ release];
	texture_ = [texture retain];
	[fastGrid_ setTexture:texture_];
}

-(CCTexture2D*) texture
{
	return texture_;
}
@end


text:
using System.Collections.ObjectModel;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;

namespace Microsoft.VisualStudio.Debugger.ComponentInterfaces
{
    public interface IDkmClrFormatter
    {
        string GetTypeName(DkmInspectionContext inspectionContext, DkmClrType clrType, ReadOnlyCollection<string> formatSpecifiers);
        string GetUnderlyingString(DkmClrValue clrValue, DkmInspectionContext inspectionContext);
        string GetValueString(DkmClrValue clrValue, DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers);
        bool HasUnderlyingString(DkmClrValue clrValue, DkmInspectionContext inspectionContext);
    }
}


text:
using Gadfly, DataFrames, CategoricalArrays

set_default_plot_size(6inch, 3inch)

a = DataFrame(diff = CategoricalArray([1,2,3,3,3,4,3,2]))
plot(a, x="diff", Geom.histogram)


text:
DEBUG = True
SECRET_KEY = '' # enter secret key
REDIS_URL = '' # enter redis url

MSG_UNKNOWN_SHORT_URL = 'Unknown short URL'
MSG_ID_REQ_PARAM_MISSING = 'id request param missing.'
MSG_ALREADY_SHORT_URL = 'Already a short URL.'


text:
Elements (Nodes and Edges)
==========================

In Adhara DB, Nodes and Edges are immutable objects.  They are similar to
(and currently contain, as th id attribute) UUIDs.  They do have some added
conveniance methods that will be documented here.

Notes::

  You may be thinking that elements can't be immutable, because you can set
  attributes on them!  Well, that is one of the conveniance methods!  The Graph
  object stores attributes in a seperate container, so you are not actually
  changing the element at all!

Warning::

  You should not ever create an element object directly from the Element, Node,
  or Edge classes!  You should always use the graph methods (add_node, add_nodes,
  add_edge, etc.) to do this for you!  Otherwise, they won't properly register
  in the Graph structure!
_____
Nodes
_____

_____
Edges
_____


text:
package com.enterprisecoding.jraspbee.exceptions;

/**
 * Thrown when the specified user is no longer whitelisted on the bridge.
 */
@SuppressWarnings("serial")
public class UnauthorizedException extends ApiException {
    public UnauthorizedException() {
    }

    public UnauthorizedException(String message) {
        super(message);
    }
}


text:
"use strict";

require("../gpii/node_modules/registrySettingsHandler/test/testRegistrySettingsHandler.js");
require("../gpii/node_modules/spiSettingsHandler/test/testSpiSettingsHandler.js");
require("../gpii/node_modules/killProcess/test/testKillProcess.js");
require("../gpii/node_modules/registryResolver/test/testRegistryResolver.js");


text:
* install the dependencies:

```
yarn install
```

* Run development server:

```
yarn run dev
```

* Or you can run development server with [webpack-dashboard](https://github.com/FormidableLabs/webpack-dashboard):

```
yarn run dev:dashboard
```

Open the web browser to `http://localhost:8000/`

To build the production app **locally**:

```
yarn run start:local
```

To build the production app **remotely**:

```
yarn start
```


text:
import os
import datetime
import time

from azure.cli.testsdk import ScenarioTest, ResourceGroupPreparer
from knack.util import CLIError
from .batch_preparers import BatchAccountPreparer, BatchScenarioMixin

from .recording_processors import BatchAccountKeyReplacer, StorageSASReplacer

class BatchDataPlaneScenarioTests(BatchScenarioMixin, ScenarioTest):

    def __init__(self, method_name):
        super().__init__(method_name, recording_processors=[
            BatchAccountKeyReplacer(),
            StorageSASReplacer()
        ])

    def _get_test_data_file(self, filename):
        filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', filename)
        self.assertTrue(os.path.isfile(filepath), 'File {} does not exist.'.format(filepath))
        return filepath

    @ResourceGroupPreparer()
    @BatchAccountPreparer(location='northcentralus')
    def test_batch_certificate_cmd(self, resource_group, batch_account_name):
        create_cert_file_path = self._get_test_data_file('batchtest.cer')
        self.kwargs.update({
            'cert': '59833fd835f827e9ec693a4c82435a6360cc6271',
            'cert_f': create_cert_file_path
        })

        # test create certificate with default set
        self.set_account_info(batch_account_name, resource_group)

        self.batch_cmd('batch certificate create --thumbprint {cert} '
                       '--certificate-file "{cert_f}"').assert_with_checks([
                           self.check('thumbprint', '{cert}'),
                           self.check('thumbprintAlgorithm', 'sha1'),
                           self.check('state', 'active')])

        # test create account with default set
        self.batch_cmd('batch certificate list').assert_with_checks([
            self.check('length(@)', 1),
            self.check('[0].thumbprint', '{cert}')])

        self.batch_cmd("batch certificate delete --thumbprint {cert} --yes")

        self.batch_cmd('batch certificate show --thumbprint {cert}').assert_with_checks([
            self.check('thumbprint', '{cert}'),
            self.check('thumbprintAlgorithm', 'sha1'),
            self.check('state', 'deleting')])

    @ResourceGroupPreparer()
    @BatchAccountPreparer()
    def test_batch_pool_cmd(
            self,
            resource_group,
            batch_account_name):
        endpoint = self.get_account_endpoint(
            batch_account_name,
            resource_group).replace("https://", "")
        key = self.get_account_key(
            batch_account_name,
            resource_group)

        self.kwargs.update({
            'p_id': 'xplatCreatedPool',
            'c_file': self._get_test_data_file('batchCreatePool.json'),
            'u_file': self._get_test_data_file('batchUpdatePool.json'),
            'acc_n': batch_account_name,
            'acc_k': key,
            'acc_u': endpoint
        })
        self.batch_cmd('batch pool create --json-file "{c_file}"')
        result = self.batch_cmd('batch pool create --id pool_image1 --vm-size Standard_A1 '
                                '--image a:b:c --node-agent-sku-id "batch.node.windows amd64"',
                                expect_failure=True)

        result = self.batch_cmd('batch pool create --id pool_image1 --vm-size Standard_A1 '
                                '--image /subscriptions/11111111-1111-1111-1111-111111111111'
                                '/resourceGroups/test_rg/providers/Microsoft.Compute/images/custom_image '
                                '--node-agent-sku-id "batch.node.windows amd64"',
                                expect_failure=True)

        result = self.batch_cmd('batch pool create --id pool_image1 --vm-size Standard_A1 '
                                '--image canonical:ubuntuserver:18.04-lts --node-agent-sku-id "batch.node.ubuntu 18.04"'
                                ' --disk-encryption-targets "TemporaryDisk"')

        time.sleep(120)

        result = self.batch_cmd('batch pool show --pool-id {p_id}').assert_with_checks([
            self.check('allocationState', 'steady'),
            self.check('id', 'xplatCreatedPool'),
            self.check('startTask.commandLine', "cmd /c echo test"),
            self.check('startTask.userIdentity.autoUser.elevationLevel', "admin")])

        target = result.get_output_in_json()['currentLowPriorityNodes']
        self.batch_cmd('batch pool resize --pool-id {p_id} --target-dedicated-nodes 0 --target-low-priority-nodes 3')
        self.batch_cmd('batch pool show --pool-id {p_id}').assert_with_checks([
            self.check('allocationState', 'resizing'),
            self.check('targetLowPriorityNodes', 3),
            self.check('id', 'xplatCreatedPool')])

        self.batch_cmd('batch pool node-counts list').assert_with_checks([
            self.check('length(@)', 2),
            self.check('[1].poolId', 'xplatCreatedPool'),
            self.check('[1].lowPriority.total', 0)])

        self.batch_cmd('batch pool resize --pool-id {p_id} --abort')
        if self.is_live or self.in_recording:
            time.sleep(120)

        self.batch_cmd('batch pool show --pool-id {p_id}').assert_with_checks([
            self.check('allocationState', 'steady'),
            self.check('id', 'xplatCreatedPool'),
            self.check('currentLowPriorityNodes', target),
            self.check('targetLowPriorityNodes', 3)])

        self.batch_cmd('batch pool reset --pool-id {p_id} --json-file "{u_file}"').assert_with_checks([
            self.check('allocationState', 'steady'),
            self.check('id', 'xplatCreatedPool'),
            self.check('startTask.commandLine', "cmd /c echo updated")])

        self.batch_cmd('batch pool reset --pool-id {p_id} --start-task-command-line hostname '
                       '--metadata a=b c=d').assert_with_checks([
                           self.check('allocationState', 'steady'),
                           self.check('id', 'xplatCreatedPool'),
                           self.check('startTask.commandLine', "hostname"),
                           self.check('length(metadata)', 2),
                           self.check('metadata[0].name', 'a'),
                           self.check('metadata[1].value', 'd')])

        self.batch_cmd('batch pool delete --pool-id {p_id} --yes')

    @ResourceGroupPreparer()
    @BatchAccountPreparer()
    def test_batch_job_list_cmd(
            self,
            resource_group,
            batch_account_name):
        self.set_account_info(batch_account_name, resource_group)
        self.kwargs.update({
            'j_id': 'xplatJob',
            'js_id': 'xplatJobScheduleJobTests',
            'j_file': self._get_test_data_file('batchCreateJob.json'),
            'js_file': self._get_test_data_file('batchCreateJobScheduleForJobTests.json')
        })

        self.batch_cmd('batch job-schedule create --json-file "{js_file}"')
        self.addCleanup(lambda: self.batch_cmd('batch job-schedule delete --job-schedule-id {js_id} --yes'))

        self.batch_cmd('batch job create --json-file "{j_file}"')
        self.batch_cmd('batch job list --job-schedule-id {js_id}').assert_with_checks([
            self.check('length(@)', 1),
            self.check('[0].id', 'xplatJobScheduleJobTests:job-1')])

        result = self.batch_cmd('batch job list') \
            .assert_with_checks([self.check('length(@)', 2)]) \
            .get_output_in_json()

        self.assertTrue(any([i for i in result if i['id'] == 'xplatJobScheduleJobTests:job-1']))
        self.assertTrue(any([i for i in result if i['id'] == 'xplatJob']))

        self.batch_cmd('batch job delete --job-id {j_id} --yes')

    @ResourceGroupPreparer()
    @BatchAccountPreparer(location='canadacentral')
    def test_batch_task_create_cmd(self, resource_group, batch_account_name):
        self.set_account_info(batch_account_name, resource_group)
        self.kwargs.update({
            'j_id': 'xplatJobForTaskTests',
            't_id': 'xplatTask',
            'j_file': self._get_test_data_file('batchCreateJobForTaskTests.json'),
            't_file': self._get_test_data_file('batchCreateTask.json'),
            'ts_file': self._get_test_data_file('batchCreateMultiTasks.json')
        })

        self.batch_cmd('batch job create --json-file "{j_file}"')
        self.addCleanup(lambda: self.batch_cmd('batch job delete --job-id {j_id} --yes'))

        self.batch_cmd('batch task create --job-id {j_id} --json-file "{t_file}"').assert_with_checks([
            self.check('id', 'xplatTask'),
            self.check('commandLine', 'cmd /c dir /s')])

        self.batch_cmd('batch task show --job-id {j_id} --task-id {t_id}').assert_with_checks([
            self.check('userIdentity.autoUser.scope', 'pool'),
            self.check('authenticationTokenSettings.access[0]', 'job')])

        self.batch_cmd('batch task delete --job-id {j_id} --task-id {t_id} --yes')

        self.batch_cmd('batch task create --job-id {j_id} --task-id aaa'
                       ' --command-line "ping 127.0.0.1 -n 30"').assert_with_checks([
                           self.check('id', 'aaa'),
                           self.check('commandLine', 'ping 127.0.0.1 -n 30')])

        if self.is_live or self.in_recording:
            time.sleep(10)
        task_result = self.batch_cmd('batch job task-counts show --job-id {j_id}').get_output_in_json()

        self.assertEqual(task_result["taskCounts"]["completed"], 0)
        self.assertEqual(task_result["taskCounts"]["active"], 1)
        self.assertEqual(task_result["taskSlotCounts"]["completed"], 0)
        self.assertEqual(task_result["taskSlotCounts"]["active"], 1)

        self.batch_cmd('batch task delete --job-id {j_id} --task-id aaa --yes')

        result = self.batch_cmd('batch task create --job-id {j_id} --json-file "{ts_file}"')
        result = result.get_output_in_json()
        self.assertEqual(len(result), 3)
        self.assertTrue(any([i for i in result if i['taskId'] == 'xplatTask1']))

    @ResourceGroupPreparer()
    @BatchAccountPreparer(location='canadaeast')
    def test_batch_jobs_and_tasks(self, resource_group, batch_account_name):
        self.set_account_info(batch_account_name, resource_group)
        self.kwargs.update({
            'p_id': 'xplatJobForTaskTests',
            'j_id': "cli-test-job-1",
        })

        # test create paas pool using parameters
        self.batch_cmd('batch pool create --id {p_id} --vm-size small --os-family 4')

        # test create job with missing parameters
        self.kwargs['start'] = datetime.datetime.utcnow().isoformat()
        with self.assertRaises(SystemExit):
            self.batch_cmd('batch job create --id {j_id} --metadata test=value '
                           '--job-manager-task-environment-settings a=b '
                           '--job-max-task-retry-count 5 ')

        # test create job
        self.batch_cmd('batch job create --id {j_id} --metadata test=value '
                       '--job-max-task-retry-count 5 '
                       '--job-manager-task-id JobManager '
                       '--job-manager-task-command-line "cmd /c set AZ_BATCH_TASK_ID" '
                       '--job-manager-task-environment-settings '
                       'CLI_TEST_VAR=CLI_TEST_VAR_VALUE --pool-id {p_id}')

        # test get job
        self.batch_cmd('batch job show --job-id {j_id}').assert_with_checks([
            self.check('onAllTasksComplete', 'noaction'),
            self.check('constraints.maxTaskRetryCount', 5),
            self.check('jobManagerTask.id', 'JobManager'),
            self.check('jobManagerTask.environmentSettings[0].name', 'CLI_TEST_VAR'),
            self.check('jobManagerTask.environmentSettings[0].value', 'CLI_TEST_VAR_VALUE'),
            self.check('metadata[0].name', 'test'),
            self.check('metadata[0].value', 'value')])

        # test bad enum value
        with self.assertRaises(SystemExit):
            self.batch_cmd('batch job set --job-id {j_id} --on-all-tasks-complete badValue ')

        # test patch job
        self.batch_cmd('batch job set --job-id {j_id} --job-max-wall-clock-time P3Y6M4DT12H30M5S '
                       '--on-all-tasks-complete terminatejob')
        self.batch_cmd('batch job show --job-id {j_id}').assert_with_checks([
            self.check('onAllTasksComplete', 'terminatejob'),
            self.check('constraints.maxTaskRetryCount', 0),
            self.check('constraints.maxWallClockTime', '1279 days, 12:30:05'),
            self.check('jobManagerTask.id', 'JobManager'),
            self.check('jobManagerTask.environmentSettings[0].name', 'CLI_TEST_VAR'),
            self.check('jobManagerTask.environmentSettings[0].value', 'CLI_TEST_VAR_VALUE'),
            self.check('metadata[0].name', 'test'),
            self.check('metadata[0].value', 'value')])

        # test filter/header argument
        self.batch_cmd('batch job reset --job-id {j_id} --pool-id {p_id} --on-all-tasks-complete '
                       'terminatejob --if-unmodified-since {start}', expect_failure=True)

        # test reset job
        self.batch_cmd('batch job reset --job-id {j_id} --pool-id {p_id}  '
                       '--on-all-tasks-complete terminatejob ')
        job = self.batch_cmd('batch job show --job-id {j_id}').assert_with_checks([
            self.check('constraints.maxTaskRetryCount', 0),
            self.check('metadata', None)])

        job = job.get_output_in_json()
        self.assertFalse(job['constraints']['maxWallClockTime'] == '1279 days, 12:30:05')

        # TODO: test task commands

    @ResourceGroupPreparer()
    @BatchAccountPreparer()
    def test_batch_pools_and_nodes(
            self,
            resource_group,
            batch_account_name):  # pylint:disable=too-many-statements
        self.set_account_info(batch_account_name, resource_group)
        self.kwargs.update({
            'pool_p': "azure-cli-test-paas",
            'pool_i': "azure-cli-test-iaas",
            'pool_j': "azure-cli-test-json"
        })

        # test create paas pool using parameters
        self.batch_cmd('batch pool create --id {pool_p} --vm-size small --os-family 4')

        # test create iaas pool using parameters
        self.batch_cmd('batch pool create --id {pool_i} --vm-size Standard_A1 '
                       '--image Canonical:UbuntuServer:18.04-LTS '
                       '--node-agent-sku-id "batch.node.ubuntu 18.04"')

        # test create pool with missing parameters
        with self.assertRaises(SystemExit):
            self.batch_cmd('batch pool create --id missing-params-test --os-family 4')

        # test create pool with missing required mutually exclusive parameters
        with self.assertRaises(SystemExit):
            self.batch_cmd('batch pool create --id missing-required-group-test --vm-size small')

        # test create pool with parameters from mutually exclusive groups
        with self.assertRaises(SystemExit):
            self.batch_cmd('batch pool create --id mutually-exclusive-test --vm-size small '
                           '--os-family 4 --image Canonical:UbuntuServer:16-LTS:latest')

        # test create pool with invalid vm size for IaaS
        with self.assertRaises(SystemExit):
            self.batch_cmd('batch pool create --id invalid-size-test --vm-size small '
                           '--image Canonical:UbuntuServer:16.04.0-LTS --node-agent-sku-id '
                           '"batch.node.ubuntu 16.04"')

        # test create pool with missing optional parameters
        with self.assertRaises(SystemExit):
            self.batch_cmd('batch pool create --id missing-optional-test --vm-size small '
                           '--os-family 4 --start-task-wait-for-success')

        # test create pool from JSON file
        self.kwargs['json'] = self._get_test_data_file('batch-pool-create.json').replace('\\', '\\\\')
        self.batch_cmd('batch pool create --json-file "{json}"')
        self.batch_cmd('batch pool show --pool-id azure-cli-test-json').assert_with_checks([
            self.check('userAccounts[0].name', 'cliTestUser'),
            self.check('startTask.userIdentity.userName', 'cliTestUser'),
            self.check('taskSlotsPerNode', 3)
        ])

        # test create pool from non-existant JSON file
        with self.assertRaises(SystemExit):
            self.batch_cmd('batch pool create --json-file batch-pool-create-missing.json')

        # test create pool from invalid JSON file
        with self.assertRaises(CLIError):
            self.kwargs['json'] = self._get_test_data_file('batch-pool-create-invalid.json').replace('\\', '\\\\')
            self.batch_cmd('batch pool create --json-file "{json}"')

        # test create pool from JSON file with additional parameters
        with self.assertRaises(SystemExit):
            self.kwargs['json'] = self._get_test_data_file('batch-pool-create.json').replace('\\', '\\\\')
            self.batch_cmd('batch pool create --json-file "{json}" --vm-size small')

        # test list pools
        pool_list = self.batch_cmd('batch pool list')
        pool_list = pool_list.get_output_in_json()
        self.assertEqual(len(pool_list), 3)
        pool_ids = sorted([p['id'] for p in pool_list])
        self.assertEqual(pool_ids, ["azure-cli-test-iaas", "azure-cli-test-json", "azure-cli-test-paas"])

        # test list pools with select
        pool_list = self.batch_cmd('batch pool list --filter "id eq \'{pool_p}\'"').get_output_in_json()
        self.assertEqual(len(pool_list), 1)

        # test resize pool
        self.batch_cmd('batch pool resize --pool-id {pool_p} --target-dedicated-nodes 0 --target-low-priority-nodes 5')
        self.batch_cmd('batch pool show --pool-id {pool_p} '
                       '--select "allocationState, targetLowPriorityNodes"').assert_with_checks([
                           self.check('targetLowPriorityNodes', 5)])

        # test cancel pool resize
        self.batch_cmd('batch pool resize --pool-id {pool_p} --abort')

        # test enable autoscale
        self.batch_cmd('batch pool autoscale enable --pool-id {pool_i} '
                       '--auto-scale-formula "$TargetLowPriorityNodes=3"')
        self.batch_cmd('batch pool show --pool-id {pool_i} --select "enableAutoScale"').assert_with_checks([
            self.check('enableAutoScale', True)])

        # test evaluate autoscale
        self.batch_cmd('batch pool autoscale evaluate --pool-id {pool_i} '
                       '--auto-scale-formula "$TargetLowPriorityNodes=3"')

        # test disable autoscale
        self.batch_cmd('batch pool autoscale disable --pool-id {pool_i}')
        self.batch_cmd('batch pool show --pool-id {pool_i} --select "enableAutoScale"').assert_with_checks([
            self.check('enableAutoScale', False)])

        # test list usage metrics
        self.batch_cmd('batch pool usage-metrics list')

        # TODO: Test update pool from JSON file

        # test patch pool using parameters
        current = self.batch_cmd('batch pool show --pool-id {pool_j} --select "startTask"').get_output_in_json()
        self.batch_cmd('batch pool set --pool-id {pool_j} --start-task-command-line new_value')
        updated = self.batch_cmd('batch pool show --pool-id {pool_j} --select "startTask"').get_output_in_json()
        self.assertNotEqual(current['startTask']['commandLine'], updated['startTask']['commandLine'])

        # test list node agent skus
        self.batch_cmd('batch pool supported-images list')

        # test delete iaas pool
        self.batch_cmd('batch pool delete --pool-id {pool_i} --yes')

        # test app package reference
        self.batch_cmd('batch pool create --id app_package_test --vm-size small --os-family 4 '
                       '--application-package-references does-not-exist', expect_failure=True)
        self.batch_cmd('batch pool set --pool-id {pool_p} --application-package-references does-not-exist',
                       expect_failure=True)

        # TODO: Test node commands


text:
Travis.Controllers.Workers = SC.ArrayProxy.extend({
  init: function() {
    this.view = SC.View.create({
      content: this,
      templateName: 'app/templates/workers/list'
    });
    this.view.appendTo('#workers');

    this.set('workers', Travis.Worker.all({ orderBy: 'host' }));
    this.set('content', []);
  },

  workersObserver: function() {
    // if(this.getPath('workers.length') && this.groups === undefined) { // why the heck can't i just return an array here
      this.groups = {};
      var workers = this.get('workers') || [];

      workers.forEach(function(worker) {
        var host = worker.get('host');
        if(!(host in this.groups)) this.groups[host] = Travis.WorkerGroup.create();
        this.groups[host].add(worker);
      }.bind(this));

      this.set('content', $.values(this.groups));
    // }
  }.observes('workers.length')
});


text:
package com.layer.sqlite;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.layer.sqlite.migrations.CodeMigration;
import com.layer.sqlite.migrations.Migration;
import com.layer.sqlite.migrations.StreamMigration;
import com.layer.sqlite.schema.Schema;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Pattern;

public class SQLParser {
    public static void execute(SQLiteDatabase db, Schema schema) throws IOException {
        execute(db, schema.getStream());
    }

    public static void execute(SQLiteDatabase db, Migration migration) throws IOException {
        if (migration instanceof StreamMigration) {
            execute(db, ((StreamMigration) migration).getStream());
        } else if (migration instanceof CodeMigration) {
            ((CodeMigration) migration).execute(db);
        } else {
            throw new IllegalArgumentException("Unknown migration type: " + migration);
        }
    }

    protected static void execute(SQLiteDatabase db, InputStream in)
            throws IOException, SQLException {
        try {
            Execute.statements(db, Statements.fromStream(in));
        } finally {
            in.close();
        }
    }

    /**
     * Generates lists of statements for execution from various sources.
     */
    public static class Statements {
        public static List<String> fromStream(InputStream in) {
            String contents = new Scanner(in, "UTF-8").useDelimiter("\\A").next();

            // Remove block comments
            Pattern blockComment = Pattern.compile("/\\*.*?\\*/",
                    Pattern.MULTILINE | Pattern.DOTALL);
            contents = blockComment.matcher(contents).replaceAll("");

            // Remove line comments
            Pattern lineComment = Pattern.compile("^\\s*--.*?$",
                    Pattern.MULTILINE | Pattern.DOTALL);
            contents = lineComment.matcher(contents).replaceAll("");

            // TODO: make a parser smarter than simply looking for empty lines to split on
            return Arrays.asList(contents.split("(\\s*\\r?\\n\\s*){2,}"));
        }
    }

    /**
     * Executes lists of statements.
     */
    protected static class Execute {
        private final static Set<String> COMMENT_PREFIXES = new HashSet<String>(
                Arrays.asList("--"));
        private final static Set<String> EXEC_PREFIXES = new HashSet<String>(
                Arrays.asList("ALTER", "ANALYZE", "CREATE", "DELETE", "DROP", "INSERT", "UPDATE"));
        private final static Set<String> QUERY_PREFIXES = new HashSet<String>(
                Arrays.asList("PRAGMA"));

        /**
         * Returns true if the provided statement begins with a prefix from a given prefixes set.
         *
         * @param prefixes
         * @param statement
         * @return
         */
        private static boolean isPrefixMatch(Set<String> prefixes, String statement) {
            String upper = statement.toUpperCase();
            for (String prefix : prefixes) {
                if (upper.startsWith(prefix)) {
                    return true;
                }
            }
            return false;
        }

        /**
         * Executes each statement in the statements list.  The actual SQLiteDatabase method used
         * to execute each statement is determined by comparing the beginning of the statement to
         * prefixes in the COMMENT_PREFIXES, EXEC_PREFIXES, and QUERY_PREFIXES sets.
         *
         * @param db         The database on which to execute statements.
         * @param statements The list of statements to execute.
         * @throws java.io.IOException
         * @throws IllegalArgumentException If a statement cannot be parsed.
         */
        public static void statements(SQLiteDatabase db, List<String> statements)
                throws IOException, SQLException {
            for (String statement : statements) {
                statement = statement.trim();

                if (statement.isEmpty()) {
                    // Skip empty statements.
                    continue;
                }

                if (isPrefixMatch(COMMENT_PREFIXES, statement)) {
                    // Skip comments.
                    continue;
                }

                if (isPrefixMatch(EXEC_PREFIXES, statement)) {
                    // Execute.
                    db.execSQL(statement);
                    continue;
                }

                if (isPrefixMatch(QUERY_PREFIXES, statement)) {
                    // Query.
                    Cursor cursor = db.rawQuery(statement, null);
                    if (cursor != null) {
                        cursor.close();
                    }
                    continue;
                }

                throw new IllegalArgumentException("Cannot parse statement: " + statement);
            }
        }
    }
}


text:
package com.network.topology.serviceaware.routing.delaybound.vars;

import com.lpapi.entities.group.generators.LPNameGeneratorImpl;
import com.lpapi.entities.group.validators.LPDistinctPrefixValidator;
import com.lpapi.entities.group.validators.LPNumberRangeValidator;
import com.lpapi.entities.group.validators.LPPrefixClassValidator;
import com.lpapi.entities.group.validators.LPSetContainmentValidator;
import com.lpapi.exception.LPNameException;
import com.network.topology.serviceaware.ServiceAwareVariablePrefixes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class RouterInServicePathVarNameGenerator extends LPNameGeneratorImpl {

  private static final String PREFIX = ServiceAwareVariablePrefixes.ROUTER_SERVICE_PATH;

  private static final Logger log = LoggerFactory.getLogger(RouterInServicePathVarNameGenerator.class);

  public RouterInServicePathVarNameGenerator(Set<String> vertexVars, int serviceClasses) {
    super(PREFIX, 4);
    if (vertexVars==null) {
      log.error("Name generator initialized with empty set of vertices");
      vertexVars = Collections.EMPTY_SET;
    }

    if (serviceClasses <=0) {
      log.error("Service classes should be a positive integer (>0). Defaulting to 1");
      serviceClasses = 1;
    }

    //add validators
    //service class is an integer in the set serviceClassSet
    addValidator(new LPPrefixClassValidator(0, Integer.class, "Service class should be an integer"));
    addValidator(new LPNumberRangeValidator(0, 1, serviceClasses, "Not a valid service class"));

    //nodes should be strings
    addValidator(new LPPrefixClassValidator(1, String.class, "Source should be a String"));
    addValidator(new LPPrefixClassValidator(2, String.class, "Destination should be a String"));
    addValidator(new LPPrefixClassValidator(3, String.class, "Intermediate node should be a String"));

    //variables should be in the set of vertices
    addValidator(new LPSetContainmentValidator(1, vertexVars, "Source should be in the set of vertices"));
    addValidator(new LPSetContainmentValidator(2, vertexVars, "Destination should be in the set of vertices"));
    addValidator(new LPSetContainmentValidator(3, vertexVars, "intermediate should be in the set of vertices"));
    //variables should be distinct
    addValidator(new LPDistinctPrefixValidator(1, 2, "Source cannot be equal to destination"));

  }

  @Override
  protected void validatePrefixConstraint(List strings) throws LPNameException {
  }
}


text:
package joshua.phrase.lm.ngram;

public class Right implements State {

  public int[] words; // c++ typedef uint WordIndex, KENLM_MAX_ORDER - 1
  public float[] backoff; // KENLM_MAX_ORDER - 1
  public byte length;

  public byte getLength() {
    return length;
  }

  public long identify(byte index) {
    return words[index];
  }

  @Override
  public boolean equals(Object obj) {
    if (! (obj instanceof Right))
      return false;

    Right other = (Right)obj;
    if (getLength() != other.getLength())
      return false;
    if (words.length != other.words.length)
      return false;
    for (int i = 0; i < words.length; i++)
      if (words[i] != other.words[i])
        return false;

    return true;
  }

  @Override
  public int hashCode() {
    return java.util.Arrays.hashCode(words) * length;
  }
}


text:
using namespace boost::assign;

struct SeedSpec6 {
    uint8_t addr[16];
    uint16_t port;
};

#include "chainparamsseeds.h"

//
// Main network
//

// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
    // It'll only connect to one or two seed nodes because once it connects,
    // it'll get a pile of addresses with newer timestamps.
    // Seed nodes are given a random 'last seen time' of between one and two
    // weeks ago.
    const int64_t nOneWeek = 7*24*60*60;
    for (unsigned int i = 0; i < count; i++)
    {
        struct in6_addr ip;
        memcpy(&ip, data[i].addr, sizeof(ip));
        CAddress addr(CService(ip, data[i].port));
        addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
        vSeedsOut.push_back(addr);
    }
}

class CMainParams : public CChainParams {
public:
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
        // a large 4-byte int at any alignment.
        pchMessageStart[0] = 0x35;
        pchMessageStart[1] = 0x2c;
        pchMessageStart[2] = 0x46;
        pchMessageStart[3] = 0x51;
        vAlertPubKey = ParseHex("");
        nDefaultPort = 10882;
        nRPCPort = 10883;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.
        //
        //CBlock(hash=000001faef25dec4fbcf906e6242621df2c183bf232f263d0ba5b101911e4563, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=12630d16a97f24b287c8c2594dda5fb98c9e6c70fc61d44191931ea2aa08dc90, nTime=1393221600, nBits=1e0fffff, nNonce=164482, vtx=1, vchBlockSig=)
        //  Coinbase(hash=12630d16a9, nTime=1393221600, ver=1, vin.size=1, vout.size=1, nLockTime=0)
        //    CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a24323020466562203230313420426974636f696e2041544d7320636f6d6520746f20555341)
        //    CTxOut(empty)
        //  vMerkleTree: 12630d16a9
        const char* pszTimestamp = "Madcoin To the Moon";
        std::vector<CTxIn> vin;
        vin.resize(1);
        vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        std::vector<CTxOut> vout;
        vout.resize(1);
        vout[0].SetEmpty();
        CTransaction txNew(1, 1513082722, vin, vout, 0);
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1513082722;
        genesis.nBits    = bnProofOfWorkLimit.GetCompact();
        genesis.nNonce   = 94085;

        hashGenesisBlock = genesis.GetHash();
   	//	  printf("genesis.GetHash = %s\n", genesis.GetHash().ToString().c_str());
        // printf("genesis.hashMerkleRoot = %s\n", genesis.hashMerkleRoot.ToString().c_str());

        assert(hashGenesisBlock == uint256("0x00000f216972f79ed7cdde62f6d9f1ae4543a26f54da916f6eb13b05c0f9d55b"));
        assert(genesis.hashMerkleRoot == uint256("0xcc58742bea9f8dd08670232a77ddb212687bc4703748e5f2bf0908d045d925f4"));

        vFixedSeeds.clear();
        vSeeds.clear();
        vSeeds.push_back(CDNSSeedData("block.madcoin.life", "block.madcoin.life"));
        vSeeds.push_back(CDNSSeedData("node1.madcoin.life", "node1.madcoin.life"));
        vSeeds.push_back(CDNSSeedData("node2.madcoin.life", "node2.madcoin.life"));

        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,110);
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,44);
        base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,142);
        base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
        base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();

        convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));

        nLastPOWBlock = 525600; // 2 years
    }

    virtual const CBlock& GenesisBlock() const { return genesis; }
    virtual Network NetworkID() const { return CChainParams::MAIN; }

    virtual const vector<CAddress>& FixedSeeds() const {
        return vFixedSeeds;
    }
protected:
    CBlock genesis;
    vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;

//
// Testnet
//

class CTestNetParams : public CMainParams {
public:
    CTestNetParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
        // a large 4-byte int at any alignment.
        pchMessageStart[0] = 0x1d;
        pchMessageStart[1] = 0x12;
        pchMessageStart[2] = 0x45;
        pchMessageStart[3] = 0x3a;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
        vAlertPubKey = ParseHex("");
        nDefaultPort = 11882;
        nRPCPort = 11883;
        strDataDir = "testnet";

        // Modify the testnet genesis block so the timestamp is valid for a later start.
        genesis.nBits  = 1513082722;
        genesis.nNonce = 0;

        hashGenesisBlock = genesis.GetHash();
        //assert(hashGenesisBlock == uint256("0x"));

        vFixedSeeds.clear();
        vSeeds.clear();

        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,61);
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196);
        base58Prefixes[SECRET_KEY]     = std::vector<unsigned char>(1,229);
        base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
        base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();

        convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));

        nLastPOWBlock = 0x7fffffff;
    }
    virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;

static CChainParams *pCurrentParams = &mainParams;

const CChainParams &Params() {
    return *pCurrentParams;
}

void SelectParams(CChainParams::Network network) {
    switch (network) {
        case CChainParams::MAIN:
            pCurrentParams = &mainParams;
            break;
        case CChainParams::TESTNET:
            pCurrentParams = &testNetParams;
            break;
        default:
            assert(false && "Unimplemented network");
            return;
    }
}

bool SelectParamsFromCommandLine() {

    bool fTestNet = GetBoolArg("-testnet", false);

    if (fTestNet) {
        SelectParams(CChainParams::TESTNET);
    } else {
        SelectParams(CChainParams::MAIN);
    }
    return true;
}


text:
[![Travis](https://img.shields.io/travis/iTofu/RingView.svg?style=flat)](https://travis-ci.org/iTofu/RingView)
[![CocoaPods](https://img.shields.io/cocoapods/v/RingView.svg)](http://cocoadocs.org/docsets/RingView)
[![CocoaPods](https://img.shields.io/cocoapods/l/RingView.svg)](https://raw.githubusercontent.com/iTofu/RingView/master/LICENSE)
[![CocoaPods](https://img.shields.io/cocoapods/p/RingView.svg)](http://cocoadocs.org/docsets/RingView)
[![LeoDev](https://img.shields.io/badge/blog-LeoDev.me-brightgreen.svg)](https://leodev.me)

⭕ Ring View.

```
In me the tiger sniffs the rose.

心有猛虎,细嗅蔷薇。
```

## Installation

### CocoaPods

RingView is available on [CocoaPods][01]. Just add the following to your project Podfile:

```ruby
pod 'RingView' # Podfile
```

### Non-CocoaPods Installation

Just drag the RingView folder into your project.

## Usage

* In `ViewController.swift`:

  ```swift
  self.ringView = RingView(lineWidth: 5.0, strokeColor: .red)
  self.ringView.backgroundColor = .cyan
  self.view.addSubview(self.ringView)
  self.ringView.center = self.view.center
  self.ringView.bounds = CGRect(x: 0, y: 0, width: 200.0, height: 100.0)

  if #available(iOS 10.0, *) {
      Timer.scheduledTimer(withTimeInterval: 1 / 60.0, repeats: true) { (timer) in
          self.ringView.progress += 1 / 60.0 / 5.0

          if self.ringView.progress >= 1.0 {
              timer.invalidate()
          }
      }
  }
  ```

## Support

* If you have any question, just [commit a issue](https://github.com/iTofu/RingView/issues/new).

* Mail: `echo bGVvZGF4aWFAZ21haWwuY29tCg== | base64 -D`

* Blog: https://LeoDev.me

* Donations:

  * PayPal:

    [![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=leodaxia@gmail.com&item_name=leodaxia@gmail.com)

  * Alipay or Wechat Pay:

  Please note: Donation does not imply any type of service contract.

## License

RingView is released under the [MIT License](https://github.com/iTofu/RingView/blob/master/LICENSE).

  [01]: https://cocoapods.org/


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _typeof3 = require("@babel/runtime/helpers/typeof");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.MessageBar = void 0;

var _taggedTemplateLiteral2 = _interopRequireDefault(require("@babel/runtime/helpers/taggedTemplateLiteral"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var _designTokens = require("@looker/design-tokens");

var _Close = require("@styled-icons/material/Close");

var _noop = _interopRequireDefault(require("lodash/noop"));

var _isUndefined = _interopRequireDefault(require("lodash/isUndefined"));

var _react = _interopRequireWildcard(require("react"));

var _styledComponents = _interopRequireDefault(require("styled-components"));

var _Button = require("../Button");

var _Space = require("../Layout/Space");

var _simple = require("../Layout/utils/simple");

var _utils = require("../utils");

var _Status = require("../Status");

var _templateObject, _templateObject2;

var _excluded = ["id", "children", "intent", "visible", "onPrimaryClick", "onSecondaryClick", "primaryAction", "secondaryAction", "noActions"];

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof3(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

var NoopComponent = function NoopComponent() {
  return _react["default"].createElement(_react["default"].Fragment, null);
};

function getPrimaryActionButton(t, primaryAction) {
  switch ((0, _typeof2["default"])(primaryAction)) {
    case 'string':
      return function (_ref) {
        var onClick = _ref.onClick;
        return _react["default"].createElement(_Button.ButtonTransparent, {
          onClick: onClick
        }, primaryAction);
      };

    case 'object':
      return function () {
        return primaryAction;
      };

    default:
      return function (_ref2) {
        var intent = _ref2.intent,
            onClick = _ref2.onClick,
            id = _ref2.id;
        return _react["default"].createElement(_Button.IconButton, {
          id: id ? "".concat(id, "-iconButton") : undefined,
          onClick: onClick,
          icon: _react["default"].createElement(_Close.Close, null),
          size: "small",
          label: "".concat(t('DismissIntent', {
            intent: (0, _Status.getIntentLabel)(t, intent),
            ns: 'MessageBar'
          }))
        });
      };
  }
}

function getSecondaryActionButton(secondaryAction) {
  switch ((0, _typeof2["default"])(secondaryAction)) {
    case 'string':
      return function (_ref3) {
        var onClick = _ref3.onClick;
        return _react["default"].createElement(_Button.ButtonTransparent, {
          onClick: onClick,
          color: "neutral"
        }, secondaryAction);
      };

    case 'object':
      return function () {
        return secondaryAction;
      };

    default:
      return NoopComponent;
  }
}

var MessageBarLayout = (0, _react.forwardRef)(function (_ref4, ref) {
  var id = _ref4.id,
      children = _ref4.children,
      _ref4$intent = _ref4.intent,
      intent = _ref4$intent === void 0 ? 'inform' : _ref4$intent,
      visibleProp = _ref4.visible,
      _ref4$onPrimaryClick = _ref4.onPrimaryClick,
      onPrimaryClick = _ref4$onPrimaryClick === void 0 ? _noop["default"] : _ref4$onPrimaryClick,
      _ref4$onSecondaryClic = _ref4.onSecondaryClick,
      onSecondaryClick = _ref4$onSecondaryClic === void 0 ? _noop["default"] : _ref4$onSecondaryClic,
      primaryAction = _ref4.primaryAction,
      secondaryAction = _ref4.secondaryAction,
      _ref4$noActions = _ref4.noActions,
      noActions = _ref4$noActions === void 0 ? false : _ref4$noActions,
      props = (0, _objectWithoutProperties2["default"])(_ref4, _excluded);
  (0, _utils.useReadOnlyWarn)('MessageBar', visibleProp, onPrimaryClick);

  var _useState = (0, _react.useState)((0, _isUndefined["default"])(visibleProp) ? true : visibleProp),
      _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
      visible = _useState2[0],
      setVisible = _useState2[1];

  var handlePrimaryClick = function handlePrimaryClick() {
    setVisible(visibleProp || false);
    onPrimaryClick();
  };

  var handleSecondaryClick = function handleSecondaryClick() {
    setVisible(visibleProp || false);
    onSecondaryClick();
  };

  (0, _react.useEffect)(function () {
    if (!(0, _isUndefined["default"])(visibleProp)) {
      setVisible(visibleProp);
    }
  }, [visibleProp]);

  var _useTranslation = (0, _utils.useTranslation)('MessageBar'),
      t = _useTranslation.t;

  var PrimaryButton = getPrimaryActionButton(t, primaryAction);
  var SecondaryButton = getSecondaryActionButton(secondaryAction);

  var messageBarMarkup = _react["default"].createElement("div", (0, _extends2["default"])({
    "aria-live": "polite",
    ref: ref,
    role: "status"
  }, (0, _designTokens.omitStyledProps)(props)), _react["default"].createElement(_Status.Status, {
    intent: intent
  }), _react["default"].createElement(MessageBarContent, null, children), !noActions && _react["default"].createElement(_Space.Space, {
    width: "auto"
  }, _react["default"].createElement(SecondaryButton, {
    onClick: handleSecondaryClick
  }), _react["default"].createElement(PrimaryButton, {
    intent: intent,
    onClick: handlePrimaryClick,
    id: id
  })));

  return visible ? messageBarMarkup : null;
});
MessageBarLayout.displayName = 'MessageBarLayout';

var MessageBarContent = _styledComponents["default"].div.withConfig({
  displayName: "MessageBar__MessageBarContent",
  componentId: "sc-11gt222-0"
})(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2["default"])(["\n  flex-grow: 1;\n  padding: 0 ", ";\n"])), function (_ref5) {
  var space = _ref5.theme.space;
  return space.u5;
});

var backgroundColor = (0, _designTokens.variant)({
  prop: 'intent',
  variants: {
    critical: {
      backgroundColor: 'criticalAccent'
    },
    inform: {
      backgroundColor: 'informAccent'
    },
    positive: {
      backgroundColor: 'positiveAccent'
    },
    warn: {
      backgroundColor: 'warnAccent'
    }
  }
});
var MessageBar = (0, _styledComponents["default"])(MessageBarLayout).attrs(function (_ref6) {
  var _ref6$intent = _ref6.intent,
      intent = _ref6$intent === void 0 ? 'inform' : _ref6$intent,
      _ref6$px = _ref6.px,
      px = _ref6$px === void 0 ? 'medium' : _ref6$px,
      _ref6$py = _ref6.py,
      py = _ref6$py === void 0 ? 'small' : _ref6$py,
      _ref6$width = _ref6.width,
      width = _ref6$width === void 0 ? '100%' : _ref6$width;
  return {
    intent: intent,
    px: px,
    py: py,
    width: width
  };
}).withConfig({
  displayName: "MessageBar",
  componentId: "sc-11gt222-1"
})(_templateObject2 || (_templateObject2 = (0, _taggedTemplateLiteral2["default"])(["\n  ", "\n  align-items: center;\n  ", "\n  border-radius: ", ";\n  color: ", ";\n  display: flex;\n  font-size: ", ";\n"])), _simple.simpleLayoutCSS, backgroundColor, function (_ref7) {
  var radii = _ref7.theme.radii;
  return radii.medium;
}, function (_ref8) {
  var colors = _ref8.theme.colors;
  return colors.text5;
}, function (_ref9) {
  var fontSizes = _ref9.theme.fontSizes;
  return fontSizes.small;
});
exports.MessageBar = MessageBar;
//# sourceMappingURL=MessageBar.js.map


text:
Description
===========

Installs and configures newrelic for server monitoring.

https://newrelic.com/docs/server/new-relic-for-server-monitoring

Requirements
============

## Platforms

* Debian, Ubuntu

Tested on:

* Debian Wheezy (7.0)

Attributes
==========

## Required

* `node[:newrelic][:license_key]` - license key for server monitoring

## Optional

* `node[:newrelic]["apt-key"]` - newrelic apt-key
* `node[:newrelic][:keyserver]` - address of key server
* `node[:newrelic][:config_file]` - config file
* `node[:newrelic][:log_path]`- path to logs
* `node[:newrelic][:loglevel]` - log level
* `node[:newrelic][:logfile]` - log file
* `node[:newrelic][:proxy]` - address of proxy server
* `node[:newrelic][:ssl]` - turns SSL on/off
* `node[:newrelic][:ssl_ca_bundle]` - CA certificate
* `node[:newrelic][:ssl_ca_path]` - path to CA files
* `node[:newrelic][:pidfile]` - pidfile
* `node[:newrelic][:collector_host]` - address of newrelic's collector
* `node[:newrelic][:timeout]` - connection timeout

Usage
=====

Prepare role newrelic:

```ruby
name "newrelic"
description %q{
  Configures machine to use newrelic server monitoring.
}

run_list(
  "recipe[newrelic]"
)

default_attributes(
 newrelic: {license_key: "your_license_key"}
)
```
and add it to run list.


text:
package org.apache.solr.handler.component.test;

import org.apache.solr.common.SolrInputDocument;

public class Transaction {

    public Float amount;

    public Integer quantity;

    public String upc;

    public String category;

    public String subcategory;

    public String manufacturer;

    public String corporation;

    public String brand;

    public String type;

    public String subtype;

    public Boolean private_label;

    public SolrInputDocument asDocument() {
        SolrInputDocument d = new SolrInputDocument();
        d.addField("noun", "xact");
        d.addField("product_brand_name", this.brand);
        d.addField("product_category_name", this.category);
        d.addField("product_purchase_quantity", this.quantity);
        d.addField("product_purchase_amount", this.amount);
        return d;
    }
}


text:
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using Microsoft.Rest.Azure;
    using Models;

    /// <summary>
    /// XMsClientRequestIdOperations operations.
    /// </summary>
    internal partial class XMsClientRequestIdOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IXMsClientRequestIdOperations
    {
        /// <summary>
        /// Initializes a new instance of the XMsClientRequestIdOperations class.
        /// </summary>
        /// <param name='client'>
        /// Reference to the service client.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        internal XMsClientRequestIdOperations(AutoRestAzureSpecialParametersTestClient client)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }
            this.Client = client;
        }

        /// <summary>
        /// Gets a reference to the AutoRestAzureSpecialParametersTestClient
        /// </summary>
        public AutoRestAzureSpecialParametersTestClient Client { get; private set; }

        /// <summary>
        /// Get method that overwrites x-ms-client-request header with value
        /// 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
        /// </summary>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse> GetWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/overwrite/x-ms-client-request-id/method/").ToString();
            List<string> _queryParameters = new List<string>();
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("GET");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_httpResponse.Headers.Contains("x-ms-request-id"))
                {
                    ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                }
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

        /// <summary>
        /// Get method that overwrites x-ms-client-request header with value
        /// 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
        /// </summary>
        /// <param name='xMsClientRequestId'>
        /// This should appear as a method parameter, use value
        /// '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0'
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task<AzureOperationResponse> ParamGetWithHttpMessagesAsync(string xMsClientRequestId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (xMsClientRequestId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "xMsClientRequestId");
            }
            // Tracing
            bool _shouldTrace = ServiceClientTracing.IsEnabled;
            string _invocationId = null;
            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("xMsClientRequestId", xMsClientRequestId);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "ParamGet", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/overwrite/x-ms-client-request-id/via-param/method/").ToString();
            List<string> _queryParameters = new List<string>();
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            HttpRequestMessage _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;
            _httpRequest.Method = new HttpMethod("GET");
            _httpRequest.RequestUri = new Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
            }
            if (xMsClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("x-ms-client-request-id"))
                {
                    _httpRequest.Headers.Remove("x-ms-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", xMsClientRequestId);
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach(var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;
            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;
            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse();
            _result.Request = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return _result;
        }

    }
}


text:
```ts
notification.open('message', 'title');
```

```ts
notification.afterClosed().subscribe((result) => {
  console.log('The notification was closed');
});

notification.close()
```

```ts
notification.open('message','title', {
  duration: 3000
});
```

### Theming
```ts
notification.success('message','title', {
  duration: 3000
});
notification.info('message','title', {
  duration: 3000
});
notification.warn('message','title', {
  duration: 3000
});
```


text:
require 'spec_helper'

describe "Issues" do
  before do
    login_as :user
  end

  describe "GET /keys" do
    before do
      @key = Factory :key, :user => @user
      visit keys_path
    end

    subject { page }

    it { should have_content(@key.title) }

    describe "Destroy" do
      before { visit key_path(@key) }

      it "should remove entry" do
        expect {
          click_link "Remove"
        }.to change { @user.keys.count }.by(-1)
      end
    end
  end

  describe "New key" do
    before do
      visit keys_path
      click_link "Add new"
    end

    it "should open new key popup" do
      page.should have_content("New key")
    end

    describe "fill in" do
      before do
        fill_in "key_title", :with => "laptop"
        fill_in "key_key", :with => "publickey234="
      end

      it { expect { click_button "Save" }.to change {Key.count}.by(1) }

      it "should add new key to table" do
        click_button "Save"

        page.should_not have_content("New key")
        page.should have_content "laptop"
      end
    end
  end

  describe "Show page" do
    before do
      @key = Factory :key, :user => @user
      visit key_path(@key)
    end

    it { page.should have_content @key.title }
    it { page.should have_content @key.key[0..10] }
  end
end


text:
#ifndef __PRIMITIVE_H__
#define __PRIMITIVE_H__

#include "MathGeoLib/include/Math/Quat.h"
#include "Entity.h"

class Primitive
	: public Entity
{
public:

	/*
	 * Basic Primitive
	 */
	Primitive()
	{
	}

	/*
	 * Primitive with Position and Rotation
	 */
	Primitive(const float3& position, const Quat& rotation) : Position(position), Rotation(rotation)
	{
	}

	/*
	* Primitive with Position, Rotation and Color
	*/
	Primitive(const float3& position, const Quat& rotation, const float3& color) : Position(position), Rotation(rotation), Color(color)
	{
	}

	virtual ~Primitive()
	{
	}

	virtual void Draw() = 0;

public:
	float3 Position = float3(0, 0, 0);
	Quat Rotation = Quat::FromEulerXYZ(0, 0, 0);
	float3 Color = float3(0, 0, 0);
	float3 Scale = float3(1, 1, 1);
};

#endif // __PRIMITIVE_H__


text:
<?php

defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );

/**
 * Input Class
 *
 * Pre-processes global input data for security
 *
 * @package CodeIgniter
 * @subpackage Libraries
 * @category Input
 * @author EllisLab Dev Team
 * @link http://codeigniter.com/user_guide/libraries/input.html
 */
class CI_Input {

	/**
	 * IP address of the current user
	 *
	 * @var string
	 */
	protected $ip_address = FALSE;

	/**
	 * Allow GET array flag
	 *
	 * If set to FALSE, then $_GET will be set to an empty array.
	 *
	 * @var bool
	 */
	protected $_allow_get_array = TRUE;

	/**
	 * Standardize new lines flag
	 *
	 * If set to TRUE, then newlines are standardized.
	 *
	 * @var bool
	 */
	protected $_standardize_newlines;

	/**
	 * Enable XSS flag
	 *
	 * Determines whether the XSS filter is always active when
	 * GET, POST or COOKIE data is encountered.
	 * Set automatically based on config setting.
	 *
	 * @var bool
	 */
	protected $_enable_xss = FALSE;

	/**
	 * Enable CSRF flag
	 *
	 * Enables a CSRF cookie token to be set.
	 * Set automatically based on config setting.
	 *
	 * @var bool
	 */
	protected $_enable_csrf = FALSE;

	/**
	 * List of all HTTP request headers
	 *
	 * @var array
	 */
	protected $headers = array ();

	/**
	 * Raw input stream data
	 *
	 * Holds a cache of php://input contents
	 *
	 * @var string
	 */
	protected $_raw_input_stream;

	/**
	 * Parsed input stream data
	 *
	 * Parsed from php://input at runtime
	 *
	 * @see CI_Input::input_stream()
	 * @var array
	 */
	protected $_input_stream;
	protected $security;
	protected $uni;

	// --------------------------------------------------------------------

	/**
	 * Class constructor
	 *
	 * Determines whether to globally enable the XSS processing
	 * and whether to allow the $_GET array.
	 *
	 * @return void
	 */
	public function __construct() {
		$this->_allow_get_array = (config_item ( 'allow_get_array' ) === TRUE);
		$this->_enable_xss = (config_item ( 'global_xss_filtering' ) === TRUE);
		$this->_enable_csrf = (config_item ( 'csrf_protection' ) === TRUE);
		$this->_standardize_newlines = ( bool ) config_item ( 'standardize_newlines' );

		$this->security = & load_class ( 'Security', 'core' );

		// Do we need the UTF-8 class?
		if (UTF8_ENABLED === TRUE) {
			$this->uni = & load_class ( 'Utf8', 'core' );
		}

		// Sanitize global arrays
		$this->_sanitize_globals ();

		log_message ( 'info', 'Input Class Initialized' );
	}

	// --------------------------------------------------------------------

	/**
	 * Fetch from array
	 *
	 * Internal method used to retrieve values from global arrays.
	 *
	 * @param
	 *        	array &$array $_GET, $_POST, $_COOKIE, $_SERVER, etc.
	 * @param mixed $index
	 *        	item to be fetched from $array
	 * @param bool $xss_clean
	 *        	apply XSS filtering
	 * @return mixed
	 */
	protected function _fetch_from_array(&$array, $index = NULL, $xss_clean = NULL) {
		is_bool ( $xss_clean ) or $xss_clean = $this->_enable_xss;

		// If $index is NULL, it means that the whole $array is requested
		isset ( $index ) or $index = array_keys ( $array );

		// allow fetching multiple keys at once
		if (is_array ( $index )) {
			$output = array ();
			foreach ( $index as $key ) {
				$output [$key] = $this->_fetch_from_array ( $array, $key, $xss_clean );
			}

			return $output;
		}

		if (isset ( $array [$index] )) {
			$value = $array [$index];
		} elseif (($count = preg_match_all ( '/(?:^[^\[]+)|\[[^]]*\]/', $index, $matches )) > 1) // Does the index contain array notation
{
			$value = $array;
			for($i = 0; $i < $count; $i ++) {
				$key = trim ( $matches [0] [$i], '[]' );
				if ($key === '') // Empty notation will return the value as array
{
					break;
				}

				if (isset ( $value [$key] )) {
					$value = $value [$key];
				} else {
					return NULL;
				}
			}
		} else {
			return NULL;
		}

		return ($xss_clean === TRUE) ? $this->security->xss_clean ( $value ) : $value;
	}

	// --------------------------------------------------------------------

	/**
	 * Fetch an item from the GET array
	 *
	 * @param mixed $index
	 *        	item to be fetched from $_GET
	 * @param bool $xss_clean
	 *        	apply XSS filtering
	 * @return mixed
	 */
	public function get($index = NULL, $xss_clean = NULL) {
		return $this->_fetch_from_array ( $_GET, $index, $xss_clean );
	}

	// --------------------------------------------------------------------

	/**
	 * Fetch an item from the POST array
	 *
	 * @param mixed $index
	 *        	item to be fetched from $_POST
	 * @param bool $xss_clean
	 *        	apply XSS filtering
	 * @return mixed
	 */
	public function post($index = NULL, $xss_clean = NULL) {
		return $this->_fetch_from_array ( $_POST, $index, $xss_clean );
	}

	// --------------------------------------------------------------------

	/**
	 * Fetch an item from POST data with fallback to GET
	 *
	 * @param string $index
	 *        	item to be fetched from $_POST or $_GET
	 * @param bool $xss_clean
	 *        	apply XSS filtering
	 * @return mixed
	 */
	public function post_get($index, $xss_clean = NULL) {
		return isset ( $_POST [$index] ) ? $this->post ( $index, $xss_clean ) : $this->get ( $index, $xss_clean );
	}

	// --------------------------------------------------------------------

	/**
	 * Fetch an item from GET data with fallback to POST
	 *
	 * @param string $index
	 *        	item to be fetched from $_GET or $_POST
	 * @param bool $xss_clean
	 *        	apply XSS filtering
	 * @return mixed
	 */
	public function get_post($index, $xss_clean = NULL) {
		return isset ( $_GET [$index] ) ? $this->get ( $index, $xss_clean ) : $this->post ( $index, $xss_clean );
	}

	// --------------------------------------------------------------------

	/**
	 * Fetch an item from the COOKIE array
	 *
	 * @param mixed $index
	 *        	item to be fetched from $_COOKIE
	 * @param bool $xss_clean
	 *        	apply XSS filtering
	 * @return mixed
	 */
	public function cookie($index = NULL, $xss_clean = NULL) {
		return $this->_fetch_from_array ( $_COOKIE, $index, $xss_clean );
	}

	// --------------------------------------------------------------------

	/**
	 * Fetch an item from the SERVER array
	 *
	 * @param mixed $index
	 *        	item to be fetched from $_SERVER
	 * @param bool $xss_clean
	 *        	apply XSS filtering
	 * @return mixed
	 */
	public function server($index, $xss_clean = NULL) {
		return $this->_fetch_from_array ( $_SERVER, $index, $xss_clean );
	}

	// ------------------------------------------------------------------------

	/**
	 * Fetch an item from the php://input stream
	 *
	 * Useful when you need to access PUT, DELETE or PATCH request data.
	 *
	 * @param string $index
	 *        	item to be fetched
	 * @param bool $xss_clean
	 *        	apply XSS filtering
	 * @return mixed
	 */
	public function input_stream($index = NULL, $xss_clean = NULL) {
		// Prior to PHP 5.6, the input stream can only be read once,
		// so we'll need to check if we have already done that first.
		if (! is_array ( $this->_input_stream )) {
			// $this->raw_input_stream will trigger __get().
			parse_str ( $this->raw_input_stream, $this->_input_stream );
			is_array ( $this->_input_stream ) or $this->_input_stream = array ();
		}

		return $this->_fetch_from_array ( $this->_input_stream, $index, $xss_clean );
	}

	// ------------------------------------------------------------------------

	/**
	 * Set cookie
	 *
	 * Accepts an arbitrary number of parameters (up to 7) or an associative
	 * array in the first parameter containing all the values.
	 *
	 * @param string|mixed[] $name
	 *        	or an array containing parameters
	 * @param string $value
	 * @param int $expire
	 *        	time in seconds
	 * @param string $domain
	 *        	(e.g.: '.yourdomain.com')
	 * @param string $path
	 *        	(default: '/')
	 * @param string $prefix
	 *        	prefix
	 * @param bool $secure
	 *        	only transfer cookies via SSL
	 * @param bool $httponly
	 *        	only makes the cookie accessible via HTTP (no javascript)
	 * @return void
	 */
	public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE, $httponly = FALSE) {
		if (is_array ( $name )) {
			// always leave 'name' in last place, as the loop will break otherwise, due to $$item
			foreach ( array (
					'value',
					'expire',
					'domain',
					'path',
					'prefix',
					'secure',
					'httponly',
					'name'
			) as $item ) {
				if (isset ( $name [$item] )) {
					$$item = $name [$item];
				}
			}
		}

		if ($prefix === '' && config_item ( 'cookie_prefix' ) !== '') {
			$prefix = config_item ( 'cookie_prefix' );
		}

		if ($domain == '' && config_item ( 'cookie_domain' ) != '') {
			$domain = config_item ( 'cookie_domain' );
		}

		if ($path === '/' && config_item ( 'cookie_path' ) !== '/') {
			$path = config_item ( 'cookie_path' );
		}

		if ($secure === FALSE && config_item ( 'cookie_secure' ) === TRUE) {
			$secure = config_item ( 'cookie_secure' );
		}

		if ($httponly === FALSE && config_item ( 'cookie_httponly' ) !== FALSE) {
			$httponly = config_item ( 'cookie_httponly' );
		}

		if (! is_numeric ( $expire )) {
			$expire = time () - 86500;
		} else {
			$expire = ($expire > 0) ? time () + $expire : 0;
		}

		setcookie ( $prefix . $name, $value, $expire, $path, $domain, $secure, $httponly );
	}

	// --------------------------------------------------------------------

	/**
	 * Fetch the IP Address
	 *
	 * Determines and validates the visitor's IP address.
	 *
	 * @return string address
	 */
	public function ip_address() {
		if ($this->ip_address !== FALSE) {
			return $this->ip_address;
		}

		$proxy_ips = config_item ( 'proxy_ips' );
		if (! empty ( $proxy_ips ) && ! is_array ( $proxy_ips )) {
			$proxy_ips = explode ( ',', str_replace ( ' ', '', $proxy_ips ) );
		}

		$this->ip_address = $this->server ( 'REMOTE_ADDR' );

		if ($proxy_ips) {
			foreach ( array (
					'HTTP_X_FORWARDED_FOR',
					'HTTP_CLIENT_IP',
					'HTTP_X_CLIENT_IP',
					'HTTP_X_CLUSTER_CLIENT_IP'
			) as $header ) {
				if (($spoof = $this->server ( $header )) !== NULL) {
					// Some proxies typically list the whole chain of IP
					// addresses through which the client has reached us.
					// e.g. client_ip, proxy_ip1, proxy_ip2, etc.
					sscanf ( $spoof, '%[^,]', $spoof );

					if (! $this->valid_ip ( $spoof )) {
						$spoof = NULL;
					} else {
						break;
					}
				}
			}

			if ($spoof) {
				for($i = 0, $c = count ( $proxy_ips ); $i < $c; $i ++) {
					// Check if we have an IP address or a subnet
					if (strpos ( $proxy_ips [$i], '/' ) === FALSE) {
						// An IP address (and not a subnet) is specified.
						// We can compare right away.
						if ($proxy_ips [$i] === $this->ip_address) {
							$this->ip_address = $spoof;
							break;
						}

						continue;
					}

					// We have a subnet ... now the heavy lifting begins
					isset ( $separator ) or $separator = $this->valid_ip ( $this->ip_address, 'ipv6' ) ? ':' : '.';

					// If the proxy entry doesn't match the IP protocol - skip it
					if (strpos ( $proxy_ips [$i], $separator ) === FALSE) {
						continue;
					}

					// Convert the REMOTE_ADDR IP address to binary, if needed
					if (! isset ( $ip, $sprintf )) {
						if ($separator === ':') {
							// Make sure we're have the "full" IPv6 format
							$ip = explode ( ':', str_replace ( '::', str_repeat ( ':', 9 - substr_count ( $this->ip_address, ':' ) ), $this->ip_address ) );

							for($j = 0; $j < 8; $j ++) {
								$ip [$j] = intval ( $ip [$j], 16 );
							}

							$sprintf = '%016b%016b%016b%016b%016b%016b%016b%016b';
						} else {
							$ip = explode ( '.', $this->ip_address );
							$sprintf = '%08b%08b%08b%08b';
						}

						$ip = vsprintf ( $sprintf, $ip );
					}

					// Split the netmask length off the network address
					sscanf ( $proxy_ips [$i], '%[^/]/%d', $netaddr, $masklen );

					// Again, an IPv6 address is most likely in a compressed form
					if ($separator === ':') {
						$netaddr = explode ( ':', str_replace ( '::', str_repeat ( ':', 9 - substr_count ( $netaddr, ':' ) ), $netaddr ) );
						for($i = 0; $i < 8; $i ++) {
							$netaddr [$i] = intval ( $netaddr [$i], 16 );
						}
					} else {
						$netaddr = explode ( '.', $netaddr );
					}

					// Convert to binary and finally compare
					if (strncmp ( $ip, vsprintf ( $sprintf, $netaddr ), $masklen ) === 0) {
						$this->ip_address = $spoof;
						break;
					}
				}
			}
		}

		if (! $this->valid_ip ( $this->ip_address )) {
			return $this->ip_address = '0.0.0.0';
		}

		return $this->ip_address;
	}

	// --------------------------------------------------------------------

	/**
	 * Validate IP Address
	 *
	 * @param string $ip
	 * @param string $which
	 *        	'ipv4' or 'ipv6'
	 * @return bool
	 */
	public function valid_ip($ip, $which = '') {
		switch (strtolower ( $which )) {
			case 'ipv4' :
				$which = FILTER_FLAG_IPV4;
				break;
			case 'ipv6' :
				$which = FILTER_FLAG_IPV6;
				break;
			default :
				$which = NULL;
				break;
		}

		return ( bool ) filter_var ( $ip, FILTER_VALIDATE_IP, $which );
	}

	// --------------------------------------------------------------------

	/**
	 * Fetch User Agent string
	 *
	 * @return string|null Agent string or NULL if it doesn't exist
	 */
	public function user_agent($xss_clean = NULL) {
		return $this->_fetch_from_array ( $_SERVER, 'HTTP_USER_AGENT', $xss_clean );
	}

	// --------------------------------------------------------------------

	/**
	 * Sanitize Globals
	 *
	 * Internal method serving for the following purposes:
	 *
	 * - Unsets $_GET data, if query strings are not enabled
	 * - Cleans POST, COOKIE and SERVER data
	 * - Standardizes newline characters to PHP_EOL
	 *
	 * @return void
	 */
	protected function _sanitize_globals() {
		// Is $_GET data allowed? If not we'll set the $_GET to an empty array
		if ($this->_allow_get_array === FALSE) {
			$_GET = array ();
		} elseif (is_array ( $_GET ) && count ( $_GET ) > 0) {
			foreach ( $_GET as $key => $val ) {
				$_GET [$this->_clean_input_keys ( $key )] = $this->_clean_input_data ( $val );
			}
		}

		// Clean $_POST Data
		if (is_array ( $_POST ) && count ( $_POST ) > 0) {
			foreach ( $_POST as $key => $val ) {
				$_POST [$this->_clean_input_keys ( $key )] = $this->_clean_input_data ( $val );
			}
		}

		// Clean $_COOKIE Data
		if (is_array ( $_COOKIE ) && count ( $_COOKIE ) > 0) {
			// Also get rid of specially treated cookies that might be set by a server
			// or silly application, that are of no use to a CI application anyway
			// but that when present will trip our 'Disallowed Key Characters' alarm
			// http://www.ietf.org/rfc/rfc2109.txt
			// note that the key names below are single quoted strings, and are not PHP variables
			unset ( $_COOKIE ['$Version'], $_COOKIE ['$Path'], $_COOKIE ['$Domain'] );

			foreach ( $_COOKIE as $key => $val ) {
				if (($cookie_key = $this->_clean_input_keys ( $key )) !== FALSE) {
					$_COOKIE [$cookie_key] = $this->_clean_input_data ( $val );
				} else {
					unset ( $_COOKIE [$key] );
				}
			}
		}

		// Sanitize PHP_SELF
		$_SERVER ['PHP_SELF'] = strip_tags ( $_SERVER ['PHP_SELF'] );

		// CSRF Protection check
		if ($this->_enable_csrf === TRUE && ! is_cli ()) {
			$this->security->csrf_verify ();
		}

		log_message ( 'debug', 'Global POST, GET and COOKIE data sanitized' );
	}

	// --------------------------------------------------------------------

	/**
	 * Clean Input Data
	 *
	 * Internal method that aids in escaping data and
	 * standardizing newline characters to PHP_EOL.
	 *
	 * @param string|string[] $str
	 * @return string
	 */
	protected function _clean_input_data($str) {
		if (is_array ( $str )) {
			$new_array = array ();
			foreach ( array_keys ( $str ) as $key ) {
				$new_array [$this->_clean_input_keys ( $key )] = $this->_clean_input_data ( $str [$key] );
			}
			return $new_array;
		}

		/*
		 * We strip slashes if magic quotes is on to keep things consistent
		 *
		 * NOTE: In PHP 5.4 get_magic_quotes_gpc() will always return 0 and
		 * it will probably not exist in future versions at all.
		 */
		if (! is_php ( '5.4' ) && get_magic_quotes_gpc ()) {
			$str = stripslashes ( $str );
		}

		// Clean UTF-8 if supported
		if (UTF8_ENABLED === TRUE) {
			$str = $this->uni->clean_string ( $str );
		}

		// Remove control characters
		$str = remove_invisible_characters ( $str, FALSE );

		// Standardize newlines if needed
		if ($this->_standardize_newlines === TRUE) {
			return preg_replace ( '/(?:\r\n|[\r\n])/', PHP_EOL, $str );
		}

		return $str;
	}

	// --------------------------------------------------------------------

	/**
	 * Clean Keys
	 *
	 * Internal method that helps to prevent malicious users
	 * from trying to exploit keys we make sure that keys are
	 * only named with alpha-numeric text and a few other items.
	 *
	 * @param string $str
	 * @param bool $fatal
	 *        	terminate script exection
	 *        	or to return FALSE if an invalid
	 *        	key is encountered
	 * @return string|bool
	 */
	protected function _clean_input_keys($str, $fatal = TRUE) {
		if (! preg_match ( '/^[a-z0-9:_\/|-]+$/i', $str )) {
			if ($fatal === TRUE) {
				return FALSE;
			} else {
				set_status_header ( 503 );
				echo 'Disallowed Key Characters.';
				exit ( 7 ); // EXIT_USER_INPUT
			}
		}

		// Clean UTF-8 if supported
		if (UTF8_ENABLED === TRUE) {
			return $this->uni->clean_string ( $str );
		}

		return $str;
	}

	// --------------------------------------------------------------------

	/**
	 * Request Headers
	 *
	 * @param bool $xss_clean
	 *        	apply XSS filtering
	 * @return array
	 */
	public function request_headers($xss_clean = FALSE) {
		// If header is already defined, return it immediately
		if (! empty ( $this->headers )) {
			return $this->headers;
		}

		// In Apache, you can simply call apache_request_headers()
		if (function_exists ( 'apache_request_headers' )) {
			return $this->headers = apache_request_headers ();
		}

		$this->headers ['Content-Type'] = isset ( $_SERVER ['CONTENT_TYPE'] ) ? $_SERVER ['CONTENT_TYPE'] : @getenv ( 'CONTENT_TYPE' );

		foreach ( $_SERVER as $key => $val ) {
			if (sscanf ( $key, 'HTTP_%s', $header ) === 1) {
				// take SOME_HEADER and turn it into Some-Header
				$header = str_replace ( '_', ' ', strtolower ( $header ) );
				$header = str_replace ( ' ', '-', ucwords ( $header ) );

				$this->headers [$header] = $this->_fetch_from_array ( $_SERVER, $key, $xss_clean );
			}
		}

		return $this->headers;
	}

	// --------------------------------------------------------------------

	/**
	 * Get Request Header
	 *
	 * Returns the value of a single member of the headers class member
	 *
	 * @param string $index
	 * @param bool $xss_clean
	 *        	apply XSS filtering
	 * @return string|null requested header on success or NULL on failure
	 */
	public function get_request_header($index, $xss_clean = FALSE) {
		if (empty ( $this->headers )) {
			$this->request_headers ();
		}

		if (! isset ( $this->headers [$index] )) {
			return NULL;
		}

		return ($xss_clean === TRUE) ? $this->security->xss_clean ( $this->headers [$index] ) : $this->headers [$index];
	}

	// --------------------------------------------------------------------

	/**
	 * Is AJAX request?
	 *
	 * Test to see if a request contains the HTTP_X_REQUESTED_WITH header.
	 *
	 * @return bool
	 */
	public function is_ajax_request() {
		return (! empty ( $_SERVER ['HTTP_X_REQUESTED_WITH'] ) && strtolower ( $_SERVER ['HTTP_X_REQUESTED_WITH'] ) === 'xmlhttprequest');
	}

	// --------------------------------------------------------------------

	/**
	 * Is CLI request?
	 *
	 * Test to see if a request was made from the command line.
	 *
	 * @deprecated 3.0.0 Use is_cli() instead
	 * @return bool
	 */
	public function is_cli_request() {
		return is_cli ();
	}

	// --------------------------------------------------------------------

	/**
	 * Get Request Method
	 *
	 * Return the request method
	 *
	 * @param bool $upper
	 *        	return in upper or lower case
	 *        	(default: FALSE)
	 * @return string
	 */
	public function method($upper = FALSE) {
		return ($upper) ? strtoupper ( $this->server ( 'REQUEST_METHOD' ) ) : strtolower ( $this->server ( 'REQUEST_METHOD' ) );
	}

	// ------------------------------------------------------------------------

	/**
	 * Magic __get()
	 *
	 * Allows read access to protected properties
	 *
	 * @param string $name
	 * @return mixed
	 */
	public function __get($name) {
		if ($name === 'raw_input_stream') {
			isset ( $this->_raw_input_stream ) or $this->_raw_input_stream = file_get_contents ( 'php://input' );
			return $this->_raw_input_stream;
		} elseif ($name === 'ip_address') {
			return $this->ip_address;
		}
	}
}