text:
"""Tests for the ironic driver."""

from ironicclient import client as ironic_client
from ironicclient import exc as ironic_exception
import mock
from oslo.config import cfg

from nova.compute import power_state as nova_states
from nova import context as nova_context
from nova import exception
from nova.openstack.common import uuidutils
from nova import test
from nova.tests import fake_instance
from nova.tests import utils
from nova.virt import fake
from nova.virt.ironic import driver as ironic_driver
from nova.virt.ironic import ironic_states

CONF = cfg.CONF

IRONIC_FLAGS = dict(
    instance_type_extra_specs=['test_spec:test_value'],
    api_version=1,
    group='ironic',
)

def get_test_validation(**kw):
    return type('interfaces', (object,),
               {'power': kw.get('power', True),
                'deploy': kw.get('deploy', True),
                'console': kw.get('console', True),
                'rescue': kw.get('rescue', True)})()

def get_test_node(**kw):
    return type('node', (object,),
               {'uuid': kw.get('uuid', 'eeeeeeee-dddd-cccc-bbbb-aaaaaaaaaaaa'),
                'chassis_uuid': kw.get('chassis_uuid'),
                'power_state': kw.get('power_state',
                                      ironic_states.NOSTATE),
                'target_power_state': kw.get('target_power_state',
                                             ironic_states.NOSTATE),
                'provision_state': kw.get('provision_state',
                                          ironic_states.NOSTATE),
                'target_provision_state': kw.get('target_provision_state',
                                                 ironic_states.NOSTATE),
                'last_error': kw.get('last_error'),
                'instance_uuid': kw.get('instance_uuid'),
                'driver': kw.get('driver', 'fake'),
                'driver_info': kw.get('driver_info', {}),
                'properties': kw.get('properties', {}),
                'reservation': kw.get('reservation'),
                'maintenance': kw.get('maintenance', False),
                'extra': kw.get('extra', {}),
                'updated_at': kw.get('created_at'),
                'created_at': kw.get('updated_at')})()

def get_test_port(**kw):
    return type('port', (object,),
               {'uuid': kw.get('uuid', 'gggggggg-uuuu-qqqq-ffff-llllllllllll'),
                'node_uuid': kw.get('node_uuid', get_test_node().uuid),
                'address': kw.get('address', 'FF:FF:FF:FF:FF:FF'),
                'extra': kw.get('extra', {}),
                'created_at': kw.get('created_at'),
                'updated_at': kw.get('updated_at')})()

class FakePortClient(object):

    def get(self, port_uuid):
        pass

    def update(self, port_uuid, patch):
        pass

class FakeNodeClient(object):

    def list(self):
        return []

    def get(self, node_uuid):
        pass

    def get_by_instance_uuid(self, instance_uuid):
        pass

    def list_ports(self, node_uuid):
        pass

    def set_power_state(self, node_uuid, target):
        pass

    def set_provision_state(self, node_uuid, target):
        pass

    def update(self, node_uuid, patch):
        pass

    def validate(self, node_uuid):
        pass

class FakeClient(object):

    node = FakeNodeClient()
    port = FakePortClient()

FAKE_CLIENT = FakeClient()

