text:
import testtools

from tempest.common import utils
from tempest.common import waiters
from tempest import config
from tempest.lib.common.utils import data_utils
from tempest.lib.common.utils import test_utils
from tempest.lib import decorators
from tempest.lib import exceptions as lib_exc
from tempest.scenario import manager

CONF = config.CONF

class NetworkQoSPlacementTestBase(manager.NetworkScenarioTest):
    """Base class for Network QoS testing

    Base class for testing Network QoS scenarios involving placement
    resource allocations.
    """
    credentials = ['primary', 'admin']
    # The feature QoS minimum bandwidth allocation in Placement API depends on
    # Granular resource requests to GET /allocation_candidates and Support
    # allocation candidates with nested resource providers features in
    # Placement (see: https://specs.openstack.org/openstack/nova-specs/specs/
    # stein/approved/bandwidth-resource-provider.html#rest-api-impact) and this
    # means that the minimum placement microversion is 1.29
    placement_min_microversion = '1.29'
    placement_max_microversion = 'latest'

    # Nova rejects to boot VM with port which has resource_request field, below
    # microversion 2.72
    compute_min_microversion = '2.72'
    compute_max_microversion = 'latest'

    INGRESS_DIRECTION = 'ingress'
    EGRESS_DIRECTION = 'egress'
    ANY_DIRECTION = 'any'
    INGRESS_RESOURCE_CLASS = "NET_BW_IGR_KILOBIT_PER_SEC"
    EGRESS_RESOURCE_CLASS = "NET_BW_EGR_KILOBIT_PER_SEC"

    # For any realistic inventory value (that is inventory != MAX_INT) an
    # allocation candidate request of MAX_INT is expected to be rejected, see:
    # https://github.com/openstack/placement/blob/master/placement/
    # db/constants.py#L16
    PLACEMENT_MAX_INT = 0x7FFFFFFF

    @classmethod
    def setup_clients(cls):
        super().setup_clients()
        cls.placement_client = cls.os_admin.placement_client
        cls.networks_client = cls.os_admin.networks_client
        cls.subnets_client = cls.os_admin.subnets_client
        cls.ports_client = cls.os_primary.ports_client
        cls.routers_client = cls.os_adm.routers_client
        cls.qos_client = cls.os_admin.qos_client
        cls.qos_min_bw_client = cls.os_admin.qos_min_bw_client
        cls.flavors_client = cls.os_adm.flavors_client
        cls.servers_client = cls.os_primary.servers_client

    def _create_flavor_to_resize_to(self):
        old_flavor = self.flavors_client.show_flavor(
            CONF.compute.flavor_ref)['flavor']
        new_flavor = self.flavors_client.create_flavor(**{
            'ram': old_flavor['ram'],
            'vcpus': old_flavor['vcpus'],
            'name': old_flavor['name'] + 'extra-%s' % data_utils.rand_int_id(),
            'disk': old_flavor['disk'] + 1
        })['flavor']
        self.addCleanup(test_utils.call_and_ignore_notfound_exc,
                        self.flavors_client.delete_flavor, new_flavor['id'])
        return new_flavor

