text:
"""
Tests of acquiring IPs in multiple subnets for isolated network or vpc
"""

from nose.plugins.attrib import attr
from marvin.cloudstackAPI import rebootRouter
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from marvin.lib.utils import (validateList,
                              get_host_credentials,
                              get_process_status,
                              cleanup_resources)
from marvin.lib.base import (Account,
                             Domain,
                             VirtualMachine,
                             ServiceOffering,
                             Zone,
                             Network,
                             NetworkOffering,
                             VPC,
                             VpcOffering,
                             PrivateGateway,
                             StaticNATRule,
                             NATRule,
                             PublicIPAddress,
                             PublicIpRange)
from marvin.lib.common import (get_domain,
                               get_zone,
                               get_free_vlan,
                               get_template,
                               list_hosts,
                               list_routers)
import logging
import random
class TestMultiplePublicIpSubnets(cloudstackTestCase):
    @classmethod
    def setUpClass(cls):
        cls.testClient = super(
            TestMultiplePublicIpSubnets,
            cls).getClsTestClient()
        cls.apiclient = cls.testClient.getApiClient()
        cls.services = cls.testClient.getParsedTestDataConfig()

        zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
        cls.zone = Zone(zone.__dict__)
        cls.template = get_template(cls.apiclient, cls.zone.id)
        cls._cleanup = []
        cls.skip = False

        if str(cls.zone.securitygroupsenabled) == "True":
            cls.skip = True
            return

        cls.hypervisor = cls.testClient.getHypervisorInfo()
        if cls.hypervisor.lower() not in ['kvm']:
            cls.skip = True
            return

        cls.logger = logging.getLogger("TestMultiplePublicIpSubnets")
        cls.stream_handler = logging.StreamHandler()
        cls.logger.setLevel(logging.DEBUG)
        cls.logger.addHandler(cls.stream_handler)

        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.apiclient)

        # Create small service offering
        cls.service_offering = ServiceOffering.create(
            cls.apiclient,
            cls.services["service_offerings"]["small"]
        )
        cls._cleanup.append(cls.service_offering)

    @classmethod
    def tearDownClass(cls):
        try:
            cleanup_resources(cls.apiclient, cls._cleanup)
        except Exception as e:
            raise Exception("Warning: Exception during cleanup : %s" % e)
        return

    def setUp(cls):
        if cls.skip:
            cls.skipTest("Test can be run only on advanced zone and KVM hypervisor")
        cls.apiclient = cls.testClient.getApiClient()
        cls.cleanup = []
        return

    def tearDown(cls):
        try:
            cleanup_resources(cls.apiclient, cls.cleanup)
        except Exception as e:
            raise Exception("Warning: Exception during cleanup : %s" % e)
        return

    def get_router(self, router_id):
        routers = list_routers(
            self.apiclient,
            id=router_id,
            listall=True)
        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )
        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )
        return routers[0]

    def get_routers(self, network_id):
        routers = list_routers(
            self.apiclient,
            networkid=network_id,
            listall=True)
        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )
        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )
        return routers

    def get_vpc_routers(self, vpc_id):
        routers = list_routers(
            self.apiclient,
            vpcid=vpc_id,
            listall=True)
        self.assertEqual(
            isinstance(routers, list),
            True,
            "Check for list routers response return valid data"
        )
        self.assertNotEqual(
            len(routers),
            0,
            "Check list router response"
        )
        return routers

    def get_router_host(self, router):
        self.assertEqual(
            router.state,
            'Running',
            "Check list router response for router state"
        )
        hosts = list_hosts(
            self.apiclient,
            id=router.hostid)
        self.assertEqual(
            isinstance(hosts, list),
            True,
            "Check for list hosts response return valid data")
        host = hosts[0]
        if host.hypervisor.lower() not in "kvm":
            return
        host.user, host.password = get_host_credentials(self.config, host.ipaddress)
        host.port=22
        return host

    def get_vpc_router_ips(self, router):
        controlIp = None
        sourcenatIp = None
        tier1_Ip = None
        tier2_Ip = None
        for nic in router.nic:
            if nic.traffictype == "Guest" and nic.ipaddress.startswith("10.250.1."):
                tier1_Ip = nic.ipaddress
            elif nic.traffictype == "Guest" and nic.ipaddress.startswith("10.250.2."):
                tier2_Ip = nic.ipaddress
            elif nic.traffictype == "Control":
                controlIp = nic.ipaddress
            elif sourcenatIp is None and nic.traffictype == "Public":
                sourcenatIp = nic.ipaddress
        return controlIp, sourcenatIp, tier1_Ip, tier2_Ip

    def verify_router_publicnic_state(self, router, host, publicNics):
        command = '/opt/cloud/bin/checkrouter.sh | cut -d ":" -f2 |tr -d " "'
        self.logger.debug("Executing command '%s'" % command)
        result = get_process_status(
            host.ipaddress,
            host.port,
            host.user,
            host.password,
            router.linklocalip,
            command)
        self.assertTrue(len(result) > 0, "Cannot get router %s redundant state" % router.name)
        redundant_state = result[0]
        self.logger.debug("router %s redudnant state is %s" % (router.name, redundant_state))
        if redundant_state == "FAULT":
            self.logger.debug("Skip as redundant_state is %s" % redundant_state)
            return
        elif redundant_state == "MASTER":
            command = 'ip link show |grep BROADCAST | egrep "%s" |grep "state DOWN" |wc -l' % publicNics
        elif redundant_state == "BACKUP":
            command = 'ip link show |grep BROADCAST | egrep "%s" |grep "state UP" |wc -l' % publicNics
        result = get_process_status(
            host.ipaddress,
            host.port,
            host.user,
            host.password,
            router.linklocalip,
            command)
        self.assertTrue(len(result) > 0 and result[0] == "0", "Expected result is 0 but actual result is %s" % result[0])

    def verify_network_interfaces_in_router(self, router, host, expectedNics):
        command = 'ip link show |grep BROADCAST | cut -d ":" -f2 |tr -d " "|tr "\n" ","'
        self.logger.debug("Executing command '%s'" % command)
        result = get_process_status(
            host.ipaddress,
            host.port,
            host.user,
            host.password,
            router.linklocalip,
            command)[0]
        self.assertEqual(result, expectedNics, "Expected nics are %s but actual nics are %s" %(expectedNics, result))

    def verify_ip_address_in_router(self, router, host, ipaddress, device, isExist=True):
        command = 'ip addr show %s |grep "inet "|cut -d " " -f6 |cut -d "/" -f1 |grep -w %s' % (device,ipaddress)
        self.logger.debug("Executing command '%s'" % command)
        result = get_process_status(
            host.ipaddress,
            host.port,
            host.user,
            host.password,
            router.linklocalip,
            command)
        self.assertEqual(len(result) > 0 and result[0] == ipaddress, isExist, "ip %s verification failed" % ipaddress)

    def get_free_ipaddress(self, vlanId):
        ipaddresses = PublicIPAddress.list(
            self.apiclient,
            vlanid=vlanId,
            state='Free'
        )
        self.assertEqual(
            isinstance(ipaddresses, list),
            True,
            "List ipaddresses should return a valid response for Free ipaddresses"
             )
        random.shuffle(ipaddresses)
        return ipaddresses[0].ipaddress

    @attr(tags=["advanced"], required_hardware="false")
    def test_04_acquire_public_ips_in_vpc_with_redundant_vrs(self):
        """ Acquire IPs in multiple subnets in vpc with redundant VRs
        # Steps
        # 1. get vpc offering with redundant VRs
        # 2. create a vpc with the vpc offering
        #   verify the available nics in VR should be "eth0,eth1"
        #   verify the IPs in VR. eth0 -> control nic, eth1 -> source nat IP
        # 3. create a tier in the vpc, and create a vm in the tier.
        #   verify the available nics in VR should be "eth0,eth1,eth2"
        #   verify the IPs in VR. eth0 -> control nic, eth1 -> source nat IP, eth2 -> tier 1
        # 4. get a free public ip, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2"
        #   verify the IPs in VR. eth0 -> control nic, eth1 -> source nat IP, eth2 -> tier 1
        # 5. remove the port forwarding rule, and release the new ip
        #   verify the available nics in VR should be "eth0,eth1,eth2"
        #   verify the IPs in VR. eth0 -> control nic, eth1 -> source nat IP, eth2 -> tier 1

        # 6. create new public ip range 1
        # 7. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 1
        # 8. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 1/2
        # 9. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 1/2/3
        # 10. release new ip 2
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 1/3
        # 11. release new ip 1
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3

        # 12. create a tier 2 in the vpc, and create a vm 2 in the tier2.
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2

        # 13. create new public ip range 2
        # 14. get a free ip 4 in new ip range 2, assign to network, and enable static nat to vm 2 in tier 2
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4
        # 15. get a free ip 5 in new ip range 2, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4/5
        # 16. get a free ip 6 in new ip range 2, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4/5/6
        # 17. release new ip 5
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4/6
        # 18. release new ip 4
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 6
        # 19. release new ip 3
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth4 -> tier 2, eth5 -> new ip 6
        # 20. restart tier1
        # 22. restart VPC
        # 23. Add private gateway
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth4 -> tier 2, eth5 -> new ip 6, eth3-> private gateway
        # 24. reboot router
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> new ip 6, eth3 -> private gateway, eth4 -> tier 1, eth5 -> tier 2
        # 25. restart VPC with cleanup
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> new ip 6, eth3 -> private gateway, eth4 -> tier 1, eth5 -> tier 2
        # 26. restart VPC with cleanup, makeredundant=true
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> new ip 6, eth3 -> private gateway, eth4 -> tier 1, eth5 -> tier 2
        """

        # Create new domain1
        self.domain1 = Domain.create(
            self.apiclient,
            services=self.services["acl"]["domain1"],
            parentdomainid=self.domain.id)
        # Create account1
        self.account1 = Account.create(
            self.apiclient,
            self.services["acl"]["accountD1"],
            domainid=self.domain1.id
        )
        self.cleanup.append(self.account1)
        self.cleanup.append(self.domain1)

        # Create new domain1
        self.domain1 = Domain.create(
            self.apiclient,
            services=self.services["acl"]["domain1"],
            parentdomainid=self.domain.id)
        # Create account1
        self.account1 = Account.create(
            self.apiclient,
            self.services["acl"]["accountD1"],
            domainid=self.domain1.id
        )
        self.cleanup.append(self.account1)
        self.cleanup.append(self.domain1)

        # 1. get vpc offering with redundant VRs
        vpc_offering = VpcOffering.list(self.apiclient, name="Redundant VPC offering")

        # 2. create a vpc with the vpc offering
        self.services["vpc"]["cidr"] = "10.250.0.0/16"
        self.vpc1 = VPC.create(
            apiclient=self.apiclient,
            services=self.services["vpc"],
            vpcofferingid=vpc_offering[0].id,
            zoneid=self.zone.id,
            account=self.account1.name,
            domainid=self.account1.domainid
        )

        #   verify the available nics in VR should be "eth0,eth1"
        #   verify the IPs in VR. eth0 -> control nic, eth1 -> source nat IP
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)

        # 3. create a tier in the vpc, and create a vm in the tier.
        vpc_tier_offerings = NetworkOffering.list(self.apiclient, name="DefaultIsolatedNetworkOfferingForVpcNetworks")
        self.assertTrue(vpc_tier_offerings is not None and len(vpc_tier_offerings) > 0, "No VPC based network offering")
        vpc_tier_offering = vpc_tier_offerings[0]
        self.services["vpctier"] = {}
        self.services["vpctier"]["name"] = "vpc-tier-1"
        self.services["vpctier"]["displaytext"] = "vpc-tier-1"
        vpc_tier_1 = Network.create(
            apiclient=self.apiclient,
            services=self.services["vpctier"],
            accountid=self.account1.name,
            domainid=self.domain1.id,
            networkofferingid=vpc_tier_offering.id,
            zoneid=self.zone.id,
            vpcid=self.vpc1.id,
            gateway="10.250.1.1",
            netmask="255.255.255.0"
        )

        try:
            self.virtual_machine1 = VirtualMachine.create(
                self.apiclient,
                self.services["virtual_machine"],
                accountid=self.account1.name,
                domainid=self.account1.domainid,
                serviceofferingid=self.service_offering.id,
                templateid=self.template.id,
                zoneid=self.zone.id,
                networkids=vpc_tier_1.id
            )
        except Exception as e:
            self.fail("Exception while deploying virtual machine: %s" % e)

        #   verify the available nics in VR should be "eth0,eth1,eth2"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_router_publicnic_state(router, host, "eth1")

        # 4. get a free public ip, assign to network, and create port forwarding rules (ssh) to the vm
        ipaddress = PublicIPAddress.create(
            self.apiclient,
            zoneid=self.zone.id,
            vpcid=self.vpc1.id,
        )
        nat_rule = NATRule.create(
            self.apiclient,
            self.virtual_machine1,
            self.services["natrule"],
            ipaddressid=ipaddress.ipaddress.id,
            networkid=vpc_tier_1.id
        )
        #   verify the available nics in VR should be "eth0,eth1,eth2"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP/new ip
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, ipaddress.ipaddress.ipaddress, "eth1", True)
            self.verify_router_publicnic_state(router, host, "eth1")

        # 5. release the new ip
        ipaddress.delete(self.apiclient)

        #   verify the available nics in VR should be "eth0,eth1,eth2"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, ipaddress.ipaddress.ipaddress, "eth1", False)
            self.verify_router_publicnic_state(router, host, "eth1")

        # 6. create new public ip range 1
        self.services["publiciprange"]["zoneid"] = self.zone.id
        self.services["publiciprange"]["forvirtualnetwork"] = "true"
        random_subnet_number = random.randrange(10,50)
        self.services["publiciprange"]["vlan"] = get_free_vlan(
            self.apiclient,
            self.zone.id)[1]
        self.services["publiciprange"]["gateway"] = "172.16." + str(random_subnet_number) + ".1"
        self.services["publiciprange"]["startip"] = "172.16." + str(random_subnet_number) + ".2"
        self.services["publiciprange"]["endip"] = "172.16." + str(random_subnet_number) + ".10"
        self.services["publiciprange"]["netmask"] = "255.255.255.0"
        self.public_ip_range1 = PublicIpRange.create(
            self.apiclient,
            self.services["publiciprange"]
        )
        self.cleanup.append(self.public_ip_range1)

        # 7. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
        ip_address_1 = self.get_free_ipaddress(self.public_ip_range1.vlan.id)
        ipaddress_1 = PublicIPAddress.create(
            self.apiclient,
            zoneid=self.zone.id,
            vpcid=self.vpc1.id,
            ipaddress=ip_address_1
        )

        StaticNATRule.enable(
            self.apiclient,
            virtualmachineid=self.virtual_machine1.id,
            ipaddressid=ipaddress_1.ipaddress.id,
            networkid=vpc_tier_1.id
        )

        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, ipaddress_1.ipaddress.ipaddress, "eth3", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth3")

        # 8. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1, new ip 2,
        ip_address_2 = self.get_free_ipaddress(self.public_ip_range1.vlan.id)
        ipaddress_2 = PublicIPAddress.create(
            self.apiclient,
            zoneid=self.zone.id,
            vpcid=self.vpc1.id,
            ipaddress=ip_address_2
        )

        nat_rule = NATRule.create(
            self.apiclient,
            self.virtual_machine1,
            self.services["natrule"],
            ipaddressid=ipaddress_2.ipaddress.id,
            networkid=vpc_tier_1.id
        )
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, ipaddress_1.ipaddress.ipaddress, "eth3", True)
            self.verify_ip_address_in_router(router, host, ipaddress_2.ipaddress.ipaddress, "eth3", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth3")

        # 9. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1, new ip 2, new ip 3
        ip_address_3 = self.get_free_ipaddress(self.public_ip_range1.vlan.id)
        ipaddress_3 = PublicIPAddress.create(
            self.apiclient,
            zoneid=self.zone.id,
            vpcid=self.vpc1.id,
            ipaddress=ip_address_3
        )

        nat_rule = NATRule.create(
            self.apiclient,
            self.virtual_machine1,
            self.services["natrule"],
            ipaddressid=ipaddress_3.ipaddress.id,
            networkid=vpc_tier_1.id
        )
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, ipaddress_1.ipaddress.ipaddress, "eth3", True)
            self.verify_ip_address_in_router(router, host, ipaddress_2.ipaddress.ipaddress, "eth3", True)
            self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth3")

        # 10. release new ip 2
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 1, new ip 3
        ipaddress_2.delete(self.apiclient)

        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, ipaddress_1.ipaddress.ipaddress, "eth3", True)
            self.verify_ip_address_in_router(router, host, ipaddress_2.ipaddress.ipaddress, "eth3", False)
            self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth3")

        # 11. release new ip 1
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3"
        #   verify the IPs in VR. eth0 -> guest nic, eth2 -> source nat IP, eth3 -> new ip 3
        ipaddress_1.delete(self.apiclient)
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, ipaddress_1.ipaddress.ipaddress, "eth3", False)
            self.verify_ip_address_in_router(router, host, ipaddress_2.ipaddress.ipaddress, "eth3", False)
            self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth3")

        # 12. create a tier in the vpc, and create a vm in the tier.
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2
        self.services["vpctier"]["name"] = "vpc-tier-2"
        self.services["vpctier"]["displaytext"] = "vpc-tier-2"
        vpc_tier_2 = Network.create(
            apiclient=self.apiclient,
            services=self.services["vpctier"],
            accountid=self.account1.name,
            domainid=self.domain1.id,
            networkofferingid=vpc_tier_offering.id,
            zoneid=self.zone.id,
            vpcid=self.vpc1.id,
            gateway="10.250.2.1",
            netmask="255.255.255.0"
        )

        try:
            self.virtual_machine2 = VirtualMachine.create(
                self.apiclient,
                self.services["virtual_machine"],
                accountid=self.account1.name,
                domainid=self.account1.domainid,
                serviceofferingid=self.service_offering.id,
                templateid=self.template.id,
                zoneid=self.zone.id,
                networkids=vpc_tier_2.id
            )
        except Exception as e:
            self.fail("Exception while deploying virtual machine: %s" % e)

        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
            self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth3")

        # 13. create new public ip range 2
        self.services["publiciprange"]["zoneid"] = self.zone.id
        self.services["publiciprange"]["forvirtualnetwork"] = "true"
        self.services["publiciprange"]["vlan"] = get_free_vlan(
            self.apiclient,
            self.zone.id)[1]
        self.services["publiciprange"]["gateway"] = "172.16." + str(random_subnet_number + 1) + ".1"
        self.services["publiciprange"]["startip"] = "172.16." + str(random_subnet_number + 1) + ".2"
        self.services["publiciprange"]["endip"] = "172.16." + str(random_subnet_number + 1) + ".10"
        self.services["publiciprange"]["netmask"] = "255.255.255.0"
        self.public_ip_range2 = PublicIpRange.create(
            self.apiclient,
            self.services["publiciprange"]
        )
        self.cleanup.append(self.public_ip_range2)

        # 14. get a free ip 4 in new ip range 2, assign to network, and enable static nat to vm 2 in tier 2
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4
        ip_address_4 = self.get_free_ipaddress(self.public_ip_range2.vlan.id)
        ipaddress_4 = PublicIPAddress.create(
            self.apiclient,
            zoneid=self.zone.id,
            vpcid=self.vpc1.id,
            ipaddress=ip_address_4
        )

        StaticNATRule.enable(
            self.apiclient,
            virtualmachineid=self.virtual_machine2.id,
            ipaddressid=ipaddress_4.ipaddress.id,
            networkid=vpc_tier_2.id
        )

        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
            self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
            self.verify_ip_address_in_router(router, host, ipaddress_4.ipaddress.ipaddress, "eth5", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth3|eth5")

        # 15. get a free ip 5 in new ip range 2, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4/5
        ip_address_5 = self.get_free_ipaddress(self.public_ip_range2.vlan.id)
        ipaddress_5 = PublicIPAddress.create(
            self.apiclient,
            zoneid=self.zone.id,
            vpcid=self.vpc1.id,
            ipaddress=ip_address_5
        )

        nat_rule = NATRule.create(
            self.apiclient,
            self.virtual_machine2,
            self.services["natrule"],
            ipaddressid=ipaddress_5.ipaddress.id,
            networkid=vpc_tier_2.id
        )
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
            self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
            self.verify_ip_address_in_router(router, host, ipaddress_4.ipaddress.ipaddress, "eth5", True)
            self.verify_ip_address_in_router(router, host, ipaddress_5.ipaddress.ipaddress, "eth5", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth3|eth5")

        # 16. get a free ip 6 in new ip range 2, assign to network, and create port forwarding rules (ssh) to the vm
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4/5/6
        ip_address_6 = self.get_free_ipaddress(self.public_ip_range2.vlan.id)
        ipaddress_6 = PublicIPAddress.create(
            self.apiclient,
            zoneid=self.zone.id,
            vpcid=self.vpc1.id,
            ipaddress=ip_address_6
        )

        nat_rule = NATRule.create(
            self.apiclient,
            self.virtual_machine2,
            self.services["natrule"],
            ipaddressid=ipaddress_6.ipaddress.id,
            networkid=vpc_tier_2.id
        )
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
            self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
            self.verify_ip_address_in_router(router, host, ipaddress_4.ipaddress.ipaddress, "eth5", True)
            self.verify_ip_address_in_router(router, host, ipaddress_5.ipaddress.ipaddress, "eth5", True)
            self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth3|eth5")

        # 17. release new ip 5
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 4/6
        ipaddress_5.delete(self.apiclient)

        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
            self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
            self.verify_ip_address_in_router(router, host, ipaddress_4.ipaddress.ipaddress, "eth5", True)
            self.verify_ip_address_in_router(router, host, ipaddress_5.ipaddress.ipaddress, "eth5", False)
            self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth3|eth5")

        # 18. release new ip 4
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2, eth5 -> new ip 6
        ipaddress_4.delete(self.apiclient)
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", True)
            self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
            self.verify_ip_address_in_router(router, host, ipaddress_4.ipaddress.ipaddress, "eth5", False)
            self.verify_ip_address_in_router(router, host, ipaddress_5.ipaddress.ipaddress, "eth5", False)
            self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth3|eth5")

        # 19. release new ip 3
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth4 -> tier 2, eth5 -> new ip 6
        ipaddress_3.delete(self.apiclient)
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth4,eth5,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
            self.verify_ip_address_in_router(router, host, ipaddress_4.ipaddress.ipaddress, "eth5", False)
            self.verify_ip_address_in_router(router, host, ipaddress_5.ipaddress.ipaddress, "eth5", False)
            self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth5")

        # 20. restart tier1
        vpc_tier_1.restart(self.apiclient)
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth4,eth5,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
            self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth5")

        #21. restart tier2
        vpc_tier_2.restart(self.apiclient)
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth4,eth5,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
            self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth5")

        # 22. restart VPC
        self.vpc1.restart(self.apiclient)
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth4,eth5,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
            self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth5")

        # 23. Add private gateway
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth4 -> tier 2, eth5 -> new ip 6, eth3-> private gateway
        private_gateway_ip = "172.16." + str(random_subnet_number + 2) + ".1"
        private_gateway = PrivateGateway.create(
            self.apiclient,
            gateway=private_gateway_ip,
            ipaddress=private_gateway_ip,
            netmask='255.255.255.0',
            vlan=get_free_vlan(self.apiclient, self.zone.id)[1],
            vpcid=self.vpc1.id
        )
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth4,eth5,eth3,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth2", True)
            self.verify_ip_address_in_router(router, host, private_gateway_ip, "eth3", True)
            self.verify_ip_address_in_router(router, host, ipaddress_3.ipaddress.ipaddress, "eth3", False)
            self.verify_ip_address_in_router(router, host, tier2_Ip, "eth4", True)
            self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth5", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth3|eth5")

        # 24. reboot router
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> new ip 6, eth3 -> private gateway, eth4 -> tier 1, eth5 -> tier 2
        routers = self.get_vpc_routers(self.vpc1.id)
        if len(routers) > 0:
            router = routers[0]
            cmd = rebootRouter.rebootRouterCmd()
            cmd.id = router.id
            self.apiclient.rebootRouter(cmd)
            router = self.get_router(router.id)
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth2", True)
            self.verify_ip_address_in_router(router, host, private_gateway_ip, "eth3", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth4", True)
            self.verify_ip_address_in_router(router, host, tier2_Ip, "eth5", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth2|eth3")

        # 25. restart VPC with cleanup
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> new ip 6, eth3 -> private gateway, eth4 -> tier 1, eth5 -> tier 2
        self.vpc1.restart(self.apiclient, cleanup=True)
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth2", True)
            self.verify_ip_address_in_router(router, host, private_gateway_ip, "eth3", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth4", True)
            self.verify_ip_address_in_router(router, host, tier2_Ip, "eth5", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth2|eth3")

        # 26. restart VPC with cleanup, makeredundant=true
        #   verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4,eth5,"
        #   verify the IPs in VR. eth1 -> source nat IP, eth2 -> new ip 6, eth3 -> private gateway, eth4 -> tier 1, eth5 -> tier 2
        self.vpc1.restart(self.apiclient, cleanup=True, makeredundant=True)
        routers = self.get_vpc_routers(self.vpc1.id)
        for router in routers:
            host = self.get_router_host(router)
            self.verify_network_interfaces_in_router(router, host, "eth0,eth1,eth2,eth3,eth4,eth5,")
            controlIp, sourcenatIp, tier1_Ip, tier2_Ip = self.get_vpc_router_ips(router)
            self.verify_ip_address_in_router(router, host, controlIp, "eth0", True)
            self.verify_ip_address_in_router(router, host, sourcenatIp, "eth1", True)
            self.verify_ip_address_in_router(router, host, ipaddress_6.ipaddress.ipaddress, "eth2", True)
            self.verify_ip_address_in_router(router, host, private_gateway_ip, "eth3", True)
            self.verify_ip_address_in_router(router, host, tier1_Ip, "eth4", True)
            self.verify_ip_address_in_router(router, host, tier2_Ip, "eth5", True)
            self.verify_router_publicnic_state(router, host, "eth1|eth2|eth3")


text:
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

      <link rel="stylesheet" href="./../helpwin.css">
      <title>MATLAB File Help: prtNewClass</title>

            MATLAB File Help: prtNewClass

prtNewClass

  prtNewClass creates a new prtClass* M-file

    prtNewClass creates a new prtClass* M-file including definitions for
    all required methods and properties for prtClass objects.  By
    convention, prtClass M-files should start with the string prtClass, and
    file names must be valid MATLAB function names (no special characters,
    spaces, etc.)

    prtNewClass(FILENAME) enables the user to specify the name of the new
    prtClass object from the command line.

    %Example:
    prtNewClass('prtClassAwesome');

redpajama_set_name: RedPajamaGithub


text:
class Exploitdb < Formula
  desc "The official Exploit Database"
  homepage "https://www.exploit-db.com/"
  url "https://github.com/offensive-security/exploit-database.git",
      :tag => "2018-01-01",
      :revision => "07e51f4126f518780ad3ef8761cc1458e936dfb8"
  version "2018-01-01"
  head "https://github.com/offensive-security/exploit-database.git"

  bottle :unneeded

  def install
    inreplace "searchsploit", "gitpath=\"/opt/exploit-database\"", "gitpath=\"#{pkgshare}\""
    bin.install "searchsploit"
    pkgshare.install %w[.git exploits files_exploits.csv files_shellcodes.csv
                        shellcodes]
  end

  test do
    system "#{bin}/searchsploit", "sendpage"
  end
end


text:
var request = require('request');

/**
 * Regexp for extracting expiration time from cache-control header
 * @constant
 */
var MAX_AGE_RE = /.*max-age=(\d+).*/;

/**
 * Small helper for caching Google's certificates.
 *
 * @constructor
 */
var KeyManager = function() {
  this.certificates = {};
  this.expiry = 0;
};

/**
 * @callback CertificateCallback
 * @param {String} err Error message if certificate not available
 * @param {String} cert Matched key/certificate
 */

/**
 * Fetch a key. Since the key may need to be fetched via HTTP a callback
 * is required. Keys are usually cached though.
 *
 * @param {String} keyId ID of the key to use.
 * @param {CertificateCallback} callback Callback for when certificate is ready
 * @param {Object} options Additional options
 */
KeyManager.prototype.fetchKey = function(keyId, callback, options) {
  options = options || {};

  var shouldFetch = Date.now() >= this.expiry;
  var self = this;

  if (this.certificates[keyId]) {
    callback(null, this.certificates[keyId]);
  } else if (!shouldFetch || options.skipFetch) {
    callback("Key not found", null);
  } else {
    this.refreshCertificates(function(err, certificates) {
      self.fetchKey(keyId, callback, {skipFetch: true});
    });
  }
};

/**
 * Parses cache-control header to get expiration time of the certificates.
 *
 * @param {String} header Value of the cache-control header
 * @returns {Number} expiration time in millis
 */
KeyManager.prototype.parseCacheControlHeader = function(header) {
  var match = header.match(MAX_AGE_RE);
  if (match) {
    return match[1];
  }
  return 0;
};

/**
 * Fetch current certificates from Google.
 *
 * @param {Function} callback Completion handler
 */
KeyManager.prototype.refreshCertificates = function(callback) {
  var self = this;
  request.get('https://www.googleapis.com/oauth2/v1/certs', function(err, res, body) {
    if (res.statusCode == 200) {
      var cacheControl = res.headers['cache-control'] || '';
      var expiry = self.parseCacheControlHeader(cacheControl);
      self.expiry = Date.now() + expiry;
      self.certificates = JSON.parse(body);
      callback(null, self.certificates);
    } else {
      callback(err, self.certificates);
    }
  });
};

module.exports = KeyManager;


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Invalidate Framebuffer Against WebGL 2</title>
<link rel="stylesheet" href="../../resources/js-test-style.css"/>

<canvas id="canvas" width="20" height="20"> </canvas>


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using OpenSage.Content.Loaders;
using OpenSage.Data.StreamFS;
using OpenSage.Data.W3x;
using OpenSage.Graphics.Shaders;
using OpenSage.Utilities.Extensions;
using Veldrid;

namespace OpenSage.Graphics
{
    partial class ModelMesh
    {
        internal static ModelMesh ParseAsset(BinaryReader reader, Asset asset, AssetImportCollection imports, AssetParseContext context)
        {
            var w3xMesh = W3xMesh.Parse(reader, imports, asset.Header);

            return new ModelMesh(w3xMesh, asset, context.AssetStore.LoadContext);
        }

        private ModelMesh(W3xMesh w3xMesh, Asset asset, AssetLoadContext loadContext)
        {
            SetNameAndInstanceId(asset);

            var effectName = w3xMesh.FXShader.ShaderName.Replace(".fx", string.Empty);
            //var shaderResources = loadContext.ShaderResources.GetShaderMaterialResources(effectName); // TODO: Uncomment this.
            var shaderResources = loadContext.ShaderResources.GetShaderMaterialResources("NormalMapped");
            _depthPipeline = loadContext.ShaderResources.MeshDepth.Pipeline;

            // TODO: Extract state properties from shader material.

            var pipeline = shaderResources.Pipeline;

            // TODO: Uncomment this.

            //var materialResourceSetBuilder = AddDisposable(new ShaderMaterialResourceSetBuilder(
            //    loadContext.GraphicsDevice,
            //    shaderResources));

            //foreach (var shaderConstant in w3xMesh.FXShader.Constants)
            //{
            //    switch (shaderConstant.Type)
            //    {
            //        case FXShaderConstantType.Float:
            //            switch (shaderConstant.FloatValueCount)
            //            {
            //                case 1:
            //                    materialResourceSetBuilder.SetConstant(shaderConstant.Name, shaderConstant.Value.Float);
            //                    break;

            //                case 2:
            //                    materialResourceSetBuilder.SetConstant(shaderConstant.Name, shaderConstant.Value.Vector2);
            //                    break;

            //                case 3:
            //                    materialResourceSetBuilder.SetConstant(shaderConstant.Name, shaderConstant.Value.Vector3);
            //                    break;

            //                case 4:
            //                    materialResourceSetBuilder.SetConstant(shaderConstant.Name, shaderConstant.Value.Vector4);
            //                    break;

            //                default:
            //                    throw new InvalidOperationException();
            //            }
            //            break;

            //        case FXShaderConstantType.Bool:
            //            materialResourceSetBuilder.SetConstant(shaderConstant.Name, shaderConstant.Value.Bool);
            //            break;

            //        case FXShaderConstantType.Int:
            //            materialResourceSetBuilder.SetConstant(shaderConstant.Name, shaderConstant.Value.Int);
            //            break;

            //        case FXShaderConstantType.Texture:
            //            materialResourceSetBuilder.SetTexture(shaderConstant.Name, shaderConstant.TextureValue);
            //            break;

            //        default:
            //            throw new NotSupportedException();
            //    }
            //}

            //var materialResourceSet = materialResourceSetBuilder.CreateResourceSet();

            var materialResourceSet = (ResourceSet) null;

            MeshParts = new List<ModelMeshPart>();
            MeshParts.Add(new ModelMeshPart(
                null,
                0,
                (uint)(w3xMesh.Triangles.Length * 3),
                false, // TODO
                pipeline,
                pipeline, // TODO
                materialResourceSet));

            BoundingBox = w3xMesh.BoundingBox;

            _shaderSet = shaderResources.ShaderSet;

            Skinned = w3xMesh.GeometryType == MeshGeometryType.Skin;
            Hidden = w3xMesh.Hidden;
            CameraOriented = w3xMesh.GeometryType == MeshGeometryType.CameraOriented;

            _vertexBuffer = AddDisposable(loadContext.GraphicsDevice.CreateStaticBuffer(
                w3xMesh.VertexData.VertexData,
                BufferUsage.VertexBuffer));

            _indexBuffer = AddDisposable(loadContext.GraphicsDevice.CreateStaticBuffer(
                CreateIndices(w3xMesh),
                BufferUsage.IndexBuffer));

            var hasHouseColor = false; // TODO
            _meshConstantsResourceSet = loadContext.ShaderResources.Mesh.GetCachedMeshResourceSet(
                Skinned,
                hasHouseColor);

            PostInitialize(loadContext);
        }

        private static ushort[] CreateIndices(W3xMesh w3xMesh)
        {
            var triangles = w3xMesh.Triangles;
            var indices = new ushort[(uint) triangles.Length * 3];

            var indexIndex = 0;
            for (var i = 0; i < triangles.Length; i++)
            {
                indices[indexIndex++] = (ushort) triangles[i].VIndex0;
                indices[indexIndex++] = (ushort) triangles[i].VIndex1;
                indices[indexIndex++] = (ushort) triangles[i].VIndex2;
            }

            return indices;
        }
    }
}


text:
using System.Collections.Generic;
using System.Windows.Documents;
using Algebra.Core.Expr;
using Algebra.QL.Print.Expr;

namespace Algebra.QL.Extensions.Print.Expr
{
    public class PowerExpr : BinaryExpr<IPrintExpr>, IPrintExpr
    {
        public PowerExpr(IPrintExpr l, IPrintExpr r)
            : base(l, r)
        {

        }

        public IEnumerable<Inline> BuildDocument()
        {
            List<Inline> inlines = new List<Inline>();
            inlines.AddRange(Expr1.BuildDocument());
            inlines.Add(new Run(" ^ "));
            inlines.AddRange(Expr2.BuildDocument());
            return inlines;
        }
    }
}


text:
namespace Xenosynth.Admin.Content.ImageGallery {

    public partial class EditImage {
        protected Xenosynth.Admin.Content.ImageGallery.ImageTasks ImageTasks1;
        protected Xenosynth.Admin.Content.ImageGallery.ImageGalleryTasks ImageGalleryTasks1;
        protected Xenosynth.Admin.Content.PathBrowser PathBrowser1;
        protected Xenosynth.Admin.Controls.MessageBox MessageBox1;
        protected Xenosynth.Admin.Content.ImageGallery.ImageTabControl ImageTabControl1;
        protected System.Web.UI.WebControls.TextBox TextBoxFileName;
        protected System.Web.UI.WebControls.TextBox TextBoxTitle;
        protected System.Web.UI.WebControls.TextBox TextBoxAltText;
        protected System.Web.UI.WebControls.TextBox TextBoxDescription;
        protected System.Web.UI.WebControls.TextBox TextBoxDescriptionCount;
        protected Fluent.MultiLineTextBoxValidator Multilinetextboxvalidator1;
        protected System.Web.UI.WebControls.TextBox TextBoxKeywords;
        protected System.Web.UI.WebControls.TextBox TextBoxKeywordsCount;
        protected Fluent.MultiLineTextBoxValidator Multilinetextboxvalidator2;
        protected System.Web.UI.WebControls.TextBox TextBoxDateCreated;
        protected System.Web.UI.WebControls.TextBox TextBoxDateModified;
        protected System.Web.UI.WebControls.TextBox TextBoxVersion;
        protected System.Web.UI.WebControls.TextBox TextBoxStatus;
        protected System.Web.UI.WebControls.TextBox TextBoxFullPath;
        protected System.Web.UI.WebControls.Button Button1;
        protected System.Web.UI.WebControls.Button Button2;
        protected Fluent.DataBinding.DataBindingManager DataBindingManagerImage;
    }
}


text:
from heat.common import exception

class Timestamp(object):
    """A descriptor for writing a timestamp to the database."""

    def __init__(self, db_fetch, attribute):
        """Initialise the timestamp descriptor.

        Initialise with a function to fetch the database representation of an
        object (given a context and ID) and the name of the attribute to
        retrieve.
        """
        self.db_fetch = db_fetch
        self.attribute = attribute

    def __get__(self, obj, obj_class):
        """Get timestamp for the given object and class."""
        if obj is None or obj.id is None:
            return None

        o = self.db_fetch(obj.context, obj.id)
        return getattr(o, self.attribute)

    def __set__(self, obj, timestamp):
        """Update the timestamp for the given object."""
        if obj.id is None:
            raise exception.ResourceNotAvailable(resource_name=obj.name)
        o = self.db_fetch(obj.context, obj.id)
        o.update_and_save({self.attribute: timestamp})


text:
import { Sprite } from '@pixi/sprite';
import { expect } from 'chai';
import { skipHello } from '@pixi/utils';
import { Texture, RenderTexture, BatchRenderer, Renderer } from '@pixi/core';
import { Extract } from '@pixi/extract';

skipHello();

describe('Extract', function ()
{
    before(function ()
    {
        Renderer.registerPlugin('extract', Extract);
        Renderer.registerPlugin('batch', BatchRenderer);
    });

    it('should access extract on renderer', function ()
    {
        const renderer = new Renderer();

        expect(renderer.plugins.extract).to.be.an.instanceof(Extract);

        renderer.destroy();
    });

    it('should extract an sprite', function ()
    {
        const renderer = new Renderer();
        const sprite = new Sprite(Texture.WHITE);
        const extract = renderer.plugins.extract as Extract;

        expect(extract.canvas(sprite)).to.be.an.instanceof(HTMLCanvasElement);
        expect(extract.base64(sprite)).to.be.a('string');
        expect(extract.pixels(sprite)).to.be.instanceOf(Uint8Array);
        expect(extract.image(sprite)).to.be.instanceOf(HTMLImageElement);

        renderer.destroy();
        sprite.destroy();
    });

    it('should extract with no arguments', function ()
    {
        const renderer = new Renderer();
        const extract = renderer.plugins.extract as Extract;

        expect(extract.canvas()).to.be.an.instanceof(HTMLCanvasElement);
        expect(extract.base64()).to.be.a('string');
        expect(extract.pixels()).to.be.instanceOf(Uint8Array);
        expect(extract.image()).to.be.instanceOf(HTMLImageElement);

        renderer.destroy();
    });

    it('should extract a render texture', function ()
    {
        const renderer = new Renderer();
        const extract = renderer.plugins.extract as Extract;
        const renderTexture = RenderTexture.create({ width: 10, height: 10 });
        const sprite = new Sprite(Texture.WHITE);

        renderer.render(sprite, { renderTexture });

        expect(extract.canvas(renderTexture)).to.be.an.instanceof(HTMLCanvasElement);
        expect(extract.base64(renderTexture)).to.be.a('string');
        expect(extract.pixels(renderTexture)).to.be.instanceOf(Uint8Array);
        expect(extract.image(renderTexture)).to.be.instanceOf(HTMLImageElement);

        renderer.destroy();
        renderTexture.destroy();
        sprite.destroy();
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/DECORATION/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/DECORATION/1.1.0 http://maven.apache.org/xsd/decoration-1.1.0.xsd"
  name="${project.name}">

  <bannerLeft>
    <name>Apache Oltu OAuth reference implementation</name>
    <src>images/oltu_head.png</src>
    <href>${project.url}/index.html</href>
  </bannerLeft>

  <bannerRight>
    <name>The Apache Software Foundation</name>
    <src>http://www.apache.org/images/asf_logo.gif</src>
    <href>http://www.apache.org/</href>
  </bannerRight>

  <skin>
    <groupId>org.apache.maven.skins</groupId>
    <artifactId>maven-fluido-skin</artifactId>
    <version>1.3.0</version>
  </skin>

  <version position="left" />

    <menu name="ASF" inherit="bottom">
      <item name="How Apache Works" href="http://www.apache.org/foundation/how-it-works.html" />
      <item name="Foundation" href="http://www.apache.org/foundation/" />
      <item name="Sponsoring Apache" href="http://www.apache.org/foundation/sponsorship.html" />
      <item name="Thanks" href="http://www.apache.org/foundation/thanks.html" />
      <item name="Apache Incubator" href="http://incubator.apache.org/" />
    </menu>

Apache Oltu, Apache, the Apache feather logo, and the Apache Oltu project logos are trademarks of The Apache Software Foundation.
      All other marks mentioned may be trademarks or registered trademarks of their respective owners.

</project>


text:
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/select.h>

#include <linux/lightsensor.h>

#include <cutils/log.h>

#include "LightSensor.h"

/*****************************************************************************/

LightSensor::LightSensor()
    : SensorBase(LS_DEVICE_NAME, "lightsensor-level"),
      mEnabled(0),
      mInputReader(4),
      mHasPendingEvent(false)
{
    mPendingEvent.version = sizeof(sensors_event_t);
    mPendingEvent.sensor = ID_L;
    mPendingEvent.type = SENSOR_TYPE_LIGHT;
    memset(mPendingEvent.data, 0, sizeof(mPendingEvent.data));

     open_device();

    int flags = 0;
    if (!ioctl(dev_fd, LIGHTSENSOR_IOCTL_GET_ENABLED, &flags)) {
        if (flags) {
            mEnabled = 1;
            setInitialState();
        }
    }

    if (!mEnabled) {
        close_device();
    }
}

LightSensor::~LightSensor() {
}

int LightSensor::setInitialState() {
    struct input_absinfo absinfo;
    if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_LIGHT), &absinfo)) {
        mPendingEvent.light = indexToValue(absinfo.value);
        mHasPendingEvent = true;
    }
    return 0;
}

int LightSensor::enable(int32_t, int en) {
    int flags = en ? 1 : 0;
    int err = 0;
    if (flags != mEnabled) {
        if (!mEnabled) {
            open_device();
        }
        err = ioctl(dev_fd, LIGHTSENSOR_IOCTL_ENABLE, &flags);
        err = err<0 ? -errno : 0;
        ALOGE_IF(err, "LIGHTSENSOR_IOCTL_ENABLE failed (%s)", strerror(-err));
        if (!err) {
            mEnabled = en ? 1 : 0;
            if (en) {
                setInitialState();
            }
        }
        if (!mEnabled) {
            close_device();
        }
    }
    return err;
}

bool LightSensor::hasPendingEvents() const {
    return mHasPendingEvent;
}

int LightSensor::readEvents(sensors_event_t* data, int count)
{
    if (count < 1)
        return -EINVAL;

    if (mHasPendingEvent) {
        mHasPendingEvent = false;
        mPendingEvent.timestamp = getTimestamp();
        *data = mPendingEvent;
        return mEnabled ? 1 : 0;
    }

    ssize_t n = mInputReader.fill(data_fd);
    if (n < 0)
        return n;

    int numEventReceived = 0;
    input_event const* event;

    while (count && mInputReader.readEvent(&event)) {
        int type = event->type;
        if (type == EV_ABS) {
            if (event->code == EVENT_TYPE_LIGHT) {
                if (event->value != -1) {
                    // FIXME: not sure why we're getting -1 sometimes
                    mPendingEvent.light = indexToValue(event->value);
                }
            }
        } else if (type == EV_SYN) {
            mPendingEvent.timestamp = timevalToNano(event->time);
            if (mEnabled) {
                *data++ = mPendingEvent;
                count--;
                numEventReceived++;
            }
        } else {
            ALOGE("LightSensor: unknown event (type=%d, code=%d)",
                    type, event->code);
        }
        mInputReader.next();
    }

    return numEventReceived;
}

float LightSensor::indexToValue(size_t index) const
{
    static const float luxValues[10] = {
            1.0, 3.0, 5.0, 19.0, 26.0, 69.0,
            219.0, 309.0, 498.0, 1024.0
    };

    const size_t maxIndex = sizeof(luxValues)/sizeof(*luxValues) - 1;
    if (index > maxIndex)
        index = maxIndex;
    return luxValues[index];
}


text:
package parquet.column.values.delta.benchmark;

import org.junit.Test;
import parquet.column.values.delta.DeltaBinaryPackingValuesWriter;
import parquet.column.values.rle.RunLengthBitPackingHybridValuesWriter;
import java.util.Random;

public class BenchmarkIntegerOutputSize {
  public static int blockSize=128;
  public static int miniBlockNum=4;
  public static int dataSize=10000 * blockSize;

  private interface IntFunc {
    public int getIntValue();
  }

  @Test
  public void testBigNumbers() {
    final Random r=new Random();
    testRandomIntegers(new IntFunc() {
      @Override
      public int getIntValue() {
        return r.nextInt();
      }
    },32);
  }

  @Test
  public void testRangedNumbersWithSmallVariations() {
    final Random r=new Random();
    testRandomIntegers(new IntFunc() {
      @Override
      public int getIntValue() {
        return 1000+r.nextInt(20);
      }
    },10);
  }

  @Test
  public void testSmallNumbersWithSmallVariations() {
    final Random r=new Random();
    testRandomIntegers(new IntFunc() {
      @Override
      public int getIntValue() {
        return 40+r.nextInt(20);
      }
    },6);
  }

  @Test
  public void testSmallNumberVariation() {
      final Random r=new Random();
      testRandomIntegers(new IntFunc() {
        @Override
        public int getIntValue() {
          return r.nextInt(20)-10;
        }
      },4);
  }

  public void testRandomIntegers(IntFunc func,int bitWidth) {
    DeltaBinaryPackingValuesWriter delta=new DeltaBinaryPackingValuesWriter(blockSize,miniBlockNum,100);
    RunLengthBitPackingHybridValuesWriter rle= new RunLengthBitPackingHybridValuesWriter(bitWidth,100);
    for (int i = 0; i < dataSize; i++) {
      int v = func.getIntValue();
      delta.writeInteger(v);
      rle.writeInteger(v);
    }
    System.out.println("delta size: "+delta.getBytes().size());
    System.out.println("estimated size"+estimatedSize());
    System.out.println("rle size: "+rle.getBytes().size());
  }

  private double estimatedSize(){
    int miniBlockSize = blockSize / miniBlockNum;
    double miniBlockFlushed = Math.ceil(((double) dataSize - 1) / miniBlockSize);
    double blockFlushed = Math.ceil(((double) dataSize - 1) / blockSize);
    double estimatedSize = 4 * 5 //blockHeader
            + 4 * miniBlockFlushed * miniBlockSize //data(aligned to miniBlock)
            + blockFlushed * miniBlockNum //bitWidth of mini blocks
            + (5.0 * blockFlushed);//min delta for each block
    return estimatedSize;
  }
}


text:
class RemoveNotificationAcceptedFromResponseMap < ActiveRecord::Migration
  def change
    remove_column "response_maps","notification_accepted"
  end
end


text:
import React, { Component } from 'react';
import { View, Text, Image, TouchableOpacity } from 'react-native';
import PropTypes from 'prop-types';
import { ParallaxImage } from 'react-native-snap-carousel';
import styles from 'example/src/styles/SliderEntry.style';

export default class SliderEntry extends Component {

    static propTypes = {
        data: PropTypes.object.isRequired,
        even: PropTypes.bool,
        parallax: PropTypes.bool,
        parallaxProps: PropTypes.object
    };

    get image () {
        const { data: { illustration }, parallax, parallaxProps, even } = this.props;

        return parallax ? (
            <ParallaxImage
              source={{ uri: illustration }}
              containerStyle={[styles.imageContainer, even ? styles.imageContainerEven : {}]}
              style={styles.image}
              parallaxFactor={0.35}
              showSpinner={true}
              spinnerColor={even ? 'rgba(255, 255, 255, 0.4)' : 'rgba(0, 0, 0, 0.25)'}
              {...parallaxProps}
            />
        ) : (
            <Image
              source={{ uri: illustration }}
              style={styles.image}
            />
        );
    }

    render () {
        const { data: { title, subtitle }, even } = this.props;

        const uppercaseTitle = title ? (
            <Text
              style={[styles.title, even ? styles.titleEven : {}]}
              numberOfLines={2}
            >
                { title.toUpperCase() }
            </Text>
        ) : false;

        return (
            <TouchableOpacity
              activeOpacity={1}
              style={styles.slideInnerContainer}
              onPress={() => { alert(`You've clicked '${title}'`); }}
              >
                <View style={styles.shadow} />
                <View style={[styles.imageContainer, even ? styles.imageContainerEven : {}]}>
                    { this.image }
                    <View style={[styles.radiusMask, even ? styles.radiusMaskEven : {}]} />
                </View>
                <View style={[styles.textContainer, even ? styles.textContainerEven : {}]}>
                    { uppercaseTitle }
                    <Text
                      style={[styles.subtitle, even ? styles.subtitleEven : {}]}
                      numberOfLines={2}
                    >
                        { subtitle }
                    </Text>
                </View>
            </TouchableOpacity>
        );
    }
}


text:
import threading
from datetime import datetime
import time
from pytibrv.api import *
from pytibrv.status import *
from pytibrv.tport import *
from pytibrv.events import *
from pytibrv.disp import *
from pytibrv.queue import *
from pytibrv.ft import *
import unittest

def callback(member: tibrvftMember, groupName: bytes, action: tibrvftAction, closure):
    name = groupName.decode()
    obj = tibrvClosure(closure)
    obj.action = action

    print(datetime.now(), obj.name, ' -> ', action)

def ft_mon(monitor: tibrvftMonitor, groupName: bytes, numActiveMembers: int, closure):
    name = groupName.decode()
    obj = tibrvClosure(closure)
    obj.cnt = numActiveMembers
    print(datetime.now(), name, numActiveMembers)

class App(threading.Thread):
    def __init__(self, name: str):
        threading.Thread.__init__(self)
        self.action = 0
        self.tx = 0
        self.que = 0
        self.disp = 0
        self.ft = 0
        self.name = name

    def start(self, weight: int = 50):
        status, self.tx = tibrvTransport_Create(None, None, None)
        assert TIBRV_OK == status, tibrvStatus_GetText(status)

        status, self.que = tibrvQueue_Create()
        assert TIBRV_OK == status, tibrvStatus_GetText(status)

        status, self.ft = tibrvftMember_Create(self.que, callback, self.tx, 'TEST', \
                                               weight, 1, 1.0, 1.5, 2.0, self)
        assert TIBRV_OK == status, tibrvStatus_GetText(status)

        status, self.disp = tibrvDispatcher_Create(self.que)
        assert TIBRV_OK == status, tibrvStatus_GetText(status)

        threading.Thread.start(self)

    def stop(self):
        if self.ft != 0:
            print(datetime.now(), self.name, 'IS STOPING ...')
            status = tibrvftMember_Destroy(self.ft)
            assert TIBRV_OK == status, tibrvStatus_GetText(status)
            self.ft = 0

    def close(self):
        if self.tx != 0:
            self.stop()

        if self.disp != 0:
            status = tibrvDispatcher_Destroy(self.disp)
            assert TIBRV_OK == status, tibrvStatus_GetText(status)
            self.disp = 0

        if self.que != 0:
            status = tibrvQueue_Destroy(self.que)
            assert TIBRV_OK == status, tibrvStatus_GetText(status)
            self.que = 0

        if self.tx != 0:
            status = tibrvTransport_Destroy(self.tx)
            assert TIBRV_OK == status, tibrvStatus_GetText(status)
            self.tx = 0

    def run(self):

        print(datetime.now(), self.name, 'START RUNNING ')

        # when thread stopped, self.ft is 0
        while self.ft != 0:
            if self.action != TIBRVFT_ACTIVATE:
                print(datetime.now(), self.name, 'IS DEACTIVATED')
                time.sleep(0.5)
                continue

            print(datetime.now(), self.name, 'IS ACTIVATED')
            time.sleep(1.0)
            print(datetime.now(), self.name, 'RUN SOMETHING')

        print(datetime.now(), self.name, 'EXIT NOW')

class MonitorTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        status = tibrv_Open()
        assert TIBRV_OK == status, tibrvStatus_GetText(status)

    @classmethod
    def tearDownClass(cls):
        tibrv_Close()

    def test_create(self):

        print('')
        ap1 = App('AP1')
        ap1.start()

        # WAIT AP1 became ACTIVATED
        # wait for activationInterval
        time.sleep(2.5)
        self.assertEqual(TIBRVFT_ACTIVATE, ap1.action)

        status, tx = tibrvTransport_Create(None, None, None)
        self.assertEqual(TIBRV_OK, status, tibrvStatus_GetText(status))
        que = TIBRV_DEFAULT_QUEUE

        status, disp = tibrvDispatcher_Create(que)
        self.assertEqual(TIBRV_OK, status, tibrvStatus_GetText(status))

        # pass self as closure, reset cnt = 0
        self.cnt = 0
        status, monitor = tibrvftMonitor_Create(que, ft_mon, tx, 'TEST', 1.0, self)
        self.assertEqual(TIBRV_OK, status, tibrvStatus_GetText(status))

        # wait at least for a HBT
        time.sleep(1.5)

        self.assertEqual(1, self.cnt)

        # let ap1 do something
        time.sleep(1.0)
        ap1.stop()

        # let monitor detect the change
        time.sleep(0.1)

        self.assertEqual(0, self.cnt)

        ap1.close()

        status = tibrvDispatcher_Destroy(disp)
        self.assertEqual(TIBRV_OK, status, tibrvStatus_GetText(status))

        status = tibrvTransport_Destroy(tx)
        self.assertEqual(TIBRV_OK, status, tibrvStatus_GetText(status))

    def test_getset(self):
        status, tx = tibrvTransport_Create(None, None, None)
        self.assertEqual(TIBRV_OK, status, tibrvStatus_GetText(status))
        que = TIBRV_DEFAULT_QUEUE

        # pass self as closure, reset cnt = 0
        self.cnt = 0
        status, monitor = tibrvftMonitor_Create(que, ft_mon, tx, 'MonitorTest', 1.0, self)
        self.assertEqual(TIBRV_OK, status, tibrvStatus_GetText(status))

        status, q = tibrvftMonitor_GetQueue(monitor)
        self.assertEqual(TIBRV_OK, status, tibrvStatus_GetText(status))
        self.assertEqual(que, q)

        status, t = tibrvftMonitor_GetTransport(monitor)
        self.assertEqual(TIBRV_OK, status, tibrvStatus_GetText(status))
        self.assertEqual(tx, t)

        status, sz = tibrvftMonitor_GetGroupName(monitor)
        self.assertEqual(TIBRV_OK, status, tibrvStatus_GetText(status))
        self.assertEqual('MonitorTest', sz)

        status = tibrvftMonitor_Destroy(monitor)
        self.assertEqual(TIBRV_OK, status, tibrvStatus_GetText(status))

        status = tibrvTransport_Destroy(tx)
        self.assertEqual(TIBRV_OK, status, tibrvStatus_GetText(status))

if __name__ == "__main__" :
    unittest.main(verbosity=2)


text:
Implementation of [RE2](https://github.com/google/re2), done natively in Go. Not related to the native implementation. Handles pathological cases with style and does not backtrack.

There are two available matchers: a fast matcher that does not attempt to track submatches, and a slower matcher that does. Internally, sre2 acts only on runes, not bytes; thus, the only missing part of syntax is `\C` (consume a single byte, even in UTF-8 mode).

The code provides a small library with small suite of tests. The package also includes a tiny main test binary, mostly useful for simple tests and for speed comparisons versus the standard regexp module.

This project was previously hosted on [Google Code](https://code.google.com/p/sre2/).

## Usage

```go
// MustParse will panic on compile failure; useful for init()
m := sre2.MustParse(re)
m, err := sre2.Parse(re)

// Simpler matcher just returns true/false
match := m.Match(str)

// Complex matcher returns indexes of found result: match n will be between (n*2,(n*2)+1).
// The 0th match is reserved for the complete found string. On failure, will return nil.
index := m.MatchIndex(str)

// After this example, fooidx will equal: {3, 12, 3, 6, 7, 12}
foo := sre2.MustParse(`(foo+|bar)\w(.*)`)
fooidx := m.MatchIndex("hi fooo test")
```


text:
from drawBot import *
"""
I find dealing with color tuples in drawbot to be cumbersome.
Usually, I'd rather deal with colors as a single object, rather than
tuples or individual r/g/b/a elements that I have to pass individually
to the fill() or stroke() function.

fillColor() and fillStroke() will accept a unified tuple, RGBColor,
or CMYKColor object. That means if you switch from RGB to CMYK,
I don't have to find every instance of fill() in my code.

"""

class RGBColor:
	"""
	A simple RGB color object.
	"""
	def __init__(self, r=0, g=0, b=0, a=1):
		self.r = r
		self.g = g
		self.b = b
		self.a = a
		self.colorMode = 'RGB'

	def asTuple(self):
		return (self.r, self.g, self.b, self.a)

	def setFill(self):
		fill(self.r, self.g, self.b, self.a)

	def setStroke(self):
		stroke(self.r, self.g, self.b, self.a)

class CMYKColor:
	"""
	A simple CMYK color object.
	"""
	def __init__(self, c=0, m=0, y=0, k=0, a=1):
		self.c = c
		self.m = m
		self.y = y
		self.k = k
		self.a = a
		self.colorMode = 'CMYK'

	def asTuple(self):
		return (self.c, self.m, self.y, self.k, self.a)

	def setFill(self):
		fill(self.c, self.m, self.y, self.k, self.a)

	def setStroke(self):
		cmykFill(self.c, self.m, self.y, self.k, self.a)

def fillColor(c, mode='RGB'):
    """
    a helper function that processes rgba or cymka tuples.
    I use this because I hate having to switch back and forth between
    color spaces, and splitting up colors from tuples each time.
    """

    # if we are using a color object (defined above), use the object's fill method
    if hasattr(c, 'colorMode'):
    	c.setFill()

    # if we are passed an integer or float, set it as a simple RGB.
    elif isinstance(c, (int, float)):
    	fill(c, c, c)

    # if we are dealing with a CMYKA tuple, set it
    elif len(c) == 5:
        cmykFill(c[0], c[1], c[2], c[3], c[4])

    # if we have a CMYK tuple and mode is set to CMYK
    elif len(c) and mode.upper() == 'CMYK':
    	cmykFill(c[0], c[1], c[2], c[3])

    # otherwise we will assume that four-item tuples are RGBA
    elif len(c) == 4:
        fill(c[0], c[1], c[2], c[3])

    # last but not least, RGB!
    elif len(c) == 3:
        fill(c[0], c[1], c[2])

def strokeColor(c, mode='RGB'):
    """
    Just like fillColor, but for strokes!
    """

    # if we are using a color object (defined above), use the object's fill method
    if hasattr(c, 'colorMode'):
    	c.setStroke()

    # if we are passed an integer or float, set it as a simple RGB.
    elif isinstance(c, (int, float)):
    	stroke(c, c, c)

    # if we are dealing with a CMYKA tuple, set it
    elif len(c) == 5:
        cmykStroke(c[0], c[1], c[2], c[3], c[4])

    # a four-element tuple can either be RGBA or CMYK.

    # if we have explicitly set the mode to CMYK, do that
    elif len(c) and mode.upper() == 'CMYK':
    	cmykStroke(c[0], c[1], c[2], c[3])

    # otherwise we will assume that four-item tuples are RGBA
    elif len(c) == 4:
        stroke(c[0], c[1], c[2], c[3])

    # last but not least, RGB!
    elif len(c) == 3:
        stroke(c[0], c[1], c[2])


text:
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'puppet_x', 'bobtfish', 'unordered_list_prop.rb'))
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'puppet_x', 'bobtfish', 'read_only_prop.rb'))
Puppet::Type.newtype(:aws_ec2_instance) do
  @doc = "Manage AWS EC2 instances"
  newparam(:name)
  ensurable
  newproperty(:image_id)
  newproperty(:instance_type)
  newproperty(:iam_role)
  newproperty(:region)
  newproperty(:subnet)
  newproperty(:key_name)
  newproperty(:tags)
  newparam(:associate_public_ip_address)
  newproperty(:elastic_ip)
  newproperty(:block_device_mappings, :parent => Puppet_X::Bobtfish::UnorderedValueListProperty)
  newproperty(:security_groups, :parent => Puppet_X::Bobtfish::UnorderedValueListProperty) do
    defaultto []
  end

  autorequire(:aws_subnet) do
    self[:subnet]
  end
  autorequire(:aws_iam_role) do
    self[:iam_role]
  end
  autorequire(:aws_security_group) do
    self[:security_groups]
  end

  newproperty(:public_ip_address, :parent => Puppet_X::Bobtfish::ReadOnlyProperty) do
    desc "Read-only: public ip of machine"
  end
end