text:
<!DOCTYPE html>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<body>
<script>
function testDataset(getTestElement) {
	function testGet(attr, expected)
	{
	    var e = getTestElement();
	    e.setAttribute(attr, "value");
	    return e.dataset[expected] == "value";
	}

	test (function() {
		assert_true(testGet('data-foo', 'foo'));
		assert_true(testGet('data-foo-bar', 'fooBar'));
		assert_true(testGet('data--', '-'));
		assert_true(testGet('data--foo', 'Foo'));
		assert_true(testGet('data---foo', '-Foo'));
		assert_true(testGet('data---foo--bar', '-Foo-Bar'));
		assert_true(testGet('data---foo---bar', '-Foo--Bar'));
		assert_true(testGet('data-foo-', 'foo-'));
		assert_true(testGet('data-foo--', 'foo--'));
		assert_true(testGet('data-', ''));
		assert_true(testGet('data-\xE0', '\xE0'));
		assert_true(testGet('data-1', '1'));
		assert_true(testGet('data-01', '01'));
		assert_true(testGet('data-zx81', 'zx81'));
		assert_true(testGet('data-i4770k', 'i4770k'));
		assert_true(testGet('data-r-7', 'r-7'));
		assert_true(testGet('data-r-7-k', 'r-7K'));
		assert_equals(document.body.dataset.nonExisting, undefined);
	},'This tests Get function');

	test (function() {
		var e = getTestElement();
		e.setAttribute('data-Foo', 'value');
		// HTML lowercases all attributes whereas SVG does not.
		if (e instanceof HTMLElement)
			assert_true(e.dataset['foo'] == "value");
		else
			assert_true(e.dataset['Foo'] == "value");
	}, 'This tests case sensitive scenario');

	function testIsUndefined(attr, prop)
	{
	    var e = getTestElement();
	    e.setAttribute(attr, "value");
	    return e.dataset[prop] === undefined;
	}

	test (function() {
		assert_true(testIsUndefined('data-022', '22'));
		assert_true(testIsUndefined('data-22', '022'));
	},'Tests Undefined');

	function matchesNothingInDataset(attr)
	{
	    var e = getTestElement();
	    e.setAttribute(attr, "value");

	    var count = 0;
	    for (var item in e.dataset)
	        count++;
	    return count == 0;
	}

	test (function() {
		assert_true(matchesNothingInDataset('dataFoo'));
	},'Tests matchesNothingInDataset');

	function testSet(prop, expected)
	{
	    var e = getTestElement();
	    e.dataset[prop] = "value";
	    return e.getAttribute(expected) == "value";
	}

	test (function() {
		assert_true(testSet('foo', 'data-foo'));
		assert_true(testSet('fooBar', 'data-foo-bar'));
		assert_true(testSet('-', 'data--'));
		assert_true(testSet('Foo', 'data--foo'));
		assert_true(testSet('-Foo', 'data---foo'));
		assert_true(testSet('', 'data-'));
		assert_true(testSet('\xE0', 'data-\xE0'));
		assert_true(testSet('32', 'data-32'));
		assert_true(testSet('0032', 'data-0032'));
		assert_true(testSet('i18n', 'data-i18n'));
		assert_true(testSet('d2', 'data-d2'));
		assert_true(testSet('2d', 'data-2d'));
		assert_true(testSet('d-2', 'data-d-2'));
		assert_true(testSet('A--S', 'data--a---s'));
		assert_throws_dom("SyntaxError", function() { testSet('-foo', 'dummy'); }, '"SyntaxError: Failed to set the \'-foo\' property on \'DOMStringMap\': \'-foo\' is not a valid property name."');
		assert_throws_dom("InvalidCharacterError", function() { testSet('foo\x20', 'dummy'); }, '"InvalidCharacterError: Failed to set the \'foo\x20\' property on \'DOMStringMap\': \'data-foo\x20\' is not a valid attribute name."');
		assert_throws_dom("InvalidCharacterError", function() { testSet('foo\uF900', 'dummy'); }, '"InvalidCharacterError: Failed to set the \'foo\uF900\' property on \'DOMStringMap\': \'data-foo\uF900\' is not a valid attribute name."');
	},'Tests Set');

	function testIsNull(prop, attr)
	{
	    var e = getTestElement();
	    e.dataset[prop] = "value";
	    return e.getAttribute(attr) === null;
	}

	test (function() {
		assert_true(testIsNull('0123', 'data-123'));
		assert_true(testIsNull('123', 'data-0123'));
	},'Tests Is Null');

	function testDelete(attr, prop)
	{
	    var e = getTestElement();
	    e.setAttribute(attr, "value");
	    delete e.dataset[prop];
	    return e.getAttribute(attr) != "value";
	}

	test (function() {
		assert_true(testDelete('data-foo', 'foo'));
		assert_true(testDelete('data-foo-bar', 'fooBar'));
		assert_true(testDelete('data--', '-'));
		assert_true(testDelete('data--foo', 'Foo'));
		assert_true(testDelete('data---foo', '-Foo'));
		assert_true(testDelete('data-', ''));
		assert_true(testDelete('data-\xE0', '\xE0'));
		assert_true(testDelete('data-33', '33'));
		assert_true(testDelete('data-00033', '00033'));
		assert_true(testDelete('data-r2', 'r2'));
		assert_true(testDelete('data-2r', '2r'));
		assert_true(testDelete('data-r-2', 'r-2'));
		assert_true(testDelete('data--r-2-', 'R-2-'));
		assert_true(testDelete('data--r-2r', 'R-2r'));
		assert_true(testDelete('data--r-2-----r', 'R-2----R'));
		assert_false(testDelete('dummy', '-foo'));
	},'Tests Delete');

	// The (HTML/SVG)Element.dataset deleter is only applied to properties
	// that are present; check that any underlying native property
	// is deleted instead.
	function testNativeDelete(prop, isConfigurable)
	{
	    var e = getTestElement();
	    Object.defineProperty(e.dataset, prop, {configurable: isConfigurable, value: "native_value"});
	    delete e.dataset[prop];
	    return isConfigurable ? !(prop in e.dataset) : (e.dataset[prop] === "native_value");
	}

	test (function() {
		// TODO(jochen): Reenable this once it behaves correctly
		//assert_true(testNativeDelete('-r-2-', false));
		assert_true(testNativeDelete('foo', true));
	},'Tests Native Delete');

	function testForIn(array)
	{
	    var e = getTestElement();

	    for (var i = 0; i < array.length; ++i) {
	        e.setAttribute(array[i], "value");
	    }

	    var count = 0;
	    for (var item in e.dataset)
	        count++;

	    return count;
	}

	test (function() {
		assert_equals(testForIn(['data-foo', 'data-bar', 'data-baz']), 3);
		assert_equals(testForIn(['data-foo', 'data-bar', 'dataFoo']), 2);
		assert_equals(testForIn(['data-foo', 'data-bar', 'style']), 2);
		assert_equals(testForIn(['data-foo', 'data-bar', 'data-']), 3);
		assert_equals(testForIn(['data-foo', 'data-bar', 'data-43']), 3);
		assert_equals(testForIn(['data-foo', 'data-oric1', 'data-bar']), 3);
		assert_equals(testForIn(['data-foo', 'data-oric-1', 'data-bar']), 3);
		assert_equals(testForIn(['data-foo', 'data-oric-1x', 'data-bar']), 3);
	},'Tests For In');

	test (function() {
		var e = getTestElement();
		e.dataset.foo = null;
		assert_equals(e.dataset.foo, 'null');
	},'Set null');
}

function testDatasetPropertyOverride(getTestElement) {
	var e = getTestElement();

	// If the Object prototype already has "foo", dataset doesnot create the corresponding attribute for foo
	Object.prototype.foo = 'on Object';
	assert_equals(e.dataset.foo, 'on Object');
	e.dataset['foo'] = 'on dataset';
	assert_equals(e.dataset.foo, 'on dataset');
	assert_true(e.hasAttribute('data-foo'));
	e.setAttribute('data-foo', 'attr');
	assert_equals(e.dataset.foo, 'attr');

	// Update the JavaScript property
	e.dataset.foo = 'updated';
	assert_equals(e.dataset.foo, 'updated');
	assert_equals(e.getAttribute('data-foo'), 'updated');

	// "Bar" can't be represented as a data- attribute.
	e.dataset.Bar = 'on dataset';
	assert_equals(e.dataset.Bar, 'on dataset');
	assert_false(e.hasAttribute('data-Bar'));

	// Make the JavaScript property empty
	e.dataset.foo = '';
	assert_equals(e.dataset.foo, '');
	assert_equals(e.getAttribute('data-foo'), '');

	// Remove the attribute
	e.removeAttribute('data-foo');
	assert_equals(e.dataset.foo, 'on Object');

	// Remove the JavaScript property
	e.setAttribute('data-foo', 'attr');
	delete e.dataset.foo;
	assert_equals(e.dataset.foo, 'on Object');
	assert_false(e.hasAttribute('foo'));
	delete e.dataset.Bar;
	assert_equals(e.dataset.Bar, undefined);
	Object.prototype[11] = 'on Object';
	assert_equals(e.dataset[11], 'on Object');
	e.dataset['11'] = 'on dataset';
	assert_equals(e.dataset[11], 'on dataset');
	assert_true(e.hasAttribute('data-11'));
	e.setAttribute('data-11', 'attr');
	assert_equals(e.dataset[11], 'attr');

	// Update the JavaScript property
	e.dataset[11] = 'updated';
	assert_equals(e.dataset[11], 'updated');
	assert_equals(e.getAttribute('data-11'), 'updated');

	Object.prototype['a500'] = 'on Object';
	assert_equals(e.dataset['a500'], 'on Object');
	e.dataset['a500'] = 'on dataset';
	assert_equals(e.dataset['a500'], 'on dataset');
	assert_true(e.hasAttribute('data-a500'));
	e.setAttribute('data-a500', 'attr');
	assert_equals(e.dataset['a500'], 'attr');

	// Update the JavaScript property
	e.dataset['a500'] = 'updated';
	assert_equals(e.dataset['a500'], 'updated');
	assert_equals(e.getAttribute('data-a500'), 'updated');
	Object.prototype['a-500k'] = 'on Object';
	assert_equals(e.dataset['a-500k'], 'on Object');
	e.dataset['a-500k'] = 'on dataset';
	assert_equals(e.dataset['a-500k'], 'on dataset');
	assert_true(e.hasAttribute('data-a-500k'));
	e.setAttribute('data-a-500k', 'attr');
	assert_equals(e.dataset['a-500k'], 'attr');

	// Update the JavaScript property
	e.dataset['a-500k'] = 'updated';
	assert_equals(e.dataset['a-500k'], 'updated');
	assert_equals(e.getAttribute('data-a-500k'), 'updated');
}

