text:
<?php

/**
 * This is the Amazon CloudWatch API Reference. This guide provides detailed information
 * about Amazon CloudWatch actions, data types, parameters, and errors. For detailed information
 * about Amazon CloudWatch features and their associated API calls, go to the Amazon CloudWatch
 * Developer Guide.
 *
 * Amazon CloudWatch is a web service that enables you to publish, monitor, and manage various
 * metrics, as well as configure alarm actions based on data from metrics. For more information
 * about this product go to http://aws.amazon.com/cloudwatch.
 *
 * Use the following links to get started using the Amazon CloudWatch API Reference:
 *
 *

 *

 * 	Actions: An alphabetical list of all Amazon CloudWatch actions.

 *
Data
 * 	Types: An alphabetical list of all Amazon CloudWatch data types.

 *

 * 	Common Parameters: Parameters that all Query actions can use.

 *
Common
 * 	Errors: Client and server errors that all actions can return.

 *
Regions
 * 	and Endpoints: Itemized regions and endpoints for all AWS products.

 *
WSDL Location:
 * 	http://monitoring.amazonaws.com/doc/2010-08-01/CloudWatch.wsdl

 *

 *
 * @version 2011.12.13
 * @license See the included NOTICE.md file for complete information.
 * @copyright See the included NOTICE.md file for complete information.
 * @link http://aws.amazon.com/cloudwatch/ Amazon CloudWatch
 * @link http://aws.amazon.com/cloudwatch/documentation/ Amazon CloudWatch documentation
 */
class AmazonCloudWatch extends CFRuntime
{
	/*%******************************************************************************************%*/
	// CLASS CONSTANTS

	/**
	 * Specify the queue URL for the United States East (Northern Virginia) Region.
	 */
	const REGION_US_E1 = 'monitoring.us-east-1.amazonaws.com';

	/**
	 * Specify the queue URL for the United States East (Northern Virginia) Region.
	 */
	const REGION_VIRGINIA = self::REGION_US_E1;

	/**
	 * Specify the queue URL for the United States West (Northern California) Region.
	 */
	const REGION_US_W1 = 'monitoring.us-west-1.amazonaws.com';

	/**
	 * Specify the queue URL for the United States West (Northern California) Region.
	 */
	const REGION_CALIFORNIA = self::REGION_US_W1;

	/**
	 * Specify the queue URL for the United States West (Oregon) Region.
	 */
	const REGION_US_W2 = 'monitoring.us-west-2.amazonaws.com';

	/**
	 * Specify the queue URL for the United States West (Oregon) Region.
	 */
	const REGION_OREGON = self::REGION_US_W2;

	/**
	 * Specify the queue URL for the Europe West (Ireland) Region.
	 */
	const REGION_EU_W1 = 'monitoring.eu-west-1.amazonaws.com';

	/**
	 * Specify the queue URL for the Europe West (Ireland) Region.
	 */
	const REGION_IRELAND = self::REGION_EU_W1;

	/**
	 * Specify the queue URL for the Asia Pacific Southeast (Singapore) Region.
	 */
	const REGION_APAC_SE1 = 'monitoring.ap-southeast-1.amazonaws.com';

	/**
	 * Specify the queue URL for the Asia Pacific Southeast (Singapore) Region.
	 */
	const REGION_SINGAPORE = self::REGION_APAC_SE1;

	/**
	 * Specify the queue URL for the Asia Pacific Northeast (Tokyo) Region.
	 */
	const REGION_APAC_NE1 = 'monitoring.ap-northeast-1.amazonaws.com';

	/**
	 * Specify the queue URL for the Asia Pacific Northeast (Tokyo) Region.
	 */
	const REGION_TOKYO = self::REGION_APAC_NE1;

	/**
	 * Specify the queue URL for the United States GovCloud Region.
	 */
	const REGION_US_GOV1 = 'monitoring.us-gov-west-1.amazonaws.com';

	/**
	 * Specify the queue URL for the South America (Sao Paulo) Region.
	 */
	const REGION_SA_E1 = 'monitoring.sa-east-1.amazonaws.com';

	/**
	 * Specify the queue URL for the South America (Sao Paulo) Region.
	 */
	const REGION_SAO_PAULO = self::REGION_SA_E1;

	/**
	 * Default service endpoint.
	 */
	const DEFAULT_URL = self::REGION_US_E1;

	/*%******************************************************************************************%*/
	// CONSTRUCTOR

	/**
	 * Constructs a new instance of <AmazonCloudWatch>.
	 *
	 * @param array $options (Optional) An associative array of parameters that can have the following keys:

	 *
certificate_authority - boolean - Optional - Determines which Cerificate Authority file to use. A value of boolean false will use the Certificate Authority file available on the system. A value of boolean true will use the Certificate Authority provided by the SDK. Passing a file system path to a Certificate Authority file (chmodded to 0755) will use that. Leave this set to false if you're not sure.

	 *
credentials - string - Optional - The name of the credential set to use for authentication.

	 *
default_cache_config - string - Optional - This option allows a preferred storage type to be configured for long-term caching. This can be changed later using the <set_cache_config()> method. Valid values are: apc, xcache, or a file system path such as ./cache or /tmp/cache/.

	 *
key - string - Optional - Your AWS key, or a session key. If blank, the default credential set will be used.

	 *
secret - string - Optional - Your AWS secret key, or a session secret key. If blank, the default credential set will be used.

	 *
token - string - Optional - An AWS session token.

	 * @return void
	 */
	public function __construct(array $options = array())
	{
		$this->api_version = '2010-08-01';
		$this->hostname = self::DEFAULT_URL;
		$this->auth_class = 'AuthV2Query';

		return parent::__construct($options);
	}

	/*%******************************************************************************************%*/
	// SETTERS

	/**
	 * This allows you to explicitly sets the region for the service to use.
	 *
	 * @param string $region (Required) The region to explicitly set. Available options are <REGION_US_E1>, <REGION_US_W1>, <REGION_US_W2>, <REGION_EU_W1>, <REGION_APAC_SE1>, <REGION_APAC_NE1>, <REGION_US_GOV1>, <REGION_SA_E1>.
	 * @return $this A reference to the current instance.
	 */
	public function set_region($region)
	{
		// @codeCoverageIgnoreStart
		$this->set_hostname($region);
		return $this;
		// @codeCoverageIgnoreEnd
	}

	/*%******************************************************************************************%*/
	// SERVICE METHODS

	/**
	 * Deletes all specified alarms. In the event of an error, no alarms are deleted.
	 *
	 * @param string|array $alarm_names (Required) A list of alarms to be deleted. Pass a string for a single value, or an indexed array for multiple values.
	 * @param array $opt (Optional) An associative array of parameters that can have the following keys:

	 *
curlopts - array - Optional - A set of values to pass directly into curl_setopt(), where the key is a pre-defined CURLOPT_* constant.

	 *
returnCurlHandle - boolean - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.

	 * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
	 */
	public function delete_alarms($alarm_names, $opt = null)
	{
		if (!$opt) $opt = array();

		// Required list (non-map)
		$opt = array_merge($opt, CFComplexType::map(array(
			'AlarmNames' => (is_array($alarm_names) ? $alarm_names : array($alarm_names))
		), 'member'));

		return $this->authenticate('DeleteAlarms', $opt);
	}

	/**
	 * Retrieves history for the specified alarm. Filter alarms by date range or item type. If an
	 * alarm name is not specified, Amazon CloudWatch returns histories for all of the owner's alarms.
	 *
	 *

	 * Amazon CloudWatch retains the history of an alarm for two weeks, whether or not you delete the
	 * alarm.
	 *

	 *
	 * @param array $opt (Optional) An associative array of parameters that can have the following keys:

	 *
AlarmName - string - Optional - The name of the alarm.

	 *
HistoryItemType - string - Optional - The type of alarm histories to retrieve. [Allowed values: ConfigurationUpdate, StateUpdate, Action]

	 *
StartDate - string - Optional - The starting date to retrieve alarm history. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.

	 *
EndDate - string - Optional - The ending date to retrieve alarm history. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.

	 *
MaxRecords - integer - Optional - The maximum number of alarm history records to retrieve.

	 *
NextToken - string - Optional - The token returned by a previous call to indicate that there is more data available.

	 *
curlopts - array - Optional - A set of values to pass directly into curl_setopt(), where the key is a pre-defined CURLOPT_* constant.

	 *
returnCurlHandle - boolean - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.

	 * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
	 */
	public function describe_alarm_history($opt = null)
	{
		if (!$opt) $opt = array();

		// Optional DateTime
		if (isset($opt['StartDate']))
		{
			$opt['StartDate'] = $this->util->convert_date_to_iso8601($opt['StartDate']);
		}

		// Optional DateTime
		if (isset($opt['EndDate']))
		{
			$opt['EndDate'] = $this->util->convert_date_to_iso8601($opt['EndDate']);
		}

		return $this->authenticate('DescribeAlarmHistory', $opt);
	}