class IronicDriverTestCase(test.NoDBTestCase):

    def setUp(self):
        super(IronicDriverTestCase, self).setUp()
        self.flags(**IRONIC_FLAGS)
        self.driver = ironic_driver.IronicDriver(None)
        self.driver.virtapi = fake.FakeVirtAPI()
        self.ctx = nova_context.get_admin_context()
        # mock _get_client
        self.mock_cli_patcher = mock.patch.object(self.driver, '_get_client')
        self.mock_cli = self.mock_cli_patcher.start()
        self.mock_cli.return_value = FAKE_CLIENT

        def stop_patchers():
            if self.mock_cli:
                self.mock_cli_patcher.stop()

        self.addCleanup(stop_patchers)

    def test_validate_driver_loading(self):
        self.assertIsInstance(self.driver, ironic_driver.IronicDriver)

    def test_get_hypervisor_type(self):
        self.assertEqual(self.driver.get_hypervisor_type(), 'ironic')

    def test_get_hypervisor_version(self):
        self.assertEqual(self.driver.get_hypervisor_version(), 1)

    def test__get_client_no_auth_token(self):
        self.flags(admin_auth_token=None, group='ironic')

        # stop _get_client mock
        self.mock_cli_patcher.stop()
        self.mock_cli = None

        with mock.patch.object(nova_context, 'get_admin_context') as mock_ctx:
            mock_ctx.return_value = self.ctx
            with mock.patch.object(ironic_client, 'get_client') as mock_ir_cli:
                self.driver._get_client()
                expected = {'os_username': CONF.ironic.admin_username,
                            'os_password': CONF.ironic.admin_password,
                            'os_auth_url': CONF.ironic.admin_url,
                            'os_tenant_name': CONF.ironic.admin_tenant_name,
                            'os_service_type': 'baremetal',
                            'os_endpoint_type': 'public'}
                mock_ir_cli.assert_called_once_with(CONF.ironic.api_version,
                                                    **expected)

    def test__get_client_with_auth_token(self):
        self.flags(admin_auth_token='fake-token', group='ironic')

        # stop _get_client mock
        self.mock_cli_patcher.stop()
        self.mock_cli = None

        with mock.patch.object(nova_context, 'get_admin_context') as mock_ctx:
            mock_ctx.return_value = self.ctx
            with mock.patch.object(ironic_client, 'get_client') as mock_ir_cli:
                self.driver._get_client()
                expected = {'os_auth_token': self.ctx.auth_token,
                            'ironic_url': CONF.ironic.api_endpoint}
                mock_ir_cli.assert_called_once_with(CONF.ironic.api_version,
                                                    **expected)

    def test__require_node(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        test_instance = fake_instance.fake_instance_obj(self.ctx,
                                                        node=node_uuid)
        self.assertEqual(node_uuid, self.driver._require_node(test_instance))

    def test__require_node_fail(self):
        test_instance = fake_instance.fake_instance_obj(self.ctx, node=None)
        self.assertRaises(exception.NovaException,
                          self.driver._require_node, test_instance)

    def test__node_resource(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        cpus = 2
        mem = 512
        disk = 10
        arch = 'x86_64'
        properties = {'cpus': cpus, 'memory_mb': mem,
                      'local_gb': disk, 'cpu_arch': arch}
        node = get_test_node(uuid=node_uuid,
                             instance_uuid=uuidutils.generate_uuid(),
                             properties=properties)

        result = self.driver._node_resource(node)
        self.assertEqual(cpus, result['vcpus'])
        self.assertEqual(cpus, result['vcpus_used'])
        self.assertEqual(mem, result['memory_mb'])
        self.assertEqual(mem, result['memory_mb_used'])
        self.assertEqual(disk, result['local_gb'])
        self.assertEqual(disk, result['local_gb_used'])
        self.assertEqual(node_uuid, result['hypervisor_hostname'])
        self.assertEqual('{"cpu_arch": "x86_64", "ironic_driver": "'
                         'nova.virt.ironic.driver.IronicDriver", '
                         '"test_spec": "test_value"}',
                         result['stats'])

    def test__node_resource_no_instance_uuid(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        cpus = 2
        mem = 512
        disk = 10
        arch = 'x86_64'
        properties = {'cpus': cpus, 'memory_mb': mem,
                      'local_gb': disk, 'cpu_arch': arch}
        node = get_test_node(uuid=node_uuid,
                             instance_uuid=None,
                             properties=properties)

        result = self.driver._node_resource(node)
        self.assertEqual(cpus, result['vcpus'])
        self.assertEqual(0, result['vcpus_used'])
        self.assertEqual(mem, result['memory_mb'])
        self.assertEqual(0, result['memory_mb_used'])
        self.assertEqual(disk, result['local_gb'])
        self.assertEqual(0, result['local_gb_used'])
        self.assertEqual(node_uuid, result['hypervisor_hostname'])
        self.assertEqual('{"cpu_arch": "x86_64", "ironic_driver": "'
                         'nova.virt.ironic.driver.IronicDriver", '
                         '"test_spec": "test_value"}',
                         result['stats'])

    def test__retry_on_conflict(self):
        test_list = []

        def test_func(test_list):
            test_list.append(1)

        self.driver._retry_on_conflict(test_func, test_list)
        self.assertIn(1, test_list)

    def test__retry_on_conflict_fail(self):
        CONF.set_default('api_max_retries', default=1, group='ironic')
        CONF.set_default('api_retry_interval', default=0, group='ironic')

        def test_func():
            raise ironic_exception.HTTPConflict()

        self.assertRaises(ironic_driver.MaximumRetriesReached,
                          self.driver._retry_on_conflict, test_func)

    def test__start_firewall(self):
        func_list = ['setup_basic_filtering',
                     'prepare_instance_filter',
                     'apply_instance_filter']
        patch_list = [mock.patch.object(self.driver.firewall_driver, func)
                      for func in func_list]
        mock_list = [patcher.start() for patcher in patch_list]
        for p in patch_list:
            self.addCleanup(p.stop)

        fake_inst = 'fake-inst'
        fake_net_info = utils.get_test_network_info()
        self.driver._start_firewall(fake_inst, fake_net_info)

        # assert all methods were invoked with the right args
        for m in mock_list:
            m.assert_called_once_with(fake_inst, fake_net_info)

    def test__stop_firewall(self):
        fake_inst = 'fake-inst'
        fake_net_info = utils.get_test_network_info()
        with mock.patch.object(self.driver.firewall_driver,
                               'unfilter_instance') as mock_ui:
            self.driver._stop_firewall(fake_inst, fake_net_info)
            mock_ui.assert_called_once_with(fake_inst, fake_net_info)

    def test_list_instances(self):
        num_nodes = 2
        nodes = []
        for n in range(num_nodes):
            nodes.append(get_test_node(
                            instance_uuid=uuidutils.generate_uuid()))
        # append a node w/o instance_uuid which shouldn't be listed
        nodes.append(get_test_node(instance_uuid=None))

        with mock.patch.object(FAKE_CLIENT.node, 'list') as mock_list:
            mock_list.return_value = nodes

            expected = [n for n in nodes if n.instance_uuid]
            instances = self.driver.list_instances()
            self.assertEqual(sorted(expected), sorted(instances))
            self.assertEqual(num_nodes, len(instances))

    def test_get_available_nodes(self):
        num_nodes = 2
        nodes = []
        for n in range(num_nodes):
            nodes.append(get_test_node(uuid=uuidutils.generate_uuid(),
                                       power_state=ironic_states.POWER_OFF))
        # append a node w/o power_state which shouldn't be listed
        nodes.append(get_test_node(power_state=None))

        with mock.patch.object(FAKE_CLIENT.node, 'list') as mock_list:
            mock_list.return_value = nodes

            expected = [n.uuid for n in nodes if n.power_state]
            available_nodes = self.driver.get_available_nodes()
            self.assertEqual(sorted(expected), sorted(available_nodes))
            self.assertEqual(num_nodes, len(available_nodes))

    def test_get_available_resource(self):
        node = get_test_node()
        fake_resource = 'fake-resource'
        mock_get = mock.patch.object(FAKE_CLIENT.node, 'get').start()
        mock_get.return_value = node
        self.addCleanup(mock_get.stop)

        with mock.patch.object(self.driver, '_node_resource') as mock_nr:
            mock_nr.return_value = fake_resource

            result = self.driver.get_available_resource(node.uuid)
            self.assertEqual(fake_resource, result)
            mock_nr.assert_called_once_with(node)

    def test_get_info(self):
        instance_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        properties = {'memory_mb': 512, 'cpus': 2}
        power_state = ironic_states.POWER_ON
        node = get_test_node(instance_uuid=instance_uuid,
                             properties=properties,
                             power_state=power_state)

        with mock.patch.object(FAKE_CLIENT.node, 'get_by_instance_uuid') \
                as mock_gbiu:
            mock_gbiu.return_value = node

            # ironic_states.POWER_ON should me be mapped to
            # nova_states.RUNNING
            expected = {'state': nova_states.RUNNING,
                        'max_mem': properties['memory_mb'],
                        'mem': properties['memory_mb'],
                        'num_cpu': properties['cpus'],
                        'cpu_time': 0}
            instance = fake_instance.fake_instance_obj('fake-context',
                                                       uuid=instance_uuid)
            result = self.driver.get_info(instance)
            self.assertEqual(expected, result)

    def test_get_info_http_not_found(self):
        with mock.patch.object(FAKE_CLIENT.node, 'get_by_instance_uuid') \
                as mock_gbiu:
            mock_gbiu.side_effect = ironic_exception.HTTPNotFound()

            expected = {'state': nova_states.NOSTATE,
                        'max_mem': 0,
                        'mem': 0,
                        'num_cpu': 0,
                        'cpu_time': 0}
            instance = fake_instance.fake_instance_obj(
                                      self.ctx, uuid=uuidutils.generate_uuid())
            result = self.driver.get_info(instance)
            self.assertEqual(expected, result)

    def test_macs_for_instance(self):
        node = get_test_node()
        port = get_test_port()
        mock_get = mock.patch.object(FAKE_CLIENT.node, 'get').start()
        mock_get.return_value = node
        self.addCleanup(mock_get.stop)

        with mock.patch.object(FAKE_CLIENT.node, 'list_ports') as mock_lp:
            mock_lp.return_value = [port]
            instance = fake_instance.fake_instance_obj(self.ctx,
                                                       node=node.uuid)
            result = self.driver.macs_for_instance(instance)
            self.assertEqual([port.address], result)
            mock_lp.assert_called_once_with(node.uuid)

    def test_macs_for_instance_http_not_found(self):
        with mock.patch.object(FAKE_CLIENT.node, 'get') as mock_get:
            mock_get.side_effect = ironic_exception.HTTPNotFound()

            instance = fake_instance.fake_instance_obj(
                                      self.ctx, node=uuidutils.generate_uuid())
            result = self.driver.macs_for_instance(instance)
            self.assertEqual([], result)

    def test_spawn(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        node = get_test_node(driver='fake', uuid=node_uuid)
        instance = fake_instance.fake_instance_obj(self.ctx, node=node_uuid)
        fake_flavor = 'fake-flavor'

        mock_get = mock.patch.object(FAKE_CLIENT.node, 'get').start()
        mock_get.return_value = node
        self.addCleanup(mock_get.stop)
        mock_fg = mock.patch.object(self.driver.virtapi, 'flavor_get').start()
        mock_fg.return_value = fake_flavor
        self.addCleanup(mock_fg.stop)
        mock_validate = mock.patch.object(FAKE_CLIENT.node, 'validate').start()
        mock_validate.return_value = get_test_validation()
        self.addCleanup(mock_validate.stop)

        mock_adf = mock.patch.object(self.driver, '_add_driver_fields').start()
        self.addCleanup(mock_adf.stop)
        mock_pvifs = mock.patch.object(self.driver, 'plug_vifs').start()
        self.addCleanup(mock_pvifs.stop)
        mock_sf = mock.patch.object(self.driver, '_start_firewall').start()
        self.addCleanup(mock_pvifs.stop)

        with mock.patch.object(FAKE_CLIENT.node, 'set_provision_state') \
                as mock_sps:
            self.driver.spawn(self.ctx, instance, None, [], None)

            mock_get.assert_called_once_with(node_uuid)
            mock_validate.assert_called_once_with(node_uuid)
            mock_fg.assert_called_once_with(self.ctx,
                                            instance['instance_type_id'])
            mock_adf.assert_called_once_with(node, instance, None, fake_flavor)
            mock_pvifs.assert_called_once_with(instance, None)
            mock_sf.assert_called_once_with(instance, None)
            mock_sps.assert_called_once_with(node_uuid, 'active')

    def test_spawn_setting_instance_uuid_fail(self):
        instance = fake_instance.fake_instance_obj(self.ctx,
                                                node=uuidutils.generate_uuid())
        with mock.patch.object(FAKE_CLIENT.node, 'update') as mock_update:
            mock_update.side_effect = ironic_exception.HTTPBadRequest()
            self.assertRaises(exception.NovaException, self.driver.spawn,
                              self.ctx, instance, None, [], None)

    def test_spawn_node_driver_validation_fail(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        node = get_test_node(driver='fake', uuid=node_uuid)
        instance = fake_instance.fake_instance_obj(self.ctx, node=node_uuid)
        fake_flavor = 'fake-flavor'

        mock_get = mock.patch.object(FAKE_CLIENT.node, 'get').start()
        mock_get.return_value = node
        self.addCleanup(mock_get.stop)
        mock_fg = mock.patch.object(self.driver.virtapi, 'flavor_get').start()
        mock_fg.return_value = fake_flavor
        self.addCleanup(mock_fg.stop)

        mock_adf = mock.patch.object(self.driver, '_add_driver_fields').start()
        self.addCleanup(mock_adf.stop)

        with mock.patch.object(FAKE_CLIENT.node, 'validate') as mock_validate:
            mock_validate.return_value = get_test_validation(power=False,
                                                             deploy=False)
            self.assertRaises(exception.ValidationError, self.driver.spawn,
                              self.ctx, instance, None, [], None)

            mock_get.assert_called_once_with(node_uuid)
            mock_validate.assert_called_once_with(node_uuid)
            mock_fg.assert_called_once_with(self.ctx,
                                            instance['instance_type_id'])
            mock_adf.assert_called_once_with(node, instance, None, fake_flavor)

    def test_spawn_node_prepare_for_deploy_fail(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        node = get_test_node(driver='fake', uuid=node_uuid)
        instance = fake_instance.fake_instance_obj(self.ctx, node=node_uuid)

        mock_get = mock.patch.object(FAKE_CLIENT.node, 'get').start()
        mock_get.return_value = node
        self.addCleanup(mock_get.stop)
        mock_validate = mock.patch.object(FAKE_CLIENT.node, 'validate').start()
        mock_validate.return_value = get_test_validation()
        self.addCleanup(mock_validate.stop)

        mock_fg = mock.patch.object(self.driver.virtapi, 'flavor_get').start()
        self.addCleanup(mock_fg.stop)
        mock_pvifs = mock.patch.object(self.driver, 'plug_vifs').start()
        self.addCleanup(mock_pvifs.stop)
        mock_upvifs = mock.patch.object(self.driver, 'unplug_vifs').start()
        self.addCleanup(mock_upvifs.stop)
        mock_stof = mock.patch.object(self.driver, '_stop_firewall').start()
        self.addCleanup(mock_stof.stop)

        class TestException(Exception):
            pass

        with mock.patch.object(self.driver, '_start_firewall') as mock_sf:
            mock_sf.side_effect = TestException()
            self.assertRaises(TestException, self.driver.spawn,
                              self.ctx, instance, None, [], None)

            mock_get.assert_called_once_with(node_uuid)
            mock_validate.assert_called_once_with(node_uuid)
            mock_fg.assert_called_once_with(self.ctx,
                                            instance['instance_type_id'])
            mock_upvifs.assert_called_once_with(instance, None)
            mock_stof.assert_called_once_with(instance, None)

    def test_spawn_node_trigger_deploy_fail(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        node = get_test_node(driver='fake', uuid=node_uuid)
        instance = fake_instance.fake_instance_obj(self.ctx, node=node_uuid)

        mock_get = mock.patch.object(FAKE_CLIENT.node, 'get').start()
        mock_get.return_value = node
        self.addCleanup(mock_get.stop)
        mock_validate = mock.patch.object(FAKE_CLIENT.node, 'validate').start()
        mock_validate.return_value = get_test_validation()
        self.addCleanup(mock_validate.stop)

        mock_fg = mock.patch.object(self.driver.virtapi, 'flavor_get').start()
        self.addCleanup(mock_fg.stop)
        mock_pvifs = mock.patch.object(self.driver, 'plug_vifs').start()
        self.addCleanup(mock_pvifs.stop)
        mock_sf = mock.patch.object(self.driver, '_start_firewall').start()
        self.addCleanup(mock_sf.stop)
        mock_upvifs = mock.patch.object(self.driver, 'unplug_vifs').start()
        self.addCleanup(mock_upvifs.stop)
        mock_stof = mock.patch.object(self.driver, '_stop_firewall').start()
        self.addCleanup(mock_stof.stop)

        with mock.patch.object(FAKE_CLIENT.node, 'set_provision_state') \
                as mock_sps:
            mock_sps.side_effect = ironic_driver.MaximumRetriesReached
            self.assertRaises(exception.NovaException, self.driver.spawn,
                              self.ctx, instance, None, [], None)

            mock_get.assert_called_once_with(node_uuid)
            mock_validate.assert_called_once_with(node_uuid)
            mock_fg.assert_called_once_with(self.ctx,
                                            instance['instance_type_id'])
            mock_upvifs.assert_called_once_with(instance, None)
            mock_stof.assert_called_once_with(instance, None)

    def test_destroy(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        node = get_test_node(driver='fake', uuid=node_uuid)
        instance = fake_instance.fake_instance_obj(self.ctx, node=node_uuid)

        mock_get = mock.patch.object(FAKE_CLIENT.node, 'get').start()
        mock_get.return_value = node
        self.addCleanup(mock_get.stop)
        mock_sps = mock.patch.object(FAKE_CLIENT.node,
                                     'set_provision_state').start()
        self.addCleanup(mock_sps.stop)
        mock_update = mock.patch.object(FAKE_CLIENT.node, 'update').start()
        self.addCleanup(mock_update.stop)
        mock_upvifs = mock.patch.object(self.driver, 'unplug_vifs').start()
        self.addCleanup(mock_upvifs.stop)
        mock_stof = mock.patch.object(self.driver, '_stop_firewall').start()
        self.addCleanup(mock_stof.stop)

        self.driver.destroy(self.ctx, instance, None, None)
        mock_sps.assert_called_once_with(node_uuid, 'deleted')
        mock_get.assert_called_with(node_uuid)
        mock_upvifs.assert_called_once_with(instance, None)
        mock_stof.assert_called_once_with(instance, None)

    def test_destroy_trigger_undeploy_fail(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        instance = fake_instance.fake_instance_obj(self.ctx, node=node_uuid)

        with mock.patch.object(FAKE_CLIENT.node, 'set_provision_state') \
                as mock_sps:
            mock_sps.side_effect = ironic_driver.MaximumRetriesReached
            self.assertRaises(exception.NovaException, self.driver.destroy,
                              self.ctx, instance, None, None)

    def test_destroy_unprovision_fail(self):
        CONF.set_default('api_max_retries', default=1, group='ironic')
        CONF.set_default('api_retry_interval', default=0, group='ironic')

        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        node = get_test_node(driver='fake', uuid=node_uuid,
                             provision_state='fake-state')
        instance = fake_instance.fake_instance_obj(self.ctx, node=node_uuid)

        mock_get = mock.patch.object(FAKE_CLIENT.node, 'get').start()
        mock_get.return_value = node
        self.addCleanup(mock_get.stop)
        mock_sps = mock.patch.object(FAKE_CLIENT.node,
                                     'set_provision_state').start()
        self.addCleanup(mock_sps.stop)

        self.assertRaises(exception.NovaException, self.driver.destroy,
                          self.ctx, instance, None, None)
        mock_sps.assert_called_once_with(node_uuid, 'deleted')

    def test_destroy_unassociate_fail(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        node = get_test_node(driver='fake', uuid=node_uuid)
        instance = fake_instance.fake_instance_obj(self.ctx, node=node_uuid)

        mock_get = mock.patch.object(FAKE_CLIENT.node, 'get').start()
        mock_get.return_value = node
        self.addCleanup(mock_get.stop)
        mock_sps = mock.patch.object(FAKE_CLIENT.node,
                                     'set_provision_state').start()
        self.addCleanup(mock_sps.stop)

        with mock.patch.object(FAKE_CLIENT.node, 'update') as mock_update:
            mock_update.side_effect = ironic_driver.MaximumRetriesReached()
            self.assertRaises(exception.NovaException, self.driver.destroy,
                              self.ctx, instance, None, None)
            mock_sps.assert_called_once_with(node_uuid, 'deleted')
            mock_get.assert_called_with(node_uuid)

    def test_reboot(self):
        #TODO(lucasagomes): Not implemented in the driver.py
        pass

    def test_power_off(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        instance = fake_instance.fake_instance_obj(self.ctx,
                                                   node=node_uuid)
        with mock.patch.object(FAKE_CLIENT.node, 'set_power_state') as mock_sp:
            self.driver.power_off(instance)
            mock_sp.assert_called_once_with(node_uuid, 'off')

    def test_power_on(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        instance = fake_instance.fake_instance_obj(self.ctx,
                                                   node=node_uuid)
        with mock.patch.object(FAKE_CLIENT.node, 'set_power_state') as mock_sp:
            self.driver.power_on(self.ctx, instance,
                                 utils.get_test_network_info())
            mock_sp.assert_called_once_with(node_uuid, 'on')

    def test_get_host_stats(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        cpu_arch = 'x86_64'
        node = get_test_node(uuid=node_uuid,
                             properties={'cpu_arch': cpu_arch})
        supported_instances = 'fake-supported-instances'
        resource = {'supported_instances': supported_instances,
                    'hypervisor_hostname': uuidutils.generate_uuid(),
                    'cpu_info': 'baremetal cpu',
                    'hypervisor_version': 1,
                    'local_gb': 10,
                    'memory_mb_used': 512,
                    'stats': {'cpu_arch': 'x86_64',
                              'ironic_driver':
                                        'nova.virt.ironic.driver.IronicDriver',
                              'test_spec': 'test_value'},
                    'vcpus_used': 2,
                    'hypervisor_type': 'ironic',
                    'local_gb_used': 10,
                    'memory_mb': 512,
                    'vcpus': 2}

        # Reset driver specs
        test_extra_spec = 'test-spec'
        self.driver.extra_specs = {test_extra_spec: test_extra_spec}

        with mock.patch.object(FAKE_CLIENT.node, 'list') as mock_list:
            mock_list.return_value = [node]
            with mock.patch.object(self.driver, '_node_resource') as mock_nr:
                mock_nr.return_value = resource
                with mock.patch.object(ironic_driver,
                                '_get_nodes_supported_instances') as mock_gnsi:
                    mock_gnsi.return_value = supported_instances

                    expected = {'vcpus': resource['vcpus'],
                          'vcpus_used': resource['vcpus_used'],
                          'cpu_info': resource['cpu_info'],
                          'disk_total': resource['local_gb'],
                          'disk_used': resource['local_gb'],
                          'disk_available': 0,
                          'host_memory_total': resource['memory_mb'],
                          'host_memory_free': 0,
                          'hypervisor_type': resource['hypervisor_type'],
                          'hypervisor_version': resource['hypervisor_version'],
                          'supported_instances': supported_instances,
                          'host': CONF.host,
                          'hypervisor_hostname': node_uuid,
                          'node': node_uuid,
                          'cpu_arch': cpu_arch,
                          test_extra_spec: test_extra_spec}

                    result = self.driver.get_host_stats()
                    self.assertEqual([expected], result)

    def test_plug_vifs(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        node = get_test_node(uuid=node_uuid)
        port = get_test_port()

        mock_get = mock.patch.object(FAKE_CLIENT.node, 'get').start()
        mock_get.return_value = node
        self.addCleanup(mock_get.stop)
        mock_uvifs = mock.patch.object(self.driver, 'unplug_vifs').start()
        self.addCleanup(mock_uvifs.stop)
        mock_update = mock.patch.object(FAKE_CLIENT.port, 'update').start()
        self.addCleanup(mock_update.stop)

        with mock.patch.object(FAKE_CLIENT.node, 'list_ports') as mock_lp:
            mock_lp.return_value = [port]

            instance = fake_instance.fake_instance_obj(self.ctx,
                                                       node=node_uuid)
            network_info = utils.get_test_network_info()

            port_id = unicode(network_info[0]['id'])
            expected_patch = [{'op': 'add',
                               'path': '/extra/vif_port_id',
                               'value': port_id}]
            self.driver.plug_vifs(instance, network_info)

            # asserts
            mock_uvifs.assert_called_once_with(instance, network_info)
            mock_get.assert_called_once_with(node_uuid)
            mock_lp.assert_called_once_with(node_uuid)
            mock_update.assert_called_once_with(port.uuid, expected_patch)

    def test_plug_vifs_count_missmatch(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        node = get_test_node(uuid=node_uuid)
        port = get_test_port()

        mock_get = mock.patch.object(FAKE_CLIENT.node, 'get').start()
        mock_get.return_value = node
        self.addCleanup(mock_get.stop)
        mock_uvifs = mock.patch.object(self.driver, 'unplug_vifs').start()
        self.addCleanup(mock_uvifs.stop)
        mock_update = mock.patch.object(FAKE_CLIENT.port, 'update').start()
        self.addCleanup(mock_update.stop)

        with mock.patch.object(FAKE_CLIENT.node, 'list_ports') as mock_lp:
            mock_lp.return_value = [port]

            instance = fake_instance.fake_instance_obj(self.ctx,
                                                       node=node_uuid)
            # len(network_info) > len(ports)
            network_info = (utils.get_test_network_info() +
                            utils.get_test_network_info())
            self.assertRaises(exception.NovaException,
                              self.driver.plug_vifs, instance,
                              network_info)

            # asserts
            mock_uvifs.assert_called_once_with(instance, network_info)
            mock_get.assert_called_once_with(node_uuid)
            mock_lp.assert_called_once_with(node_uuid)
            # assert port.update() was not called
            assert not mock_update.called

    def test_plug_vifs_no_network_info(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        node = get_test_node(uuid=node_uuid)
        port = get_test_port()

        mock_get = mock.patch.object(FAKE_CLIENT.node, 'get').start()
        mock_get.return_value = node
        self.addCleanup(mock_get.stop)
        mock_uvifs = mock.patch.object(self.driver, 'unplug_vifs').start()
        self.addCleanup(mock_uvifs.stop)
        mock_update = mock.patch.object(FAKE_CLIENT.port, 'update').start()
        self.addCleanup(mock_update.stop)

        with mock.patch.object(FAKE_CLIENT.node, 'list_ports') as mock_lp:
            mock_lp.return_value = [port]

            instance = fake_instance.fake_instance_obj(self.ctx,
                                                       node=node_uuid)
            network_info = []
            self.driver.plug_vifs(instance, network_info)

            # asserts
            mock_uvifs.assert_called_once_with(instance, network_info)
            mock_get.assert_called_once_with(node_uuid)
            mock_lp.assert_called_once_with(node_uuid)
            # assert port.update() was not called
            assert not mock_update.called

    def test_unplug_vifs(self):
        node_uuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
        node = get_test_node(uuid=node_uuid)
        port = get_test_port()

        mock_update = mock.patch.object(FAKE_CLIENT.port, 'update').start()
        self.addCleanup(mock_update.stop)
        mock_get = mock.patch.object(FAKE_CLIENT.node, 'get').start()
        mock_get.return_value = node
        self.addCleanup(mock_get.stop)

        with mock.patch.object(FAKE_CLIENT.node, 'list_ports') as mock_lp:
            mock_lp.return_value = [port]

            instance = fake_instance.fake_instance_obj(self.ctx,
                                                       node=node_uuid)
            expected_patch = [{'op': 'remove', 'path':
                               '/extra/vif_port_id'}]
            self.driver.unplug_vifs(instance,
                                    utils.get_test_network_info())

            # asserts
            mock_get.assert_called_once_with(node_uuid)
            mock_lp.assert_called_once_with(node_uuid)
            mock_update.assert_called_once_with(port.uuid, expected_patch)

    def test_unplug_vifs_no_network_info(self):
        mock_update = mock.patch.object(FAKE_CLIENT.port, 'update').start()
        self.addCleanup(mock_update.stop)

        instance = fake_instance.fake_instance_obj(self.ctx)
        network_info = []
        self.driver.unplug_vifs(instance, network_info)

        # assert port.update() was not called
        assert not mock_update.called


text:
import json

import httmock
import mock
from oslotest import base
import requests

from refstack.api import guidelines

class GuidelinesTestCase(base.BaseTestCase):

    def setUp(self):
        super(GuidelinesTestCase, self).setUp()
        self.guidelines = guidelines.Guidelines()

    def test_guidelines_list(self):
        @httmock.all_requests
        def github_api_mock(url, request):
            headers = {'content-type': 'application/json'}
            content = [{'name': '2015.03.json',
                        'path': '2015.03.json',
                        'type': 'file'},
                       {'name': '2015.next.json',
                        'path': '2015.next.json',
                        'type': 'file'},
                       {'name': '2015.03',
                        'path': '2015.03',
                        'type': 'dir'},
                       {'name': 'test.2018.02.json',
                        'path': 'add-ons/test.2018.02.json',
                        'type': 'file'},
                       {'name': 'test.next.json',
                        'path': 'add-ons/test.next.json',
                        'type': 'file'}]
            content = json.dumps(content)
            return httmock.response(200, content, headers, None, 5, request)
        with httmock.HTTMock(github_api_mock):
            result = self.guidelines.get_guideline_list()
        expected_keys = ['powered', u'test']
        expected_powered = [
            {'name': u'2015.03.json',
             'file': u'2015.03.json'},
            {'name': u'2015.next.json',
             'file': u'2015.next.json'}
        ]
        expected_test_addons = [
            {'name': u'2018.02.json',
             'file': u'test.2018.02.json'},
            {'name': u'next.json',
             'file': u'test.next.json'}
        ]

        self.assertIn('powered', expected_keys)
        self.assertIn(u'test', expected_keys)
        self.assertEqual(expected_powered,
                         result['powered'])
        self.assertEqual(expected_test_addons,
                         result[u'test'])

    def test_get_guidelines_list_error_code(self):
        """Test when the HTTP status code isn't a 200 OK."""
        @httmock.all_requests
        def github_api_mock(url, request):
            content = {'title': 'Not Found'}
            return httmock.response(404, content, None, None, 5, request)

        with httmock.HTTMock(github_api_mock):
            result = self.guidelines.get_guideline_list()
        self.assertEqual(result, {'powered': []})

    @mock.patch('requests.get')
    def test_get_guidelines_exception(self, mock_requests_get):
        """Test when the GET request raises an exception."""
        mock_requests_get.side_effect = requests.exceptions.RequestException()
        result = self.guidelines.get_guideline_list()
        self.assertEqual(result, {'powered': []})

    def test_get_capability_file(self):
        """Test when getting a specific guideline file."""
        @httmock.all_requests
        def github_mock(url, request):
            content = {'foo': 'bar'}
            return httmock.response(200, content, None, None, 5, request)

        with httmock.HTTMock(github_mock):
            gl_file_name = 'dns.2018.02.json'
            result = self.guidelines.get_guideline_contents(gl_file_name)
        self.assertEqual({'foo': 'bar'}, result)

    def test_get_capability_file_error_code(self):
        """Test when the HTTP status code isn't a 200 OK."""
        @httmock.all_requests
        def github_api_mock(url, request):
            content = {'title': 'Not Found'}
            return httmock.response(404, content, None, None, 5, request)

        with httmock.HTTMock(github_api_mock):
            result = self.guidelines.get_guideline_contents('2010.03.json')
        self.assertIsNone(result)

    @mock.patch('requests.get')
    def test_get_capability_file_exception(self, mock_requests_get):
        """Test when the GET request raises an exception."""
        mock_requests_get.side_effect = requests.exceptions.RequestException()
        result = self.guidelines.get_guideline_contents('2010.03.json')
        self.assertIsNone(result)

    def test_get_target_capabilities(self):
        """Test getting relevant capabilities."""

        # Schema version 2.0
        json = {
            'metadata': {
                'id': '2017.08',
                'schema': '2.0',
                'scoring': {},
                'os_trademark_approval': {
                    'target_approval': '2017.08',
                    'replaces': '2017.01',
                    'releases': ['newton', 'ocata', 'pike'],
                    'status': 'approved'
                }
            },
            'platforms': {
                'OpenStack Powered Platform': {
                    'description': 'foo platform',
                    'components': [
                        {'name': 'os_powered_compute'},
                        {'name': 'os_powered_storage'}
                    ]
                },
                'OpenStack Powered Storage': {
                    'description': 'foo storage',
                    'components': [
                        {'name': 'os_powered_storage'}
                    ]
                },
            },
            'components': {
                'os_powered_compute': {
                    'capabilities': {
                        'required': ['cap_id_1'],
                        'advisory': ['cap_id_2'],
                        'deprecated': ['cap_id_3'],
                        'removed': []
                    }
                },
                'os_powered_storage': {
                    'capabilities': {
                        'required': ['cap_id_5'],
                        'advisory': ['cap_id_6'],
                        'deprecated': [],
                        'removed': []
                    }
                }
            }
        }

        caps = self.guidelines.get_target_capabilities(json)
        expected = sorted(['cap_id_1', 'cap_id_2', 'cap_id_3',
                           'cap_id_5', 'cap_id_6'])
        self.assertEqual(expected, sorted(caps))

        caps = self.guidelines.get_target_capabilities(json,
                                                       types=['required'],
                                                       target='object')
        expected = ['cap_id_5']
        self.assertEqual(expected, caps)

        # Schema version 1.4
        json = {
            'platform': {'required': ['compute', 'object']},
            'schema': '1.4',
            'components': {
                'compute': {
                    'required': ['cap_id_1'],
                    'advisory': [],
                    'deprecated': [],
                    'removed': []
                },
                'object': {
                    'required': ['cap_id_2'],
                    'advisory': ['cap_id_3'],
                    'deprecated': [],
                    'removed': []
                }
            }
        }

        # Test platform capabilities
        caps = self.guidelines.get_target_capabilities(json)
        expected = sorted(['cap_id_1', 'cap_id_2', 'cap_id_3'])
        self.assertEqual(expected, sorted(caps))

        caps = self.guidelines.get_target_capabilities(json,
                                                       types=['required'],
                                                       target='object')
        expected = ['cap_id_2']
        self.assertEqual(expected, caps)

    def test_get_test_list(self):
        """Test when getting the guideline test list."""

        # Schema version 2.0
        json = {
            'metadata': {
                'schema': '2.0',
            },
            'capabilities': {
                'cap-1': {
                    'tests': {
                        'test_1': {'idempotent_id': 'id-1234'},
                        'test_2': {'idempotent_id': 'id-5678',
                                   'aliases': ['test_2_1']},
                        'test_3': {'idempotent_id': 'id-1111',
                                   'flagged': {'reason': 'foo'}}
                    }
                },
                'cap-2': {
                    'tests': {
                        'test_4': {'idempotent_id': 'id-1233'}
                    }
                }
            }
        }

        tests = self.guidelines.get_test_list(json, ['cap-1'])
        expected = ['test_1[id-1234]', 'test_2[id-5678]',
                    'test_2_1[id-5678]', 'test_3[id-1111]']
        self.assertEqual(expected, tests)

        tests = self.guidelines.get_test_list(json, ['cap-1'],
                                              alias=False, show_flagged=False)
        expected = ['test_1[id-1234]', 'test_2[id-5678]']
        self.assertEqual(expected, tests)

        # Schema version 1.4
        json = {
            'schema': '1.4',
            'capabilities': {
                'cap-1': {
                    'tests': {
                        'test_1': {'idempotent_id': 'id-1234'},
                        'test_2': {'idempotent_id': 'id-5678',
                                   'aliases': ['test_2_1']},
                        'test_3': {'idempotent_id': 'id-1111',
                                   'flagged': {'reason': 'foo'}}
                    }
                },
                'cap-2': {
                    'tests': {
                        'test_4': {'idempotent_id': 'id-1233'}
                    }
                }
            }
        }
        tests = self.guidelines.get_test_list(json, ['cap-1'])
        expected = ['test_1[id-1234]', 'test_2[id-5678]',
                    'test_2_1[id-5678]', 'test_3[id-1111]']
        self.assertEqual(expected, tests)

        tests = self.guidelines.get_test_list(json, ['cap-1'],
                                              alias=False, show_flagged=False)
        expected = ['test_1[id-1234]', 'test_2[id-5678]']
        self.assertEqual(expected, tests)

        # Schema version 1.2
        json = {
            'schema': '1.2',
            'capabilities': {
                'cap-1': {
                    'tests': ['test_1', 'test_2']
                },
                'cap-2': {
                    'tests': ['test_3']
                }
            }
        }
        tests = self.guidelines.get_test_list(json, ['cap-2'])
        self.assertEqual(['test_3'], tests)

redpajama_set_name: RedPajamaGithub


text:
package org.elasticsoftware.rtp.packet;

import org.jboss.netty.buffer.ChannelBuffer;

/**
 * @author <a:mailto="bruno.carvalho@wit-software.com" />Bruno de Carvalho</a>
 */
public class AppDataPacket extends ControlPacket {

    // constructors ---------------------------------------------------------------------------------------------------

    public AppDataPacket(Type type) {
        super(type);
    }

    // public static methods ------------------------------------------------------------------------------------------

    public static ChannelBuffer encode(int currentCompoundLength, int fixedBlockSize, AppDataPacket packet) {
        return null;
    }

    // ControlPacket --------------------------------------------------------------------------------------------------

    @Override
    public ChannelBuffer encode(int currentCompoundLength, int fixedBlockSize) {
        return encode(currentCompoundLength, fixedBlockSize, this);
    }

    @Override
    public ChannelBuffer encode() {
        return encode(0, 0, this);
    }
}


text:
import math
import numpy as np
import pysam
import clodius.tiles.bigwig as ctbw

def abs2genomic(chromsizes, start_pos, end_pos):
    abs_chrom_offsets = np.r_[0, np.cumsum(chromsizes)]
    cid_lo, cid_hi = (
        np.searchsorted(abs_chrom_offsets, [start_pos, end_pos], side="right") - 1
    )
    rel_pos_lo = start_pos - abs_chrom_offsets[cid_lo]
    rel_pos_hi = end_pos - abs_chrom_offsets[cid_hi]
    start = rel_pos_lo
    for cid in range(cid_lo, cid_hi):
        yield cid, start, chromsizes[cid]
        start = 0
    yield cid_hi, start, rel_pos_hi

def load_reads(samfile, start_pos, end_pos, chrom_order=None):
    """
    Sample reads from the specified region, assuming that the chromosomes
    are ordered in some fashion. Returns an list of pysam reads

    Parameters:
    -----------
    samfile: pysam.AlignmentFile
        A pysam entry into an indexed bam file
    start_pos: int
        The start position of the sampled region
    end_pos: int
        The end position of the sampled region
    chrom_order: ['chr1', 'chr2',...]
        A listing of chromosome names to use as the order

    Returns
    -------
    reads: [read1, read2...]
        The list of in the sampled regions
    """
    # if chromorder is not None...
    # specify the chromosome order for the fetched reads

    references = np.array(samfile.references)
    lengths = np.array(samfile.lengths)

    ref_lengths = dict(zip(references, lengths))

    # we're going to create a natural ordering for references
    # e.g. (chr1, chr2,..., chr10, chr11...chr22,chrX, chrY, chrM...)
    references = ctbw.natsorted(references)
    lengths = [ref_lengths[r] for r in references]

    abs_chrom_offsets = np.r_[0, np.cumsum(lengths)]

    if chrom_order:
        chrom_order = np.array(chrom_order)
        chrom_order_ixs = np.nonzero(np.in1d(references, chrom_order))
        lengths = lengths[chrom_order_ixs]

    results = {
        "id": [],
        "from": [],
        "to": [],
        "md": [],
        "chrName": [],
        "chrOffset": [],
        "cigar": [],
    }

    for cid, start, end in abs2genomic(lengths, start_pos, end_pos):
        chr_offset = int(abs_chrom_offsets[cid])

        seq_name = f"{references[cid]}"
        reads = samfile.fetch(seq_name, start, end)

        for read in reads:
            if read.is_unmapped:
                continue
            # query_seq = read.query_sequence

            # differences = []

            # try:
            #     for counter, (qpos, rpos, ref_base) in enumerate(read.get_aligned_pairs(with_seq=True)):
            #         # inferred from the pysam source code:
            #         # https://github.com/pysam-developers/pysam/blob/3defba98911d99abf8c14a483e979431f069a9d2/pysam/libcalignedsegment.pyx
            #         # and GitHub issue:
            #         # https://github.com/pysam-developers/pysam/issues/163
            #         #print('qpos, rpos, ref_base', qpos, rpos, ref_base)
            #         if rpos is None:
            #             differences += [(qpos, 'I')]
            #         elif qpos is None:
            #             differences += [(counter, 'D')]
            #         elif ref_base.islower():
            #             differences += [(qpos, query_seq[qpos], ref_base)]
            # except ValueError as ve:
            #     # probably lacked an MD string
            #     pass
            try:
                results["id"] += [read.query_name]
                results["from"] += [int(read.reference_start + chr_offset)]
                results["to"] += [int(read.reference_end + chr_offset)]
                results["chrName"] += [read.reference_name]
                results["chrOffset"] += [chr_offset]
                results["cigar"] += [read.cigarstring]
            except:
                raise

            try:
                results["md"] += [read.get_tag("MD")]
            except KeyError:
                results["md"] += [""]
                continue

    return results

def tileset_info(filename):
    """
    Get the tileset info for a bam file

    Parameters
    ----------
    tileset: tilesets.models.Tileset object
        The tileset that the tile ids should be retrieved from

    Returns
    -------
    tileset_info: {'min_pos': [],
                    'max_pos': [],
                    'tile_size': 1024,
                    'max_zoom': 7
                    }
    """
    samfile = pysam.AlignmentFile(filename)
    total_length = sum(samfile.lengths)

    references = np.array(samfile.references)
    lengths = np.array(samfile.lengths)

    ref_lengths = dict(zip(references, lengths))
    lengths = [ref_lengths[r] for r in references]

    tile_size = 256
    max_zoom = math.ceil(math.log(total_length / tile_size) / math.log(2))

    tileset_info = {
        "min_pos": [0],
        "max_pos": [total_length],
        "max_width": tile_size * 2 ** max_zoom,
        "tile_size": tile_size,
        "chromsizes": list(zip(references, [int(l) for l in lengths])),
        "max_zoom": max_zoom,
    }

    return tileset_info

def tiles(filename, tile_ids, index_filename=None, max_tile_width=None):
    """
    Generate tiles from a bigwig file.

    Parameters
    ----------
    tileset: tilesets.models.Tileset object
        The tileset that the tile ids should be retrieved from
    tile_ids: [str,...]
        A list of tile_ids (e.g. xyx.0.0) identifying the tiles
        to be retrieved
    index_filename: str
        The name of the file containing the index
    max_tile_width: int
        How wide can each tile be before we return no data. This
        can be used to limit the amount of data returned.

    Returns
    -------
    tile_list: [(tile_id, tile_data),...]
        A list of tile_id, tile_data tuples
    """
    generated_tiles = []
    tsinfo = tileset_info(filename)
    samfile = pysam.AlignmentFile(filename, index_filename=index_filename)

    for tile_id in tile_ids:
        tile_id_parts = tile_id.split("|")[0].split(".")
        tile_position = list(map(int, tile_id_parts[1:3]))

        tile_width = tsinfo["max_width"] / 2 ** int(tile_position[0])

        if max_tile_width and tile_width >= max_tile_width:
            # this tile is larger than the max allowed
            return [
                (
                    tile_id,
                    {
                        "error": f"Tile too large, no data returned. Max tile size: {max_tile_width}"
                    },
                )
            ]
        else:
            start_pos = int(tile_position[1]) * tile_width
            end_pos = start_pos + tile_width

            tile_value = load_reads(samfile, start_pos=start_pos, end_pos=end_pos)
            generated_tiles += [(tile_id, tile_value)]

    return generated_tiles


text:
package server

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"
	"time"

	"github.com/intervention-engine/multifactorriskservice/models"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"gopkg.in/mgo.v2/dbtest"

	"github.com/gin-gonic/gin"
	"github.com/intervention-engine/fhir/server"
	"github.com/robfig/cron"
	"github.com/stretchr/testify/suite"
)

// In order for 'go test' to run this suite, we need to create
// a normal test function and pass our suite to suite.Run
func TestCronSuite(t *testing.T) {
	suite.Run(t, new(CronSuite))
}

type CronSuite struct {
	suite.Suite
	DBServer     *dbtest.DBServer
	DBServerPath string
	Session      *mgo.Session
	Database     *mgo.Database
	FHIRServer   *httptest.Server
	REDCapServer *httptest.Server
	Studies      models.StudyMap
}

func (suite *CronSuite) SetupSuite() {
	require := suite.Require()

	// Turn off debug mode since all of the logging gets in the way
	gin.SetMode(gin.ReleaseMode)

	suite.DBServer = &dbtest.DBServer{}
	var err error
	suite.DBServerPath, err = ioutil.TempDir("", "mongotestdb")
	if err != nil {
		panic(err)
	}
	suite.DBServer.SetPath(suite.DBServerPath)

	// Setup the mock REDCap server
	f, err := os.Open("../fixtures/example_records.json")
	require.NoError(err)
	suite.REDCapServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		io.Copy(w, f)
	}))
}

func (suite *CronSuite) SetupTest() {
	require := suite.Require()

	suite.Session = suite.DBServer.Session()
	suite.Database = suite.Session.DB("redcap-riskservice-test")

	fe := gin.New()
	server.RegisterRoutes(fe, nil, server.NewMongoDataAccessLayer(suite.Database), server.Config{})
	suite.FHIRServer = httptest.NewServer(fe)

	// Add the patients to the database
	data, err := os.Open("../fixtures/patients_bundle.json")
	require.NoError(err)
	defer data.Close()
	res, err := http.Post(suite.FHIRServer.URL+"/", "application/json", data)
	require.NoError(err)
	defer res.Body.Close()
}

func (suite *CronSuite) TearDownTest() {
	if suite.FHIRServer != nil {
		suite.FHIRServer.Close()
	}
	suite.Session.Close()
	suite.DBServer.Wipe()
}

func (suite *CronSuite) TearDownSuite() {
	suite.DBServer.Stop()
	if err := os.RemoveAll(suite.DBServerPath); err != nil {
		fmt.Fprintf(os.Stderr, "WARNING: Error cleaning up temp directory: %s", err.Error())
	}
	if suite.REDCapServer != nil {
		suite.REDCapServer.Close()
	}
}

// Warning: This test *should* be OK -- but because it relies on timing, it *could* get flakey
func (suite *CronSuite) TestCron() {
	require := suite.Require()
	assert := suite.Assert()

	// Schedule the cron
	c := cron.New()
	err := ScheduleRefreshRiskAssessmentsCron(c, "@every 1s", suite.FHIRServer.URL, suite.REDCapServer.URL, "12345", suite.Database.C("pies"), "http://example.org/pies/")
	c.Start()
	defer c.Stop()

	// Check we have no risk assessments yet
	raCollection := suite.Database.C("riskassessments")
	count, err := raCollection.Find(bson.M{"method.coding.code": "MultiFactor"}).Count()
	require.NoError(err)
	assert.Equal(0, count)

	// Check for updated count every 500 ms for a total of 10s, then give up.
	// This helps account for slow machines.
	for i := 0; i < 20 && count != 3; i++ {
		time.Sleep(500 * time.Millisecond)
		count, err = raCollection.Find(bson.M{"method.coding.code": "MultiFactor"}).Count()
		require.NoError(err)
	}
	assert.Equal(3, count)
}


text:
angular.module("appSoftware")
        .controller("appSoftwareCtrl", AppSoftwareCtrl);

AppSoftwareCtrl.$inject = ['$scope', 'FactoryService', '$location', 'CategoriaService', '$routeParams', 'PaginatorService'];
function AppSoftwareCtrl($scope, FactoryService, $location, CategoriaService, $routeParams, PaginatorService) {

    $scope.titulo = "Gerenciamento de Softwares";
    $scope.empresas = [];
    $scope.empresa = {};
    $scope.softwares = [];
    $scope.software = {};
    $scope.categorias = CategoriaService.all();
    $scope.filtro = {
        categoria_id: "0"
    };

    $scope.paginador = PaginatorService;

    if ($routeParams !== undefined && $routeParams.categoria_id !== undefined) {
        $scope.filtro.categoria_id = $routeParams.categoria_id;
    }
    if ($routeParams !== undefined && $routeParams.empresa_id !== undefined) {
        $scope.software.empresa_id = parseInt($routeParams.empresa_id);
    }

    $scope.mensagem = "";
    $scope.notificacaoClass = "";

    var carregarLista = function () {
        FactoryService.all('software').then(function (data) {
            $scope.paginador.setData(data);
            $scope.softwares = data;
        });
    };

    $scope.adicionar = function (software) {

        var data = angular.copy(software);

        FactoryService.save('software', null, null, data).then(function (data) {
            if (data !== false) {
                $scope.software = {};
                $scope.formulario.$setPristine();
                carregarLista();
                $scope.mensagem = "Operação realizada com sucesso";
                $scope.notificacaoClass = "alert-success";
            } else {
                $scope.mensagem = "Erro ao inserir software";
                $scope.notificacaoClass = "alert-error";
            }
        });

    };

    $scope.editData = function (obj) {
        $scope.mensagem = "";
        $scope.software = obj;
    };

    $scope.apagar = function () {
        FactoryService.delete('software', $scope.software).then(function () {
            $scope.software = {};
            $scope.formulario.$setPristine();
            carregarLista();
            $scope.mensagem = "Registro excluído com sucesso";
            $scope.notificacaoClass = "alert-success";
        });

    };

    var carregarEmpresas = function () {
        FactoryService.all('empresa').then(function (data) {
            $scope.empresas = data;
        });
    };

    $scope.go = function (path) {
        $location.path(path);
    };

    $scope.isSelecionado = function () {
        return  $scope.empresa.id > 0;
    };

    $scope.getFiltros = function (filtro) {
        var filtros = [];
        if (filtro.categoria_id !== "0") {
            filtros['categoria_id'] = filtro.categoria_id;
        }
        if (filtro.nome !== undefined && filtro.nome !== "") {
            filtros['nome'] = filtro.nome;
        }
        return filtros;
    }

    carregarEmpresas();
    carregarLista();

}


text:
<?php

class Model_Country_Create extends Model_Country_Coord
{
	/**
	 * The ruler name of the country.
	 *
	 * @access private
	 * @var    string
	 */
	private $_countryRulerName;

	/**
	 * The name of the country.
	 *
	 * @access private
	 * @var    string
	 */
	private $_countryName;

	/**
	 * Class constructor, set the variables.
	 *
	 * @access public
	 * @param string  $countryRulerName
	 * @param string  $countryName
	 */
	public function __construct($countryRulerName, $countryName) {
		$this->_countryRulerName = trim($countryRulerName);
		$this->_countryName      = trim($countryName);
	}

	/**
	 * Create the country.
	 *
	 * @access public
	 * @param  Model_User_Instance $user
	 * @throws Exception           If the ruler or country name are empty.
	 * @throws Exception           If the ruler and country name combo is already taken.
	 * @return int
	 */
	public function create($user) {
		// Has the user actually entered a ruler and a country name?
		if (empty($this->_countryRulerName) || empty($this->_countryName)) {
			throw new Exception('register-error-empty');
		}

		// Does the ruler name and country name combination already exist?
		if (Model_Country_RulerAndCountryNameExist::check($this->_countryRulerName, $this->_countryName)) {
			throw new Exception('register-error-name-combo-taken');
		}

		// Generate coords
		$this->generateCoords();

		// Insert the country into the database
		// Get the database connection
		$database  = Core_Database::getInstance();
		$statement = $database->prepare("
			INSERT INTO `country`
			(
				`round_id`,
				`user_id`,
				`country_x_coord`,
				`country_y_coord`,
				`country_z_coord`,
				`country_status`,
				`country_ruler_name`,
				`country_name`
			)
			VALUES
			(
				:round_id,
				:user_id,
				:country_x_coord,
				:country_y_coord,
				:country_z_coord,
				:country_status,
				:country_ruler_name,
				:country_name
			)
		");

		// Execute the query
		$statement->execute(array(
			':round_id'           => GAME_ROUND,
			':user_id'            => $user->getInfo('user_id'),
			':country_x_coord'    => $this->getCoord('x'),
			':country_y_coord'    => $this->getCoord('y'),
			':country_z_coord'    => $this->getCoord('z'),
			':country_status'     => PLANET_MEMBER,
			':country_ruler_name' => $this->_countryRulerName,
			':country_name'       => $this->_countryName
		));

        // Get the country ID
        $countryId = $database->lastInsertId();

        // Log this event
        Core_Log::add(array(
            'user_id'     => $user->getInfo('user_id'),
            'country_id'  => $countryId,
            'log_action'  => 'country-create',
            'log_status'  => 'success',
            'log_message' => 'User successfully created their country.'
        ));

		// Return the user ID
		return $countryId;
	}
}


text:
package com.lostcode.javalib.entities.components;

/**
 * Base interface for components.
 *
 * @author Natman64
 *
 */
public interface Component {

	/**
	 * Called when this Component is added to a {@link ComponentManager}.
	 *
	 * @param container
	 *            The {@link ComponentManager} this Component is added to.
	 */
	void onAdd(ComponentManager container);

	/**
	 * Called when this Component is removed from a {@link ComponentManager}.
	 *
	 * @param container
	 *            The {@link ComponentManager} this Component is removed from.
	 */
	void onRemove(ComponentManager container);

}


text:
package com.github.onsdigital.search.util;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

import java.io.IOException;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.junit.Assert;

import com.github.onsdigital.search.EmbeddedElasticSearchServer;
import com.github.onsdigital.search.bean.SearchResult;

public class SearchHelperTest {

	private EmbeddedElasticSearchServer embeddedServer;

	public void startEmbeddedServer() throws ElasticsearchException,
			IOException {
		Settings settings = ImmutableSettings.builder()
				.put("http.enabled", false)
				.put("path.data", "target/elasticsearch-data").build();
		embeddedServer = new EmbeddedElasticSearchServer(settings, "testNode");
		prepareMockData();
	}

	private void prepareMockData() throws ElasticsearchException, IOException {
		embeddedServer
				.getClient()
				.prepareIndex("testindex", "testtype", String.valueOf(1))
				.setSource(
						jsonBuilder().startObject().field("title", "testTitle")
								.field("tags", "taggy", "tennis", "doh")
								.field("theme", "testTheme").endObject()).get();
	}

	public void shutdownEmbeddedServer() {
		embeddedServer.shutdown();
	}

	public void testSearchQuery() throws Exception {
//		SearchHelper util = new SearchHelper(embeddedServer.getClient());
//		SearchResult result = util.search(new ONSQueryBuilder("testindex")
//				.setSearchTerm("do").setFields("tags"));
//		Assert.assertEquals(1, result.getNumberOfResults());
	}

}


text:
<?php

namespace Colibri\Query\Expr\Func;

use Colibri\Exception\BadCallMethodException;
use Colibri\Query\Expr\Func;

class Power extends Func
{

    /**
     * Power constructor.
     * MySQL Function POWER
     *
     * @param array $parameters
     *
     * @throws BadCallMethodException
     */
    public function __construct(...$parameters)
    {
        parent::__construct('POWER', $parameters);
    }

}


text:
export CATALINA_HOME=/opt/cloudstack/apache-tomcat-6.0.32
cd /opt/cloudstack/incubator-cloudstack/
nohup ant run > /dev/null 2>&1 &
exit 0


text:
////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove() {
	var move = null;
	if(move === null){
    	var i = 0
    	while(i < 5){
        	move = getInput();
        	if(move == "paper"){
            	console.log("player chose "+move);
        		i+=5
        	}else if(move == "rock"){
        	    console.log("player chose "+move);
    	    	i+=5
	        }else if(move == "scissors"){
            	console.log("player chose "+move);
        		i+=5
    	    }else{
        		console.log(move+" is not a valid input");
        	}
    	}
	}
    return move;
}

function getComputerMove() {
    // Write an expression that operates on a variable called `move`
    var computerMove = null;
    // If a `move` has a value, your expression should evaluate to that value.
	if(computerMove === null){
		computerMove = randomPlay();
	}
	// However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    console.log("computer choses "+computerMove);
    return computerMove;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    if (playerMove == "rock" && computerMove == "paper"){
    	winner = "computer";
    }else if (playerMove == "rock" && computerMove == "scissors"){
    	winner = "player";
    }else if (playerMove == computerMove){
    	winner = "tie";
    }else if (playerMove == "paper" && computerMove == "scissors"){
    	winner = "computer";
    }else if (playerMove == "paper" && computerMove == "rock"){
    	winner = "player";
    }else if (playerMove == "scissors" && computerMove == "rock"){
    	winner = "computer";
    }else if (playerMove == "scissors" && computerMove == "paper"){
    	winner = "player";
    }
    return winner;
}

function playToFive() {
	console.log('Let\'s play Rock Paper Scissors');
	var playerWins = 0;
	var computerWins = 0;
	var count = 0;
	while(count < 30){
		var atmwinner = getWinner(getPlayerMove(),getComputerMove())
		console.log(atmwinner+" wins this round");

		if(atmwinner === "player"){
			playerWins+=1;
		}else if(atmwinner === "computer" ){
			computerWins+=1;
		}
		console.log("player "+playerWins+"|"+"computer "+computerWins);

        if(computerWins == 5){
        	console.log("computer wins the match!");
        	count += 31;
        }else if(playerWins == 5){
        	console.log("player wins the match!");
        	count += 31;
        }
	}

	return [playerWins, computerWins];
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE component SYSTEM "../misc/component.dtd" [
<!ENTITY standard_uicomponent_attributes		SYSTEM "../entities/standard_uicomponent_attributes.xml">
<!ENTITY widget_var_attribute					SYSTEM "../entities/widget_var_attribute.xml">
]>
<component>
	<tag>outputLabel</tag>
	<tagClass>org.primefaces.component.outputlabel.OutputLabelTag</tagClass>
	<componentClass>org.primefaces.component.outputlabel.OutputLabel</componentClass>
	<componentType>org.primefaces.component.Outputlabelk</componentType>
	<componentFamily>org.primefaces.component</componentFamily>
	<rendererType>org.primefaces.component.OutputLabelRenderer</rendererType>
	<rendererClass>org.primefaces.component.outputlabel.OutputLabelRenderer</rendererClass>
	<parent>javax.faces.component.html.HtmlOutputLabel</parent>
    <description>OutputLabel is an extension to the standard outputLabel.</description>
	<attributes>
		&standard_uicomponent_attributes;
        <attribute>
			<name>value</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Label to display.</description>
		</attribute>
        <attribute>
			<name>accesskey</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>The accesskey attribute is a standard HTML attribute that sets the access key that transfers focus to this element when pressed.</description>
		</attribute>
        <attribute>
			<name>dir</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Direction indication for text that does not inherit directionality. Valid values are LTR and RTL.</description>
		</attribute>
        <attribute>
			<name>escape</name>
			<required>false</required>
			<type>java.lang.Boolean</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Defines if value should be escaped or not.</description>
		</attribute>
        <attribute>
			<name>for</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Id of the associated input component.</description>
		</attribute>
		<attribute>
			<name>lang</name>
            <required>false</required>
			<type>java.lang.String</type>
            <ignoreInComponent>true</ignoreInComponent>
            <description>The lang attribute is a standard HTML attribute that sets the code describing the language to be used in the markup generated by this component..</description>
		</attribute>
		<attribute>
			<name>tabindex</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Position in the tabbing order.</description>
		</attribute>
		<attribute>
			<name>title</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Advisory tooltip informaton.</description>
		</attribute>
		<attribute>
			<name>style</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Inline style of the component.</description>
		</attribute>
		<attribute>
			<name>styleClass</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Style class of the component.</description>
		</attribute>
		<attribute>
			<name>onblur</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Client side callback to execute when component loses focus.</description>
		</attribute>
		<attribute>
			<name>onclick</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Client side callback to execute when component is clicked.</description>
        </attribute>
		<attribute>
			<name>ondblclick</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Client side callback to execute when component is double clicked.</description>
		</attribute>
		<attribute>
			<name>onfocus</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Client side callback to execute when component receives focus.</description>
		</attribute>
		<attribute>
			<name>onkeydown</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Client side callback to execute when a key is pressed down over component.</description>
		</attribute>
		<attribute>
			<name>onkeypress</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Client side callback to execute when a key is pressed and released over component.</description>
		</attribute>
		<attribute>
			<name>onkeyup</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Client side callback to execute when a key is released over component.</description>
		</attribute>
		<attribute>
			<name>onmousedown</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Client side callback to execute when a pointer button is pressed down over component.</description>
		</attribute>
		<attribute>
			<name>onmousemove</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Client side callback to execute when a pointer button is moved within component.</description>
		</attribute>
		<attribute>
			<name>onmouseout</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Client side callback to execute when a pointer button is moved away from component.</description>
		</attribute>
		<attribute>
			<name>onmouseover</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Client side callback to execute when a pointer button is moved onto component.</description>
		</attribute>
		<attribute>
			<name>onmouseup</name>
			<required>false</required>
			<type>java.lang.String</type>
			<ignoreInComponent>true</ignoreInComponent>
            <description>Client side callback to execute when a pointer button is released over component.</description>
		</attribute>
	</attributes>
</component>


text:
"""
Support for Google Play Music Desktop Player.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.gpmdp/
"""
import logging
import json
import socket

from homeassistant.components.media_player import (
    MEDIA_TYPE_MUSIC, SUPPORT_NEXT_TRACK, SUPPORT_PREVIOUS_TRACK,
    SUPPORT_PAUSE, MediaPlayerDevice)
from homeassistant.const import (
    STATE_PLAYING, STATE_PAUSED, STATE_OFF)

_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['websocket-client==0.37.0']
SUPPORT_GPMDP = SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the GPMDP platform."""
    from websocket import create_connection

    name = config.get("name", "GPM Desktop Player")
    address = config.get("address")

    if address is None:
        _LOGGER.error("Missing address in config")
        return False

    add_devices([GPMDP(name, address, create_connection)])

class GPMDP(MediaPlayerDevice):
    """Representation of a GPMDP."""

    # pylint: disable=too-many-public-methods, abstract-method
    # pylint: disable=too-many-instance-attributes
    def __init__(self, name, address, create_connection):
        """Initialize the media player."""
        self._connection = create_connection
        self._address = address
        self._name = name
        self._status = STATE_OFF
        self._ws = None
        self._title = None
        self._artist = None
        self._albumart = None
        self.update()

    def get_ws(self):
        """Check if the websocket is setup and connected."""
        if self._ws is None:
            try:
                self._ws = self._connection(("ws://" + self._address +
                                             ":5672"), timeout=1)
            except (socket.timeout, ConnectionRefusedError,
                    ConnectionResetError):
                self._ws = None
        elif self._ws.connected is True:
            self._ws.close()
            try:
                self._ws = self._connection(("ws://" + self._address +
                                             ":5672"), timeout=1)
            except (socket.timeout, ConnectionRefusedError,
                    ConnectionResetError):
                self._ws = None
        return self._ws

    def update(self):
        """Get the latest details from the player."""
        websocket = self.get_ws()
        if websocket is None:
            self._status = STATE_OFF
            return
        else:
            state = websocket.recv()
            state = ((json.loads(state))['payload'])
            if state is True:
                websocket.recv()
                websocket.recv()
                song = websocket.recv()
                song = json.loads(song)
                self._title = (song['payload']['title'])
                self._artist = (song['payload']['artist'])
                self._albumart = (song['payload']['albumArt'])
                self._status = STATE_PLAYING
            elif state is False:
                self._status = STATE_PAUSED

    @property
    def media_content_type(self):
        """Content type of current playing media."""
        return MEDIA_TYPE_MUSIC

    @property
    def state(self):
        """Return the state of the device."""
        return self._status

    @property
    def media_title(self):
        """Title of current playing media."""
        return self._title

    @property
    def media_artist(self):
        """Artist of current playing media (Music track only)."""
        return self._artist

    @property
    def media_image_url(self):
        """Image url of current playing media."""
        return self._albumart

    @property
    def name(self):
        """Return the name of the device."""
        return self._name

    @property
    def supported_media_commands(self):
        """Flag of media commands that are supported."""
        return SUPPORT_GPMDP

    def media_next_track(self):
        """Send media_next command to media player."""
        websocket = self.get_ws()
        if websocket is None:
            return
        websocket.send('{"namespace": "playback", "method": "forward"}')

    def media_previous_track(self):
        """Send media_previous command to media player."""
        websocket = self.get_ws()
        if websocket is None:
            return
        websocket.send('{"namespace": "playback", "method": "rewind"}')

    def media_play(self):
        """Send media_play command to media player."""
        websocket = self.get_ws()
        if websocket is None:
            return
        websocket.send('{"namespace": "playback", "method": "playPause"}')
        self._status = STATE_PAUSED
        self.update_ha_state()

    def media_pause(self):
        """Send media_pause command to media player."""
        websocket = self.get_ws()
        if websocket is None:
            return
        websocket.send('{"namespace": "playback", "method": "playPause"}')
        self._status = STATE_PAUSED
        self.update_ha_state()


text:
/**
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */
package net.sourceforge.pmd.lang.rule.properties;

import java.util.Map;

import net.sourceforge.pmd.PropertyDescriptorFactory;
import net.sourceforge.pmd.lang.rule.properties.factories.BasicPropertyDescriptorFactory;

/**
 * Defines a datatype that supports the single Long property values within an upper and lower boundary.
 *
 * @author Brian Remedios
 */
public class LongProperty extends AbstractNumericProperty<Long> {

	public static final PropertyDescriptorFactory FACTORY = new BasicPropertyDescriptorFactory<LongProperty>(Long.class, numberFieldTypesByKey) {

		public LongProperty createWith(Map<String, String> valuesById) {
			final String[] minMax = minMaxFrom(valuesById);
			return new LongProperty(
					nameIn(valuesById),
					descriptionIn(valuesById),
					Long.valueOf(minMax[0]),
					Long.valueOf(minMax[1]),
					Long.valueOf(numericDefaultValueIn(valuesById)),
					0f);
		}
	};

	/**
	 * Constructor for LongProperty.
	 * @param theName String
	 * @param theDescription String
	 * @param min Long
	 * @param max Long
	 * @param theDefault Long
	 * @param theUIOrder float
	 * @throws IllegalArgumentException
	 */
	public LongProperty(String theName, String theDescription, Long min, Long max, Long theDefault, float theUIOrder) {
		super(theName, theDescription, min, max, theDefault, theUIOrder);
	}

	/**
     * Constructor for LongProperty that limits itself to a single value within the specified limits.
     * Converts string arguments into the Long values.
     *
     * @param theName String
     * @param theDescription String
     * @param minStr String
     * @param maxStr String
     * @param defaultStr String
     * @param theUIOrder float
     * @throws IllegalArgumentException
     */
    public LongProperty(String theName, String theDescription, String minStr, String maxStr, String defaultStr, float theUIOrder) {
        this(theName, theDescription, longFrom(minStr), longFrom(maxStr), longFrom(defaultStr), theUIOrder);
    }

    /**
     * @param numberString String
     * @return Long
     */
    public static Long longFrom(String numberString) {
        return Long.valueOf(numberString);
    }

	/**
	 * @return Class
	 * @see net.sourceforge.pmd.PropertyDescriptor#type()
	 */
	public Class<Long> type() {
		return Long.class;
	}

	/**
	 * @param value String
	 * @return Object
	 */
	protected Object createFrom(String value) {
		return longFrom(value);
	}
}


text:
var Comment = function(id, user, message, rating, date){
	this.id = id;
	this.user = user;
	this.message = message;
	this.rating = rating;
	this.date = date;
};

module.exports = Comment;


text:
package com;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * test
 *
 * @author ZhangShaowei on 2018/4/3 10:05
 **/
public class StaticTests {

	private static final Gson gson = new GsonBuilder()
			.setLenient()
			.setDateFormat("yyyy-MM-dd HH:mm:ss").create();

	/**
	 * jackson的json转换器
	 */
	private static ObjectMapper mapper = new ObjectMapper();

	/**
	 * 初始化mapper参数
	 */
	static {
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //忽略没有的属性asd
		mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); //允许没有双引号
		mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); //允许转义字符
		mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); //允许单引号
		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	}

	private static final String RANDOM_STR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

	private static final java.util.Random RANDOM = new java.util.Random();

	private static final String MAC_NAME = "HmacSHA1";
	private static final String ENCODING = "UTF-8";

	public static void main(String[] args) throws Exception {

		String json = "{\"FULL_NAME\":\"name\"}";

		System.out.println(gson.fromJson(json, A.class));

//		System.out.println(System.currentTimeMillis());

//		JsonElement jsonBody = gson.fromJson("123", JsonElement.class);asd
//		System.out.println(jsonBody);
//		System.err.println(jsonBody.isJsonObject());
//		System.out.println(jsonBody.toString());

//		SortedMap<String, String> sortedMap = new TreeMap<>();
//		sortedMap.put("Notice", "11886");
//		sortedMap.put("SecretId", "289efb7512e54146273b982456b03f42ea93");
//		sortedMap.put("Timestamp", "1484718385");
//		sortedMap.put("content", "ew0KICAgICJQYXJhbWV0ZXIiOiAiMSINCn0=");
//		sortedMap.put("encryptCode", "0");
//		sortedMap.put("zipCode", "0");
//
//		sortedMap.keySet().forEach(System.out::println);

//		String data = "GETapi.ele-cloud.com/invoice/v1/interfaceTest?Nonce=11886&SecretId=289efb7512e54146273b982456b03f42ea93&Timestamp=1484718385&content=ew0KICAgICJQYXJhbWV0ZXIiOiAiMSINCn0=&encryptCode=0&zipCode=0";
//
//		String key = "27a06832a2214a4fa3b7105e4a72d370;";
//
//		byte[] encrypt = hmacSHA1Encrypt(data, key);
//
//		System.out.println(Base64.encodeBase64String(encrypt));

//		String body = "{\"data\":{\"name\"=\"name\",\"age\":1}}";
//		Dto<A> dto = toDto(body, A.class);
//		System.out.println(dto);
	}

	public static byte[] hmacSHA1Encrypt(String body, String key) throws Exception {
		byte[] data = key.getBytes(ENCODING);
		//根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称asd
		SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);

		//生成一个指定 Mac 算法 的 Mac 对象
		Mac mac = Mac.getInstance(MAC_NAME);
		//用给定密钥初始化 Mac 对象
		mac.init(secretKey);

		//完成 Mac 操作
		return mac.doFinal(body.getBytes(ENCODING));
	}

	public static <T> Dto<T> toDto(String body, Class<T> clazz) {
//		Type type = new TypeToken<Dto<T>>() {
//		}.getType();
		Type type = new ParameterizedType() {
			@Override
			public Type[] getActualTypeArguments() {
				return new Type[]{clazz};
			}

			@Override
			public Type getRawType() {
				return Dto.class;
			}

			@Override
			public Type getOwnerType() {
				return null;
			}
		};
		Dto<T> dto = gson.fromJson(body, type);
		return dto;
	}

	@Data
	@AllArgsConstructor
	static class Dto<T> {
		private T data;
	}

	@Data
	static class A {
		@SerializedName("FULL_NAMEasd")
		private String name;
		private Integer age;
	}

	@Data
	static class B {
		private Integer age;
	}

}


text:
/**
 * Created by CSIP on 2016/12/21.
 */
define(function (require, exports, module) {

    require("jquery");
    require("style");
    var Class = require("class");
    var Element = require("./Element");
    /**
     * 图片按钮组件
     */
    var ImageButtonElement = Class("ImageButtonElement", {
        Extends : Element,
        STATIC: {
            MODULE_NAME : "ImageButtonElement"
        },
        initialize: function(width, height, fontCss, fontSize) {
            ImageButtonElement.Super.call(this, width, height);
            this.fontCss = fontCss;
            this.fontSize = fontSize;
        },
        init : function(where){
            var statement = "";
            var fontCss = this.fontCss || "fa fa-power-off";
            var fontSize = this.fontSize || "18px";
            this.element = ImageButtonElement.Super.prototype.init.call(this, where, statement);
            this.element
                .html("").css({
                    "font-size" : fontSize,
                    "margin" : "8px"
                });
            return this;

        },
        /**
         * 点击事件
         * @param callback
         * @returns {ImageButtonElement}
         */
        click : function(callback){
            this.element.click(callback);
            return this;
        },
        setFontCss : function(fontCss){
            $(this.element.children("i")).removeAttr("class").addClass(fontCss);
            return this;
        },
        toggleFontCss : function(fontCss){
            $(this.element.children("i")).toggleClass(fontCss);
            return this;
        },
        getFontCss : function(){
            return $(this.element.children("i")).attr("class");
        },
        getModuleName : function(){
            return ImageButtonElement.MODULE_NAME;
        }

    });

    module.exports = ImageButtonElement;
});


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace CSC.CSClassroom.Model.Assignments
{
	/// <summary>
	/// An exercise.
	/// </summary>
	public abstract class Question
	{
		/// <summary>
		/// The unique ID for the exercise.
		/// </summary>
		public int Id { get; set; }

		/// <summary>
		/// The ID of the category that contains this exercise.
		/// </summary>
		[Display
		(
			Name = "Category",
			Description = "Select the category for the question."
		)]
		public int QuestionCategoryId { get; set; }

		/// <summary>
		/// The name of the exercise.
		/// </summary>
		[Required]
		[MaxLength(50)]
		[Display
		(
			Name = "Question Name",
			Description = "Enter the name of the question."
		)]
		public string Name { get; set; }

		/// <summary>
		/// The description of the exericse.
		/// </summary>
		[Required]
		[Display
		(
			Name = "Description",
			Description = "Enter the description for the question, using the Markdown language."
		)]
		public string Description { get; set; }

		/// <summary>
		/// Allows partial credit.
		/// </summary>
		[Display
		(
			Name = "Allow Partial Credit",
			Description = "Select whether to allow partial credit."
		)]
		public bool AllowPartialCredit { get; set; }

		/// <summary>
		/// The category that contains this exercise.
		/// </summary>
		public virtual QuestionCategory QuestionCategory { get; set; }

		/// <summary>
		/// The assignment questions referring to this question.
		/// </summary>
		public virtual ICollection<AssignmentQuestion> AssignmentQuestions { get; set; }

		/// <summary>
		/// Returns whether or not the question is a randomly selected question.
		/// </summary>
		public abstract bool HasChoices { get; }

		/// <summary>
		/// Returns whether or not the question is a generated question template.
		/// </summary>
		public abstract bool IsQuestionTemplate { get; }

		/// <summary>
		/// Returns whether or not this question can be duplicated.
		/// </summary>
		public abstract bool CanDuplicate { get; }

		/// <summary>
		/// Returns whether or not this question can be turned into a generated question template.
		/// </summary>
		public abstract bool CanRandomize { get; }

		/// <summary>
		/// The type of solver(s) supported for this question.
		/// </summary>
		protected abstract QuestionSolverType SolverTypes { get; }

		/// <summary>
		/// Returns whether or not the question supports the given solver type.
		/// </summary>
		public bool SupportedSolver(QuestionSolverType solverType)
			=> (SolverTypes & solverType) == solverType;

		/// <summary>
		/// Returns whether or not the question does not support the given solver type.
		/// </summary>
		public bool UnsupportedSolver(QuestionSolverType solverType)
			=> (SolverTypes & solverType) == 0;

		/// <summary>
		/// Returns whether or not the description should be hidden from the edit page.
		/// </summary>
		public bool HideDescription => IsQuestionTemplate || HasChoices;

		/// <summary>
		/// The string displayed for the type of question
		/// </summary>
		public abstract string QuestionTypeDisplay { get; }

		/// <summary>
		/// The string displayed for the description of the question type
		/// </summary>
		public abstract string QuestionTypeDescription { get; }

		/// <summary>
		/// Accepts a question visitor.
		/// </summary>
		public abstract void Accept(IQuestionVisitor questionVisitor);

		/// <summary>
		/// Accepts a question visitor that returns a result.
		/// </summary>
		public abstract TResult Accept<TResult>(IQuestionResultVisitor<TResult> questionVisitor);

		/// <summary>
		/// Accepts a question visitor that returns a result.
		/// </summary>
		public abstract TResult Accept<TResult, TParam1>(
			IQuestionResultVisitor<TResult, TParam1> questionVisitor,
			TParam1 param1);
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>AsymmetricCipherKeyPair (Bouncy Castle Library 1.54 API Specification)</title>
<meta name="date" content="2015-12-29">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.54

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.bouncycastle.crypto

Class AsymmetricCipherKeyPair

java.lang.Object

org.bouncycastle.crypto.AsymmetricCipherKeyPair

public class AsymmetricCipherKeyPair
extends java.lang.Object

a holding class for public/private parameter pairs.

Constructor Summary

Constructors

Constructor and Description

AsymmetricCipherKeyPair(AsymmetricKeyParameter publicParam,
                       AsymmetricKeyParameter privateParam)

basic constructor.

AsymmetricCipherKeyPair(CipherParameters publicParam,
                       CipherParameters privateParam)

Deprecated.

use AsymmetricKeyParameter

Method Summary

Methods

Modifier and Type
Method and Description

AsymmetricKeyParameter
getPrivate()

return the private key parameters.

AsymmetricKeyParameter
getPublic()

return the public key parameters.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AsymmetricCipherKeyPair

public AsymmetricCipherKeyPair(AsymmetricKeyParameter publicParam,
                       AsymmetricKeyParameter privateParam)

basic constructor.

Parameters:

publicParam - a public key parameters object.

privateParam - the corresponding private key parameters.

AsymmetricCipherKeyPair

public AsymmetricCipherKeyPair(CipherParameters publicParam,
                       CipherParameters privateParam)

Deprecated. use AsymmetricKeyParameter

basic constructor.

Parameters:

publicParam - a public key parameters object.

privateParam - the corresponding private key parameters.

Method Detail

getPublic

public AsymmetricKeyParameter getPublic()

return the public key parameters.

Returns:

the public key parameters.

getPrivate

public AsymmetricKeyParameter getPrivate()

return the private key parameters.

Returns:

the private key parameters.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.54

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
__author__ = "Liu Fei"
__github__ = "http://github.com/lfblogs"
__all__ = [
    "Pool",
    "select",
    "execute",
    "pool",
    "exc",
    "field",
    "metaclass",
    "models",
]

"""

Define database connection pool , execute method and simple orm.

"""

from aio2py.db.pool import Pool
from aio2py.db.exc import select,execute