class MinBwAllocationPlacementTest(NetworkQoSPlacementTestBase):

    required_extensions = ['port-resource-request',
                           'qos',
                           'qos-bw-minimum-ingress']

    SMALLEST_POSSIBLE_BW = 1
    BANDWIDTH_1 = 1000
    BANDWIDTH_2 = 2000

    @classmethod
    def skip_checks(cls):
        super(MinBwAllocationPlacementTest, cls).skip_checks()
        if not CONF.network_feature_enabled.qos_placement_physnet:
            msg = "Skipped as no physnet is available in config for " \
                  "placement based QoS allocation."
            raise cls.skipException(msg)

    def setUp(self):
        super(MinBwAllocationPlacementTest, self).setUp()
        self._check_if_allocation_is_possible()

    def _create_policy_and_min_bw_rule(
        self, name_prefix, min_kbps, direction="ingress"
    ):
        policy = self.qos_client.create_qos_policy(
            name=data_utils.rand_name(name_prefix),
            shared=True)['policy']
        self.addCleanup(test_utils.call_and_ignore_notfound_exc,
                        self.qos_client.delete_qos_policy, policy['id'])
        rule = self.qos_min_bw_client.create_minimum_bandwidth_rule(
            policy['id'],
            **{
                'min_kbps': min_kbps,
                'direction': direction,
            })['minimum_bandwidth_rule']
        self.addCleanup(
            test_utils.call_and_ignore_notfound_exc,
            self.qos_min_bw_client.delete_minimum_bandwidth_rule, policy['id'],
            rule['id'])

        return policy

    def _create_qos_basic_policies(self):
        self.qos_policy_valid = self._create_policy_and_min_bw_rule(
            name_prefix='test_policy_valid',
            min_kbps=self.SMALLEST_POSSIBLE_BW)
        self.qos_policy_not_valid = self._create_policy_and_min_bw_rule(
            name_prefix='test_policy_not_valid',
            min_kbps=self.PLACEMENT_MAX_INT)

    def _create_qos_policies_from_life(self):
        # For tempest-slow the max bandwidth configured is 1000000,
        # https://opendev.org/openstack/tempest/src/branch/master/
        # .zuul.yaml#L416-L420
        self.qos_policy_1 = self._create_policy_and_min_bw_rule(
            name_prefix='test_policy_1',
            min_kbps=self.BANDWIDTH_1
        )
        self.qos_policy_2 = self._create_policy_and_min_bw_rule(
            name_prefix='test_policy_2',
            min_kbps=self.BANDWIDTH_2
        )

    def _create_network_and_qos_policies(self, policy_method):
        physnet_name = CONF.network_feature_enabled.qos_placement_physnet
        base_segm = \
            CONF.network_feature_enabled.provider_net_base_segmentation_id

        self.prov_network, _, _ = self.setup_network_subnet_with_router(
            networks_client=self.networks_client,
            routers_client=self.routers_client,
            subnets_client=self.subnets_client,
            **{
                'shared': True,
                'provider:network_type': 'vlan',
                'provider:physical_network': physnet_name,
                'provider:segmentation_id': base_segm
            })

        policy_method()

    def _check_if_allocation_is_possible(self):
        alloc_candidates = self.placement_client.list_allocation_candidates(
            resources1='%s:%s' % (self.INGRESS_RESOURCE_CLASS,
                                  self.SMALLEST_POSSIBLE_BW))
        if len(alloc_candidates['provider_summaries']) == 0:
            self.fail('No allocation candidates are available for %s:%s' %
                      (self.INGRESS_RESOURCE_CLASS, self.SMALLEST_POSSIBLE_BW))

        # Just to be sure check with impossible high (placement max_int),
        # allocation
        alloc_candidates = self.placement_client.list_allocation_candidates(
            resources1='%s:%s' % (self.INGRESS_RESOURCE_CLASS,
                                  self.PLACEMENT_MAX_INT))
        if len(alloc_candidates['provider_summaries']) != 0:
            self.fail('For %s:%s there should be no available candidate!' %
                      (self.INGRESS_RESOURCE_CLASS, self.PLACEMENT_MAX_INT))

    def _boot_vm_with_min_bw(self, qos_policy_id, status='ACTIVE'):
        wait_until = (None if status == 'ERROR' else status)
        port = self.create_port(
            self.prov_network['id'], qos_policy_id=qos_policy_id)

        server = self.create_server(networks=[{'port': port['id']}],
                                    wait_until=wait_until)
        waiters.wait_for_server_status(
            client=self.servers_client, server_id=server['id'],
            status=status, ready_wait=False, raise_on_error=False)
        return server, port

    def _assert_allocation_is_as_expected(
        self, consumer, port_ids, min_kbps=SMALLEST_POSSIBLE_BW,
        expected_rc=NetworkQoSPlacementTestBase.INGRESS_RESOURCE_CLASS,
    ):
        allocations = self.placement_client.list_allocations(
            consumer)['allocations']
        self.assertGreater(len(allocations), 0)
        bw_resource_in_alloc = False
        allocation_rp = None
        for rp, resources in allocations.items():
            if expected_rc in resources['resources']:
                self.assertEqual(
                    min_kbps,
                    resources['resources'][expected_rc])
                bw_resource_in_alloc = True
                allocation_rp = rp
        if min_kbps:
            self.assertTrue(
                bw_resource_in_alloc,
                f"expected {min_kbps} bandwidth allocation from {expected_rc} "
                f"but instance has allocation {allocations} instead."
            )

            # Check binding_profile of the port is not empty and equals with
            # the rp uuid
            for port_id in port_ids:
                port = self.os_admin.ports_client.show_port(port_id)
                port_binding_alloc = port['port']['binding:profile'][
                    'allocation']
                # NOTE(gibi): the format of the allocation key depends on the
                # existence of port-resource-request-groups API extension.
                # TODO(gibi): drop the else branch once tempest does not need
                # to support Xena release any more.
                if utils.is_extension_enabled(
                        'port-resource-request-groups', 'network'):
                    self.assertEqual(
                        {allocation_rp},
                        set(port_binding_alloc.values()))
                else:
                    self.assertEqual(allocation_rp, port_binding_alloc)

    @decorators.idempotent_id('78625d92-212c-400e-8695-dd51706858b8')
    @utils.services('compute', 'network')
    def test_qos_min_bw_allocation_basic(self):
        """"Basic scenario with QoS min bw allocation in placement.

        Steps:
        * Create prerequisites:
        ** VLAN type provider network with subnet.
        ** valid QoS policy with minimum bandwidth rule with min_kbps=1
        (This is a simplification to skip the checks in placement for
        detecting the resource provider tree and inventories, as if
        bandwidth resource is available 1 kbs will be available).
        ** invalid QoS policy with minimum bandwidth rule with
        min_kbs=max integer from placement (this is a simplification again
        to avoid detection of RP tress and inventories, as placement will
        reject such big allocation).
        * Create port with valid QoS policy, and boot VM with that, it should
        pass.
        * Create port with invalid QoS policy, and try to boot VM with that,
        it should fail.
        """
        self._create_network_and_qos_policies(self._create_qos_basic_policies)
        server1, valid_port = self._boot_vm_with_min_bw(
            qos_policy_id=self.qos_policy_valid['id'])
        self._assert_allocation_is_as_expected(server1['id'],
                                               [valid_port['id']])

        server2, not_valid_port = self._boot_vm_with_min_bw(
            self.qos_policy_not_valid['id'], status='ERROR')
        allocations = self.placement_client.list_allocations(server2['id'])

        self.assertEqual(0, len(allocations['allocations']))
        server2 = self.servers_client.show_server(server2['id'])
        self.assertIn('fault', server2['server'])
        self.assertIn('No valid host', server2['server']['fault']['message'])
        # Check that binding_profile of the port is empty
        port = self.os_admin.ports_client.show_port(not_valid_port['id'])
        self.assertEqual(0, len(port['port']['binding:profile']))

    @decorators.idempotent_id('8a98150c-a506-49a5-96c6-73a5e7b04ada')
    @testtools.skipUnless(CONF.compute_feature_enabled.cold_migration,
                          'Cold migration is not available.')
    @testtools.skipUnless(CONF.compute.min_compute_nodes > 1,
                          'Less than 2 compute nodes, skipping multinode '
                          'tests.')
    @utils.services('compute', 'network')
    def test_migrate_with_qos_min_bw_allocation(self):
        """Scenario to migrate VM with QoS min bw allocation in placement

        Boot a VM like in test_qos_min_bw_allocation_basic, do the same
        checks, and
        * migrate the server
        * confirm the resize, if the VM state is VERIFY_RESIZE
        * If the VM goes to ACTIVE state check that allocations are as
        expected.
        """
        self._create_network_and_qos_policies(self._create_qos_basic_policies)
        server, valid_port = self._boot_vm_with_min_bw(
            qos_policy_id=self.qos_policy_valid['id'])
        self._assert_allocation_is_as_expected(server['id'],
                                               [valid_port['id']])

        self.os_adm.servers_client.migrate_server(server_id=server['id'])
        waiters.wait_for_server_status(
            client=self.servers_client, server_id=server['id'],
            status='VERIFY_RESIZE', ready_wait=False, raise_on_error=False)

        # TODO(lajoskatona): Check that the allocations are ok for the
        #  migration?
        self._assert_allocation_is_as_expected(server['id'],
                                               [valid_port['id']])

        self.os_adm.servers_client.confirm_resize_server(
            server_id=server['id'])
        waiters.wait_for_server_status(
            client=self.servers_client, server_id=server['id'],
            status='ACTIVE', ready_wait=False, raise_on_error=True)
        self._assert_allocation_is_as_expected(server['id'],
                                               [valid_port['id']])

    @decorators.idempotent_id('c29e7fd3-035d-4993-880f-70819847683f')
    @testtools.skipUnless(CONF.compute_feature_enabled.resize,
                          'Resize not available.')
    @utils.services('compute', 'network')
    def test_resize_with_qos_min_bw_allocation(self):
        """Scenario to resize VM with QoS min bw allocation in placement.

        Boot a VM like in test_qos_min_bw_allocation_basic, do the same
        checks, and
        * resize the server with new flavor
        * confirm the resize, if the VM state is VERIFY_RESIZE
        * If the VM goes to ACTIVE state check that allocations are as
        expected.
        """
        self._create_network_and_qos_policies(self._create_qos_basic_policies)
        server, valid_port = self._boot_vm_with_min_bw(
            qos_policy_id=self.qos_policy_valid['id'])
        self._assert_allocation_is_as_expected(server['id'],
                                               [valid_port['id']])

        new_flavor = self._create_flavor_to_resize_to()

        self.servers_client.resize_server(
            server_id=server['id'], flavor_ref=new_flavor['id'])
        waiters.wait_for_server_status(
            client=self.servers_client, server_id=server['id'],
            status='VERIFY_RESIZE', ready_wait=False, raise_on_error=False)

        # TODO(lajoskatona): Check that the allocations are ok for the
        #  migration?
        self._assert_allocation_is_as_expected(server['id'],
                                               [valid_port['id']])

        self.servers_client.confirm_resize_server(server_id=server['id'])
        waiters.wait_for_server_status(
            client=self.servers_client, server_id=server['id'],
            status='ACTIVE', ready_wait=False, raise_on_error=True)
        self._assert_allocation_is_as_expected(server['id'],
                                               [valid_port['id']])

    @decorators.idempotent_id('79fdaa1c-df62-4738-a0f0-1cff9dc415f6')
    @utils.services('compute', 'network')
    def test_qos_min_bw_allocation_update_policy(self):
        """Test the update of QoS policy on bound port

        Related RFE in neutron: #1882804
        The scenario is the following:
        * Have a port with QoS policy and minimum bandwidth rule.
        * Boot a VM with the port.
        * Update the port with a new policy with different minimum bandwidth
        values.
        * The allocation on placement side should be according to the new
        rules.
        """
        if not utils.is_network_feature_enabled('update_port_qos'):
            raise self.skipException("update_port_qos feature is not enabled")

        self._create_network_and_qos_policies(
            self._create_qos_policies_from_life)

        port = self.create_port(
            self.prov_network['id'], qos_policy_id=self.qos_policy_1['id'])

        server1 = self.create_server(
            networks=[{'port': port['id']}])

        self._assert_allocation_is_as_expected(server1['id'], [port['id']],
                                               self.BANDWIDTH_1)

        self.ports_client.update_port(
            port['id'],
            **{'qos_policy_id': self.qos_policy_2['id']})
        self._assert_allocation_is_as_expected(server1['id'], [port['id']],
                                               self.BANDWIDTH_2)

        # I changed my mind
        self.ports_client.update_port(
            port['id'],
            **{'qos_policy_id': self.qos_policy_1['id']})
        self._assert_allocation_is_as_expected(server1['id'], [port['id']],
                                               self.BANDWIDTH_1)

        # bad request....
        self.qos_policy_not_valid = self._create_policy_and_min_bw_rule(
            name_prefix='test_policy_not_valid',
            min_kbps=self.PLACEMENT_MAX_INT)
        port_orig = self.ports_client.show_port(port['id'])['port']
        self.assertRaises(
            lib_exc.Conflict,
            self.ports_client.update_port,
            port['id'], **{'qos_policy_id': self.qos_policy_not_valid['id']})
        self._assert_allocation_is_as_expected(server1['id'], [port['id']],
                                               self.BANDWIDTH_1)

        port_upd = self.ports_client.show_port(port['id'])['port']
        self.assertEqual(port_orig['qos_policy_id'],
                         port_upd['qos_policy_id'])
        self.assertEqual(self.qos_policy_1['id'], port_upd['qos_policy_id'])

    @decorators.idempotent_id('9cfc3bb8-f433-4c91-87b6-747cadc8958a')
    @utils.services('compute', 'network')
    def test_qos_min_bw_allocation_update_policy_from_zero(self):
        """Test port without QoS policy to have QoS policy

        This scenario checks if updating a port without QoS policy to
        have QoS policy with minimum_bandwidth rule succeeds only on
        controlplane, but placement allocation remains 0.
        """
        if not utils.is_network_feature_enabled('update_port_qos'):
            raise self.skipException("update_port_qos feature is not enabled")

        self._create_network_and_qos_policies(
            self._create_qos_policies_from_life)

        port = self.create_port(self.prov_network['id'])

        server1 = self.create_server(
            networks=[{'port': port['id']}])

        self._assert_allocation_is_as_expected(server1['id'], [port['id']], 0)

        self.ports_client.update_port(
            port['id'], **{'qos_policy_id': self.qos_policy_2['id']})
        self._assert_allocation_is_as_expected(server1['id'], [port['id']], 0)

    @decorators.idempotent_id('a9725a70-1d28-4e3b-ae0e-450abc235962')
    @utils.services('compute', 'network')
    def test_qos_min_bw_allocation_update_policy_to_zero(self):
        """Test port with QoS policy to remove QoS policy

        In this scenario port with QoS minimum_bandwidth rule update to
        remove QoS policy results in 0 placement allocation.
        """
        if not utils.is_network_feature_enabled('update_port_qos'):
            raise self.skipException("update_port_qos feature is not enabled")

        self._create_network_and_qos_policies(
            self._create_qos_policies_from_life)

        port = self.create_port(
            self.prov_network['id'], qos_policy_id=self.qos_policy_1['id'])

        server1 = self.create_server(
            networks=[{'port': port['id']}])
        self._assert_allocation_is_as_expected(server1['id'], [port['id']],
                                               self.BANDWIDTH_1)

        self.ports_client.update_port(
            port['id'],
            **{'qos_policy_id': None})
        self._assert_allocation_is_as_expected(server1['id'], [port['id']], 0)

    @decorators.idempotent_id('756ced7f-6f1a-43e7-a851-2fcfc16f3dd7')
    @utils.services('compute', 'network')
    def test_qos_min_bw_allocation_update_with_multiple_ports(self):
        if not utils.is_network_feature_enabled('update_port_qos'):
            raise self.skipException("update_port_qos feature is not enabled")

        self._create_network_and_qos_policies(
            self._create_qos_policies_from_life)

        port1 = self.create_port(
            self.prov_network['id'], qos_policy_id=self.qos_policy_1['id'])
        port2 = self.create_port(
            self.prov_network['id'], qos_policy_id=self.qos_policy_2['id'])

        server1 = self.create_server(
            networks=[{'port': port1['id']}, {'port': port2['id']}])
        self._assert_allocation_is_as_expected(
            server1['id'], [port1['id'], port2['id']],
            self.BANDWIDTH_1 + self.BANDWIDTH_2)

        self.ports_client.update_port(
            port1['id'],
            **{'qos_policy_id': self.qos_policy_2['id']})
        self._assert_allocation_is_as_expected(
            server1['id'], [port1['id'], port2['id']],
            2 * self.BANDWIDTH_2)

    @decorators.idempotent_id('0805779e-e03c-44fb-900f-ce97a790653b')
    @utils.services('compute', 'network')
    def test_empty_update(self):
        if not utils.is_network_feature_enabled('update_port_qos'):
            raise self.skipException("update_port_qos feature is not enabled")

        self._create_network_and_qos_policies(
            self._create_qos_policies_from_life)

        port = self.create_port(
            self.prov_network['id'], qos_policy_id=self.qos_policy_1['id'])

        server1 = self.create_server(
            networks=[{'port': port['id']}])
        self._assert_allocation_is_as_expected(server1['id'], [port['id']],
                                               self.BANDWIDTH_1)
        self.ports_client.update_port(
            port['id'],
            **{'description': 'foo'})
        self._assert_allocation_is_as_expected(server1['id'], [port['id']],
                                               self.BANDWIDTH_1)

    @decorators.idempotent_id('372b2728-cfed-469a-b5f6-b75779e1ccbe')
    @utils.services('compute', 'network')
    def test_qos_min_bw_allocation_update_policy_direction_change(self):
        """Test QoS min bw direction change on a bound port

        Related RFE in neutron: #1882804
        The scenario is the following:
        * Have a port with QoS policy and minimum bandwidth rule with ingress
        direction
        * Boot a VM with the port.
        * Update the port with a new policy to egress direction in
        minimum bandwidth rule.
        * The allocation on placement side should be according to the new
        rules.
        """
        if not utils.is_network_feature_enabled('update_port_qos'):
            raise self.skipException("update_port_qos feature is not enabled")

        def create_policies():
            self.qos_policy_ingress = self._create_policy_and_min_bw_rule(
                name_prefix='test_policy_ingress',
                min_kbps=self.BANDWIDTH_1,
                direction=self.INGRESS_DIRECTION,
            )
            self.qos_policy_egress = self._create_policy_and_min_bw_rule(
                name_prefix='test_policy_egress',
                min_kbps=self.BANDWIDTH_1,
                direction=self.EGRESS_DIRECTION,
            )

        self._create_network_and_qos_policies(create_policies)

        port = self.create_port(
            self.prov_network['id'],
            qos_policy_id=self.qos_policy_ingress['id'])

        server1 = self.create_server(
            networks=[{'port': port['id']}])

        self._assert_allocation_is_as_expected(
            server1['id'], [port['id']], self.BANDWIDTH_1,
            expected_rc=self.INGRESS_RESOURCE_CLASS)

        self.ports_client.update_port(
            port['id'],
            qos_policy_id=self.qos_policy_egress['id'])

        self._assert_allocation_is_as_expected(
            server1['id'], [port['id']], self.BANDWIDTH_1,
            expected_rc=self.EGRESS_RESOURCE_CLASS)
        self._assert_allocation_is_as_expected(
            server1['id'], [port['id']], 0,
            expected_rc=self.INGRESS_RESOURCE_CLASS)