	/**
	 * Retrieves alarms with the specified names. If no name is specified, all alarms for the user are
	 * returned. Alarms can be retrieved by using only a prefix for the alarm name, the alarm state,
	 * or a prefix for any action.
	 *
	 * @param array $opt (Optional) An associative array of parameters that can have the following keys:

	 *
AlarmNames - string|array - Optional - A list of alarm names to retrieve information for. Pass a string for a single value, or an indexed array for multiple values.

	 *
AlarmNamePrefix - string - Optional - The alarm name prefix. AlarmNames cannot be specified if this parameter is specified.

	 *
StateValue - string - Optional - The state value to be used in matching alarms. [Allowed values: OK, ALARM, INSUFFICIENT_DATA]

	 *
ActionPrefix - string - Optional - The action name prefix.

	 *
MaxRecords - integer - Optional - The maximum number of alarm descriptions to retrieve.

	 *
NextToken - string - Optional - The token returned by a previous call to indicate that there is more data available.

	 *
curlopts - array - Optional - A set of values to pass directly into curl_setopt(), where the key is a pre-defined CURLOPT_* constant.

	 *
returnCurlHandle - boolean - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.

	 * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
	 */
	public function describe_alarms($opt = null)
	{
		if (!$opt) $opt = array();

		// Optional list (non-map)
		if (isset($opt['AlarmNames']))
		{
			$opt = array_merge($opt, CFComplexType::map(array(
				'AlarmNames' => (is_array($opt['AlarmNames']) ? $opt['AlarmNames'] : array($opt['AlarmNames']))
			), 'member'));
			unset($opt['AlarmNames']);
		}

		return $this->authenticate('DescribeAlarms', $opt);
	}

	/**
	 * Retrieves all alarms for a single metric. Specify a statistic, period, or unit to filter the
	 * set of alarms further.
	 *
	 * @param string $metric_name (Required) The name of the metric.
	 * @param string $namespace (Required) The namespace of the metric. [Constraints: The value must be between 1 and 255 characters, and must match the following regular expression pattern: [^:].*]
	 * @param array $opt (Optional) An associative array of parameters that can have the following keys:

	 *
Statistic - string - Optional - The statistic for the metric. [Allowed values: SampleCount, Average, Sum, Minimum, Maximum]

	 *
Dimensions - array - Optional - The list of dimensions associated with the metric.

	 *
x - array - Optional - This represents a simple array index.

	 *
Name - string - Required - The name of the dimension.

	 *
Value - string - Required - The value representing the dimension measurement

	 *

	 *

	 *
Period - integer - Optional - The period in seconds over which the statistic is applied.

	 *
Unit - string - Optional - The unit for the metric. [Allowed values: Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits, Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second, Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None]

	 *
curlopts - array - Optional - A set of values to pass directly into curl_setopt(), where the key is a pre-defined CURLOPT_* constant.

	 *
returnCurlHandle - boolean - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.

	 * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
	 */
	public function describe_alarms_for_metric($metric_name, $namespace, $opt = null)
	{
		if (!$opt) $opt = array();
		$opt['MetricName'] = $metric_name;
		$opt['Namespace'] = $namespace;

		// Optional list + map
		if (isset($opt['Dimensions']))
		{
			$opt = array_merge($opt, CFComplexType::map(array(
				'Dimensions' => $opt['Dimensions']
			), 'member'));
			unset($opt['Dimensions']);
		}

		return $this->authenticate('DescribeAlarmsForMetric', $opt);
	}

	/**
	 * Disables actions for the specified alarms. When an alarm's actions are disabled the alarm's
	 * state may change, but none of the alarm's actions will execute.
	 *
	 * @param string|array $alarm_names (Required) The names of the alarms to disable actions for. Pass a string for a single value, or an indexed array for multiple values.
	 * @param array $opt (Optional) An associative array of parameters that can have the following keys:

	 *
curlopts - array - Optional - A set of values to pass directly into curl_setopt(), where the key is a pre-defined CURLOPT_* constant.

	 *
returnCurlHandle - boolean - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.

	 * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
	 */
	public function disable_alarm_actions($alarm_names, $opt = null)
	{
		if (!$opt) $opt = array();

		// Required list (non-map)
		$opt = array_merge($opt, CFComplexType::map(array(
			'AlarmNames' => (is_array($alarm_names) ? $alarm_names : array($alarm_names))
		), 'member'));

		return $this->authenticate('DisableAlarmActions', $opt);
	}

	/**
	 * Enables actions for the specified alarms.
	 *
	 * @param string|array $alarm_names (Required) The names of the alarms to enable actions for. Pass a string for a single value, or an indexed array for multiple values.
	 * @param array $opt (Optional) An associative array of parameters that can have the following keys:

	 *
curlopts - array - Optional - A set of values to pass directly into curl_setopt(), where the key is a pre-defined CURLOPT_* constant.

	 *
returnCurlHandle - boolean - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.

	 * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
	 */
	public function enable_alarm_actions($alarm_names, $opt = null)
	{
		if (!$opt) $opt = array();

		// Required list (non-map)
		$opt = array_merge($opt, CFComplexType::map(array(
			'AlarmNames' => (is_array($alarm_names) ? $alarm_names : array($alarm_names))
		), 'member'));

		return $this->authenticate('EnableAlarmActions', $opt);
	}

	/**
	 * Gets statistics for the specified metric.
	 *
	 *

	 * The maximum number of data points returned from a single GetMetricStatistics
	 * request is 1,440. If a request is made that generates more than 1,440 data points, Amazon
	 * CloudWatch returns an error. In such a case, alter the request by narrowing the specified time
	 * range or increasing the specified period. Alternatively, make multiple requests across adjacent
	 * time ranges.
	 *

	 * Amazon CloudWatch aggregates data points based on the length of the period that
	 * you specify. For example, if you request statistics with a one-minute granularity, Amazon
	 * CloudWatch aggregates data points with time stamps that fall within the same one-minute period.
	 * In such a case, the data points queried can greatly outnumber the data points returned.
	 *
	 *

	 * The maximum number of data points that can be queried is 50,850; whereas the maximum number of
	 * data points returned is 1,440.
	 *

	 * The following examples show various statistics allowed by the data point query maximum of
	 * 50,850 when you call GetMetricStatistics on Amazon EC2 instances with detailed
	 * (one-minute) monitoring enabled:
	 *
	 *

	 *
Statistics for up to 400 instances for a span of one hour

	 *
Statistics for up to 35 instances over a span of 24 hours

	 *
Statistics for up to 2 instances over a span of 2 weeks

	 *

	 *
	 * For information about the namespace, metric names, and dimensions that other Amazon Web
	 * Services products use to send metrics to Cloudwatch, go to
	 * CloudWatch Support for AWS Products in the Amazon CloudWatch Developer Guide.
	 *
	 * @param string $namespace (Required) The namespace of the metric. [Constraints: The value must be between 1 and 255 characters, and must match the following regular expression pattern: [^:].*]
	 * @param string $metric_name (Required) The name of the metric.
	 * @param string $start_time (Required) The time stamp to use for determining the first datapoint to return. The value specified is inclusive; results include datapoints with the time stamp specified.
The specified start time is rounded down to the nearest value. Datapoints are returned for start times up to two weeks in the past. Specified start times that are more than two weeks in the past will not return datapoints for metrics that are older than two weeks.
 May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.
	 * @param string $end_time (Required) The time stamp to use for determining the last datapoint to return. The value specified is exclusive; results will include datapoints up to the time stamp specified. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.
	 * @param integer $period (Required) The granularity, in seconds, of the returned datapoints. Period must be at least 60 seconds and must be a multiple of 60. The default value is 60.
	 * @param string|array $statistics (Required) The metric statistics to return. For information about specific statistics returned by GetMetricStatistics, go to Statistics in the Amazon CloudWatch Developer Guide. Valid Values: Average | Sum | SampleCount | Maximum | Minimum Pass a string for a single value, or an indexed array for multiple values.
	 * @param string $unit (Required) The unit for the metric. [Allowed values: Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits, Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second, Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None]
	 * @param array $opt (Optional) An associative array of parameters that can have the following keys:

	 *
Dimensions - array - Optional - A list of dimensions describing qualities of the metric.

	 *
x - array - Optional - This represents a simple array index.

	 *
Name - string - Required - The name of the dimension.

	 *
Value - string - Required - The value representing the dimension measurement

	 *

	 *

	 *
curlopts - array - Optional - A set of values to pass directly into curl_setopt(), where the key is a pre-defined CURLOPT_* constant.

	 *
returnCurlHandle - boolean - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.

	 * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
	 */
	public function get_metric_statistics($namespace, $metric_name, $start_time, $end_time, $period, $statistics, $unit, $opt = null)
	{
		if (!$opt) $opt = array();
		$opt['Namespace'] = $namespace;
		$opt['MetricName'] = $metric_name;
		$opt['Period'] = $period;
		$opt['Unit'] = $unit;
		$opt['StartTime'] = $this->util->convert_date_to_iso8601($start_time);
		$opt['EndTime'] = $this->util->convert_date_to_iso8601($end_time);

		// Required list (non-map)
		$opt = array_merge($opt, CFComplexType::map(array(
			'Statistics' => (is_array($statistics) ? $statistics : array($statistics))
		), 'member'));

		// Optional list + map
		if (isset($opt['Dimensions']))
		{
			$opt = array_merge($opt, CFComplexType::map(array(
				'Dimensions' => $opt['Dimensions']
			), 'member'));
			unset($opt['Dimensions']);
		}

		return $this->authenticate('GetMetricStatistics', $opt);
	}