var svgNS = "http://www.w3.org/2000/svg";
testDataset(function() { return document.createElement("div"); });
testDataset(function() { return document.createElementNS(svgNS, "circle"); });
testDatasetPropertyOverride(function() { return document.createElement("div"); });
testDatasetPropertyOverride(function() { return document.createElementNS(svgNS, "circle"); });
</script>
</body>


text:
<?xml version="1.0"?>

<iati-organisations version="xx">

  <iati-organisation xmlns:example-namespace="http://example.org/example-namespace/ns#"><!-- Include namespace declaration. -->
    <organisation-identifier>12345</organisation-identifier>
    <name>
      <narrative>Name here</narrative>
    </name>
    <reporting-org type="xx" ref="xx">
      <narrative>Organisation name</narrative>
    </reporting-org>
    <document-link url="xx" format="xx">
      <title>
        <narrative>Sample text</narrative>
      </title>
      <description example-namespace:namespace-attribute="xx"><!-- PASS: Optional description element added with required child element. -->
        <narrative>Sample text</narrative>
      </description>
      <category code="xx"/>
    </document-link>
  </iati-organisation>

</iati-organisations>

redpajama_set_name: RedPajamaGithub


text:
lastmod: 2015-01-27
date: 2014-02-27T20:35:00Z
description: Kieran Healy's Website
license: ""
licenseLink: ""
sitelink: http://kieranhealy.org/
sourceLink: https://github.com/kjhealy/kieranhealy.hugo
tags:
- personal
- blog
- academic
thumbnail: /img/kjhealy-tn.jpg
title: Kieran Healy
---


text:
from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: lightsail
short_description: Create or delete a virtual machine instance in AWS Lightsail
description:
     - Creates or instances in AWS Lightsail and optionally wait for it to be 'running'.
version_added: "2.4"
author: "Nick Ball (@nickball)"
options:
  state:
    description:
      - Indicate desired state of the target.
    default: present
    choices: ['present', 'absent', 'running', 'restarted', 'stopped']
  name:
    description:
      - Name of the instance
    required: true
  zone:
    description:
      - AWS availability zone in which to launch the instance. Required when state='present'
  blueprint_id:
    description:
      - ID of the instance blueprint image. Required when state='present'
  bundle_id:
    description:
      - Bundle of specification info for the instance. Required when state='present'
  user_data:
    description:
      - Launch script that can configure the instance with additional data
  key_pair_name:
    description:
      - Name of the key pair to use with the instance
  wait:
    description:
      - Wait for the instance to be in state 'running' before returning.  If wait is "no" an ip_address may not be returned
    type: bool
    default: 'yes'
  wait_timeout:
    description:
      - How long before wait gives up, in seconds.
    default: 300

requirements:
  - "python >= 2.6"
  - boto3

extends_documentation_fragment:
  - aws
  - ec2
'''

EXAMPLES = '''
# Create a new Lightsail instance, register the instance details
- lightsail:
    state: present
    name: myinstance
    region: us-east-1
    zone: us-east-1a
    blueprint_id: ubuntu_16_04
    bundle_id: nano_1_0
    key_pair_name: id_rsa
    user_data: " echo 'hello world' > /home/ubuntu/test.txt"
    wait_timeout: 500
  register: my_instance

- debug:
    msg: "Name is {{ my_instance.instance.name }}"

- debug:
    msg: "IP is {{ my_instance.instance.public_ip_address }}"

# Delete an instance if present
- lightsail:
    state: absent
    region: us-east-1
    name: myinstance

'''

RETURN = '''
changed:
  description: if a snapshot has been modified/created
  returned: always
  type: bool
  sample:
    changed: true
instance:
  description: instance data
  returned: always
  type: dict
  sample:
    arn: "arn:aws:lightsail:us-east-1:448830907657:Instance/1fef0175-d6c8-480e-84fa-214f969cda87"
    blueprint_id: "ubuntu_16_04"
    blueprint_name: "Ubuntu"
    bundle_id: "nano_1_0"
    created_at: "2017-03-27T08:38:59.714000-04:00"
    hardware:
      cpu_count: 1
      ram_size_in_gb: 0.5
    is_static_ip: false
    location:
      availability_zone: "us-east-1a"
      region_name: "us-east-1"
    name: "my_instance"
    networking:
      monthly_transfer:
        gb_per_month_allocated: 1024
      ports:
        - access_direction: "inbound"
          access_from: "Anywhere (0.0.0.0/0)"
          access_type: "public"
          common_name: ""
          from_port: 80
          protocol: tcp
          to_port: 80
        - access_direction: "inbound"
          access_from: "Anywhere (0.0.0.0/0)"
          access_type: "public"
          common_name: ""
          from_port: 22
          protocol: tcp
          to_port: 22
    private_ip_address: "172.26.8.14"
    public_ip_address: "34.207.152.202"
    resource_type: "Instance"
    ssh_key_name: "keypair"
    state:
      code: 16
      name: running
    support_code: "588307843083/i-0997c97831ee21e33"
    username: "ubuntu"