class QoSBandwidthAndPacketRateTests(NetworkQoSPlacementTestBase):

    PPS_RESOURCE_CLASS = "NET_PACKET_RATE_KILOPACKET_PER_SEC"

    @classmethod
    def skip_checks(cls):
        super().skip_checks()
        if not CONF.network_feature_enabled.qos_min_bw_and_pps:
            msg = (
                "Skipped as no resource inventories are configured for QoS "
                "minimum bandwidth and packet rate testing.")
            raise cls.skipException(msg)

    @classmethod
    def setup_clients(cls):
        super().setup_clients()
        cls.qos_min_pps_client = cls.os_admin.qos_min_pps_client

    def setUp(self):
        super().setUp()
        self.network = self._create_network()

    def _create_qos_policy_with_bw_and_pps_rules(self, min_kbps, min_kpps):
        policy = self.qos_client.create_qos_policy(
            name=data_utils.rand_name(),
            shared=True
        )['policy']
        self.addCleanup(
            test_utils.call_and_ignore_notfound_exc,
            self.qos_client.delete_qos_policy,
            policy['id']
        )

        if min_kbps > 0:
            bw_rule = self.qos_min_bw_client.create_minimum_bandwidth_rule(
                policy['id'],
                min_kbps=min_kbps,
                direction=self.INGRESS_DIRECTION
            )['minimum_bandwidth_rule']
            self.addCleanup(
                test_utils.call_and_ignore_notfound_exc,
                self.qos_min_bw_client.delete_minimum_bandwidth_rule,
                policy['id'],
                bw_rule['id']
            )

        if min_kpps > 0:
            pps_rule = self.qos_min_pps_client.create_minimum_packet_rate_rule(
                policy['id'],
                min_kpps=min_kpps,
                direction=self.ANY_DIRECTION
            )['minimum_packet_rate_rule']
            self.addCleanup(
                test_utils.call_and_ignore_notfound_exc,
                self.qos_min_pps_client.delete_minimum_packet_rate_rule,
                policy['id'],
                pps_rule['id']
            )

        return policy

    def _create_network(self):
        physnet_name = CONF.network_feature_enabled.qos_placement_physnet
        base_segm = (
            CONF.network_feature_enabled.provider_net_base_segmentation_id)

        # setup_network_subnet_with_router will add the necessary cleanup calls
        network, _, _ = self.setup_network_subnet_with_router(
            networks_client=self.networks_client,
            routers_client=self.routers_client,
            subnets_client=self.subnets_client,
            shared=True,
            **{
                'provider:network_type': 'vlan',
                'provider:physical_network': physnet_name,
                # +1 to be different from the segmentation_id used in
                # MinBwAllocationPlacementTest
                'provider:segmentation_id': int(base_segm) + 1,
            }
        )
        return network

    def _create_port_with_qos_policy(self, policy):
        port = self.ports_client.create_port(
            name=data_utils.rand_name(self.__class__.__name__),
            network_id=self.network['id'],
            qos_policy_id=policy['id'] if policy else None,
        )['port']
        self.addCleanup(
            test_utils.call_and_ignore_notfound_exc,
            self.ports_client.delete_port, port['id']
        )
        return port

    def assert_allocations(
            self, server, port, expected_min_kbps, expected_min_kpps
    ):
        allocations = self.placement_client.list_allocations(
            server['id'])['allocations']

        # one allocation for the flavor related resources on the compute RP
        expected_allocation = 1
        # one allocation due to bw rule
        if expected_min_kbps > 0:
            expected_allocation += 1
        # one allocation due to pps rule
        if expected_min_kpps > 0:
            expected_allocation += 1
        self.assertEqual(expected_allocation, len(allocations), allocations)

        expected_rp_uuids_in_binding_allocation = set()

        if expected_min_kbps > 0:
            bw_rp_allocs = {
                rp: alloc['resources'][self.INGRESS_RESOURCE_CLASS]
                for rp, alloc in allocations.items()
                if self.INGRESS_RESOURCE_CLASS in alloc['resources']
            }
            self.assertEqual(1, len(bw_rp_allocs))
            bw_rp, bw_alloc = list(bw_rp_allocs.items())[0]
            self.assertEqual(expected_min_kbps, bw_alloc)
            expected_rp_uuids_in_binding_allocation.add(bw_rp)

        if expected_min_kpps > 0:
            pps_rp_allocs = {
                rp: alloc['resources'][self.PPS_RESOURCE_CLASS]
                for rp, alloc in allocations.items()
                if self.PPS_RESOURCE_CLASS in alloc['resources']
            }
            self.assertEqual(1, len(pps_rp_allocs))
            pps_rp, pps_alloc = list(pps_rp_allocs.items())[0]
            self.assertEqual(expected_min_kpps, pps_alloc)
            expected_rp_uuids_in_binding_allocation.add(pps_rp)

        # Let's check port.binding:profile.allocation points to the two
        # provider resource allocated from
        port = self.os_admin.ports_client.show_port(port['id'])
        port_binding_alloc = port[
            'port']['binding:profile'].get('allocation', {})
        self.assertEqual(
            expected_rp_uuids_in_binding_allocation,
            set(port_binding_alloc.values())
        )

    def assert_no_allocation(self, server, port):
        # check that there are no allocations
        allocations = self.placement_client.list_allocations(
            server['id'])['allocations']
        self.assertEqual(0, len(allocations))

        # check that binding_profile of the port is empty
        port = self.os_admin.ports_client.show_port(port['id'])
        self.assertEqual(0, len(port['port']['binding:profile']))

    @decorators.idempotent_id('93d1a88d-235e-4b7b-b44d-2a17dcf4e213')
    @utils.services('compute', 'network')
    def test_server_create_delete(self):
        min_kbps = 1000
        min_kpps = 100
        policy = self._create_qos_policy_with_bw_and_pps_rules(
            min_kbps, min_kpps)
        port = self._create_port_with_qos_policy(policy)

        server = self.create_server(
            networks=[{'port': port['id']}],
            wait_until='ACTIVE'
        )

        self.assert_allocations(server, port, min_kbps, min_kpps)

        self.servers_client.delete_server(server['id'])
        waiters.wait_for_server_termination(self.servers_client, server['id'])

        self.assert_no_allocation(server, port)

    def _test_create_server_negative(self, min_kbps=1000, min_kpps=100):
        policy = self._create_qos_policy_with_bw_and_pps_rules(
            min_kbps, min_kpps)
        port = self._create_port_with_qos_policy(policy)

        server = self.create_server(
            networks=[{'port': port['id']}],
            wait_until=None)
        waiters.wait_for_server_status(
            client=self.servers_client, server_id=server['id'],
            status='ERROR', ready_wait=False, raise_on_error=False)

        # check that the creation failed with No valid host
        server = self.servers_client.show_server(server['id'])['server']
        self.assertIn('fault', server)
        self.assertIn('No valid host', server['fault']['message'])

        self.assert_no_allocation(server, port)

    @decorators.idempotent_id('915dd2ce-4890-40c8-9db6-f3e04080c6c1')
    @utils.services('compute', 'network')
    def test_server_create_no_valid_host_due_to_bandwidth(self):
        self._test_create_server_negative(min_kbps=self.PLACEMENT_MAX_INT)

    @decorators.idempotent_id('2d4a755e-10b9-4ac0-bef2-3f89de1f150b')
    @utils.services('compute', 'network')
    def test_server_create_no_valid_host_due_to_packet_rate(self):
        self._test_create_server_negative(min_kpps=self.PLACEMENT_MAX_INT)

    @decorators.idempotent_id('69d93e4f-0dfc-4d17-8d84-cc5c3c842cd5')
    @testtools.skipUnless(
        CONF.compute_feature_enabled.resize, 'Resize not available.')
    @utils.services('compute', 'network')
    def test_server_resize(self):
        min_kbps = 1000
        min_kpps = 100
        policy = self._create_qos_policy_with_bw_and_pps_rules(
            min_kbps, min_kpps)
        port = self._create_port_with_qos_policy(policy)

        server = self.create_server(
            networks=[{'port': port['id']}],
            wait_until='ACTIVE'
        )

        self.assert_allocations(server, port, min_kbps, min_kpps)

        new_flavor = self._create_flavor_to_resize_to()

        self.servers_client.resize_server(
            server_id=server['id'], flavor_ref=new_flavor['id']
        )
        waiters.wait_for_server_status(
            client=self.servers_client, server_id=server['id'],
            status='VERIFY_RESIZE', ready_wait=False, raise_on_error=False)

        self.assert_allocations(server, port, min_kbps, min_kpps)

        self.servers_client.confirm_resize_server(server_id=server['id'])
        waiters.wait_for_server_status(
            client=self.servers_client, server_id=server['id'],
            status='ACTIVE', ready_wait=False, raise_on_error=True)

        self.assert_allocations(server, port, min_kbps, min_kpps)

    @decorators.idempotent_id('d01d4aee-ca06-4e4e-add7-8a47fe0daf96')
    @testtools.skipUnless(
        CONF.compute_feature_enabled.resize, 'Resize not available.')
    @utils.services('compute', 'network')
    def test_server_resize_revert(self):
        min_kbps = 1000
        min_kpps = 100
        policy = self._create_qos_policy_with_bw_and_pps_rules(
            min_kbps, min_kpps)
        port = self._create_port_with_qos_policy(policy)

        server = self.create_server(
            networks=[{'port': port['id']}],
            wait_until='ACTIVE'
        )

        self.assert_allocations(server, port, min_kbps, min_kpps)

        new_flavor = self._create_flavor_to_resize_to()

        self.servers_client.resize_server(
            server_id=server['id'], flavor_ref=new_flavor['id']
        )
        waiters.wait_for_server_status(
            client=self.servers_client, server_id=server['id'],
            status='VERIFY_RESIZE', ready_wait=False, raise_on_error=False)

        self.assert_allocations(server, port, min_kbps, min_kpps)

        self.servers_client.revert_resize_server(server_id=server['id'])
        waiters.wait_for_server_status(
            client=self.servers_client, server_id=server['id'],
            status='ACTIVE', ready_wait=False, raise_on_error=True)

        self.assert_allocations(server, port, min_kbps, min_kpps)

    @decorators.idempotent_id('bdd0b31c-c8b0-4b7b-b80a-545a46b32abe')
    @testtools.skipUnless(
        CONF.compute_feature_enabled.cold_migration,
        'Cold migration is not available.')
    @testtools.skipUnless(
        CONF.compute.min_compute_nodes > 1,
        'Less than 2 compute nodes, skipping multinode tests.')
    @utils.services('compute', 'network')
    def test_server_migrate(self):
        min_kbps = 1000
        min_kpps = 100
        policy = self._create_qos_policy_with_bw_and_pps_rules(
            min_kbps, min_kpps)
        port = self._create_port_with_qos_policy(policy)

        server = self.create_server(
            networks=[{'port': port['id']}],
            wait_until='ACTIVE'
        )

        self.assert_allocations(server, port, min_kbps, min_kpps)

        self.os_adm.servers_client.migrate_server(server_id=server['id'])
        waiters.wait_for_server_status(
            client=self.servers_client, server_id=server['id'],
            status='VERIFY_RESIZE', ready_wait=False, raise_on_error=False)

        self.assert_allocations(server, port, min_kbps, min_kpps)

        self.os_adm.servers_client.confirm_resize_server(
            server_id=server['id'])
        waiters.wait_for_server_status(
            client=self.servers_client, server_id=server['id'],
            status='ACTIVE', ready_wait=False, raise_on_error=True)

        self.assert_allocations(server, port, min_kbps, min_kpps)

    @decorators.idempotent_id('fdb260e3-caa5-482d-ac7c-8c22adf3d750')
    @utils.services('compute', 'network')
    def test_qos_policy_update_on_bound_port(self):
        min_kbps = 1000
        min_kpps = 100
        policy = self._create_qos_policy_with_bw_and_pps_rules(
            min_kbps, min_kpps)

        min_kbps2 = 2000
        min_kpps2 = 50
        policy2 = self._create_qos_policy_with_bw_and_pps_rules(
            min_kbps2, min_kpps2)

        port = self._create_port_with_qos_policy(policy)

        server = self.create_server(
            networks=[{'port': port['id']}],
            wait_until='ACTIVE'
        )

        self.assert_allocations(server, port, min_kbps, min_kpps)

        self.ports_client.update_port(
            port['id'],
            qos_policy_id=policy2['id'])

        self.assert_allocations(server, port, min_kbps2, min_kpps2)

    @decorators.idempotent_id('e6a20125-a02e-49f5-bcf6-894305ee3715')
    @utils.services('compute', 'network')
    def test_qos_policy_update_on_bound_port_from_null_policy(self):
        min_kbps = 1000
        min_kpps = 100
        policy = self._create_qos_policy_with_bw_and_pps_rules(
            min_kbps, min_kpps)

        port = self._create_port_with_qos_policy(policy=None)

        server = self.create_server(
            networks=[{'port': port['id']}],
            wait_until='ACTIVE'
        )

        self.assert_allocations(server, port, 0, 0)

        self.ports_client.update_port(
            port['id'],
            qos_policy_id=policy['id'])

        # NOTE(gibi): This is unintuitive but it is the expected behavior.
        # If there was no policy attached to the port when the server was
        # created then neutron still allows adding a policy to the port later
        # as this operation was support before placement enforcement was added
        # for the qos minimum bandwidth rule. However neutron cannot create
        # the placement resource allocation for this port.
        self.assert_allocations(server, port, 0, 0)

    @decorators.idempotent_id('f5864761-966c-4e49-b430-ac0044b7d658')
    @utils.services('compute', 'network')
    def test_qos_policy_update_on_bound_port_additional_rule(self):
        min_kbps = 1000
        policy = self._create_qos_policy_with_bw_and_pps_rules(
            min_kbps, 0)

        min_kbps2 = 2000
        min_kpps2 = 50
        policy2 = self._create_qos_policy_with_bw_and_pps_rules(
            min_kbps2, min_kpps2)

        port = self._create_port_with_qos_policy(policy=policy)

        server = self.create_server(
            networks=[{'port': port['id']}],
            wait_until='ACTIVE'
        )

        self.assert_allocations(server, port, min_kbps, 0)

        self.ports_client.update_port(
            port['id'],
            qos_policy_id=policy2['id'])

        # FIXME(gibi): Agree in the spec: do we ignore the pps request or we
        # reject the update? It seems current implementation goes with
        # ignoring the additional pps rule.
        self.assert_allocations(server, port, min_kbps2, 0)

    @decorators.idempotent_id('fbbb9c81-ed21-48c3-bdba-ce2361e93aad')
    @utils.services('compute', 'network')
    def test_qos_policy_update_on_bound_port_to_null_policy(self):
        min_kbps = 1000
        min_kpps = 100
        policy = self._create_qos_policy_with_bw_and_pps_rules(
            min_kbps, min_kpps)

        port = self._create_port_with_qos_policy(policy=policy)

        server = self.create_server(
            networks=[{'port': port['id']}],
            wait_until='ACTIVE'
        )

        self.assert_allocations(server, port, min_kbps, min_kpps)

        self.ports_client.update_port(
            port['id'],
            qos_policy_id=None)

        self.assert_allocations(server, port, 0, 0)

    @decorators.idempotent_id('0393d038-03ad-4844-a0e4-83010f69dabb')
    @utils.services('compute', 'network')
    def test_interface_attach_detach(self):
        min_kbps = 1000
        min_kpps = 100
        policy = self._create_qos_policy_with_bw_and_pps_rules(
            min_kbps, min_kpps)

        port = self._create_port_with_qos_policy(policy=None)

        port2 = self._create_port_with_qos_policy(policy=policy)

        server = self.create_server(
            networks=[{'port': port['id']}],
            wait_until='ACTIVE'
        )

        self.assert_allocations(server, port, 0, 0)

        self.interface_client.create_interface(
            server_id=server['id'],
            port_id=port2['id'])
        waiters.wait_for_interface_status(
            self.interface_client, server['id'], port2['id'], 'ACTIVE')

        self.assert_allocations(server, port2, min_kbps, min_kpps)

        req_id = self.interface_client.delete_interface(
            server_id=server['id'],
            port_id=port2['id']).response['x-openstack-request-id']
        waiters.wait_for_interface_detach(
            self.servers_client, server['id'], port2['id'], req_id)

        self.assert_allocations(server, port2, 0, 0)

    @decorators.idempotent_id('36ffdb85-6cc2-4cc9-a426-cad5bac8626b')
    @testtools.skipUnless(
        CONF.compute.min_compute_nodes > 1,
        'Less than 2 compute nodes, skipping multinode tests.')
    @testtools.skipUnless(
        CONF.compute_feature_enabled.live_migration,
        'Live migration not available')
    @utils.services('compute', 'network')
    def test_server_live_migrate(self):
        min_kbps = 1000
        min_kpps = 100
        policy = self._create_qos_policy_with_bw_and_pps_rules(
            min_kbps, min_kpps)

        port = self._create_port_with_qos_policy(policy=policy)

        server = self.create_server(
            networks=[{'port': port['id']}],
            wait_until='ACTIVE'
        )

        self.assert_allocations(server, port, min_kbps, min_kpps)

        server_details = self.os_adm.servers_client.show_server(server['id'])
        source_host = server_details['server']['OS-EXT-SRV-ATTR:host']

        self.os_adm.servers_client.live_migrate_server(
            server['id'], block_migration=True, host=None)
        waiters.wait_for_server_status(
            self.servers_client, server['id'], 'ACTIVE')

        server_details = self.os_adm.servers_client.show_server(server['id'])
        new_host = server_details['server']['OS-EXT-SRV-ATTR:host']

        self.assertNotEqual(source_host, new_host, "Live migration failed")

        self.assert_allocations(server, port, min_kbps, min_kpps)


text:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
	<persistence-unit name="defaultPersistenceUnit" transaction-type="JTA">
		<provider>oracle.toplink.essentials.PersistenceProvider</provider>
		<properties>
			<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
			<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:testdb"/>
			<property name="javax.persistence.jdbc.user" value="sa"/>
			<property name="javax.persistence.jdbc.password" value=""/>
			<property name="eclipselink.ddl-generation" value="create-tables"/>
		</properties>
	</persistence-unit>
</persistence>

redpajama_set_name: RedPajamaGithub


text:
using Neo.Core;
using Neo.Cryptography.ECC;

using Neo.Gui.Base.Data;

namespace Neo.Gui.ViewModels.Tests.Builders
{
    // TODO Add NEP5AssetItemBuilder class
    public class FirstClassAssetItemBuilder
    {
        private string internalName = "Name";
        private string internalValue = "Value";
        private string internalIssuer = "Issuer";
        private UInt256 internalAssetId = UInt256.Parse("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF");
        private ECPoint internalAssetOwner = new ECPoint();
        private AssetType internalAssetType = AssetType.Token;

        public FirstClassAssetItemBuilder WithName(string name)
        {
            this.internalName = name;
            return this;
        }

        public FirstClassAssetItemBuilder WithValue(string value)
        {
            this.internalValue = value;
            return this;
        }