	/**
	 * Returns a list of valid metrics stored for the AWS account owner. Returned metrics can be used
	 * with GetMetricStatistics to obtain statistical data for a given metric.
	 *
	 *

	 * Up to 500 results are returned for any one call. To retrieve further results, use returned
	 * NextToken values with subsequent ListMetrics operations.
	 *

	 *

	 * If you create a metric with the PutMetricData action, allow up to fifteen minutes
	 * for the metric to appear in calls to the ListMetrics action. Statistics about the
	 * metric, however, are available sooner using GetMetricStatistics.
	 *

	 *
	 * @param array $opt (Optional) An associative array of parameters that can have the following keys:

	 *
Namespace - string - Optional - The namespace to filter against. [Constraints: The value must be between 1 and 255 characters, and must match the following regular expression pattern: [^:].*]

	 *
MetricName - string - Optional - The name of the metric to filter against.

	 *
Dimensions - array - Optional - A list of dimensions to filter against.

	 *
x - array - Optional - This represents a simple array index.

	 *
Name - string - Required - The dimension name to be matched.

	 *
Value - string - Optional - The value of the dimension to be matched.
Specifying a Name without specifying a Value returns all values associated with that Name.

	 *

	 *

	 *
NextToken - string - Optional - The token returned by a previous call to indicate that there is more data available.

	 *
curlopts - array - Optional - A set of values to pass directly into curl_setopt(), where the key is a pre-defined CURLOPT_* constant.

	 *
returnCurlHandle - boolean - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.

	 * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
	 */
	public function list_metrics($opt = null)
	{
		if (!$opt) $opt = array();

		// Optional list + map
		if (isset($opt['Dimensions']))
		{
			$opt = array_merge($opt, CFComplexType::map(array(
				'Dimensions' => $opt['Dimensions']
			), 'member'));
			unset($opt['Dimensions']);
		}

		return $this->authenticate('ListMetrics', $opt);
	}

	/**
	 * Creates or updates an alarm and associates it with the specified Amazon CloudWatch metric.
	 * Optionally, this operation can associate one or more Amazon Simple Notification Service
	 * resources with the alarm.
	 *
	 * When this operation creates an alarm, the alarm state is immediately set to
	 * INSUFFICIENT_DATA. The alarm is evaluated and its StateValue is set
	 * appropriately. Any actions associated with the StateValue is then executed.
	 *
	 *

	 * When updating an existing alarm, its StateValue is left unchanged.
	 *

	 *
	 * @param string $alarm_name (Required) The descriptive name for the alarm. This name must be unique within the user's AWS account
	 * @param string $metric_name (Required) The name for the alarm's associated metric.
	 * @param string $namespace (Required) The namespace for the alarm's associated metric. [Constraints: The value must be between 1 and 255 characters, and must match the following regular expression pattern: [^:].*]
	 * @param string $statistic (Required) The statistic to apply to the alarm's associated metric. [Allowed values: SampleCount, Average, Sum, Minimum, Maximum]
	 * @param integer $period (Required) The period in seconds over which the specified statistic is applied.
	 * @param integer $evaluation_periods (Required) The number of periods over which data is compared to the specified threshold.
	 * @param double $threshold (Required) The value against which the specified statistic is compared.
	 * @param string $comparison_operator (Required) The arithmetic operation to use when comparing the specified Statistic and Threshold. The specified Statistic value is used as the first operand. [Allowed values: GreaterThanOrEqualToThreshold, GreaterThanThreshold, LessThanThreshold, LessThanOrEqualToThreshold]
	 * @param array $opt (Optional) An associative array of parameters that can have the following keys:

	 *
AlarmDescription - string - Optional - The description for the alarm.

	 *
ActionsEnabled - boolean - Optional - Indicates whether or not actions should be executed during any changes to the alarm's state.

	 *
OKActions - string|array - Optional - The list of actions to execute when this alarm transitions into an OK state from any other state. Each action is specified as an Amazon Resource Number (ARN). Currently the only action supported is publishing to an Amazon SNS topic or an Amazon Auto Scaling policy. Pass a string for a single value, or an indexed array for multiple values.

	 *
AlarmActions - string|array - Optional - The list of actions to execute when this alarm transitions into an ALARM state from any other state. Each action is specified as an Amazon Resource Number (ARN). Currently the only action supported is publishing to an Amazon SNS topic or an Amazon Auto Scaling policy. Pass a string for a single value, or an indexed array for multiple values.

	 *
InsufficientDataActions - string|array - Optional - The list of actions to execute when this alarm transitions into an INSUFFICIENT_DATA state from any other state. Each action is specified as an Amazon Resource Number (ARN). Currently the only action supported is publishing to an Amazon SNS topic or an Amazon Auto Scaling policy. Pass a string for a single value, or an indexed array for multiple values.

	 *
Dimensions - array - Optional - The dimensions for the alarm's associated metric.

	 *
x - array - Optional - This represents a simple array index.

	 *
Name - string - Required - The name of the dimension.

	 *
Value - string - Required - The value representing the dimension measurement

	 *

	 *

	 *
Unit - string - Optional - The unit for the alarm's associated metric. [Allowed values: Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits, Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second, Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None]

	 *
curlopts - array - Optional - A set of values to pass directly into curl_setopt(), where the key is a pre-defined CURLOPT_* constant.

	 *
returnCurlHandle - boolean - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.

	 * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
	 */
	public function put_metric_alarm($alarm_name, $metric_name, $namespace, $statistic, $period, $evaluation_periods, $threshold, $comparison_operator, $opt = null)
	{
		if (!$opt) $opt = array();
		$opt['AlarmName'] = $alarm_name;
		$opt['MetricName'] = $metric_name;
		$opt['Namespace'] = $namespace;
		$opt['Statistic'] = $statistic;
		$opt['Period'] = $period;
		$opt['EvaluationPeriods'] = $evaluation_periods;
		$opt['Threshold'] = $threshold;
		$opt['ComparisonOperator'] = $comparison_operator;

		// Optional list (non-map)
		if (isset($opt['OKActions']))
		{
			$opt = array_merge($opt, CFComplexType::map(array(
				'OKActions' => (is_array($opt['OKActions']) ? $opt['OKActions'] : array($opt['OKActions']))
			), 'member'));
			unset($opt['OKActions']);
		}

		// Optional list (non-map)
		if (isset($opt['AlarmActions']))
		{
			$opt = array_merge($opt, CFComplexType::map(array(
				'AlarmActions' => (is_array($opt['AlarmActions']) ? $opt['AlarmActions'] : array($opt['AlarmActions']))
			), 'member'));
			unset($opt['AlarmActions']);
		}

		// Optional list (non-map)
		if (isset($opt['InsufficientDataActions']))
		{
			$opt = array_merge($opt, CFComplexType::map(array(
				'InsufficientDataActions' => (is_array($opt['InsufficientDataActions']) ? $opt['InsufficientDataActions'] : array($opt['InsufficientDataActions']))
			), 'member'));
			unset($opt['InsufficientDataActions']);
		}

		// Optional list + map
		if (isset($opt['Dimensions']))
		{
			$opt = array_merge($opt, CFComplexType::map(array(
				'Dimensions' => $opt['Dimensions']
			), 'member'));
			unset($opt['Dimensions']);
		}

		return $this->authenticate('PutMetricAlarm', $opt);
	}

	/**
	 * Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch associates the data points
	 * with the specified metric. If the specified metric does not exist, Amazon CloudWatch creates
	 * the metric.
	 *
	 *

	 * If you create a metric with the PutMetricData action, allow up to fifteen minutes
	 * for the metric to appear in calls to the ListMetrics action.
	 *

	 * The size of aPutMetricDatarequest is limited to 8 KB for HTTP GET requests and 40 KB for HTTP
	 * POST requests.
	 *
	 *

	 * Although the Value parameter accepts numbers of type Double, Amazon
	 * CloudWatch truncates values with very large exponents. Values with base-10 exponents greater
	 * than 126 (1 x 10^126) are truncated. Likewise, values with base-10 exponents less than -130 (1
	 * x 10^-130) are also truncated.
	 *

	 *
	 * @param string $namespace (Required) The namespace for the metric data.
You cannot specify a namespace that begins with "AWS/". Namespaces that begin with "AWS/" are reserved for other Amazon Web Services products that send metrics to Amazon CloudWatch.
 [Constraints: The value must be between 1 and 255 characters, and must match the following regular expression pattern: [^:].*]
	 * @param array $metric_data (Required) A list of data describing the metric.

	 *
x - array - Optional - This represents a simple array index.

	 *
MetricName - string - Required - The name of the metric.

	 *
Dimensions - array - Optional - A list of dimensions associated with the metric.

	 *
x - array - Optional - This represents a simple array index.

	 *
Name - string - Required - The name of the dimension.

	 *
Value - string - Required - The value representing the dimension measurement

	 *

	 *

	 *
Timestamp - string - Optional - The time stamp used for the metric. If not specified, the default value is set to the time the metric data was received. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.

	 *
Value - double - Optional - The value for the metric.
Although the Value parameter accepts numbers of type Double, Amazon CloudWatch truncates values with very large exponents. Values with base-10 exponents greater than 126 (1 x 10^126) are truncated. Likewise, values with base-10 exponents less than -130 (1 x 10^-130) are also truncated.

	 *
StatisticValues - array - Optional - A set of statistical values describing the metric.

	 *
x - array - Optional - This represents a simple array index.

	 *
SampleCount - double - Required - The number of samples used for the statistic set.

	 *
Sum - double - Required - The sum of values for the sample set.

	 *
Minimum - double - Required - The minimum value of the sample set.

	 *
Maximum - double - Required - The maximum value of the sample set.

	 *

	 *

	 *
Unit - string - Optional - The unit of the metric. [Allowed values: Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits, Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second, Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None]

	 *

	 *

	 * @param array $opt (Optional) An associative array of parameters that can have the following keys:

	 *
curlopts - array - Optional - A set of values to pass directly into curl_setopt(), where the key is a pre-defined CURLOPT_* constant.

	 *
returnCurlHandle - boolean - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.

	 * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
	 */
	public function put_metric_data($namespace, $metric_data, $opt = null)
	{
		if (!$opt) $opt = array();
		$opt['Namespace'] = $namespace;

		// Handle Timestamps
		for ($i = 0, $max = count($metric_data); $i < $max; $i++)
		{
			if (isset($metric_data[$i]['Timestamp']))
			{
				$metric_data[$i]['Timestamp'] = $this->util->convert_date_to_iso8601($metric_data[$i]['Timestamp']);
			}
		}

		// Required parameter
		$opt = array_merge($opt, CFComplexType::map(array(
			'MetricData' => (is_array($metric_data) ? $metric_data : array($metric_data))
		), 'member'));

		return $this->authenticate('PutMetricData', $opt, $this->hostname);
	}