'''

import time
import traceback

try:
    import botocore
    HAS_BOTOCORE = True
except ImportError:
    HAS_BOTOCORE = False

try:
    import boto3
except ImportError:
    # will be caught by imported HAS_BOTO3
    pass

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import (ec2_argument_spec, get_aws_connection_info, boto3_conn,
                                      HAS_BOTO3, camel_dict_to_snake_dict)

def create_instance(module, client, instance_name):
    """
    Create an instance

    module: Ansible module object
    client: authenticated lightsail connection object
    instance_name: name of instance to delete

    Returns a dictionary of instance information
    about the new instance.

    """

    changed = False

    # Check if instance already exists
    inst = None
    try:
        inst = _find_instance_info(client, instance_name)
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] != 'NotFoundException':
            module.fail_json(msg='Error finding instance {0}, error: {1}'.format(instance_name, e))

    zone = module.params.get('zone')
    blueprint_id = module.params.get('blueprint_id')
    bundle_id = module.params.get('bundle_id')
    key_pair_name = module.params.get('key_pair_name')
    user_data = module.params.get('user_data')
    user_data = '' if user_data is None else user_data

    resp = None
    if inst is None:
        try:
            resp = client.create_instances(
                instanceNames=[
                    instance_name
                ],
                availabilityZone=zone,
                blueprintId=blueprint_id,
                bundleId=bundle_id,
                userData=user_data,
                keyPairName=key_pair_name,
            )
            resp = resp['operations'][0]
        except botocore.exceptions.ClientError as e:
            module.fail_json(msg='Unable to create instance {0}, error: {1}'.format(instance_name, e))
        changed = True

    inst = _find_instance_info(client, instance_name)

    return (changed, inst)

def delete_instance(module, client, instance_name):
    """
    Terminates an instance

    module: Ansible module object
    client: authenticated lightsail connection object
    instance_name: name of instance to delete

    Returns a dictionary of instance information
    about the instance deleted (pre-deletion).

    If the instance to be deleted is running
    "changed" will be set to False.

    """

    # It looks like deleting removes the instance immediately, nothing to wait for
    wait = module.params.get('wait')
    wait_timeout = int(module.params.get('wait_timeout'))
    wait_max = time.time() + wait_timeout

    changed = False

    inst = None
    try:
        inst = _find_instance_info(client, instance_name)
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] != 'NotFoundException':
            module.fail_json(msg='Error finding instance {0}, error: {1}'.format(instance_name, e))

    # Wait for instance to exit transition state before deleting
    if wait:
        while wait_max > time.time() and inst is not None and inst['state']['name'] in ('pending', 'stopping'):
            try:
                time.sleep(5)
                inst = _find_instance_info(client, instance_name)
            except botocore.exceptions.ClientError as e:
                if e.response['ResponseMetadata']['HTTPStatusCode'] == "403":
                    module.fail_json(msg="Failed to delete instance {0}. Check that you have permissions to perform the operation.".format(instance_name),
                                     exception=traceback.format_exc())
                elif e.response['Error']['Code'] == "RequestExpired":
                    module.fail_json(msg="RequestExpired: Failed to delete instance {0}.".format(instance_name), exception=traceback.format_exc())
                # sleep and retry
                time.sleep(10)

    # Attempt to delete
    if inst is not None:
        while not changed and ((wait and wait_max > time.time()) or (not wait)):
            try:
                client.delete_instance(instanceName=instance_name)
                changed = True
            except botocore.exceptions.ClientError as e:
                module.fail_json(msg='Error deleting instance {0}, error: {1}'.format(instance_name, e))

    # Timed out
    if wait and not changed and wait_max <= time.time():
        module.fail_json(msg="wait for instance delete timeout at %s" % time.asctime())

    return (changed, inst)

def restart_instance(module, client, instance_name):
    """
    Reboot an existing instance

    module: Ansible module object
    client: authenticated lightsail connection object
    instance_name: name of instance to reboot

    Returns a dictionary of instance information
    about the restarted instance

    If the instance was not able to reboot,
    "changed" will be set to False.

    Wait will not apply here as this is an OS-level operation
    """
    wait = module.params.get('wait')
    wait_timeout = int(module.params.get('wait_timeout'))
    wait_max = time.time() + wait_timeout

    changed = False

    inst = None
    try:
        inst = _find_instance_info(client, instance_name)
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] != 'NotFoundException':
            module.fail_json(msg='Error finding instance {0}, error: {1}'.format(instance_name, e))

    # Wait for instance to exit transition state before state change
    if wait:
        while wait_max > time.time() and inst is not None and inst['state']['name'] in ('pending', 'stopping'):
            try:
                time.sleep(5)
                inst = _find_instance_info(client, instance_name)
            except botocore.exceptions.ClientError as e:
                if e.response['ResponseMetadata']['HTTPStatusCode'] == "403":
                    module.fail_json(msg="Failed to restart instance {0}. Check that you have permissions to perform the operation.".format(instance_name),
                                     exception=traceback.format_exc())
                elif e.response['Error']['Code'] == "RequestExpired":
                    module.fail_json(msg="RequestExpired: Failed to restart instance {0}.".format(instance_name), exception=traceback.format_exc())
                time.sleep(3)

    # send reboot
    if inst is not None:
        try:
            client.reboot_instance(instanceName=instance_name)
        except botocore.exceptions.ClientError as e:
            if e.response['Error']['Code'] != 'NotFoundException':
                module.fail_json(msg='Unable to reboot instance {0}, error: {1}'.format(instance_name, e))
        changed = True

    return (changed, inst)

def startstop_instance(module, client, instance_name, state):
    """
    Starts or stops an existing instance

    module: Ansible module object
    client: authenticated lightsail connection object
    instance_name: name of instance to start/stop
    state: Target state ("running" or "stopped")

    Returns a dictionary of instance information
    about the instance started/stopped

    If the instance was not able to state change,
    "changed" will be set to False.

    """
    wait = module.params.get('wait')
    wait_timeout = int(module.params.get('wait_timeout'))
    wait_max = time.time() + wait_timeout

    changed = False

    inst = None
    try:
        inst = _find_instance_info(client, instance_name)
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] != 'NotFoundException':
            module.fail_json(msg='Error finding instance {0}, error: {1}'.format(instance_name, e))

    # Wait for instance to exit transition state before state change
    if wait:
        while wait_max > time.time() and inst is not None and inst['state']['name'] in ('pending', 'stopping'):
            try:
                time.sleep(5)
                inst = _find_instance_info(client, instance_name)
            except botocore.exceptions.ClientError as e:
                if e.response['ResponseMetadata']['HTTPStatusCode'] == "403":
                    module.fail_json(msg="Failed to start/stop instance {0}. Check that you have permissions to perform the operation".format(instance_name),
                                     exception=traceback.format_exc())
                elif e.response['Error']['Code'] == "RequestExpired":
                    module.fail_json(msg="RequestExpired: Failed to start/stop instance {0}.".format(instance_name), exception=traceback.format_exc())
                time.sleep(1)

    # Try state change
    if inst is not None and inst['state']['name'] != state:
        try:
            if state == 'running':
                client.start_instance(instanceName=instance_name)
            else:
                client.stop_instance(instanceName=instance_name)
        except botocore.exceptions.ClientError as e:
            module.fail_json(msg='Unable to change state for instance {0}, error: {1}'.format(instance_name, e))
        changed = True
        # Grab current instance info
        inst = _find_instance_info(client, instance_name)

    return (changed, inst)

def core(module):
    region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
    if not region:
        module.fail_json(msg='region must be specified')

    client = None
    try:
        client = boto3_conn(module, conn_type='client', resource='lightsail',
                            region=region, endpoint=ec2_url, **aws_connect_kwargs)
    except (botocore.exceptions.ClientError, botocore.exceptions.ValidationError) as e:
        module.fail_json(msg='Failed while connecting to the lightsail service: %s' % e, exception=traceback.format_exc())

    changed = False
    state = module.params['state']
    name = module.params['name']

    if state == 'absent':
        changed, instance_dict = delete_instance(module, client, name)
    elif state in ('running', 'stopped'):
        changed, instance_dict = startstop_instance(module, client, name, state)
    elif state == 'restarted':
        changed, instance_dict = restart_instance(module, client, name)
    elif state == 'present':
        changed, instance_dict = create_instance(module, client, name)

    module.exit_json(changed=changed, instance=camel_dict_to_snake_dict(instance_dict))

def _find_instance_info(client, instance_name):
    ''' handle exceptions where this function is called '''
    inst = None
    try:
        inst = client.get_instance(instanceName=instance_name)
    except botocore.exceptions.ClientError as e:
        raise
    return inst['instance']

def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(
        name=dict(type='str', required=True),
        state=dict(type='str', default='present', choices=['present', 'absent', 'stopped', 'running', 'restarted']),
        zone=dict(type='str'),
        blueprint_id=dict(type='str'),
        bundle_id=dict(type='str'),
        key_pair_name=dict(type='str'),
        user_data=dict(type='str'),
        wait=dict(type='bool', default=True),
        wait_timeout=dict(default=300, type='int'),
    ))

    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO3:
        module.fail_json(msg='Python module "boto3" is missing, please install it')

    if not HAS_BOTOCORE:
        module.fail_json(msg='Python module "botocore" is missing, please install it')

    try:
        core(module)
    except (botocore.exceptions.ClientError, Exception) as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())

if __name__ == '__main__':
    main()


text:
layout: page
title: Yates Tech Seminar
date: 2016-05-24
author: Bobby Holden
tags: weekly links, java
status: published
summary: Nam pellentesque mauris et ultricies viverra. Vestibulum vitae orci.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 09/23/2017
  endDate: 09/25/2017
  ctyhocn: PNSFLHX
  groupCode: YTS
published: true
---
Sed et magna at ipsum lacinia egestas ut vitae diam. Sed a congue odio. Sed fermentum eu ligula id iaculis. Aliquam non felis tellus. Ut imperdiet, magna eu imperdiet dictum, augue dui dignissim libero, quis dignissim risus ipsum et ligula. Morbi sed interdum massa, quis efficitur lacus. Phasellus eget ex id nibh pharetra luctus sed non arcu.

* Maecenas vehicula felis id varius condimentum
* Maecenas sed magna blandit, lobortis dui id, porta ipsum
* Sed vitae ex id elit vehicula consectetur.

In consequat maximus justo, at efficitur elit efficitur non. Proin vitae tincidunt risus, ut accumsan mi. Suspendisse et ornare odio. Donec a aliquam est, eget elementum nunc. Quisque et malesuada risus, quis posuere magna. Etiam eu congue nunc. Nulla at quam vitae sapien facilisis vulputate. In quis ligula semper, mattis metus quis, egestas diam. Aenean gravida justo vitae libero condimentum, eu pellentesque nulla commodo. Nulla id purus nulla. Nunc at pulvinar libero, vel finibus ligula. Pellentesque cursus tempus justo, tristique viverra nisl vehicula eget.


text:
<application>
  <component name="EditorSettings">
    <option name="USE_SOFT_WRAPS" value="" />
    <option name="IS_WHEEL_FONTCHANGE_ENABLED" value="true" />
  </component>
</application>


text:
require 'spec_helper'

describe 'IAM policies, profiles and roles' do
  let(:region) { vars.region }
  let(:deployment_identifier) { vars.deployment_identifier }
  let(:search_accounts) { vars.search_accounts }
  let(:peering_role_name) { vars.peering_role_name }
  let(:role_arn) { output_for(:harness, 'lambda_role_arn') }

  context 'vpc auto peering lambda role' do
    subject {
      iam_role(role_arn)
    }

    it {should exist}

    it 'can be assumed by lambda' do
      actual = JSON.parse(
          URI.decode(subject.assume_role_policy_document),
          symbolize_names: true)
      expected = {
          Version: "2012-10-17",
          Statement: [
              {
                  Sid: "",
                  Effect: "Allow",
                  Action: "sts:AssumeRole",
                  Principal: {
                      Service: "lambda.amazonaws.com"
                  }
              }
          ]
      }

      expect(actual).to(eq(expected))
    end

    it 'allows log creation' do
      expect(subject).to(be_allowed_action('logs:CreateLogStream'))
      expect(subject).to(be_allowed_action('logs:CreateLogGroup'))
      expect(subject).to(be_allowed_action('logs:PutLogEvents'))
    end

    it 'allows only assumable roles to be assumed' do
      search_accounts.each do |search_account|
        expect(subject)
            .to(be_allowed_action('sts:AssumeRole')
                .resource_arn(
                    "arn:aws:iam::#{search_account}:role/#{peering_role_name}"))
      end
      expect(subject)
          .not_to(be_allowed_action('sts:AssumeRole')
                .resource_arn('arn:aws:iam::176145454894:role/other-role'))
    end

    it 'allows the caller identity to be fetched' do
      expect(subject).to(be_allowed_action('sts:GetCallerIdentity'))
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:orientation="horizontal"
	android:gravity="center_vertical" >
	<LinearLayout android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:orientation="horizontal">
	    <ImageView android:layout_width="wrap_content"
		    android:layout_height="wrap_content"
		    android:src="@drawable/icon_notification">
	    </ImageView>
	    <TextView  android:layout_width="wrap_content"
		    android:layout_height="fill_parent"
		    android:layout_marginLeft="12sp"
		    android:text="@string/label_ongoing"
		    android:textStyle="bold"
		    android:textSize="15dip"
		    android:textColor="#FF000000">
	    </TextView>"
	</LinearLayout>
	<TextView
		 android:layout_width="fill_parent"
		 android:layout_height="fill_parent"
		 android:layout_marginLeft="12sp"
		 android:text="@string/label_ongoing"
		 android:gravity="center_vertical"
		 android:textStyle="bold"
		 android:textSize="15dip"
		 android:textColor="#FF000000">
	 </TextView>
</LinearLayout>


text:
export USER=$(whoami)

echo "--------- profile LOAD" 1>&2
echo "--------- profile LOAD"
source /etc/profile
echo "--------- modules.sh LOAD" 1>&2
echo "--------- modules.sh LOAD"
source /etc/profile.d/modules.sh

module load tools/python/2.7.9 intel/studio/2015.1.133 apps/specfem3d/2.0.2 tools/ffmpeg

unzip vercepes

PROV="provfold"$(cat control)
MODEL="modelfold"$(cat control)

mkdir -p $HOME/$PROV

export RUN_ID=$(cat control)

export DISPLAY=localhost:38.0
HOSTN=draco-ext.scai.fraunhofer.de
SOURCE_BASE=""
MYMPIEXEC_CMD_PAR_MOV="-np $(( $PBS_NUM_NODES * 4 )) -perhost 4 -f $PBS_NODEFILE"
echo $MYMPIEXEC_CMD_PAR_MOV
echo  -------------------------------------------------------
export RUN_PATH=$(pwd)
export PROV_PATH=$HOME/$PROV/

#$RUN_PATH/verce-hpc-pe/src/prov-files/

cp d4pywf $RUN_PATH/verce-hpc-pe/src/d4pywf.py

cd $RUN_PATH/verce-hpc-pe/src/
mpiexec.hydra python -m dispel4py.new.processor mpi d4pywf -f $RUN_PATH/input
#python -m dispel4py.new.processor multi  test.hpc.forwardsim.postproc_graph -n 50

echo "--- terminates PROV job -- "
touch $HOME/$PROV/exitf


text:
class UserWithLegacy
  include ActiveModel::Validations

  attr_accessor :email_address

  validates_email :email_address, :allow_blank => true, :message => "is just wrong!"
end


text:
<?php

namespace YoastSEO_Vendor\Psr\Log;

/**
 * This is a simple Logger trait that classes unable to extend AbstractLogger
 * (because they extend another class, etc) can include.
 *
 * It simply delegates all log-level-specific methods to the `log` method to
 * reduce boilerplate code that a simple Logger that does the same thing with
 * messages regardless of the error level has to implement.
 */
trait LoggerTrait
{
    /**
     * System is unusable.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function emergency($message, array $context = array())
    {
        $this->log(\YoastSEO_Vendor\Psr\Log\LogLevel::EMERGENCY, $message, $context);
    }
    /**
     * Action must be taken immediately.
     *
     * Example: Entire website down, database unavailable, etc. This should
     * trigger the SMS alerts and wake you up.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function alert($message, array $context = array())
    {
        $this->log(\YoastSEO_Vendor\Psr\Log\LogLevel::ALERT, $message, $context);
    }
    /**
     * Critical conditions.
     *
     * Example: Application component unavailable, unexpected exception.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function critical($message, array $context = array())
    {
        $this->log(\YoastSEO_Vendor\Psr\Log\LogLevel::CRITICAL, $message, $context);
    }
    /**
     * Runtime errors that do not require immediate action but should typically
     * be logged and monitored.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function error($message, array $context = array())
    {
        $this->log(\YoastSEO_Vendor\Psr\Log\LogLevel::ERROR, $message, $context);
    }
    /**
     * Exceptional occurrences that are not errors.
     *
     * Example: Use of deprecated APIs, poor use of an API, undesirable things
     * that are not necessarily wrong.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function warning($message, array $context = array())
    {
        $this->log(\YoastSEO_Vendor\Psr\Log\LogLevel::WARNING, $message, $context);
    }
    /**
     * Normal but significant events.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function notice($message, array $context = array())
    {
        $this->log(\YoastSEO_Vendor\Psr\Log\LogLevel::NOTICE, $message, $context);
    }
    /**
     * Interesting events.
     *
     * Example: User logs in, SQL logs.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function info($message, array $context = array())
    {
        $this->log(\YoastSEO_Vendor\Psr\Log\LogLevel::INFO, $message, $context);
    }
    /**
     * Detailed debug information.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function debug($message, array $context = array())
    {
        $this->log(\YoastSEO_Vendor\Psr\Log\LogLevel::DEBUG, $message, $context);
    }
    /**
     * Logs with an arbitrary level.
     *
     * @param mixed  $level
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public abstract function log($level, $message, array $context = array());
}


text:
require_relative 'smell_detector'
require_relative 'smell_warning'

module Reek
  module Smells
    #
    # An Uncommunicative Name is a name that doesn't communicate its intent
    # well enough.
    #
    # Poor names make it hard for the reader to build a mental picture
    # of what's going on in the code. They can also be mis-interpreted;
    # and they hurt the flow of reading, because the reader must slow
    # down to interpret the names.
    #
    # Currently +UncommunicativeParameterName+ checks for
    # * 1-character names
    # * names ending with a number
    #
    # See {file:docs/Uncommunicative-Parameter-Name.md} for details.
    class UncommunicativeParameterName < SmellDetector
      REJECT_KEY = 'reject'
      DEFAULT_REJECT_PATTERNS = [/^.$/, /[0-9]$/, /[A-Z]/, /^_/]

      ACCEPT_KEY = 'accept'
      DEFAULT_ACCEPT_NAMES = []

      def self.smell_category
        'UncommunicativeName'
      end

      def self.default_config
        super.merge(
          REJECT_KEY => DEFAULT_REJECT_PATTERNS,
          ACCEPT_KEY => DEFAULT_ACCEPT_NAMES
        )
      end

      #
      # Checks the given +context+ for uncommunicative names.
      #
      # @return [Array<SmellWarning>]
      #
      def inspect(context)
        expression = context.exp
        expression.parameter_names.select do |name|
          sanitized_name = sanitize name
          uncommunicative_parameter_name?(name: sanitized_name, context: context)
        end.map do |name|
          smell_warning(
            context: context,
            lines: [expression.line],
            message: "has the parameter name '#{name}'",
            parameters: { name: name.to_s })
        end
      end

      private

      def uncommunicative_parameter_name?(name: raise, context: raise)
        !acceptable_name?(name: name, context: context) && context.uses_param?(name)
      end

      def acceptable_name?(name: raise, context: raise)
        accept_names(context).any? { |accept_name| name == accept_name } ||
          reject_patterns(context).none? { |pattern| name.match pattern }
      end

      def reject_patterns(context)
        value(REJECT_KEY, context, DEFAULT_REJECT_PATTERNS)
      end

      def accept_names(context)
        value(ACCEPT_KEY, context, DEFAULT_ACCEPT_NAMES)
      end

      # :reek:UtilityFunction
      def sanitize(name)
        name.to_s.gsub(/^[@\*\&]*/, '')
      end
    end
  end
end


text:
<?php
namespace ShortUrl;

use Guzzle\Http\Client;

class AbstractShortUrl
{
    /**
     * @var Client
     */
    private $client;

    /**
     * @var string
     */
    private $url;

    public function __construct()
    {
        $this->client = new Client();
    }

    /**
     * @return Client
     */
    protected function getClient()
    {
        return $this->client;
    }

    /**
     * @return mixed
     */
    protected function getUrl()
    {
        return $this->url;
    }

    /**
     * @param mixed $url
     */
    protected function setUrl($url)
    {
        $this->url = $url;
    }

}


text:
<?php

declare(strict_types=1);

namespace Gedmo\Tests\Blameable\Fixture\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
#[ORM\Entity]
class Type
{
    /**
     * @var int|null
     *
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: Types::INTEGER)]
    private $id;

    /**
     * @var string|null
     *
     * @ORM\Column(name="title", type="string", length=128)
     */
    #[ORM\Column(name: 'title', type: Types::STRING, length: 128)]
    private $title;

    /**
     * @var Collection<int, Article>
     *
     * @ORM\OneToMany(targetEntity="Article", mappedBy="type")
     */
    #[ORM\OneToMany(targetEntity: Article::class, mappedBy: 'type')]
    private $articles;

    public function __construct()
    {
        $this->articles = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function setTitle(?string $title): void
    {
        $this->title = $title;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }
}


text:
<?php

namespace Drupal\rest\Tests;

use Drupal\Core\Session\AccountInterface;
use Drupal\rest\RestResourceConfigInterface;
use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;

/**
 * Tests the structure of a REST resource.
 *
 * @group rest
 */
class ResourceTest extends RESTTestBase {

  /**
   * Modules to install.
   *
   * @var array
   */
  public static $modules = ['hal', 'rest', 'entity_test', 'rest_test'];

  /**
   * The entity.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   */
  protected $entity;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    // Create an entity programmatic.
    $this->entity = $this->entityCreate('entity_test');
    $this->entity->save();

    Role::load(AccountInterface::ANONYMOUS_ROLE)
      ->grantPermission('view test entity')
      ->save();
  }

  /**
   * Tests that a resource without formats cannot be enabled.
   */
  public function testFormats() {
    $this->resourceConfigStorage->create([
      'id' => 'entity.entity_test',
      'granularity' => RestResourceConfigInterface::METHOD_GRANULARITY,
      'configuration' => [
        'GET' => [
          'supported_auth' => [
            'basic_auth',
          ],
        ],
      ],
    ])->save();

    // Verify that accessing the resource returns 406.
    $response = $this->httpRequest($this->entity->urlInfo()->setRouteParameter('_format', $this->defaultFormat), 'GET');
    // \Drupal\Core\Routing\RequestFormatRouteFilter considers the canonical,
    // non-REST route a match, but a lower quality one: no format restrictions
    // means there's always a match and hence when there is no matching REST
    // route, the non-REST route is used, but can't render into
    // application/hal+json, so it returns a 406.
    $this->assertResponse('406', 'HTTP response code is 406 when the resource does not define formats, because it falls back to the canonical, non-REST route.');
    $this->curlClose();
  }

  /**
   * Tests that a resource without authentication cannot be enabled.
   */
  public function testAuthentication() {
    $this->resourceConfigStorage->create([
      'id' => 'entity.entity_test',
      'granularity' => RestResourceConfigInterface::METHOD_GRANULARITY,
      'configuration' => [
        'GET' => [
          'supported_formats' => [
            'hal_json',
          ],
        ],
      ],
    ])->save();

    // Verify that accessing the resource returns 401.
    $response = $this->httpRequest($this->entity->urlInfo()->setRouteParameter('_format', $this->defaultFormat), 'GET');
    // \Drupal\Core\Routing\RequestFormatRouteFilter considers the canonical,
    // non-REST route a match, but a lower quality one: no format restrictions
    // means there's always a match and hence when there is no matching REST
    // route, the non-REST route is used, but can't render into
    // application/hal+json, so it returns a 406.
    $this->assertResponse('406', 'HTTP response code is 406 when the resource does not define formats, because it falls back to the canonical, non-REST route.');
    $this->curlClose();
  }

  /**
   * Tests that serialization_class is optional.
   */
  public function testSerializationClassIsOptional() {
    $this->enableService('serialization_test', 'POST', 'json');

    Role::load(RoleInterface::ANONYMOUS_ID)
      ->grantPermission('restful post serialization_test')
      ->save();

    $serialized = $this->container->get('serializer')->serialize(['foo', 'bar'], 'json');
    $this->httpRequest('serialization_test', 'POST', $serialized, 'application/json');
    $this->assertResponse(200);
    $this->assertResponseBody('["foo","bar"]');
  }

  /**
   * Tests that resource URI paths are formatted properly.
   */
  public function testUriPaths() {
    $this->enableService('entity:entity_test');
    /** @var \Drupal\rest\Plugin\Type\ResourcePluginManager $manager */
    $manager = \Drupal::service('plugin.manager.rest');

    foreach ($manager->getDefinitions() as $resource => $definition) {
      foreach ($definition['uri_paths'] as $key => $uri_path) {
        $this->assertFalse(strpos($uri_path, '//'), 'The resource URI path does not have duplicate slashes.');
      }
    }
  }

}


text: Based Ubuntu environment for Oncoscape (https://github.com/FredHutch/Oncoscape)


text:
namespace CentaurFactory.ExcelModel
{
    using System;
    using System.Text;

    public class DeliveryInfo
    {
        public int ProductId { get; set; }

        public int Quantity { get; set; }

        public decimal PricePerUnit { get; set; }

        public int Month { get; set; }

        public int Year { get; set; }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("ProductId {0}\n", this.ProductId);
            sb.AppendFormat("Quantity {0}\n", this.Quantity);
            sb.AppendFormat("PricePerUnit {0}\n", this.PricePerUnit);
            sb.AppendFormat("Month {0}\n", this.Month);
            sb.AppendFormat("Year {0}\n", this.Year);

            return sb.ToString();
        }
    }
}


text:
import logging
log = logging.getLogger(__name__)

import functools
from glob import glob
import json
import shutil
from pathlib import Path
import os.path

import bcolz
import numpy as np
import pandas as pd
from scipy import signal

from . import Signal

# Max size of LRU cache
MAXSIZE = 1024

def repair_carray_size(path):
    chunk_wildcard = os.path.join(path, 'data', '*.blp')
    sizes_filename = os.path.join(path, 'meta', 'sizes')
    storage_filename = os.path.join(path, 'meta', 'storage')

    with open(sizes_filename, 'r') as fh:
        sizes = json.load(fh)

    with open(storage_filename, 'r') as fh:
        storage = json.load(fh)

    if sizes['shape'] != [0]:
        raise ValueError('Data seems fine')

    chunklen = storage['chunklen']
    n_chunks = len(glob(chunk_wildcard))
    sizes['shape'] = [n_chunks * chunklen]

    # Backup the file before overwriting.
    shutil.copy(sizes_filename, sizes_filename + '.old')
    with open(sizes_filename, 'w') as fh:
        json.dump(sizes, fh)

def load_ctable_as_df(path, decode=True, archive=True):
    csv_path = f'{path}.csv'
    if os.path.exists(csv_path):
        return pd.io.parsers.read_csv(csv_path)
    table = bcolz.ctable(rootdir=path)
    df = table.todataframe()
    if decode:
        for c in table.cols:
            if table[c].dtype.char == 'S':
                df[c] = df[c].str.decode('utf8')

    if archive:
        df.to_csv(csv_path, index=False)
    return df

class BcolzSignal(Signal):

    def __init__(self, base_path):
        self.base_path = base_path

    @property
    @functools.lru_cache()
    def array(self):
        return bcolz.carray(rootdir=self.base_path)

    @property
    def fs(self):
        return self.array.attrs['fs']

    @property
    def duration(self):
        return self.array.shape[-1]/self.fs

    def __getitem__(self, slice):
        return self.array[slice]

    @property
    def shape(self):
        return self.array.shape


text:
package monitor

import (
	"context"
	"fmt"
	"strings"
	"time"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/tools/cache"

	configv1 "github.com/openshift/api/config/v1"
	configclientset "github.com/openshift/client-go/config/clientset/versioned"
)

func startClusterOperatorMonitoring(ctx context.Context, m Recorder, client configclientset.Interface) {
	coInformer := cache.NewSharedIndexInformer(
		NewErrorRecordingListWatcher(m, &cache.ListWatch{
			ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
				return client.ConfigV1().ClusterOperators().List(options)
			},
			WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
				return client.ConfigV1().ClusterOperators().Watch(options)
			},
		}),
		&configv1.ClusterOperator{},
		time.Hour,
		nil,
	)

	coChangeFns := []func(co, oldCO *configv1.ClusterOperator) []Condition{
		func(co, oldCO *configv1.ClusterOperator) []Condition {
			var conditions []Condition
			for i := range co.Status.Conditions {
				s := &co.Status.Conditions[i]
				previous := findOperatorStatusCondition(oldCO.Status.Conditions, s.Type)
				if previous == nil {
					continue
				}
				if s.Status != previous.Status {
					var msg string
					switch {
					case len(s.Reason) > 0 && len(s.Message) > 0:
						msg = fmt.Sprintf("changed %s to %s: %s: %s", s.Type, s.Status, s.Reason, s.Message)
					case len(s.Message) > 0:
						msg = fmt.Sprintf("changed %s to %s: %s", s.Type, s.Status, s.Message)
					default:
						msg = fmt.Sprintf("changed %s to %s", s.Type, s.Status)
					}
					level := Warning
					if s.Type == configv1.OperatorDegraded && s.Status == configv1.ConditionTrue {
						level = Error
					}
					if s.Type == configv1.ClusterStatusConditionType("Failing") && s.Status == configv1.ConditionTrue {
						level = Error
					}
					conditions = append(conditions, Condition{
						Level:   level,
						Locator: locateClusterOperator(co),
						Message: msg,
					})
				}
			}
			if changes := findOperatorVersionChange(oldCO.Status.Versions, co.Status.Versions); len(changes) > 0 {
				conditions = append(conditions, Condition{
					Level:   Info,
					Locator: locateClusterOperator(co),
					Message: fmt.Sprintf("versions: %v", strings.Join(changes, ", ")),
				})
			}
			return conditions
		},
	}

	startTime := time.Now().Add(-time.Minute)
	coInformer.AddEventHandler(
		cache.ResourceEventHandlerFuncs{
			AddFunc: func(obj interface{}) {
				co, ok := obj.(*configv1.ClusterOperator)
				if !ok {
					return
				}
				// filter out old pods so our monitor doesn't send a big chunk
				// of co creations
				if co.CreationTimestamp.Time.Before(startTime) {
					return
				}
				m.Record(Condition{
					Level:   Info,
					Locator: locateClusterOperator(co),
					Message: "created",
				})
			},
			DeleteFunc: func(obj interface{}) {
				co, ok := obj.(*configv1.ClusterOperator)
				if !ok {
					return
				}
				m.Record(Condition{
					Level:   Warning,
					Locator: locateClusterOperator(co),
					Message: "deleted",
				})
			},
			UpdateFunc: func(old, obj interface{}) {
				co, ok := obj.(*configv1.ClusterOperator)
				if !ok {
					return
				}
				oldCO, ok := old.(*configv1.ClusterOperator)
				if !ok {
					return
				}
				if co.UID != oldCO.UID {
					return
				}
				for _, fn := range coChangeFns {
					m.Record(fn(co, oldCO)...)
				}
			},
		},
	)

	go coInformer.Run(ctx.Done())

	cvInformer := cache.NewSharedIndexInformer(
		NewErrorRecordingListWatcher(m, &cache.ListWatch{
			ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
				options.FieldSelector = "metadata.name=version"
				return client.ConfigV1().ClusterVersions().List(options)
			},
			WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
				options.FieldSelector = "metadata.name=version"
				return client.ConfigV1().ClusterVersions().Watch(options)
			},
		}),
		&configv1.ClusterVersion{},
		time.Hour,
		nil,
	)

	cvChangeFns := []func(cv, oldCV *configv1.ClusterVersion) []Condition{
		func(cv, oldCV *configv1.ClusterVersion) []Condition {
			var conditions []Condition
			if len(cv.Status.History) == 0 {
				return nil
			}
			if len(oldCV.Status.History) == 0 {
				conditions = append(conditions, Condition{
					Level:   Warning,
					Locator: locateClusterVersion(cv),
					Message: fmt.Sprintf("cluster converging to %s", cv.Status.History[0].Version),
				})
				return conditions
			}
			cvNew, cvOld := cv.Status.History[0], oldCV.Status.History[0]
			switch {
			case cvNew.State == configv1.CompletedUpdate && cvOld.State != cvNew.State:
				conditions = append(conditions, Condition{
					Level:   Warning,
					Locator: locateClusterVersion(cv),
					Message: fmt.Sprintf("cluster reached %s", cvNew.Version),
				})
			case cvNew.State == configv1.PartialUpdate && cvOld.State == cvNew.State && cvOld.Image != cvNew.Image:
				conditions = append(conditions, Condition{
					Level:   Warning,
					Locator: locateClusterVersion(cv),
					Message: fmt.Sprintf("cluster upgrading to %s without completing %s", cvNew.Version, cvOld.Version),
				})
			}
			return conditions
		},
		func(cv, oldCV *configv1.ClusterVersion) []Condition {
			var conditions []Condition
			for i := range cv.Status.Conditions {
				s := &cv.Status.Conditions[i]
				previous := findOperatorStatusCondition(oldCV.Status.Conditions, s.Type)
				if previous == nil {
					continue
				}
				if s.Status != previous.Status {
					var msg string
					switch {
					case len(s.Reason) > 0 && len(s.Message) > 0:
						msg = fmt.Sprintf("changed %s to %s: %s: %s", s.Type, s.Status, s.Reason, s.Message)
					case len(s.Message) > 0:
						msg = fmt.Sprintf("changed %s to %s: %s", s.Type, s.Status, s.Message)
					default:
						msg = fmt.Sprintf("changed %s to %s", s.Type, s.Status)
					}
					level := Warning
					if s.Type == configv1.OperatorDegraded && s.Status == configv1.ConditionTrue {
						level = Error
					}
					if s.Type == configv1.ClusterStatusConditionType("Failing") && s.Status == configv1.ConditionTrue {
						level = Error
					}
					conditions = append(conditions, Condition{
						Level:   level,
						Locator: locateClusterVersion(cv),
						Message: msg,
					})
				}
			}
			return conditions
		},
	}

	cvInformer.AddEventHandler(
		cache.ResourceEventHandlerFuncs{
			AddFunc: func(obj interface{}) {
				cv, ok := obj.(*configv1.ClusterVersion)
				if !ok {
					return
				}
				// filter out old pods so our monitor doesn't send a big chunk
				// of co creations
				if cv.CreationTimestamp.Time.Before(startTime) {
					return
				}
				m.Record(Condition{
					Level:   Info,
					Locator: locateClusterVersion(cv),
					Message: "created",
				})
			},
			DeleteFunc: func(obj interface{}) {
				cv, ok := obj.(*configv1.ClusterVersion)
				if !ok {
					return
				}
				m.Record(Condition{
					Level:   Warning,
					Locator: locateClusterVersion(cv),
					Message: "deleted",
				})
			},
			UpdateFunc: func(old, obj interface{}) {
				cv, ok := obj.(*configv1.ClusterVersion)
				if !ok {
					return
				}
				oldCV, ok := old.(*configv1.ClusterVersion)
				if !ok {
					return
				}
				if cv.UID != oldCV.UID {
					return
				}
				for _, fn := range cvChangeFns {
					m.Record(fn(cv, oldCV)...)
				}
			},
		},
	)

	m.AddSampler(func(now time.Time) []*Condition {
		var conditions []*Condition
		for _, obj := range cvInformer.GetStore().List() {
			cv, ok := obj.(*configv1.ClusterVersion)
			if !ok {
				continue
			}
			if len(cv.Status.History) > 0 {
				if cv.Status.History[0].State != configv1.CompletedUpdate {
					conditions = append(conditions, &Condition{
						Level:   Warning,
						Locator: locateClusterVersion(cv),
						Message: fmt.Sprintf("cluster is updating to %s", cv.Status.History[0].Version),
					})
				}
			}
		}
		return conditions
	})

	go cvInformer.Run(ctx.Done())
}

func locateClusterOperator(co *configv1.ClusterOperator) string {
	return fmt.Sprintf("clusteroperator/%s", co.Name)
}

func locateClusterVersion(cv *configv1.ClusterVersion) string {
	return fmt.Sprintf("clusterversion/%s", cv.Name)
}

func findOperatorVersionChange(old, new []configv1.OperandVersion) []string {
	var changed []string
	for i := 0; i < len(new); i++ {
		for j := 0; j < len(old); j++ {
			p := (j + i) % len(old)
			if old[p].Name != new[i].Name {
				continue
			}
			if old[p].Version == new[i].Version {
				break
			}
			changed = append(changed, fmt.Sprintf("%s %s -> %s", new[i].Name, old[p].Version, new[i].Version))
			break
		}
	}
	return changed
}

func findOperatorStatusCondition(conditions []configv1.ClusterOperatorStatusCondition, conditionType configv1.ClusterStatusConditionType) *configv1.ClusterOperatorStatusCondition {
	for i := range conditions {
		if conditions[i].Type == conditionType {
			return &conditions[i]
		}
	}
	return nil
}


text:
"""
## Num_Integ.py
# ------------------------- #
# Description:
# A collection of Numerical Methods functions for solving/simulating deterministic and stochastic differential equations.
# ------------------------- #
# Created by: Ashiv Dhondea, RRSG, UCT.
# Date created: 20 June 2016
# Edits: 16 July 2016: added fnRK4_moment used to numerically integrate the moment differential equations for the CD-EKF. removed it.
#        27 July 2016: included the stochastic numerical integration schemes in this file. added references and comments.
#        28 July 2016: changed the arguments for fnRK4_vector. Q and L are included to integrate fnMoment_DE from DynFn.
         28 September 2016: cleaned up the code.
"""
# ------------------------- #
import numpy as np
# ------------------------------------------------------------------------------------------------------------------------------------------#
## References
""" 1. Kloeden, Platen: Numerical Solution of Stochastic Differential Equations.
    @book{kloeden2011numerical,
      title={Numerical Solution of Stochastic Differential Equations},
      author={Kloeden, P.E. and Platen, E.},
      series={Stochastic Modelling and Applied Probability},
      year={1992},
      publisher={Springer Berlin Heidelberg}
    }
    2.Crouse(2015) Basic tracking using nonlinear continuous-time dynamic models [Tutorial]
    @article{crouse2015basic,
      title={Basic tracking using nonlinear continuous-time dynamic models [Tutorial]},
      author={Crouse, David},
      journal={Aerospace and Electronic Systems Magazine, IEEE},
      volume={30},
      number={2},
      pages={4--41},
      year={2015},
      publisher={IEEE}
    }
    3. Burden, Faires (2011) Numerical Analysis
    @book{Burden,
     author = {Burden, Richard L. and Faires, J. Douglas},
     title = {Numerical Analysis},
     year = {2011},
     edition = {9th},
     publisher={Brooks/Cole}
    }
"""
# ------------------------------------------------------------------------------------------------------------------------------------------#
## Deterministic numerical integration
def fnRK4_vector(f, dt, x,t,Q=None,L=None):
    """
    fnRK4_vector implements the Runge-Kutta fourth order method for solving Initial Value Problems.
    f : dynamics function
    dt : fixed stepsize
    x : state vector
    t : current time instant.
    Refer to Burden, Faires (2011) for the RK4 method.
    Edit: 28/7/16: Added Q and L to integrate fnMoment_DE.
    """

    if Q is None: # Assuming L is also None.
        # Execute one RK4 integration step
        k1 = dt*  f(t         ,x         );
        k2 = dt*  f(t + 0.5*dt,x + 0.5*k1);
        k3 = dt*  f(t + 0.5*dt,x + 0.5*k2);
        k4 = dt*  f(t +     dt,x +     k3);
    else:
        # Execute one RK4 integration step
        k1 = dt*  f(t         ,x         ,Q,L);
        k2 = dt*  f(t + 0.5*dt,x + 0.5*k1,Q,L);
        k3 = dt*  f(t + 0.5*dt,x + 0.5*k2,Q,L);
        k4 = dt*  f(t +     dt,x +     k3,Q,L);

    return x + (k1 + 2*k2 + 2*k3 + k4) / 6.0
# -------------------------------------------------------------------------------------------------------------------------------------------#
## Stochastic numerical integration
def fnEuler_Maruyama(x,fnD,timevec,L,Qd):
    """
    fnEuler_Maruyama implements the 0.5 strong Euler-Maruyama scheme. See Sarkka, Solin (2014).
    x : state vector of dimensions dx by 1.
    fnD : nonlinear dynamics function.
    timevec : time vector for simulation duration.
    L : dispersion matrix of dimensions dx by dw.
    Qd : discretized covariance matrix of dimensions dw by dw.
    """
    dt = timevec[1]-timevec[0];
    dx = np.shape(L)[0]; # dimension of state vector.
    dw = np.shape(L)[1]; # dimension of process noise vector
    x_state = np.zeros([dx,len(timevec)],dtype=np.float64);
    x_state[:,0] = x;

    for index in range (1,len(timevec)):
        x_state[:,index] = x_state[:,index-1] + dt*fnD(timevec[index-1],x_state[:,index-1]) + np.dot(L,np.random.multivariate_normal(np.zeros(np.shape(L)[1],dtype=np.float64),Qd));
    return x_state

def fnEuler_Maruyama_test(x,fnD,timevec,L,Qc):
    dt = timevec[1]-timevec[0];
    dx = np.shape(L)[0]; # dimension of state vector.
    dw = np.shape(L)[1]; # dimension of process noise vector
    x_state = np.zeros([dx,len(timevec)],dtype=np.float64);
    x_state[:,0] = x;

    for index in range (1,len(timevec)):
        x_state[:,index] = x_state[:,index-1] + dt*fnD(timevec[index-1],x_state[:,index-1]) + np.dot(np.dot(L,Qc),np.random.multivariate_normal(np.zeros(np.shape(L)[1],dtype=np.float64),dt*np.eye(np.shape(L)[1])));
    return x_state

def fnSRK_Crouse(x,fnD,timevec,L,Qd):
    """
    fnSRK_Crouse implements the 1.5 strong Stochastic Runge-Kutta method in Crouse (2015).
    Note that as opposed to Crouse (2015), we have assumed that the dispersion matrix is constant, i.e. not time-varying
    and definitely not state-dependent.
    x : state vector of dimensions dx by 1.
    fnD : nonlinear dynamics function.
    timevec : time vector for simulation duration.
    L : dispersion matrix of dimensions dx by dw.
    Qd : discretized covariance matrix of dimensions dw by dw.
    Note: 27/07/16: explicit order 1.5 strong scheme in section 11.2 in Kloden, Platen (1992) and Crouse(2015).
    """
    dw = np.shape(L)[1]; # dimension of process noise vector
    dx = np.shape(L)[0]; # dimension of state vector.

    x_state = np.zeros([dx,len(timevec)],dtype=np.float64);
    x_state[:,0] = x;

    dt = timevec[1]-timevec[0];

    # Form the covariance matrix for delta_beta and delta_alpha.
    beta_beta = dt*Qd;
    beta_alpha = 0.5*(dt**2)*Qd;
    alpha_alpha = ((dt**3)/3.0)*Qd;
    Qd_aug = np.zeros([dw+dw,dw+dw],dtype=np.float64); # The covariance matrix in eqn 44.
    Qd_aug[0:dw,0:dw] = beta_beta;
    Qd_aug[0:dw,dw:] = beta_alpha;
    Qd_aug[dw:,0:dw] = beta_alpha;
    Qd_aug[dw:,dw:] = alpha_alpha;

    # Generate process noise terms according to eqn 44.
    noisevec = np.zeros([dw+dw],dtype=np.float64); # mean vector is zero.

    y_plus = np.zeros([dx,dw],dtype=np.float64);
    y_minus = np.zeros([dx,dw],dtype=np.float64);
    fy_plus = np.zeros([dx,dw],dtype=np.float64);
    fy_minus = np.zeros([dx,dw],dtype=np.float64);
    f2 = np.zeros([dx,dw],dtype=np.float64); # equal to F2 (eqn 39)
    # F3 == F2 because we assume L is a constant matrix.

    for index in range(1,len(timevec)):
        process_noise = np.random.multivariate_normal(noisevec,Qd_aug);
        delta_beta = process_noise[0:dw];
        delta_alpha = process_noise[dw:];
        summ = np.zeros([dx],dtype=np.float64);

        for j in range(0,dw):
            # find yj+ and yj-. eqns 42 and 43
            y_plus[:,j]  = x_state[:,index-1] + (dt/float(dw))*fnD(timevec[index-1],x_state[:,index-1]) + np.sqrt(dt)*L[:,j];
            y_minus[:,j] = x_state[:,index-1] + (dt/float(dw))*fnD(timevec[index-1],x_state[:,index-1]) - np.sqrt(dt)*L[:,j];
            # expressions in eqns 40 and 38
            fy_plus[:,j]  = fnD(timevec[index-1],y_plus[:,j]);
            fy_minus[:,j] = fnD(timevec[index-1],y_minus[:,j]);
            f2[:,j] = (1/(2*np.sqrt(dt)))*(fy_plus[:,j] - fy_minus[:,j]); # eqn 40
            # sum term in eqn 38
            summ += fy_plus[:,j] - 2*fnD(timevec[index-1],x_state[:,index-1]) + fy_minus[:,j];

        f1 = x_state[:,index-1] + dt*fnD(timevec[index-1],x_state[:,index-1]) + 0.25*dt*summ; # eqn 38
        x_state[:,index] = f1 + np.dot(L,delta_beta) + np.dot(f2,delta_alpha); # eqn 37

    return x_state


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package lógica;

/**
 *
 * @author Yair Lopez Poveda <ylopezp@correo.udistrital.edu.co>
 */
public class ProductoSoftware extends Producto{

    public ProductoSoftware(tipoSoftware tipo, String nombre_producto, float precio_product) {
        super(nombre_producto, precio_product);
        this.tipo = tipo;
    }

    public ProductoSoftware() {
        super();
    }

    public String tipoProducto() {
        String aux = "Tipo de hardware: ";
        switch(tipo){
            case Juego:
                aux+="Juego.";
                break;
            case SO:
                aux+="Sistema operativo.";
                break;
            case Office:
                aux+="Office.";
                break;
            case otro:
                aux+="Otro.";
                break;
        }
        return aux;
    }

    public void setTipo(tipoSoftware tipo) {
        this.tipo = tipo;
    }
    public enum tipoSoftware{
        Juego,SO,Office, otro;
    }

    private tipoSoftware tipo;

    @Override
    public String toString() {
        return "\nID producto: "+getID()+"\n"+this.tipoProducto()
                +"\nNombre del producto: "+getNombre_producto()+
                "\nMarca del producto: "+getMarca_producto()+"\nCantidad de productos: "+
                getCantidad()+"\nPrecio del producto: "+getPrecio_producto()+"\n";
    }

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>pymatgen.util.num module — pymatgen 2022.0.6 documentation</title>

  <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="_static/css/custom.css" type="text/css" />

    <link rel="canonical" href="https://pymatgen.orgpymatgen.util.num.html"/>

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="pymatgen.util.plotting module" href="pymatgen.util.plotting.html" />
    <link rel="prev" title="pymatgen.util.io_utils module" href="pymatgen.util.io_utils.html" />

             pymatgen

                2022.0.6

  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Introduction

Installation

Change log

Compatibility

Contributing

Usage

Development Team

References

API Docs

pymatgen namespace

Subpackages

pymatgen.alchemy package

pymatgen.analysis namespace

pymatgen.apps package

pymatgen.cli package

pymatgen.command_line package

pymatgen.core package

pymatgen.electronic_structure package

pymatgen.entries package

pymatgen.ext namespace

pymatgen.io namespace

pymatgen.optimization package

pymatgen.phonon package

pymatgen.symmetry package

pymatgen.transformations package

pymatgen.util package

pymatgen.vis package

Submodules

          pymatgen

 »

pymatgen »

pymatgen namespace »

pymatgen.util package »

pymatgen.util.num module

               Edit on GitHub

pymatgen.util.num module¶

This module provides utilities for basic math operations.

abs_cap(val, max_abs_val=1)[source]¶

Returns the value with its absolute value capped at max_abs_val.
Particularly useful in passing values to trignometric functions where
numerical errors may result in an argument > 1 being passed in.

Parameters

val (float) – Input value.

max_abs_val (float) – The maximum absolute value for val. Defaults to 1.

Returns

val if abs(val) < 1 else sign of val * max_abs_val.

make_symmetric_matrix_from_upper_tri(val)[source]¶

Given a symmetric matrix in upper triangular matrix form as flat array indexes as:
[A_xx,A_yy,A_zz,A_xy,A_xz,A_yz]
This will generate the full matrix:
[[A_xx,A_xy,A_xz],[A_xy,A_yy,A_yz],[A_xz,A_yz,A_zz]

maxloc(seq)[source]¶

Return the index of the (first) maximum in seq

>>> assert maxloc([1,3,2,3]) == 1

min_max_indexes(seq)[source]¶

Uses enumerate, max, and min to return the indices of the values
in a list with the maximum and minimum value:

minloc(seq)[source]¶

Return the index of the (first) minimum in seq

>>> assert minloc(range(3)) == 0

monotonic(values, mode='<', atol=1e-08)[source]¶

Returns False if values are not monotonic (decreasing|increasing).
mode is "<" for a decreasing sequence, ">" for an increasing sequence.
Two numbers are considered equal if they differ less that atol.

>>> values = [1.2, 1.3, 1.4]
>>> monotonic(values, mode="<")
False
>>> monotonic(values, mode=">")
True

non_decreasing(values)[source]¶

True if values are not decreasing.

non_increasing(values)[source]¶

True if values are not increasing.

round_to_sigfigs(num, sigfigs)[source]¶

Rounds a number rounded to a specific number of significant
figures instead of to a specific precision.

sort_dict(d, key=None, reverse=False)[source]¶

Sorts a dict by value.

Parameters

d – Input dictionary

key – Function which takes an tuple (key, object) and returns a value to
compare and sort by. By default, the function compares the values
of the dict i.e. key = lambda t : t[1]

reverse – Allows to reverse sort order.

Returns

OrderedDict object whose keys are ordered according to their value.

strictly_decreasing(values)[source]¶

True if values are stricly decreasing.

strictly_increasing(values)[source]¶

True if values are stricly increasing.

        © Copyright 2011, Pymatgen Development Team

    Built with Sphinx using a

    theme

    provided by Read the Docs.

This page uses
Google Analytics to collect statistics. You can disable it by blocking
the JavaScript coming from www.google-analytics.com.


text:
<!DOCTYPE html>
<!--
@license
Copyright (C) 2016 The Android Open Source Project

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.
-->

<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>gr-ranged-comment-layer</title>

<script src="../../../bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
<script src="../../../bower_components/web-component-tester/browser.js"></script>
<link rel="import" href="../../../test/common-test-setup.html"/>
<script src="../gr-diff/gr-diff-line.js"></script>

<link rel="import" href="gr-ranged-comment-layer.html">

<script>void(0);</script>

<test-fixture id="basic">
  <template>
    <gr-ranged-comment-layer></gr-ranged-comment-layer>
  </template>
</test-fixture>

<script>
  suite('gr-ranged-comment-layer', () => {
    let element;
    let sandbox;

    setup(() => {
      const initialCommentRanges = [
        {
          side: 'left',
          range: {
            end_character: 9,
            end_line: 39,
            start_character: 6,
            start_line: 36,
          },
        },
        {
          side: 'right',
          range: {
            end_character: 22,
            end_line: 12,
            start_character: 10,
            start_line: 10,
          },
        },
        {
          side: 'right',
          range: {
            end_character: 15,
            end_line: 100,
            start_character: 5,
            start_line: 100,
          },
        },
        {
          side: 'right',
          range: {
            end_character: 2,
            end_line: 55,
            start_character: 32,
            start_line: 55,
          },
        },
      ];

      sandbox = sinon.sandbox.create();
      element = fixture('basic');
      element.commentRanges = initialCommentRanges;
    });

    teardown(() => {
      sandbox.restore();
    });

    suite('annotate', () => {
      let sandbox;
      let el;
      let line;
      let annotateElementStub;
      const lineNumberEl = document.createElement('td');

      setup(() => {
        sandbox = sinon.sandbox.create();
        annotateElementStub = sandbox.stub(GrAnnotation, 'annotateElement');
        el = document.createElement('div');
        el.setAttribute('data-side', 'left');
        line = new GrDiffLine(GrDiffLine.Type.BOTH);
        line.text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit,';
      });

      teardown(() => {
        sandbox.restore();
      });

      test('type=Remove no-comment', () => {
        line.type = GrDiffLine.Type.REMOVE;
        line.beforeNumber = 40;

        element.annotate(el, lineNumberEl, line);

        assert.isFalse(annotateElementStub.called);
      });

      test('type=Remove has-comment', () => {
        line.type = GrDiffLine.Type.REMOVE;
        line.beforeNumber = 36;
        const expectedStart = 6;
        const expectedLength = line.text.length - expectedStart;

        element.annotate(el, lineNumberEl, line);

        assert.isTrue(annotateElementStub.called);
        const lastCall = annotateElementStub.lastCall;
        assert.equal(lastCall.args[0], el);
        assert.equal(lastCall.args[1], expectedStart);
        assert.equal(lastCall.args[2], expectedLength);
        assert.equal(lastCall.args[3], 'range');
      });

      test('type=Remove has-comment hovering', () => {
        line.type = GrDiffLine.Type.REMOVE;
        line.beforeNumber = 36;
        element.set(['commentRanges', 0, 'hovering'], true);

        const expectedStart = 6;
        const expectedLength = line.text.length - expectedStart;

        element.annotate(el, lineNumberEl, line);

        assert.isTrue(annotateElementStub.called);
        const lastCall = annotateElementStub.lastCall;
        assert.equal(lastCall.args[0], el);
        assert.equal(lastCall.args[1], expectedStart);
        assert.equal(lastCall.args[2], expectedLength);
        assert.equal(lastCall.args[3], 'rangeHighlight');
      });

      test('type=Both has-comment', () => {
        line.type = GrDiffLine.Type.BOTH;
        line.beforeNumber = 36;

        const expectedStart = 6;
        const expectedLength = line.text.length - expectedStart;

        element.annotate(el, lineNumberEl, line);

        assert.isTrue(annotateElementStub.called);
        const lastCall = annotateElementStub.lastCall;
        assert.equal(lastCall.args[0], el);
        assert.equal(lastCall.args[1], expectedStart);
        assert.equal(lastCall.args[2], expectedLength);
        assert.equal(lastCall.args[3], 'range');
      });

      test('type=Both has-comment off side', () => {
        line.type = GrDiffLine.Type.BOTH;
        line.beforeNumber = 36;
        el.setAttribute('data-side', 'right');

        element.annotate(el, lineNumberEl, line);

        assert.isFalse(annotateElementStub.called);
      });

      test('type=Add has-comment', () => {
        line.type = GrDiffLine.Type.ADD;
        line.afterNumber = 12;
        el.setAttribute('data-side', 'right');

        const expectedStart = 0;
        const expectedLength = 22;

        element.annotate(el, lineNumberEl, line);

        assert.isTrue(annotateElementStub.called);
        const lastCall = annotateElementStub.lastCall;
        assert.equal(lastCall.args[0], el);
        assert.equal(lastCall.args[1], expectedStart);
        assert.equal(lastCall.args[2], expectedLength);
        assert.equal(lastCall.args[3], 'range');
      });
    });

    test('_handleCommentRangesChange overwrite', () => {
      element.set('commentRanges', []);

      assert.equal(Object.keys(element._rangesMap.left).length, 0);
      assert.equal(Object.keys(element._rangesMap.right).length, 0);
    });

    test('_handleCommentRangesChange hovering', () => {
      const notifyStub = sinon.stub();
      element.addListener(notifyStub);

      element.set(['commentRanges', 1, 'hovering'], true);

      assert.isTrue(notifyStub.called);
      const lastCall = notifyStub.lastCall;
      assert.equal(lastCall.args[0], 10);
      assert.equal(lastCall.args[1], 12);
      assert.equal(lastCall.args[2], 'right');
    });

    test('_handleCommentRangesChange splice out', () => {
      const notifyStub = sinon.stub();
      element.addListener(notifyStub);

      element.splice('commentRanges', 1, 1);

      assert.isTrue(notifyStub.called);
      const lastCall = notifyStub.lastCall;
      assert.equal(lastCall.args[0], 10);
      assert.equal(lastCall.args[1], 12);
      assert.equal(lastCall.args[2], 'right');
    });

    test('_handleCommentRangesChange splice in', () => {
      const notifyStub = sinon.stub();
      element.addListener(notifyStub);

      element.splice('commentRanges', 1, 0, {
        side: 'left',
        range: {
          end_character: 15,
          end_line: 275,
          start_character: 5,
          start_line: 250,
        },
      });

      assert.isTrue(notifyStub.called);
      const lastCall = notifyStub.lastCall;
      assert.equal(lastCall.args[0], 250);
      assert.equal(lastCall.args[1], 275);
      assert.equal(lastCall.args[2], 'left');
    });

    test('_computeCommentMap creates maps correctly', () => {
      // There is only one ranged comment on the left, but it spans ll.36-39.
      const leftKeys = [];
      for (let i = 36; i <= 39; i++) { leftKeys.push('' + i); }
      assert.deepEqual(Object.keys(element._rangesMap.left).sort(),
          leftKeys.sort());

      assert.equal(element._rangesMap.left[36].length, 1);
      assert.equal(element._rangesMap.left[36][0].start, 6);
      assert.equal(element._rangesMap.left[36][0].end, -1);

      assert.equal(element._rangesMap.left[37].length, 1);
      assert.equal(element._rangesMap.left[37][0].start, 0);
      assert.equal(element._rangesMap.left[37][0].end, -1);

      assert.equal(element._rangesMap.left[38].length, 1);
      assert.equal(element._rangesMap.left[38][0].start, 0);
      assert.equal(element._rangesMap.left[38][0].end, -1);

      assert.equal(element._rangesMap.left[39].length, 1);
      assert.equal(element._rangesMap.left[39][0].start, 0);
      assert.equal(element._rangesMap.left[39][0].end, 9);

      // The right has two ranged comments, one spanning ll.10-12 and the other
      // on line 100.
      const rightKeys = [];
      for (let i = 10; i <= 12; i++) { rightKeys.push('' + i); }
      rightKeys.push('55', '100');
      assert.deepEqual(Object.keys(element._rangesMap.right).sort(),
          rightKeys.sort());

      assert.equal(element._rangesMap.right[10].length, 1);
      assert.equal(element._rangesMap.right[10][0].start, 10);
      assert.equal(element._rangesMap.right[10][0].end, -1);

      assert.equal(element._rangesMap.right[11].length, 1);
      assert.equal(element._rangesMap.right[11][0].start, 0);
      assert.equal(element._rangesMap.right[11][0].end, -1);

      assert.equal(element._rangesMap.right[12].length, 1);
      assert.equal(element._rangesMap.right[12][0].start, 0);
      assert.equal(element._rangesMap.right[12][0].end, 22);

      assert.equal(element._rangesMap.right[100].length, 1);
      assert.equal(element._rangesMap.right[100][0].start, 5);
      assert.equal(element._rangesMap.right[100][0].end, 15);
    });

    test('_getRangesForLine normalizes invalid ranges', () => {
      const line = {
        afterNumber: 55,
        text: '_getRangesForLine normalizes invalid ranges',
      };
      const ranges = element._getRangesForLine(line, 'right');
      assert.equal(ranges.length, 1);
      const range = ranges[0];
      assert.isTrue(range.start < range.end, 'start and end are normalized');
      assert.equal(range.end, line.text.length);
    });
  });
</script>


text:
Este es un nuevo mensaje
Esto se lo agregé Yo


text:
/*
 * SHControllers.act - GenSpeedControl
 *
 * © 2007-2016 skwas. All rights reserved.
 * This code is provided as is. Change at your own risk.
 * --------------------------------------------------
 *
 * S3D template for the GenSpeedControl controller of Silent Hunter.
 *
 * For documentation on templates, requirements and restrictions, please refer to the documentation.
 *
*/

using SilentHunter.Controllers;

namespace SHControllers
{
	/// <summary>
	/// GenSpeedControl render controller. Interpolates the WindSpeed, Velocity, Weight, Size and Opacity of the ParticleGenerators between the min and max speed limits.
	/// </summary>
	public class GenSpeedControl
		: BehaviorController
	{
		/// <summary>
		/// Min speed to start interpolate.
		/// </summary>
		public float Min;
		/// <summary>
		/// Max speed to start interpolate.
		/// </summary>
		public float Max;
	}
}


text:
<!-- 2017-08-31 -->

Welcome to another issue of Haskell Weekly!
Haskell is a purely functional programming language that focuses on correctness, productivity, and expressiveness.
This is a weekly summary of what's going on in its community.

Want to see something featured in Haskell Weekly?
We love contributions!
Tweet us at [@HaskellWeekly](https://twitter.com/haskellweekly) or [open a pull request](https://github.com/haskellweekly/haskellweekly.github.io).

## Featured

-   [Cross-referenced codebase for Stackage LTS 9.2 available](https://mail.haskell.org/pipermail/haskell-cafe/2017-August/127823.html)

    > To find out who else uses your favorite functions and how. For example, click `async` to get all the call sites of that method.

-   [Compact normal forms + linear types = efficient network communication](https://www.tweag.io/posts/2017-08-24-linear-types-packed-data.html)

    > In this post, I want to use the same idea of tracking states in types, but applied to a more unusual example from our paper: sending rich structured data types across the network and back with as little copying as possible.

-   [Roll your own Bitcoin exchange in Haskell](http://www.michaelburge.us/2017/08/31/roll-your-own-bitcoin-exchange.html)

    > This article will show you how to: Design an order book that can handle limit orders and market orders; Install automated sanity checks that run on every write to the order book, preventing hacks and implementation bugs.

-   [An example of using laziness](https://noughtmare.gitlab.io/posts/2017-08-30-an-example-of-using-laziness.html)

    > The problem is about finding out in how many ways you can make change for a certain amount of money using an infinite supply of coins of different values.

-   [Beginner mistakes and oddities I encountered](https://jaredweakly.com/blog/beginner-mistakes-and-oddities-i-encountered/)

    > Time sure does fly don't it? I'm going to go over a lot of the beginner mistakes and little pitfalls and paper cuts I've encountered so far while working on the GHC test suite.

-   [Introducing Haskey (Summer of Haskell 2017)](https://deliquus.com/posts/2017-08-24-introducing-haskey.html)

    > This blog post introduces the Haskey project, an ACID compliant embedded key-value store entirely written in Haskell, based on an MVCC B+-tree implementation.

-   [Migrating a REST API from JavaScript to Haskell](https://blog.ismail-s.com/2017/08/30/migrating-a-rest-api-from-javascript-to-haskell/)

    > I noticed that running the server was costing me more than I'd like. This was because the REST API consumed too much memory, which cost me a bit too much money. So, to save money, I decided to rewrite the API in Haskell.

-   [Exiting a Haskell process](https://www.fpcomplete.com/blog/2017/08/exiting-haskell-process)

    > To understand what's happening, let's look at a simplified version of the implementation of the `exitWith` function. I would have anticipated that this would, you know, actually exit the process.

-   [Fixed-length vector types in Haskell](https://blog.jle.im/entry/fixed-length-vector-types-in-haskell.html)

    > So here we are in 2017. GHC 8.2 is here, and base is in version 4.10. What's the "right" way to do fixed-length vectors in Haskell?

-   [Type Tac Toe: Advanced type safety](http://chrispenner.ca/posts/type-tac-toe)

    > Today we'll be looking at type programming in Haskell. Programming in type-land allows us to teach the compiler a few new tricks and to verify additional constraints at compile-time rather than run-time.

## Jobs

Sadly we aren't currently aware of any Haskell job openings.
Are you looking to hire a Haskell developer?
If so, consider [advertising with us](https://haskellweekly.news/advertising.html)!

## In brief

-   [A ByteString performance mystery](http://teh.id.au/posts/2017/08/23/bytestring-performance-mystery/)
-   [Closure conversion as coyoneda](http://prl.ccs.neu.edu/blog/2017/08/28/closure-conversion-as-coyoneda/)
-   [Haskell for Mac: The highlights of version 1.5](http://blog.haskellformac.com/blog/version-15)
-   [Haskell Platform 8.2.1](https://mail.haskell.org/pipermail/haskell-cafe/2017-August/127789.html)
-   [Monad transformer commutativity](https://jship.github.io/posts/2017-08-27-monad-transformer-commutativity.html)
-   [Nanocoin](https://github.com/tdietert/nanocoin/blob/25fe5e8f24ccf54e475b3376eedce6766094bb38/README.md)
-   [Putting the flow in Tensor Flow](https://mmhaskell.com/blog/2017/8/28/putting-the-flow-in-tensor-flow)
-   [Right and left folds, primitive recursion patterns in Python and Haskell](http://eli.thegreenplace.net/2017/right-and-left-folds-primitive-recursion-patterns-in-python-and-haskell)
-   [Stackage to Nix](https://blog.typeable.io/posts/2017-08-24-stackage2nix.html)

## Package of the week

This week's package of the week is [stm](https://www.stackage.org/lts-9.2/package/stm-2.4.4.1),
a library that provides software transactional memory.
STM is a modular, composable concurrency abstraction.

## Call for participation

-   [aeson: Documentation of Option fields disappeared](https://github.com/bos/aeson/issues/576)
-   [liquidhaskell: Annotations are ignored when comment is not closed with @-}](https://github.com/ucsd-progsys/liquidhaskell/issues/1049)
-   [nanocoin: Reward Transaction on Mining](https://github.com/tdietert/nanocoin/issues/7)
-   [stack: `stack script --optimize` clutters the current directory with *.hi and *.o files](https://github.com/commercialhaskell/stack/issues/3371)
-   [stack: Allow installing from GitHub](https://github.com/commercialhaskell/stack/issues/1278)

## Events

-   September 3 - September 9: [Oxford, United Kingdom: International Conference on Functional Programming](http://conf.researchr.org/home/icfp-2017)
-   September 6: [Berlin Haskell Programming From First Principles Study Group](https://www.meetup.com/Berlin-Functional-Programming-Group/events/242559370/)


text:
module HappyApi
  module StringTokenizer

    def self.included(base)
      base.class_eval do
        extend ClassMethods
      end
    end

    module ClassMethods

      # Take a string and replace all instances of a "[*]" in it with the matching key value in the applied hash
      # ex: "[name] is awesome", {:name => "elad"} => "elad is awesome"
      def tokenize_string(string = "", value_hash = {})
        replaced_string = string.clone
        value_hash.each_pair do |token, value|
          replaced_string.gsub!(/\[#{token}\]/, value.to_s)
        end
        replaced_string
      end
    end
  end
end


text:
          {{title}}

          {{body}}

            <svg role="img" class="b-membership-upsell__list--item-point">
              <use xlink:href="/assets/svg/svg-template.svg#tick-circle"></use>
            </svg>
            {{listItems.first}}

            <svg role="img" class="b-membership-upsell__list--item-point">
              <use xlink:href="/assets/svg/svg-template.svg#tick-circle"></use>
            </svg>
            {{listItems.second}}

            <svg role="img" class="b-membership-upsell__list--item-point">
              <use xlink:href="/assets/svg/svg-template.svg#tick-circle"></use>
            </svg>
            {{listItems.third}}

            {{cta}}

              {{continue}}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Buellia colludens var. triseptata M. Knowles ex Ch. Porter

### Remarks
null