        public FirstClassAssetItemBuilder WithIssuer(string issuer)
        {
            this.internalIssuer = issuer;
            return this;
        }

        public FirstClassAssetItemBuilder WithGoverningToken()
        {
            this.internalAssetType = AssetType.GoverningToken;
            return this;
        }

        public FirstClassAssetItemBuilder WithUtilityToken()
        {
            this.internalAssetType = AssetType.UtilityToken;
            return this;
        }

        public FirstClassAssetItemBuilder WithCustomToken()
        {
            this.internalAssetOwner = new ECPoint();
            return this;
        }

        public FirstClassAssetItemBuilder WithAssetId(UInt256 assetId)
        {
            this.internalAssetId = assetId;
            return this;
        }

        public AssetItem Build()
        {
            return new FirstClassAssetItem(this.internalAssetId, this.internalAssetOwner, this.internalAssetType, this.internalValue)
            {
                Name = this.internalName,
                Issuer = this.internalIssuer
            };
        }
    }
}


text:
import inspect
import logging
import os
import platform
import ssl
import sys
import tempfile
import threading
import unittest
import warnings
from contextlib import contextmanager

import _import_local_thrift  # noqa
from thrift.transport.TSSLSocket import TSSLSocket, TSSLServerSocket
from thrift.transport.TTransport import TTransportException

SCRIPT_DIR = os.path.realpath(os.path.dirname(__file__))
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(SCRIPT_DIR)))
SERVER_PEM = os.path.join(ROOT_DIR, 'test', 'keys', 'server.pem')
SERVER_CERT = os.path.join(ROOT_DIR, 'test', 'keys', 'server.crt')
SERVER_KEY = os.path.join(ROOT_DIR, 'test', 'keys', 'server.key')
CLIENT_CERT_NO_IP = os.path.join(ROOT_DIR, 'test', 'keys', 'client.crt')
CLIENT_KEY_NO_IP = os.path.join(ROOT_DIR, 'test', 'keys', 'client.key')
CLIENT_CERT = os.path.join(ROOT_DIR, 'test', 'keys', 'client_v3.crt')
CLIENT_KEY = os.path.join(ROOT_DIR, 'test', 'keys', 'client_v3.key')
CLIENT_CA = os.path.join(ROOT_DIR, 'test', 'keys', 'CA.pem')

TEST_CIPHERS = 'DES-CBC3-SHA'

class ServerAcceptor(threading.Thread):
    def __init__(self, server, expect_failure=False):
        super(ServerAcceptor, self).__init__()
        self.daemon = True
        self._server = server
        self._listening = threading.Event()
        self._port = None
        self._port_bound = threading.Event()
        self._client = None
        self._client_accepted = threading.Event()
        self._expect_failure = expect_failure
        frame = inspect.stack(3)[2]
        self.name = frame[3]
        del frame

    def run(self):
        self._server.listen()
        self._listening.set()

        try:
            address = self._server.handle.getsockname()
            if len(address) > 1:
                # AF_INET addresses are 2-tuples (host, port) and AF_INET6 are
                # 4-tuples (host, port, ...), but in each case port is in the second slot.
                self._port = address[1]
        finally:
            self._port_bound.set()

        try:
            self._client = self._server.accept()
        except Exception:
            logging.exception('error on server side (%s):' % self.name)
            if not self._expect_failure:
                raise
        finally:
            self._client_accepted.set()

    def await_listening(self):
        self._listening.wait()

    @property
    def port(self):
        self._port_bound.wait()
        return self._port

    @property
    def client(self):
        self._client_accepted.wait()
        return self._client

# Python 2.6 compat
class AssertRaises(object):
    def __init__(self, expected):
        self._expected = expected

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_value, traceback):
        if not exc_type or not issubclass(exc_type, self._expected):
            raise Exception('fail')
        return True