	/**
	 * Temporarily sets the state of an alarm. When the updated StateValue differs from
	 * the previous value, the action configured for the appropriate state is invoked. This is not a
	 * permanent change. The next periodic alarm check (in about a minute) will set the alarm to its
	 * actual state.
	 *
	 * @param string $alarm_name (Required) The descriptive name for the alarm. This name must be unique within the user's AWS account. The maximum length is 255 characters.
	 * @param string $state_value (Required) The value of the state. [Allowed values: OK, ALARM, INSUFFICIENT_DATA]
	 * @param string $state_reason (Required) The reason that this alarm is set to this specific state (in human-readable text format)
	 * @param array $opt (Optional) An associative array of parameters that can have the following keys:

	 *
StateReasonData - string - Optional - The reason that this alarm is set to this specific state (in machine-readable JSON format)

	 *
curlopts - array - Optional - A set of values to pass directly into curl_setopt(), where the key is a pre-defined CURLOPT_* constant.

	 *
returnCurlHandle - boolean - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.

	 * @return CFResponse A <CFResponse> object containing a parsed HTTP response.
	 */
	public function set_alarm_state($alarm_name, $state_value, $state_reason, $opt = null)
	{
		if (!$opt) $opt = array();
		$opt['AlarmName'] = $alarm_name;
		$opt['StateValue'] = $state_value;
		$opt['StateReason'] = $state_reason;

		return $this->authenticate('SetAlarmState', $opt);
	}
}

/*%******************************************************************************************%*/
// EXCEPTIONS

class CloudWatch_Exception extends Exception {}


text:
package org.jtoc.convertor;

import japa.parser.ast.body.ClassOrInterfaceDeclaration;
import japa.parser.ast.visitor.VoidVisitorAdapter;

import java.io.File;
import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jtoc.convertor.cpunit.ClassInfo;
import org.jtoc.convertor.cpunit.JtocException;
import org.jtoc.convertor.cpunit.JtocNode;

@SuppressWarnings("unchecked")
public class ClassDeclarationVisitor extends VoidVisitorAdapter<Object> {

	private static Log logger = LogFactory.getLog(ClassDeclarationVisitor.class.getName());

	/** ArrayList that contains the ClassInfos */
	private ArrayList<JtocNode> classInfos = new ArrayList<JtocNode>();

	/**
	 * constructor with File
	 *
	 * @param file
	 *            the file that is going to be parsed
	 */
	public ClassDeclarationVisitor(File file) {
		this(file.getName());
	}

	/**
	 * constructor with the name of the file
	 *
	 * @param filename
	 *            the name of the file pa. NOT FULL NAME
	 */
	public ClassDeclarationVisitor(String filename) {
		JtocNode.setFilename(filename);
	}

	/**
	 * get the classes that the code file contained
	 *
	 * @return the ArrayList of the classes that the code file contained
	 */
	public ArrayList<JtocNode> getClassInfos() {
		return classInfos;
	}

	private boolean exceptionFlag = false;

	/**
	 * get whether the parse procedure throws some Exception
	 *
	 * @return true if Exception throw in the parse procedure
	 */
	public boolean hasException() {
		return exceptionFlag;
	}

	/**
	 * traverse each ClassOrInterfaceDeclaration, parse them and added them in
	 * the ArrayList to info that the classes this code file contained.
	 */
	@Override
	public void visit(ClassOrInterfaceDeclaration n, Object arg) {
		try {
			ClassInfo ci = new ClassInfo(n);
			this.classInfos.add(ci);
			ci.parse();
		} catch (JtocException e) {
			logger.error(e.getMessage());
			this.exceptionFlag = true;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var Splitter = require('../../../app/scripts/modules/ui/SplitContainer.js');

describe('Splitter', function () {
    var fixtures = document.getElementById('fixtures');

    beforeEach(function () {
        fixtures.innerHTML = '' +
            '
' +
            '<splitter id="vertical-splitter"><start>start</start><end>end</end></splitter>' +
            '
' +
            '
' +
            '<splitter id="horizontal-splitter"><start>start</start><end>end</end></splitter>' +
            '
';
    });

    afterEach(function () {
        fixtures.innerHTML = '';
    });

    describe('constructor', function () {
        it('should create splitter with fixed width for the start container', function () {
            var splitter = new Splitter('horizontal-splitter', {
                startContainerWidth: '400px'
            });

            splitter.$this.querySelector('start').style.width.should.equal('400px');
        });

        it('should create horizontal splitter with fixed width for the end container', function () {
            var splitter = new Splitter('horizontal-splitter', {
                endContainerWidth: '400px'
            });

            splitter.$this.querySelector('end').style.width.should.equal('400px');
        });

        it('should create vertical splitter with fixed height for the start container', function () {
            var splitter = new Splitter('vertical-splitter', {
                startContainerHeight: '400px'
            });

            splitter.$this.querySelector('start').style.height.should.equal('400px');
        });

        it('should create vertical splitter with fixed height for the end container', function () {
            var splitter = new Splitter('vertical-splitter', {
                endContainerHeight: '400px'
            });

            splitter.$this.querySelector('end').style.height.should.equal('400px');
        });

        it('should create vertical splitter with title for the end container', function () {
            var splitter = new Splitter('vertical-splitter', {
                endContainerTitle: 'Some title'
            });
            var endContainer = splitter.$this.querySelector('end');

            endContainer.getAttribute('withheader').should.equal('true');
            endContainer.querySelector('header').innerText.should.equal('Some title');
        });

        it('should hide the start container', function () {
            var splitter = new Splitter('vertical-splitter', {
                hideStartContainer: true
            });

            splitter.$this.querySelector('start').style.display.should.equal('none');
        });

        it('should create vertical splitter with closable end container', function () {
            var splitter = new Splitter('vertical-splitter', {
                isEndContainerClosable: true
            });
            var endContainer = splitter.$this.querySelector('end');

            endContainer.getAttribute('verticalscrolling').should.equal('true');
            should.exist(endContainer.querySelector('.toolbar-item'));
        });

        it('should initialize the HTML for the divider', function () {
            var splitter = new Splitter('vertical-splitter');
            var divider = splitter.$this.querySelector('divider');

            should.exist(divider);
            divider.innerHTML.should.equal('<handler class="resize-handler"></handler>');
        });

    });

    describe('responsiveness', function () {
        it('should switch from horizontal to vertical on width change', function () {
            var splitter = new Splitter('horizontal-splitter');

            // check preconditions
            splitter.$this.classList.contains('verticalOrientation').should.equal(false);

            // Act: resize the container
            splitter.$this.parentElement.style.width = '600px';

            // call the resize listener synchronously
            splitter._onResize();

            splitter.$this.classList.contains('verticalOrientation').should.equal(true);
        });

        it('should switch from vertical to horizontal on width change', function () {
            var splitter = new Splitter('vertical-splitter');

            // check preconditions
            splitter.$this.classList.contains('verticalOrientation').should.equal(true);

            // Act: resize the container
            splitter.$this.parentElement.style.width = '1000px';

            // call the resize listener synchronously
            splitter._onResize();

            splitter.$this.classList.contains('verticalOrientation').should.equal(false);
        });
    });

     describe('#hideEndContainer()', function () {
        it('should hide end container', function () {
            var splitter = new Splitter('vertical-splitter');

            splitter.hideEndContainer();

            splitter.$this.querySelector('end').style.display.should.equal('none');
        });
    });

    describe('#showEndContainer()', function () {
        it('should show end container', function () {
            var splitter = new Splitter('vertical-splitter');

            splitter.hideEndContainer();
            splitter.showEndContainer();

            should.exist(splitter.$this.querySelector('end').getAttribute('style'));
        });
    });

    describe('#_mouseMoveHandler()', function () {
        var splitter;
        var horizontalSplitter;
        var mockEvent = {
            clientY: 150,
            clientX: 150
        };

        beforeEach(function () {
            splitter = new Splitter('vertical-splitter');
            horizontalSplitter = new Splitter('horizontal-splitter');
        });

        afterEach(function () {
        });

        it('should change the style height of the end container', function () {
            var splitterRect = splitter.$this.getBoundingClientRect();
            var expectedResult = (splitterRect.top + splitterRect.height - mockEvent.clientY) + 'px';

            splitter._mouseMoveHandler(mockEvent);

            splitter._$endElement.style.height.should.be.equal(expectedResult);
        });

        it('should not change the style height of the start container', function () {
            splitter._mouseMoveHandler(mockEvent);

            splitter._$startElement.style.height.should.be.equal('');
        });

        it('should change the style width of the end container', function () {
            var horizontalSplitterRect = horizontalSplitter.$this.getBoundingClientRect();
            var expectedResult = (horizontalSplitterRect.left + horizontalSplitterRect.width - mockEvent.clientX) + 'px';

            horizontalSplitter._mouseMoveHandler(mockEvent);

            horizontalSplitter._$endElement.style.width.should.be.equal(expectedResult);
        });

        it('should not change the style width of the start container', function () {
            horizontalSplitter._mouseMoveHandler(mockEvent);

            horizontalSplitter._$startElement.style.width.should.be.equal('');
        });
    });

    describe('#_mouseUpHandler()', function () {
        var splitter;

        beforeEach(function () {
            splitter = new Splitter('vertical-splitter');
            splitter._mouseUpHandler();
        });

        afterEach(function () {
        });

        it('should delete references', function () {
            should.equal(document.onmousemove, null);
            should.equal(document.body.className, '');
        });
    });

    describe('#_mouseDownHandler()', function () {
        var splitter;
        var mockEvent;

        beforeEach(function () {
            mockEvent = {
                preventDefault: sinon.spy(),
                stopPropagation: sinon.spy()
            };
        });

        afterEach(function () {
            splitter._mouseUpHandler();
        });

        it('should call "#preventDefault()"', function () {
            splitter = new Splitter('vertical-splitter');
            splitter._mouseDownHandler(mockEvent);

            mockEvent.preventDefault.callCount.should.equal(1);
        });

        it('should call "#stopPropagation()"', function () {
            splitter = new Splitter('vertical-splitter');
            splitter._mouseDownHandler(mockEvent);

            mockEvent.stopPropagation.callCount.should.equal(1);
        });

        it('should call "#stopPropagation()"', function () {
            splitter = new Splitter('vertical-splitter');
            splitter._mouseDownHandler(mockEvent);

            mockEvent.stopPropagation.callCount.should.equal(1);
        });

        it('should add class to document.body', function () {
            splitter = new Splitter('vertical-splitter');
            splitter._mouseDownHandler(mockEvent);

            document.body.className.should.be.equal('user-is-resizing-vertically');
        });

        it('should add class to document.body', function () {
            splitter = new Splitter('horizontal-splitter');
            splitter._mouseDownHandler(mockEvent);

            document.body.className.should.be.equal('user-is-resizing-horizontally');
        });

        it('should create handler for mouse move', function () {
            splitter = new Splitter('horizontal-splitter');
            splitter._mouseDownHandler(mockEvent);

            splitter.$this.onmousemove.should.be.a('function');
        });

        it('should create handler for mouse up', function () {
            splitter = new Splitter('horizontal-splitter');
            splitter._mouseDownHandler(mockEvent);

            splitter.$this.onmouseup.should.be.a('function');
        });

        it('should call "requestAnimationFrame()"', function () {
            var requestAnimationFrame = sinon.spy(window, 'requestAnimationFrame');

            splitter._mouseDownHandler(mockEvent);
            splitter.$this.onmousemove(mockEvent);

            requestAnimationFrame.callCount.should.be.equal(1);
        });

    });

    describe('UI tests', function () {
        var splitter;

        beforeEach(function () {
            splitter = new Splitter('vertical-splitter', {
                hideEndContainer: true,
                isEndContainerClosable: true
            });
        });

        afterEach(function () {
        });

        describe('Close button', function () {
            it('should has click event handler', function () {
                splitter.$this.querySelector('.toolbar-item').onclick.should.be.a('function');
            });

            it('should be visible when the end container is visible', function () {
                var closeButton = splitter.$this.querySelector('.toolbar-item');

                splitter.showEndContainer();

                closeButton.style.display.should.be.equal('flex');
            });

            it('should not be visible the end container is not vissible', function () {
                var closeButton = splitter.$this.querySelector('.toolbar-item');

                splitter.showEndContainer();
                splitter.hideEndContainer();

                closeButton.style.display.should.be.equal('none');
            });
        });
    });
});


text:
package mooklabs.nausicaamodtech.machines;

import java.util.List;

import mcp.mobius.waila.api.IWailaConfigHandler;
import mcp.mobius.waila.api.IWailaDataAccessor;
import mcp.mobius.waila.api.IWailaDataProvider;
import mcp.mobius.waila.api.SpecialChars;
import mooklabs.nausicaamod.Main;
import mooklabs.nausicaamod.blocks.machines.PowerEmitter;
import mooklabs.nausicaamodtech.TechMain;
import mooklabs.nausicaamodtech.machines.tileentity.TileEntityMachineBase;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;

public class BlockWindmill extends BlockAbstractMachine{

	int output = 0;

	public BlockWindmill() {
		super(Material.iron);
		this.setBlockName("windMill");
		this.setBlockTextureName(Main.itemfold + ":grinder");
	}
	/**
	 * Called whenever the block is added into the world. Args: world, x, y, z
	 */
	public void onBlockAdded(World world, int x, int y, int z) {
		super.onBlockAdded(world, x, y, z);

	}

	@Override
	public int maxOutput() {
		return 10;
	}

	@Override
	public int[] outputSide() {
		return this.ALL_SIDES;
	}

	@Override
	public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler config) {
		return null;
	}

	@Override
	public List<String> getWailaHead(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
		currenttip.add(this.getUnlocalizedName());
		return currenttip;
	}

	public List<String> getWailaBody(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
		currenttip.add("Current Power: " + ((TileEntityMachineBase)(accessor.getTileEntity())).currentPower);
		return currenttip;
	}
	@Override
	public List<String> getWailaTail(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
		currenttip.add(SpecialChars.BLUE + SpecialChars.ITALIC + TechMain.name);
		return currenttip;
	}
	@Override
	public TileEntity createNewTileEntity(World var1, int var2) {
		return new TileEntityMachineBase();
	}

}


text:
#include "ImportSplineInfo.h"

namespace EPI
{

void ImportSplineInfo::exportXML(const Core::Ptr<Core::XMLNode> & pXMLNode) const
{
    pXMLNode->setAttribute(L"asset", L"type", EPI::toString(SPLINE_ASSET));
    pXMLNode->setValue(L"asset.spline-file-name", fileName);
}
void ImportSplineInfo::importXML(const Core::Ptr<Core::XMLNode> & pXMLNode)
{
    bool success = true;
    success &= pXMLNode->getValue(L"asset.spline-file-name", fileName);

    if(!success)
        throw Core::Exception(L"An error occured while importing the XML ImportSplineInfo values.");
}

}//namespace EPI


text:
<?xml version="1.0"?>
<!--
/**
 * Dmitrii Makhov <dmitriimakhov@gmail.com>
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
</config>


text:
@interface ODObject()

@property (strong, nonatomic) NSMutableDictionary *dictionary;

@end

@implementation ODObject

- (instancetype)init
{
    self = [super init];
    if (self){
        _dictionary = [NSMutableDictionary dictionary];
    }
    return self;
}

- (instancetype)initWithDictionary:(NSDictionary*)dictionary
{
    // if there is no dictionary we don't want to create the object
    if (!dictionary){
        return nil;
    }
    self = [super init];
    if (self){
        _dictionary = [dictionary mutableCopy];
    }
    return self;
}

- (NSDictionary*)dictionaryFromItem
{
    NSMutableDictionary *fullDictionary = [NSMutableDictionary dictionary];
    [self.dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop){
        if ([obj respondsToSelector:@selector(dictionaryFromItem)]){
            fullDictionary[key] = [obj dictionaryFromItem];
        }
        else{
            fullDictionary[key] = obj;
        }
    }];
    return fullDictionary;
}

- (NSDate *)dateFromString:(NSString *)dateString
{
    NSDate *date = nil;
    if (dateString){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
        NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
        [dateFormatter setLocale:posix];
        date = [dateFormatter dateFromString:dateString];
    }
    return date;
}

- (NSString *)description
{
    return [[self dictionaryFromItem] description];
}

@end


text:
package com.pubnub.chatterbox.profile;

import com.google.android.gms.common.api.GoogleApiClient;
import com.pubnub.chatterbox.domain.UserProfile;

/**
 * Created by Frederick on 5/14/15.
 */
public abstract class AbstractUserProfileBuilder {

    public static AbstractUserProfileBuilder getInstance(Object o) {
        if (o instanceof GoogleApiClient) {
            GPlusUserProfileBuilder gbuilder = new GPlusUserProfileBuilder();
            gbuilder.setGoogleApiClient((GoogleApiClient) o);
            return gbuilder;
        }//else if(o instanceof) Facebook, Twitter,LinkedIn, OpenID, Custom

        //}

        //NOTE: Could throw an exception here.
        return null;
    }

    public abstract UserProfile build();

}


text:
/*
 * (c)2017, Cris Luengo.
 * Based on original DIPlib code: (c)1995-2014, Delft University of Technology.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef DIP_BUCKET_H
#define DIP_BUCKET_H

#include "diplib.h"

namespace dip {

/* Typedefs */
struct DIP_NO_EXPORT Node {
   uint8* pim;
   uint8 dirc;
};

struct DIP_NO_EXPORT Chunk {
   bool used;                       /* true if chunk currently used */
   struct Chunk* bnext;             /* pointer to next chunk of current bucket */
   struct Chunk* lnext;             /* pointer to next allocated chunk */
   std::vector< Node > nodes;       /* contains Bucket.chunksize elements */
};

struct DIP_NO_EXPORT Bucket {
   dip::uint nbuckets;              /* Number of buckets */
   dip::uint chunksize;             /* Size of chunk (#nodes) */
   //int sizeofchunk;               /* Size of chunk (in bytes, total structure) */
   dip::uint andmask;               /* Andmask for modulo operation */
   dip::uint rbuck;                 /* Number of bucket which is being read */
   dip::uint wbuck;                 /* Number of bucket in which nodes are being put */
   Chunk* pwritechunk;              /* Pointer to chunk being written in */
   Chunk* preadchunk;               /* Pointer to chunk being read */
   std::vector< Node* > plastnode;  /* Array pointers to last nodes+1 of each bucket */
   std::vector< Chunk > pchunk1;    /* Array pointers to first chunk of each bucket */
   Chunk* firstchunk;               /* First allocated chunk */
   Chunk* lastchunk;                /* Last allocated chunk */
   Chunk* freechunk;                /* Last freed chunk */
   dip::uint freecount;             /* Number of free chunks */
   //dip::uint allocated;           /* Number of chunks allocated extra */
   std::vector< std::unique_ptr< Chunk >> pextra; /* Extra chunks allocated */

   Bucket( dip::uint nb, dip::uint cs ) {
      nbuckets = nb;
      chunksize = cs;
      //sizeofchunk = sizeof( Chunk )
      andmask = nbuckets - 1;

      /* Allocate the first chunk of each bucket and set up an array of
          pointers to these first chunks. */
      pchunk1.resize( nbuckets );

      /* Allocate an array with pointers for the last nodes written */
      plastnode.resize( nbuckets );
      for( dip::uint ii = 0; ii < nbuckets; ii++ ) {
         pchunk1[ ii ].nodes.resize( chunksize );
         plastnode[ ii ] = &( pchunk1[ ii ].nodes[ 0 ] );
         pchunk1[ ii ].bnext = nullptr;
      }

      /* Set up free allocation variables */
      firstchunk = nullptr;
      lastchunk = nullptr;
      freechunk = nullptr;
      freecount = 0;
   }

   void Free( dip::sint index ) {
      dip::uint ii = static_cast< dip::uint >( index );
      plastnode[ ii & andmask ] = &( pchunk1[ ii & andmask ].nodes[ 0 ] );
      Chunk* pc = pchunk1[ ii & andmask ].bnext;
      if( pc != nullptr ) {
         freechunk = pc;
      }
      while( pc != nullptr ) {
         pc->used = false;
         freecount++;
         pc = pc->bnext;
      }
   }

   bool Empty() const {
      for( dip::uint ii = 0; ii < nbuckets; ii++ ) {
         if( plastnode[ ii ] != &( pchunk1[ ii ].nodes[ 0 ] )) {
            return false;
         }
      }
      return true;
   }

   Chunk* GetChunk() {
      Chunk* newchunk;
      if( freecount > 0 ) {
         newchunk = freechunk;
         while( newchunk->used ) {
            newchunk = newchunk->lnext;
         }
         freecount--;
         freechunk = freechunk->lnext;
      } else {
         pextra.emplace_back( new Chunk ); // allocate a new chunk
         newchunk = pextra.back().get();
         newchunk->nodes.resize( chunksize );
         if( firstchunk == nullptr ) {
            firstchunk = newchunk;
         } else {
            lastchunk->lnext = newchunk;
         }
         lastchunk = newchunk;
         newchunk->lnext = firstchunk;
      }
      newchunk->used = true;
      return newchunk;
   }

   //
   // Macros, display and storing and recalling from buckets
   //

   Node* pnr;  // where to read in bucket
   Node* pnw;  // where to write in bucket
   Node* pnre; // where to end reading
   Node* pnwe; // where to end writing
   bool go;    // TRUE if still nodes to be read

   void STR( uint8* pointer, uint8 direction ) {
      pnw->pim = pointer;
      pnw++->dirc = direction;
      if( pnw == pnwe ) {
         nextwrite();
      }
   }

   void STRP( uint8* pointer ) {
      pnw++->pim = pointer;
      if( pnw == pnwe ) {
         nextwrite();
      }
   }

   void RCL( uint8*& pointer, uint8& direction ) {
      pointer = pnr->pim;
      direction = pnr++->dirc;
      if( pnr == pnre ) {
         if( pnr == plastnode[ rbuck ] ) {
            go = false;
         } else {
            nextread();
         }
      }
   }

   void RCLP( uint8*& pointer ) {
      pointer = pnr++->pim;
      if( pnr == pnre ) {
         if( pnr == plastnode[ rbuck ] ) {
            go = false;
         } else {
            nextread();
         }
      }
   }

   void startwrite( dip::sint bucknr ) {
      wbuck = static_cast< dip::uint >( bucknr ) & andmask;
      pwritechunk = &( pchunk1[ wbuck ] );
      pnw = &( pwritechunk->nodes[ 0 ] );
      pnwe = pnw + chunksize;
   }

   void nextwrite() {
      pwritechunk->bnext = GetChunk();
      pwritechunk = pwritechunk->bnext;
      /*DIP_THROW_IF((pwritechunk == nullptr), E::NO_MEMORY;)*/
      pnw = &( pwritechunk->nodes[ 0 ] );
      pnwe = pnw + chunksize;
   }

   void closewrite() {
      pwritechunk->bnext = nullptr;
      plastnode[ wbuck ] = pnw;
   }

   void startread( dip::sint bucknr ) {
      rbuck = static_cast< dip::uint >( bucknr ) & andmask;
      preadchunk = &( pchunk1[ rbuck ] );
      pnr = &( preadchunk->nodes[ 0 ] );
      go = true;
      if( preadchunk->bnext == nullptr ) {
         pnre = plastnode[ rbuck ];
         if( pnr == pnre ) {
            go = false;
         }
      } else {
         pnre = pnr + chunksize;
      }
   }

   void nextread() {
      preadchunk = preadchunk->bnext;
      pnr = &( preadchunk->nodes[ 0 ] );
      go = true;
      if( preadchunk->bnext == nullptr ) {
         pnre = plastnode[ rbuck ];
         if( pnr == pnre ) {
            go = false;
         }
      } else {
         pnre = pnr + chunksize;
      }
   }

};

} // namespace dip

#endif // DIP_BUCKET_H


text:
import pytest

@pytest.fixture()
def parser():
    from parsers import parser
    return parser


text:
package com.facebook.buck.util;

import com.facebook.buck.log.thrift.rulekeys.FullRuleKey;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TCompactProtocol;

public class ThriftRuleKeyDeserializer {
  /**
   * Reads in a list of rule keys from a file
   *
   * @param logPath The path to the file
   * @return A list of FullRuleKey objects from the file
   * @throws IOException Could not read the file
   * @throws TException Could not deserialize an entry from the file
   */
  public static List<FullRuleKey> readRuleKeys(Path logPath) throws IOException, TException {
    ByteBuffer lengthBuf = ByteBuffer.allocate(4);
    List<FullRuleKey> ret = new ArrayList<>();
    try (FileInputStream logFileStream = new FileInputStream(logPath.toAbsolutePath().toString())) {
      while (logFileStream.available() > 0) {
        logFileStream.read(lengthBuf.array());
        int length = lengthBuf.getInt();
        lengthBuf.rewind();

        byte[] serialized = new byte[length];
        logFileStream.read(serialized);
        TDeserializer serializer = new TDeserializer(new TCompactProtocol.Factory());
        FullRuleKey ruleKey = new FullRuleKey();
        serializer.deserialize(ruleKey, serialized);
        ret.add(ruleKey);
      }
      return ret;
    }
  }
}


text:
<?php
/**
 *
 * This file is part of the Aura Project for PHP.
 *
 * @package Aura.View
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 */
namespace Aura\View\Helper\Form\Input;

/**
 *
 * Helper to generate an input field that uses a "checked" attribute (e.g.,
 * radio buttons or checkboxes).
 *
 * @package Aura.View
 *
 */
class Checked extends Generic
{
    /**
     *
     * Returns HTML for an input field that uses a "checked" attribute.
     *
     * @return string
     *
     */
    protected function exec()
    {
        // the HTML to be returned
        $html = '';

        // by default, the input is unchecked
        $this->attribs['checked'] = null;

        // examine the 'value_unchecked' pseudo-attribute to see if there is
        // there a value when unchecked
        if (isset($this->attribs['value_unchecked'])) {
            $attribs = [
                'type' => 'hidden',
                'value' => $this->attribs['value_unchecked'],
            ];
            $html .= $this->void('input', $attribs);
            // remove the pseudo-attribute
            $this->attribs['value_unchecked'] = null;
        }

        // is the input checked? make sure there's a value to compare to, and
        // use strict equality so that there is no confusion between
        // 0/'0'/false/null/''.
        $checked = isset($this->attribs['value'])
                && $this->value === $this->attribs['value'];
        if ($checked) {
            $this->attribs['checked'] = 'checked';
        }

        // extract and retain the 'label' pseudo-attribute
        $label = null;
        if (isset($this->attribs['label'])) {
            $label = $this->attribs['label'];
            $this->attribs['label'] = null;
        }

        // add the HTML for the input
        $html .= $this->void('input', $this->attribs);

        // is there a label?
        if ($label) {
            $attribs = [];
            if (isset($this->attribs['id'])) {
                $attribs['for'] = $this->attribs['id'];
            }

            if ($attribs) {
                $attribs = $this->attribs($attribs);
                $html = "{$html} {$label}";
            } else {
                $html = "{$html} {$label}";
            }
        }

        // return with indent
        return $this->indent(0, $html);
    }
}


text:
require 'date'

module Rulix
  module Validators
    class AllowNilValidator
      def self.to_proc
        new.method(:call)
      end