class TSSLSocketTest(unittest.TestCase):
    def _server_socket(self, **kwargs):
        return TSSLServerSocket(port=0, **kwargs)

    @contextmanager
    def _connectable_client(self, server, expect_failure=False, path=None, **client_kwargs):
        acc = ServerAcceptor(server, expect_failure)
        try:
            acc.start()
            acc.await_listening()

            host, port = ('localhost', acc.port) if path is None else (None, None)
            client = TSSLSocket(host, port, unix_socket=path, **client_kwargs)
            yield acc, client
        finally:
            if acc.client:
                acc.client.close()
            server.close()

    def _assert_connection_failure(self, server, path=None, **client_args):
        logging.disable(logging.CRITICAL)
        with self._connectable_client(server, True, path=path, **client_args) as (acc, client):
            try:
                # We need to wait for a connection failure, but not too long.  20ms is a tunable
                # compromise between test speed and stability
                client.setTimeout(20)
                with self._assert_raises(TTransportException):
                    client.open()
                self.assertTrue(acc.client is None)
            finally:
                logging.disable(logging.NOTSET)

    def _assert_raises(self, exc):
        if sys.hexversion >= 0x020700F0:
            return self.assertRaises(exc)
        else:
            return AssertRaises(exc)

    def _assert_connection_success(self, server, path=None, **client_args):
        with self._connectable_client(server, path=path, **client_args) as (acc, client):
            client.open()
            try:
                self.assertTrue(acc.client is not None)
            finally:
                client.close()

    # deprecated feature
    def test_deprecation(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.filterwarnings('always', category=DeprecationWarning, module=self.__module__)
            TSSLSocket('localhost', 0, validate=True, ca_certs=SERVER_CERT)
            self.assertEqual(len(w), 1)

        with warnings.catch_warnings(record=True) as w:
            warnings.filterwarnings('always', category=DeprecationWarning, module=self.__module__)
            # Deprecated signature
            # def __init__(self, host='localhost', port=9090, validate=True, ca_certs=None, keyfile=None, certfile=None, unix_socket=None, ciphers=None):
            TSSLSocket('localhost', 0, True, SERVER_CERT, CLIENT_KEY, CLIENT_CERT, None, TEST_CIPHERS)
            self.assertEqual(len(w), 7)

        with warnings.catch_warnings(record=True) as w:
            warnings.filterwarnings('always', category=DeprecationWarning, module=self.__module__)
            # Deprecated signature
            # def __init__(self, host=None, port=9090, certfile='cert.pem', unix_socket=None, ciphers=None):
            TSSLServerSocket(None, 0, SERVER_PEM, None, TEST_CIPHERS)
            self.assertEqual(len(w), 3)

    # deprecated feature
    def test_set_cert_reqs_by_validate(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.filterwarnings('always', category=DeprecationWarning, module=self.__module__)
            c1 = TSSLSocket('localhost', 0, validate=True, ca_certs=SERVER_CERT)
            self.assertEqual(c1.cert_reqs, ssl.CERT_REQUIRED)

            c1 = TSSLSocket('localhost', 0, validate=False)
            self.assertEqual(c1.cert_reqs, ssl.CERT_NONE)

            self.assertEqual(len(w), 2)

    # deprecated feature
    def test_set_validate_by_cert_reqs(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.filterwarnings('always', category=DeprecationWarning, module=self.__module__)
            c1 = TSSLSocket('localhost', 0, cert_reqs=ssl.CERT_NONE)
            self.assertFalse(c1.validate)

            c2 = TSSLSocket('localhost', 0, cert_reqs=ssl.CERT_REQUIRED, ca_certs=SERVER_CERT)
            self.assertTrue(c2.validate)

            c3 = TSSLSocket('localhost', 0, cert_reqs=ssl.CERT_OPTIONAL, ca_certs=SERVER_CERT)
            self.assertTrue(c3.validate)

            self.assertEqual(len(w), 3)

    def test_unix_domain_socket(self):
        if platform.system() == 'Windows':
            print('skipping test_unix_domain_socket')
            return
        fd, path = tempfile.mkstemp()
        os.close(fd)
        try:
            server = self._server_socket(unix_socket=path, keyfile=SERVER_KEY, certfile=SERVER_CERT)
            self._assert_connection_success(server, path=path, cert_reqs=ssl.CERT_NONE)
        finally:
            os.unlink(path)

    def test_server_cert(self):
        server = self._server_socket(keyfile=SERVER_KEY, certfile=SERVER_CERT)
        self._assert_connection_success(server, cert_reqs=ssl.CERT_REQUIRED, ca_certs=SERVER_CERT)

        server = self._server_socket(keyfile=SERVER_KEY, certfile=SERVER_CERT)
        # server cert not in ca_certs
        self._assert_connection_failure(server, cert_reqs=ssl.CERT_REQUIRED, ca_certs=CLIENT_CERT)

        server = self._server_socket(keyfile=SERVER_KEY, certfile=SERVER_CERT)
        self._assert_connection_success(server, cert_reqs=ssl.CERT_NONE)

    def test_set_server_cert(self):
        server = self._server_socket(keyfile=SERVER_KEY, certfile=CLIENT_CERT)
        with self._assert_raises(Exception):
            server.certfile = 'foo'
        with self._assert_raises(Exception):
            server.certfile = None
        server.certfile = SERVER_CERT
        self._assert_connection_success(server, cert_reqs=ssl.CERT_REQUIRED, ca_certs=SERVER_CERT)

    def test_client_cert(self):
        server = self._server_socket(
            cert_reqs=ssl.CERT_REQUIRED, keyfile=SERVER_KEY,
            certfile=SERVER_CERT, ca_certs=CLIENT_CERT)
        self._assert_connection_failure(server, cert_reqs=ssl.CERT_NONE, certfile=SERVER_CERT, keyfile=SERVER_KEY)

        server = self._server_socket(
            cert_reqs=ssl.CERT_REQUIRED, keyfile=SERVER_KEY,
            certfile=SERVER_CERT, ca_certs=CLIENT_CA)
        self._assert_connection_failure(server, cert_reqs=ssl.CERT_NONE, certfile=CLIENT_CERT_NO_IP, keyfile=CLIENT_KEY_NO_IP)

        server = self._server_socket(
            cert_reqs=ssl.CERT_REQUIRED, keyfile=SERVER_KEY,
            certfile=SERVER_CERT, ca_certs=CLIENT_CA)
        self._assert_connection_success(server, cert_reqs=ssl.CERT_NONE, certfile=CLIENT_CERT, keyfile=CLIENT_KEY)

        server = self._server_socket(
            cert_reqs=ssl.CERT_OPTIONAL, keyfile=SERVER_KEY,
            certfile=SERVER_CERT, ca_certs=CLIENT_CA)
        self._assert_connection_success(server, cert_reqs=ssl.CERT_NONE, certfile=CLIENT_CERT, keyfile=CLIENT_KEY)

    def test_ciphers(self):
        server = self._server_socket(keyfile=SERVER_KEY, certfile=SERVER_CERT, ciphers=TEST_CIPHERS)
        self._assert_connection_success(server, ca_certs=SERVER_CERT, ciphers=TEST_CIPHERS)

        if not TSSLSocket._has_ciphers:
            # unittest.skip is not available for Python 2.6
            print('skipping test_ciphers')
            return
        server = self._server_socket(keyfile=SERVER_KEY, certfile=SERVER_CERT)
        self._assert_connection_failure(server, ca_certs=SERVER_CERT, ciphers='NULL')

        server = self._server_socket(keyfile=SERVER_KEY, certfile=SERVER_CERT, ciphers=TEST_CIPHERS)
        self._assert_connection_failure(server, ca_certs=SERVER_CERT, ciphers='NULL')

    def test_ssl2_and_ssl3_disabled(self):
        if not hasattr(ssl, 'PROTOCOL_SSLv3'):
            print('PROTOCOL_SSLv3 is not available')
        else:
            server = self._server_socket(keyfile=SERVER_KEY, certfile=SERVER_CERT)
            self._assert_connection_failure(server, ca_certs=SERVER_CERT, ssl_version=ssl.PROTOCOL_SSLv3)

            server = self._server_socket(keyfile=SERVER_KEY, certfile=SERVER_CERT, ssl_version=ssl.PROTOCOL_SSLv3)
            self._assert_connection_failure(server, ca_certs=SERVER_CERT)

        if not hasattr(ssl, 'PROTOCOL_SSLv2'):
            print('PROTOCOL_SSLv2 is not available')
        else:
            server = self._server_socket(keyfile=SERVER_KEY, certfile=SERVER_CERT)
            self._assert_connection_failure(server, ca_certs=SERVER_CERT, ssl_version=ssl.PROTOCOL_SSLv2)

            server = self._server_socket(keyfile=SERVER_KEY, certfile=SERVER_CERT, ssl_version=ssl.PROTOCOL_SSLv2)
            self._assert_connection_failure(server, ca_certs=SERVER_CERT)

    def test_newer_tls(self):
        if not TSSLSocket._has_ssl_context:
            # unittest.skip is not available for Python 2.6
            print('skipping test_newer_tls')
            return
        if not hasattr(ssl, 'PROTOCOL_TLSv1_2'):
            print('PROTOCOL_TLSv1_2 is not available')
        else:
            server = self._server_socket(keyfile=SERVER_KEY, certfile=SERVER_CERT, ssl_version=ssl.PROTOCOL_TLSv1_2)
            self._assert_connection_success(server, ca_certs=SERVER_CERT, ssl_version=ssl.PROTOCOL_TLSv1_2)

        if not hasattr(ssl, 'PROTOCOL_TLSv1_1'):
            print('PROTOCOL_TLSv1_1 is not available')
        else:
            server = self._server_socket(keyfile=SERVER_KEY, certfile=SERVER_CERT, ssl_version=ssl.PROTOCOL_TLSv1_1)
            self._assert_connection_success(server, ca_certs=SERVER_CERT, ssl_version=ssl.PROTOCOL_TLSv1_1)

        if not hasattr(ssl, 'PROTOCOL_TLSv1_1') or not hasattr(ssl, 'PROTOCOL_TLSv1_2'):
            print('PROTOCOL_TLSv1_1 and/or PROTOCOL_TLSv1_2 is not available')
        else:
            server = self._server_socket(keyfile=SERVER_KEY, certfile=SERVER_CERT, ssl_version=ssl.PROTOCOL_TLSv1_2)
            self._assert_connection_failure(server, ca_certs=SERVER_CERT, ssl_version=ssl.PROTOCOL_TLSv1_1)

    def test_ssl_context(self):
        if not TSSLSocket._has_ssl_context:
            # unittest.skip is not available for Python 2.6
            print('skipping test_ssl_context')
            return
        server_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        server_context.load_cert_chain(SERVER_CERT, SERVER_KEY)
        server_context.load_verify_locations(CLIENT_CA)
        server_context.verify_mode = ssl.CERT_REQUIRED
        server = self._server_socket(ssl_context=server_context)

        client_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
        client_context.load_cert_chain(CLIENT_CERT, CLIENT_KEY)
        client_context.load_verify_locations(SERVER_CERT)
        client_context.verify_mode = ssl.CERT_REQUIRED

        self._assert_connection_success(server, ssl_context=client_context)

if __name__ == '__main__':
    # import logging
    # logging.basicConfig(level=logging.DEBUG)
    unittest.main()


text:
package com.xwray.groupie.example.core;

import android.content.Context;
import android.content.SharedPreferences;

import androidx.preference.PreferenceManager;

public class Prefs {

    private static final String KEY_COLOR = "KEY_COLOR";
    private static final String KEY_BOUNDS = "KEY_BOUNDS";
    private static final String KEY_ASYNC = "KEY_ASYNC";
    private static final String KEY_OFFSETS = "KEY_OFFSETS";

    private static volatile Prefs singleton;
    private final SharedPreferences prefs;

    private boolean showColor;
    private boolean showBounds;
    private boolean useAsync;
    private boolean showOffsets;

    private Prefs(Context context) {
        prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
        showColor = prefs.getBoolean(KEY_COLOR, false);
        showBounds = prefs.getBoolean(KEY_BOUNDS, false);
        useAsync = prefs.getBoolean(KEY_ASYNC, false);
        showOffsets = prefs.getBoolean(KEY_OFFSETS, false);
    }

    public static Prefs get(Context context) {
        if (singleton == null) {
            synchronized (Prefs.class) {
                singleton = new Prefs(context);
            }
        }
        return singleton;
    }

    public void registerListener(SharedPreferences.OnSharedPreferenceChangeListener listener) {
        prefs.registerOnSharedPreferenceChangeListener(listener);
    }

    public void unregisterListener(SharedPreferences.OnSharedPreferenceChangeListener listener) {
        prefs.unregisterOnSharedPreferenceChangeListener(listener);
    }

    public boolean getShowBounds() {
        return showBounds;
    }

    public boolean getUseAsync() {
        return useAsync;
    }

    public boolean getShowOffsets() {
        return showOffsets;
    }

    public boolean getShowColor() {
        return showColor;
    }

    public void setShowColor(boolean showColor) {
        this.showColor = showColor;
        prefs.edit().putBoolean(KEY_COLOR, showColor).apply();
    }

    void setShowOffsets(boolean showOffsets) {
        this.showOffsets = showOffsets;
        prefs.edit().putBoolean(KEY_OFFSETS, showOffsets).apply();
    }

    void setShowBounds(boolean showBounds) {
        this.showBounds = showBounds;
        prefs.edit().putBoolean(KEY_BOUNDS, showBounds).apply();
    }

    void setUseAsync(boolean useAsync) {
        this.useAsync = useAsync;
        prefs.edit().putBoolean(KEY_ASYNC, useAsync).apply();
    }

}


text:
Team Members

        <md-list>
            <md-list-item class="md-2-line" ng-repeat="member in member_chunk">
                <md-icon md-font-set="material-icons" class="md-36 md-dark">face</md-icon>

{{member.name}}
                        [{{member.status}}]

                    <md-icon md-font-set="material-icons" class="md-18 md-dark">school</md-icon>{{member.institute}}

            </md-list-item>
        </md-list>


text:
#ifndef TENSORFLOW_CORE_PLATFORM_CASTS_H_
#define TENSORFLOW_CORE_PLATFORM_CASTS_H_

#include "tensorflow/core/platform/platform.h"

#if defined(PLATFORM_GOOGLE)
#include "tensorflow/core/platform/google/casts.h"
#elif defined(PLATFORM_POSIX) || defined(PLATFORM_POSIX_ANDROID) ||    \
    defined(PLATFORM_GOOGLE_ANDROID) || defined(PLATFORM_POSIX_IOS) || \
    defined(PLATFORM_GOOGLE_IOS) || defined(PLATFORM_WINDOWS)
#include "tensorflow/core/platform/default/casts.h"
#else
#error Define the appropriate PLATFORM_<foo> macro for this platform
#endif

#endif  // TENSORFLOW_CORE_PLATFORM_CASTS_H_


text:
using UnityEngine;
using System.Collections;

public class BattleCommandAttack : BattleCommandBase
{
	public int Target { set; get; }

	public Vector2 Position { set; get; }

	public override void Handle ()
	{
		Actor attacker = battleplayer.unitActorMap[Caster];
		Actor target = battleplayer.unitActorMap[Target];

		attacker.Attack(new Vector3(Position.x, ActorMananger.ACTOR_Y, Position.y), target);
	}
}


text:
<?php
namespace Guzzle\Tests\Service\Description;

use GuzzleHttp\Command\Guzzle\Description;
use GuzzleHttp\Command\Guzzle\Operation;

/**
 * @covers \GuzzleHttp\Command\Guzzle\Operation
 */
class OperationTest extends \PHPUnit_Framework_TestCase
{
    public static function strtoupper($string)
    {
        return strtoupper($string);
    }

    public function testOperationIsDataObject()
    {
        $c = new Operation([
            'name'               => 'test',
            'summary'            => 'doc',
            'notes'              => 'notes',
            'documentationUrl'   => 'http://www.example.com',
            'httpMethod'         => 'POST',
            'uri'                => '/api/v1',
            'responseModel'      => 'abc',
            'deprecated'         => true,
            'parameters'         => [
                'key' => [
                    'required'  => true,
                    'type'      => 'string',
                    'maxLength' => 10,
                    'name'      => 'key'
                ],
                'key_2' => [
                    'required' => true,
                    'type'     => 'integer',
                    'default'  => 10,
                    'name'     => 'key_2'
                ]
            ]
        ]);

        $this->assertEquals('test', $c->getName());
        $this->assertEquals('doc', $c->getSummary());
        $this->assertEquals('http://www.example.com', $c->getDocumentationUrl());
        $this->assertEquals('POST', $c->getHttpMethod());
        $this->assertEquals('/api/v1', $c->getUri());
        $this->assertEquals('abc', $c->getResponseModel());
        $this->assertTrue($c->getDeprecated());

        $params = array_map(function ($c) {
            return $c->toArray();
        }, $c->getParams());

        $this->assertEquals([
            'key' => [
                'required'  => true,
                'type'      => 'string',
                'maxLength' => 10,
                'name'       => 'key'
            ],
            'key_2' => [
                'required' => true,
                'type'     => 'integer',
                'default'  => 10,
                'name'     => 'key_2'
            ]
        ], $params);

        $this->assertEquals([
            'required' => true,
            'type'     => 'integer',
            'default'  => 10,
            'name'     => 'key_2'
        ], $c->getParam('key_2')->toArray());

        $this->assertNull($c->getParam('afefwef'));
        $this->assertArrayNotHasKey('parent', $c->getParam('key_2')->toArray());
    }

    public function testDeterminesIfHasParam()
    {
        $command = $this->getTestCommand();
        $this->assertTrue($command->hasParam('data'));
        $this->assertFalse($command->hasParam('baz'));
    }

    protected function getTestCommand()
    {
        return new Operation([
            'parameters' => [
                'data' => ['type' => 'string']
            ]
        ]);
    }

    public function testAddsNameToParametersIfNeeded()
    {
        $command = new Operation(['parameters' => ['foo' => []]]);
        $this->assertEquals('foo', $command->getParam('foo')->getName());
    }

    public function testContainsApiErrorInformation()
    {
        $command = $this->getOperation();
        $this->assertEquals(1, count($command->getErrorResponses()));
    }

    public function testHasNotes()
    {
        $o = new Operation(['notes' => 'foo']);
        $this->assertEquals('foo', $o->getNotes());
    }

    public function testHasData()
    {
        $o = new Operation(['data' => ['foo' => 'baz', 'bar' => 123]]);
        $this->assertEquals('baz', $o->getData('foo'));
        $this->assertEquals(123, $o->getData('bar'));
        $this->assertNull($o->getData('wfefwe'));
        $this->assertEquals(['foo' => 'baz', 'bar' => 123], $o->getData());
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMesssage Parameters must be arrays
     */
    public function testEnsuresParametersAreArrays()
    {
        new Operation(['parameters' => ['foo' => true]]);
    }

    public function testHasDescription()
    {
        $s = new Description([]);
        $o = new Operation([], $s);
        $this->assertSame($s, $o->getServiceDescription());
    }

    public function testHasAdditionalParameters()
    {
        $o = new Operation([
            'additionalParameters' => [
                'type' => 'string', 'name' => 'binks',
            ],
            'parameters' => [
                'foo' => ['type' => 'integer'],
            ],
        ]);
        $this->assertEquals('string', $o->getAdditionalParameters()->getType());
    }

    /**
     * @return Operation
     */
    protected function getOperation()
    {
        return new Operation([
            'name'       => 'OperationTest',
            'class'      => get_class($this),
            'parameters' => [
                'test'          => ['type' => 'object'],
                'bool_1'        => ['default' => true, 'type' => 'boolean'],
                'bool_2'        => ['default' => false],
                'float'         => ['type' => 'numeric'],
                'int'           => ['type' => 'integer'],
                'date'          => ['type' => 'string'],
                'timestamp'     => ['type' => 'string'],
                'string'        => ['type' => 'string'],
                'username'      => ['type' => 'string', 'required' => true, 'filters' => 'strtolower'],
                'test_function' => ['type' => 'string', 'filters' => __CLASS__ . '::strtoupper'],
            ],
            'errorResponses' => [
                [
                    'code' => 503,
                    'reason' => 'InsufficientCapacity',
                    'class' => 'Guzzle\\Exception\\RuntimeException',
                ],
            ],
        ]);
    }

    public function testCanExtendFromOtherOperations()
    {
        $d = new Description([
            'operations' => [
                'A' => [
                    'parameters' => [
                        'A' => [
                            'type' => 'object',
                            'properties' => ['foo' => ['type' => 'string']]
                        ],
                        'B' => ['type' => 'string']
                    ],
                    'summary' => 'foo'
                ],
                'B' => [
                    'extends' => 'A',
                    'summary' => 'Bar'
                ],
                'C' => [
                    'extends' => 'B',
                    'summary' => 'Bar',
                    'parameters' => [
                        'B' => ['type' => 'number']
                    ]
                ]
            ]
        ]);

        $a = $d->getOperation('A');
        $this->assertEquals('foo', $a->getSummary());
        $this->assertTrue($a->hasParam('A'));
        $this->assertEquals('string', $a->getParam('B')->getType());

        $b = $d->getOperation('B');
        $this->assertTrue($a->hasParam('A'));
        $this->assertEquals('Bar', $b->getSummary());
        $this->assertEquals('string', $a->getParam('B')->getType());

        $c = $d->getOperation('C');
        $this->assertTrue($a->hasParam('A'));
        $this->assertEquals('Bar', $c->getSummary());
        $this->assertEquals('number', $c->getParam('B')->getType());
    }
}


text:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

import { LoggerService } from 'app/services/logger.service';
import { ProgressBarService } from 'app/services/progress-bar.service';
import { DecisionService } from 'app/services/decision.service';

import { Entry } from 'app/classes/entry';
import { ProgressBar } from 'app/classes/progress-bar';

@Component({
  selector: 'notification',
  templateUrl: './notification.component.html',
  styleUrls: [ './notification.component.scss' ]
})
export class NotificationComponent implements OnInit {

  entries: Entry[];
  progressbars: ProgressBar[];
  question: string;

  @ViewChild('notifications') element: ElementRef;

  constructor(
    private log: LoggerService,
    private progress: ProgressBarService,
    private decision: DecisionService) {
  }

  ngOnInit(): void {
    this.entries = [];
    this.log.changed.subscribe((entry) => {
      if (entry.notify) {
        this.entries.push(entry);
      }
    });
    this.progress.changed.subscribe((bars) => {
      this.progressbars = bars;
    });
    this.decision.changed.subscribe((question) => {
      this.question = question;
    })
  }

  notifyClass(n: any): string {
    let nClass = ['notification', n.type];
    return nClass.join(' ');
  }

  close(i: number): void {
    this.entries.splice(i, 1);
  }

  closeAll(): void {
    this.entries = [];
  }

  notificationStyles(): any {
    if (this.element.nativeElement.scrollHeight > this.element.nativeElement.offsetHeight
      && this.entries.length > 0) {
      return { 'pointer-events': 'auto'};
    }
    return { 'pointer-events': 'none'};
  }

  answer(yes: boolean): void {
    this.decision.answer(yes);
  }

}


text:
<?php

namespace RM\CategoriaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    public function obtenerFichaNivelesAction($idOpcionMenuSup, $idOpcionMenuIzq, $nivel)
    {
        $paginator = $this->get('knp_paginator');
    	$servicio = $this->get("categoriaService");

    	$selectNiveles = $servicio->getNivelesCategoria();
    	$selectCategorias = $servicio->getCategorias($nivel);

        $pagination = $paginator->paginate($selectCategorias, $this->get('request')->get('page',1), 15 );

    	return $this->render('RMCategoriaBundle:Default:indexAvanzado.html.twig', array(
    			'idOpcionMenuSup' => $idOpcionMenuSup,
    			'idOpcionMenuIzq' => $idOpcionMenuIzq,
    			'selectNiveles' => $selectNiveles,
    			'selectCategorias' => $pagination,
    			'nivel' => $nivel
    	));

    }

    public function guardarCategoriasAvanzadasAction(Request $request)
    {	/*Parametros principales:
    	 	nivel: Nivel de Categoria donde se asociaran las categorias
    		guardarCat + idCategoria: Categorias seleccionadas parta ser asociadas
    	Acci�n:
    		Asocia o desasocia las categorias de un nivel seg�n los paramentros pasados si existen o no.
    	*/
    	$servicio = $this->get("categoriaService");

    	$servicio->guardarCategoriasAsocbyPost($request);

    	$this->get('session')->getFlashBag()->add('mensaje','mensaje.ok.editar');

    	return $this->redirect($this->generateUrl('data_avanced_nivelCategoria', array(
    			'nivel' => $request->get('nivel'))));
    }

}


text:
"use strict";
// var assert = chai.assert;
// var should = chai.should();
var expect = chai.expect;

if (!window.sf) {
    window.sf = {};
}

if (!window.sf.options) {
    window.sf.options = {};
}

if (!window.sf.options.instances) {
    window.sf.options.instances = {};
}

window.sf.options.instances.testInstance = {
    testSfOptions1: "NOT expected from sf.options",
    testSfOptions2: "expected value from sf.options",
    testSfOptions3: "NOT expected value from sf.options"
};

require("../../../src/sf-wrapper");

/**
 * Lets create test instance for testing
 * @param {Object} spiral
 * @param {HTMLElement} node
 * @param {Object} options
 * @constructor
 */
var TestInstance = function (spiral, node, options) {
    this.init(spiral, node, options);
};

TestInstance.prototype = Object.create(sf.core.BaseDOMConstructor.prototype);
TestInstance.prototype.name = "testInstance";
TestInstance.prototype.optionsToGrab = {
    test1: {
        value: "test1-value"
    },
    test2: {
        processor: function (option) {
            return "aaaa";
        }
    },
    test3: {
        domAttr: "someAttr"
    },
    test4: {
        domAttr: "someAttr",
        processor: function (node, val, key) {
            return val + "aaaa";
        }
    },
    test5: {
        value: "bb",
        processor: function (node, val, key) {
            return val + "aaaa";
        }
    },
    testSfOptions2: {
        value: "test"
    },
    testSfOptions3: {
        domAttr: "someAttr"
    }
};

describe('BaseDomConstructor', function () {
    describe('#grabOptions()', function () {
        it('should have method grabOptions', function () {
            expect(TestInstance.prototype.grabOptions).to.exist;
        });
        it('grabOptions and its a function', function () {
            expect(TestInstance.prototype.grabOptions).be.a('function');
        });
        var testDomNode = document.createElement("div");
        testDomNode.setAttribute("someAttr", "test");

        var instanceOptions = new TestInstance(sf, testDomNode).options;

        it('should return default option if node have no attr', function () {
            expect(instanceOptions).to.have.property('test1').with.equal("test1-value");
        });
        it('should return processed option if processor available', function () {
            expect(instanceOptions).to.have.property('test2').with.equal("aaaa");
        });
        it('should return option from dom', function () {
            expect(instanceOptions).to.have.property('test3').with.equal("test");
        });
        it('should return processed option from dom if processor available', function () {
            expect(instanceOptions).to.have.property('test4').with.equal("testaaaa");
        });
        it('should return processed option from default value if processor available and dom attribute not available', function () {
            expect(instanceOptions).to.have.property('test5').with.equal("bbaaaa");
        });

        /* values from sf.options */
        it('should return undefined from if NOT optionsToGrab[option]', function () {
            expect(instanceOptions).to.not.have.property('testSfOptions1');
        });
        it('should return option from sf.options if optionsToGrab[option] and dom attribute not available', function () {
            expect(instanceOptions).to.have.property('testSfOptions2').with.equal("expected value from sf.options");
        });
        it('should return option from optionsToGrab value if optionsToGrab[option] and dom attribute is available', function () {
            expect(instanceOptions).to.have.property('testSfOptions3').with.equal("test");
        });
    });
});


text:
Examples of CSS3 effects that can be done by Weiss.

Developed by Dmytro Nechepurenko. Distributed by MIT license.


text:
package pro.boto.recommender.aquisiction.provider.storm.bolts;

import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pro.boto.flink.connector.kudu.schema.KuduConnector;
import pro.boto.flink.connector.kudu.schema.KuduTable;
import pro.boto.protolang.json.ProtoClient;
import pro.boto.recommender.aquisiction.domain.UserEvent;
import pro.boto.recommender.data.tables.event.EventTable;

import java.util.Map;

public class EventSaveBolt extends BaseRichBolt {

    protected Logger LOG = LoggerFactory.getLogger(this.getClass());

    private OutputCollector collector;
    private KuduTable table;
    private KuduConnector connector;

    @Override
    public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
        this.collector = outputCollector;
        try {
            this.table = EventTable.kuduTable();
            this.connector = EventTable.kuduConnector();
        }catch(Exception e) {
            LOG.error("event process ko with " + e.getLocalizedMessage(), e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void cleanup() {
        try {
            this.connector.close();
            this.table = null;
            this.collector = null;
        }catch(Exception e) {
            LOG.error("event process ko with " + e.getLocalizedMessage(), e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void execute(Tuple tuple) {
        try {
            String oriJson = tuple.getString(0);
            UserEvent event = ProtoClient.obtainObject(UserEvent.class, oriJson);

            connector.upsert(table, event.toKuduRow());

            collector.emit(tuple, new Values(event));
            collector.ack(tuple);
            LOG.debug("event process ok");
        }catch(Exception e) {
            collector.reportError(e);
            collector.fail(tuple);
            LOG.error("event process ko with " + e.getLocalizedMessage(), e);
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("eventSaved"));
    }
}


text:
<?php
namespace Aws\Build\Docs;

use Aws\Api\Service as Api;
use Aws\Api\DocModel;
use Aws\Sdk;

/**
 * Serves as a DTO for information about a service required to build various
 * aspects of the docs.
 *
 * @internal
 */
class Service
{
    /** @var Api */
    public $api;

    /** @var string */
    public $client;

    /** @var string */
    public $clientName;

    /** @var string */
    public $clientLink;

    /** @var DocModel */
    public $docs;

    /** @var string */
    public $fullNamespace;

    /** @var string */
    public $fullTitle;

    /** @var string */
    public $name;

    /** @var string */
    public $namespace;

    /** @var string */
    public $namespaceLink;

    /** @var string */
    public $serviceLink;

    /** @var string */
    public $shortTitle;

    /** @var string */
    public $slug;

    /** @var string */
    public $title;

    /** @var string */
    public $version;

    public function __construct(Api $api, DocModel $docs)
    {
        $this->name = $api->getServiceName();
        $this->api = $api;
        $this->namespace = $this->getServiceNamespace($this->name);
        $this->version = $api->getApiVersion();
        $this->docs = $docs;
        $this->slug = $this->name . '-' . $this->version;
        $this->uid = $api->getUid();
        $this->clientName = $this->namespace . 'Client';
        $this->client = 'Aws\\' . $this->namespace . '\\' . $this->clientName;
        $this->clientLink = 'class-Aws.' . $this->namespace . '.' . $this->namespace . 'Client.html';
        $this->namespaceLink = 'namespace-Aws.' . $this->namespace . '.html';
        $this->serviceLink = 'api-' . $this->slug . '.html';
        $this->shortTitle = $api->getMetadata('serviceAbbreviation');
        $this->title = $api->getServiceFullName();
        $this->fullNamespace = 'Aws\\' . $this->namespace;
        $this->fullTitle = $this->title . ' (' . $this->version . ')';
    }

    private function getServiceNamespace($service)
    {
        static $namespaces;

        if (!$namespaces) {
            // Get the namespaces from the directories.
            foreach (glob(__DIR__ . '/../../../src/*') as $dir) {
                $base = basename($dir);
                if (class_exists("Aws\\{$base}\\{$base}Client")) {
                    $namespaces[Sdk::getEndpointPrefix($base)] = $base;
                }
            }
        }

        if (!isset($namespaces[$service])) {
            throw new \RuntimeException("Could not determine the namespace for {$service}.");
        }

        return $namespaces[$service];
    }
}