      def call val
        if val.nil?
          raise AllowableNil
        else
          true
        end
      end
    end
  end
end

Rulix::Validator.register :allow_nil, Rulix::Validators::AllowNilValidator


text:
Describe New-WiFiProfileXml {
    It "Needs to have real tests" {
        $true | Should be $true
    }
}


text:
<?php

/**
 * This file is part of the Spryker Demoshop.
 * For full license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Pyz\Zed\DataImport\Business\Model\OrderSource;

use DateTime;
use Orm\Zed\ManualOrderEntry\Persistence\SpyOrderSourceQuery;
use Spryker\Zed\DataImport\Business\Model\DataImportStep\DataImportStepInterface;
use Spryker\Zed\DataImport\Business\Model\DataSet\DataSetInterface;

class OrderSourceWriterStep implements DataImportStepInterface
{
    public const KEY_ORDER_SOURCE_NAME = 'order_source_name';

    /**
     * @param \Spryker\Zed\DataImport\Business\Model\DataSet\DataSetInterface $dataSet
     *
     * @return void
     */
    public function execute(DataSetInterface $dataSet)
    {
        $orderSource = SpyOrderSourceQuery::create()
            ->filterByName($dataSet[static::KEY_ORDER_SOURCE_NAME])
            ->filterByCreatedAt(new DateTime())
            ->filterByUpdatedAt(new DateTime())
            ->findOneOrCreate();

        $orderSource->save();
    }
}


text:
import logging
import os
import unittest

from google.cloud import ndb  # type: ignore
from pathlib import Path

os.environ['SERVER_SOFTWARE'] = 'test ' + os.environ.get('SERVER_SOFTWARE', '')
os.environ['CURRENT_VERSION_ID'] = 'test.123'
os.environ['APPLICATION_ID'] = 'testing'
# Envs for datastore-emulator, same as running `gcloud beta emulators datastore env-init`.
os.environ['DATASTORE_DATASET'] = 'cr-status-staging'
os.environ['DATASTORE_EMULATOR_HOST'] = 'localhost:15606'
os.environ['DATASTORE_EMULATOR_HOST_PATH'] = 'localhost:15606/datastore'
os.environ['DATASTORE_HOST'] = 'http//localhost:15606'
os.environ['DATASTORE_PROJECT_ID'] = 'cr-status-staging'

from framework import cloud_tasks_helpers

class FakeCloudTasksClient(object):
  """We have no GCT server for unit tests, so just log."""

  def queue_path(self, project, location, queue):
    """Return a fully-qualified queue string."""
    # This is value is not actually used, but it might be good for debugging.
    return "projects/{project}/locations/{location}/queues/{queue}".format(
        project=project, location=location, queue=queue)

  def create_task(self, parent=None, task=None, **kwargs):
    """Just log that the task would have been created URL."""
    self.uri = task.get('app_engine_http_request').get('relative_uri')
    self.body = task.get('app_engine_http_request').get('body')
    logging.info('Task uri: %r', self.uri)
    logging.info('Task body: %r', self.body)
    return 'fake task'

cloud_tasks_helpers._client = FakeCloudTasksClient()

class Blank(object):
  """Simple class that assigns all named args to attributes.
  Tip: supply a lambda to define a method.
  """
  def __init__(self, **kwargs):
    vars(self).update(kwargs)
  def __repr__(self):
    return '%s(%s)' % (self.__class__.__name__, str(vars(self)))
  def __eq__(self, other):
    if other is None:
      return False
    return vars(self) == vars(other)

def sign_out():
  """Set env variables to represent a signed out user."""
  os.environ['USER_EMAIL'] = ''
  os.environ['USER_ID'] = ''
  os.environ['USER_IS_ADMIN'] = '0'
  os.environ['AUTH_DOMAIN'] = '1'

def sign_in(user_email, user_id):
  """Set env variables to represent a signed out user."""
  os.environ['USER_EMAIL'] = user_email
  os.environ['USER_ID'] = str(user_id)
  os.environ['USER_IS_ADMIN'] = '0'
  os.environ['AUTH_DOMAIN'] = '0'

class CustomTestCase(unittest.TestCase):

  def run(self, result=None):
    client = ndb.Client()
    with client.context():
      super(CustomTestCase, self).run(result=result)

class Testdata(object):
  def __init__(self, test_file_path: str):
    """Helper class to load testdata
    Common pattern to place the testdata in the following format:

    Given a test file, atest_test.py, and it is located at
    /some/module/atest_test.py.

    The testdata should be located at /some/module/testdata/atest_test/
    """
    self.testdata = {}
    test_file_name = Path(test_file_path).stem
    self.testdata_dir = os.path.join(
        os.path.abspath(os.path.dirname(test_file_path)),
        'testdata',
        test_file_name)
    for filename in os.listdir(self.testdata_dir):
      test_data_file_path = os.path.join(self.testdata_dir, filename)
      with open(test_data_file_path, 'r', encoding='UTF-8') as f:
        self.testdata[filename] = f.read()

  def make_golden(self, raw_data, test_data_file_name):
    """Helper function to make golden file
    """
    test_data_file_path = os.path.join(self.testdata_dir, test_data_file_name)
    with open(test_data_file_path, 'w', encoding='UTF-8') as f:
      f.write(raw_data)

  def __getitem__(self, key):
      return self.testdata[key]


text:
<?php

namespace AlphaLemon\Block\BootstrapButtonBlockBundle\Tests\Unit\Core\Block;

use AlphaLemon\AlphaLemonCmsBundle\Tests\Unit\Core\Content\Block\Base\AlBlockManagerContainerBase;
use AlphaLemon\Block\BootstrapButtonBlockBundle\Core\Block\AlBlockManagerBootstrapButtonBlock;

/**
 * AlBlockManagerBootstrapButtonBlockTest
 *
 * @author AlphaLemon <webmaster@alphalemon.com>
 */
class AlBlockManagerBootstrapButtonBlockTest extends AlBlockManagerContainerBase
{
    public function testDefaultValue()
    {
        $expectedValue = array(
            "Content" =>
            '
            {
                "0" : {
                    "button_text": "Button 1",
                    "button_type": "",
                    "button_attribute": "",
                    "button_block": "",
                    "button_enabled": ""
                }
            }
        '
        );

        $this->initContainer();
        $blockManager = new AlBlockManagerBootstrapButtonBlock($this->container, $this->validator);
        $this->assertEquals($expectedValue, $blockManager->getDefaultValue());
    }

    public function testGetHtml()
    {
        $value = '{
            "0" : {
                "button_text": "Button 1",
                "button_type": "danger",
                "button_attribute": "large",
                "button_block": "block",
                "button_enabled": "true"
            }
        }';

        $block = $this->initBlock($value);
        $this->initContainer();

        $blockManager = new AlBlockManagerBootstrapButtonBlock($this->container, $this->validator);
        $blockManager->set($block);

        $expectedResult = array('RenderView' => array(
            'view' => 'BootstrapButtonBlockBundle:Button:button.html.twig',
            'options' => array(
                'data' => array(
                    'button_text' => 'Button 1',
                    'button_type' => 'danger',
                    'button_attribute' => 'large',
                    'button_block' => 'block',
                    'button_enabled' => 'true',
                ),
                'block_manager' => $blockManager,
            ),
        ));

        $this->assertEquals($expectedResult, $blockManager->getHtml());
    }

    public function testEditorParameters()
    {
        $value = '
            {
                "0" : {
                    "button_text": "Button 1",
                    "button_type": "",
                    "button_attribute": "",
                    "button_block": "",
                    "button_enabled": ""
                }
            }';

        $block = $this->initBlock($value);
        $this->initContainer();

        $formFactory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
        $formFactory->expects($this->at(0))
                    ->method('create')
                    ->will($this->returnValue($this->initForm()))
        ;

        $formType = $this->getMock('Symfony\Component\Form\FormTypeInterface');
        $this->container->expects($this->at(2))
                        ->method('get')
                        ->with('bootstrap_button_block.form')
                        ->will($this->returnValue($formType))
        ;

        $this->container->expects($this->at(3))
                        ->method('get')
                        ->with('form.factory')
                        ->will($this->returnValue($formFactory))
        ;

        $blockManager = new AlBlockManagerBootstrapButtonBlock($this->container, $this->validator);
        $blockManager->set($block);
        $result = $blockManager->editorParameters();
        $this->assertEquals('BootstrapButtonBlockBundle:Editor:button_editor.html.twig', $result["template"]);
    }

    protected function initBlock($value)
    {
        $block = $this->getMock('AlphaLemon\AlphaLemonCmsBundle\Model\AlBlock');
        $block->expects($this->once())
              ->method('getContent')
              ->will($this->returnValue($value));

        return $block;
    }

    protected function initForm()
    {
        $form = $this->getMockBuilder('Symfony\Component\Form\Form')
                    ->disableOriginalConstructor()
                    ->getMock();
        $form->expects($this->once())
            ->method('createView')
        ;

        return $form;
    }
}


text:
package org.apache.hadoop.hbase.client;

import org.apache.hadoop.hbase.HRegionInfo;

class UnmodifyableHRegionInfo extends HRegionInfo {
  /*
   * Creates an unmodifyable copy of an HRegionInfo
   *
   * @param info
   */
  UnmodifyableHRegionInfo(HRegionInfo info) {
    super(info);
    this.tableDesc = new UnmodifyableHTableDescriptor(info.getTableDesc());
  }

  /**
   * @param split set split status
   */
  @Override
  public void setSplit(boolean split) {
    throw new UnsupportedOperationException("HRegionInfo is read-only");
  }

  /**
   * @param offLine set online - offline status
   */
  @Override
  public void setOffline(boolean offLine) {
    throw new UnsupportedOperationException("HRegionInfo is read-only");
  }
}


text:
/* global DEFAULT_WEBSAFE_FONTS, initGlobals, $injector */
describe('stackSearch filter', function() {
  var filter;

  beforeEach(function() {
    initGlobals();
    filter = $injector.get('$filter')('stackSearch');
  });

  it('should exist', function() {
    expect(filter).toBeInstanceOf(Function);
  });

  it('should return empty result if given wrong stack', function() {
    expect(filter(DEFAULT_WEBSAFE_FONTS, false)).toEqual([]);
  });

  it('should have a consistent set of fixture fonts', function() {
    expect(DEFAULT_WEBSAFE_FONTS.length).toBe(6);
    expect(DEFAULT_WEBSAFE_FONTS[0].name).toBe('Arial');
  });

  it('should find a font by a part of its stack', function() {
    expect(filter(DEFAULT_WEBSAFE_FONTS, DEFAULT_WEBSAFE_FONTS[0].stack)).toEqual([DEFAULT_WEBSAFE_FONTS[0]]);
  });

  it('should find a font by a part of its stack', function() {
    expect(filter(DEFAULT_WEBSAFE_FONTS, 'Arial')).toEqual([DEFAULT_WEBSAFE_FONTS[0]]);
  });

  it('should find the best fallback font if multiple stacks are matching', function() {
    expect(filter(DEFAULT_WEBSAFE_FONTS, 'Helvetica')).toEqual([DEFAULT_WEBSAFE_FONTS[3]]);
  });

  it('should return multiple fonts when we cant not figure out the best one', function() {
    expect(filter(DEFAULT_WEBSAFE_FONTS, 'sans-serif')).toEqual([DEFAULT_WEBSAFE_FONTS[0], DEFAULT_WEBSAFE_FONTS[3]]);
  });

  describe('caching', function() {
    it('should not create a weighted font List for the same input twice', function() {
      spyOn(filter, 'createWeightedFontList').and.callThrough();
      filter(DEFAULT_WEBSAFE_FONTS, 'Helvetica');
      filter(DEFAULT_WEBSAFE_FONTS, 'Arial');
      expect(filter.createWeightedFontList.calls.count()).toBe(1);
    });
  });

  describe('normalizeStack helper', function() {
    var normalizeStack;

    beforeEach(function() {
      normalizeStack = filter.normalizeStack;
    });

    it('should exist', function() {
      expect(normalizeStack).toBeInstanceOf(Function);
    });

    it('should split a string by comma', function() {
      expect(normalizeStack('a,b,c')).toEqual(['a', 'b', 'c']);
    });

    it('should clean up every token', function() {
      expect(normalizeStack('foo   ,"bar lorem " ')).toEqual(['foo', 'bar lorem']);
    });
  });

});


text:
require_relative "../s3_get_cskms_decrypt_item"

describe "#get_decrypted_object_content" do
  # Captures the data (metadata and body) put to an Amason S3 object.
  def stub_put(s3_client)
    data = {}
    s3_client.stub_responses(:put_object, lambda { |context|
      data[:metadata] = context.params[:metadata]
      data[:enc_body] = context.params[:body].read
      {}
    })
    data
  end

  # Given data from stub_put, stub a getter for the same object.
  # During the get operation, get_object is called twice: once to
  #   get the full body, and once again with a range to get just the
  #   auth_tag.
  def stub_get(s3_client, data, stub_auth_tag)
    resp_headers = Hash[*data[:metadata].flat_map { |k, v| ["x-amz-meta-#{k}", v] }]
    resp_headers["content-length"] = data[:enc_body].length
    if stub_auth_tag
      auth_tag = data[:enc_body].unpack("C*")[-16, 16].pack("C*")
    else
      auth_tag = nil
    end
    s3_client.stub_responses(
      :get_object,
      {
        status_code: 200,
        body: data[:enc_body],
        headers: resp_headers
      },
      {
        body: auth_tag
      }
    )
  end

  def stub_decrypt(kms_client, opts)
    kms_client.stub_responses(
      :decrypt, lambda do |context|
        if opts[:any_kms_key]
          expect(context.params["key_id"]).to be_nil
        else
          if opts[:raise] && context.params["key_id"] != opts[:response][:key_id]
            raise Aws::KMS::Errors::IncorrectKeyException.new(context, "")
          else
            expect(context.params[:key_id]).to eq(opts[:response][:key_id])
          end
        end
      opts[:response]
      end
    )
  end

  let(:bucket_name) { "doc-example-bucket" }
  let(:object_key) { "my-file.txt" }
  let(:object_content) { "This is the content of my-file.txt." }
  let(:kms_key_id) { "9041e78c-7a20-4db3-929e-828abEXAMPLE" }
  let(:kms_ciphertext_blob) { Base64.decode64("AQIDAHiWj6qDEnwihp7W7g6VZb1xqsat5jdSUdEaGhgZepHdLAGASCQI7LZz\nz7GzCpm6y4sHAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEH\nATAeBglghkgBZQMEAS4wEQQMJMJe6d8DkRTWwlvtAgEQgDtBCwiibCTS8pb7\n6BYKklVjy+CmO9q3r6y4u/9jJ8lk9eg5GwiskmcBtPMcWogMzx/vh+/65Cjb\nsQBpLQ==\n") }
  let(:kms_plaintext) { Base64.decode64("5V7JWe+UDRhv66TaDg+tP6JONf/GkTdXk6Jq61weM+w=\n") }
  # Note that Aws::S3::EncryptionV2::Client is a wrapper around
  #   Aws::S3::Client. So you must first stub Aws::S3::Client
  #   and then pass it into Aws::S3::EncryptionV2::Client
  #   via the client argument on initialization, as follows.
  let(:s3_client) do
    Aws::S3::Client.new(
      stub_responses: {
        get_object: {
          body: object_content
        }
      }
    )
  end
  # Aws::S3::EncryptionV2::Client also requires Aws::KMS::Client for
  #   AWS KMS scenarios. So you must also first stub Aws::KMS::Client
  #   and then pass it into Aws::S3::EncryptionV2::Client
  #   via the kms_client argument on initialization, as follows.
  let(:kms_client) do
    Aws::KMS::Client.new(
      stub_responses: {
        generate_data_key: {
          ciphertext_blob: kms_ciphertext_blob,
          key_id: "arn:aws:kms:us-west-2:111111111111:key/9041e78c-7a20-4db3-929e-828abEXAMPLE",
          plaintext: kms_plaintext
        }
      }
    )
  end
  let(:s3_encryption_client) do
    Aws::S3::EncryptionV2::Client.new(
      client: s3_client,
      kms_client: kms_client,
      kms_key_id: kms_key_id,
      key_wrap_schema: :kms_context,
      content_encryption_schema: :aes_gcm_no_padding,
      security_profile: :v2
    )
  end

  it "gets the decrypted content of an object in an Amazon S3 bucket" do
    data = stub_put(s3_client)
    s3_encryption_client.put_object(
      bucket: bucket_name,
      key: object_key,
      body: object_content
    )
    stub_get(s3_client, data, true)
    stub_decrypt(kms_client, any_kms_key: false, response:
      {
        key_id: kms_key_id,
        plaintext: kms_plaintext,
        encryption_algorithm: "SYMMETRIC_DEFAULT"
      }
    )
    expect(get_decrypted_object_content(
      s3_encryption_client,
      bucket_name,
      object_key
    )).to eq(object_content)
  end
end


text: export { default, frMarkdownFile } from 'ember-fr-markdown-file/helpers/fr-markdown-file';


text:
module ActiveRecord
  module ConnectionAdapters
    class LegacyPoolManager # :nodoc:
      def initialize
        @name_to_pool_config = {}
      end

      def shard_names
        @name_to_pool_config.keys
      end

      def pool_configs(_ = nil)
        @name_to_pool_config.values
      end

      def remove_pool_config(_, shard)
        @name_to_pool_config.delete(shard)
      end

      def get_pool_config(_, shard)
        @name_to_pool_config[shard]
      end

      def set_pool_config(role, shard, pool_config)
        if pool_config
          @name_to_pool_config[shard] = pool_config
        else
          raise ArgumentError, "The `pool_config` for the :#{role} role and :#{shard} shard was `nil`. Please check your configuration. If you want your writing role to be something other than `:writing` set `config.active_record.writing_role` in your application configuration. The same setting should be applied for the `reading_role` if applicable."
        end
      end
    end
  end
end