text:
import os
import unittest
import requests
import simplejson as json
import yaml

from emuvim.test.api_base_openstack import ApiBaseOpenStack

class testRestApi(ApiBaseOpenStack):
    """
    Tests to check the REST API endpoints of the emulator.
    """

    def setUp(self):
        # create network
        self.createNet(nswitches=3, ndatacenter=2, nhosts=2,
                       ndockers=0, autolinkswitches=True)

        # setup links
        self.net.addLink(self.dc[0], self.h[0])
        self.net.addLink(self.h[1], self.dc[1])
        self.net.addLink(self.dc[0], self.dc[1])

        # start api
        self.startApi()

        # start Mininet network
        self.startNet()

    def testNovaDummy(self):
        print('->>>>>>> test Nova Dummy Class->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        print(" ")

        headers = {'Content-type': 'application/json'}
        test_heatapi_template_create_stack = open(os.path.join(os.path.dirname(
            __file__), "templates/test_heatapi_template_create_stack.yml")).read()
        url = "http://0.0.0.0:18004/v1/tenantabc123/stacks"
        requests.post(url, data=json.dumps(yaml.load(test_heatapi_template_create_stack)),
                      headers=headers)

        print('->>>>>>> test Nova List Versions ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/"
        listapiversionnovaresponse = requests.get(url, headers=headers)
        self.assertEqual(listapiversionnovaresponse.status_code, 200)
        self.assertEqual(json.loads(listapiversionnovaresponse.content)[
                         "versions"][0]["id"], "v2.1")
        self.assertEqual(json.loads(listapiversionnovaresponse.content)[
                         "versions"][0]["status"], "CURRENT")
        self.assertEqual(json.loads(listapiversionnovaresponse.content)[
                         "versions"][0]["version"], "2.38")
        self.assertEqual(json.loads(listapiversionnovaresponse.content)[
                         "versions"][0]["min_version"], "2.1")
        self.assertEqual(json.loads(listapiversionnovaresponse.content)[
                         "versions"][0]["updated"], "2013-07-23T11:33:21Z")
        print(" ")

        print('->>>>>>> test Nova Version Show ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla"
        listapiversion21novaresponse = requests.get(url, headers=headers)
        self.assertEqual(listapiversion21novaresponse.status_code, 200)
        self.assertEqual(json.loads(listapiversion21novaresponse.content)[
                         "version"]["id"], "v2.1")
        self.assertEqual(json.loads(listapiversion21novaresponse.content)[
                         "version"]["status"], "CURRENT")
        self.assertEqual(json.loads(listapiversion21novaresponse.content)[
                         "version"]["version"], "2.38")
        self.assertEqual(json.loads(listapiversion21novaresponse.content)[
                         "version"]["min_version"], "2.1")
        self.assertEqual(json.loads(listapiversion21novaresponse.content)[
                         "version"]["updated"], "2013-07-23T11:33:21Z")
        print(" ")

        print('->>>>>>> test Nova Version List Server APIs ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/servers"
        listserverapisnovaresponse = requests.get(url, headers=headers)
        self.assertEqual(listserverapisnovaresponse.status_code, 200)
        self.assertNotEqual(json.loads(listserverapisnovaresponse.content)[
                            "servers"][0]["name"], "")
        print(" ")

        print('->>>>>>> test Nova Delete Server APIs ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/servers/%s" % (
            json.loads(listserverapisnovaresponse.content)["servers"][0]["id"])
        deleteserverapisnovaresponse = requests.delete(url, headers=headers)
        self.assertEqual(deleteserverapisnovaresponse.status_code, 204)
        print(" ")

        print('->>>>>>> test Nova Delete Non-Existing Server APIs ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/servers/non-existing-ix"
        deleteserverapisnovaresponse = requests.delete(url, headers=headers)
        self.assertEqual(deleteserverapisnovaresponse.status_code, 404)
        print(" ")

        print('->>>>>>> testNovaVersionListServerAPIs_withPortInformation ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/servers/andPorts"
        listserverapisnovaresponse = requests.get(url, headers=headers)
        self.assertEqual(listserverapisnovaresponse.status_code, 200)
        self.assertNotEqual(json.loads(listserverapisnovaresponse.content)[
                            "servers"][0]["name"], "")
        print(" ")

        print('->>>>>>> test Nova List Flavors ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/flavors"
        listflavorsresponse = requests.get(url, headers=headers)
        self.assertEqual(listflavorsresponse.status_code, 200)
        self.assertIn(json.loads(listflavorsresponse.content)["flavors"][0]["name"], [
                      "m1.nano", "m1.tiny", "m1.micro", "m1.small"])
        self.assertIn(json.loads(listflavorsresponse.content)["flavors"][1]["name"], [
                      "m1.nano", "m1.tiny", "m1.micro", "m1.small"])
        self.assertIn(json.loads(listflavorsresponse.content)["flavors"][2]["name"], [
                      "m1.nano", "m1.tiny", "m1.micro", "m1.small"])
        print(" ")

        print('->>>>>>> testNovaAddFlavors ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/flavors"
        addflavorsresponse = requests.post(url,
                                           data='{"flavor":{"name": "testFlavor", "vcpus": "test_vcpus", "ram": 1024, "disk": 10}}',
                                           headers=headers)
        self.assertEqual(addflavorsresponse.status_code, 200)
        self.assertIsNotNone(json.loads(
            addflavorsresponse.content)["flavor"]["id"])
        self.assertIsNotNone(json.loads(addflavorsresponse.content)[
                             "flavor"]["links"][0]['href'])
        print(" ")

        print('->>>>>>> test Nova List Flavors Detail ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/flavors/detail"
        listflavorsdetailresponse = requests.get(url, headers=headers)
        self.assertEqual(listflavorsdetailresponse.status_code, 200)
        self.assertIn(json.loads(listflavorsdetailresponse.content)[
                      "flavors"][0]["name"], ["m1.nano", "m1.tiny", "m1.micro", "m1.small"])
        self.assertIn(json.loads(listflavorsdetailresponse.content)[
                      "flavors"][1]["name"], ["m1.nano", "m1.tiny", "m1.micro", "m1.small"])
        self.assertIn(json.loads(listflavorsdetailresponse.content)[
                      "flavors"][2]["name"], ["m1.nano", "m1.tiny", "m1.micro", "m1.small"])
        print(" ")

        print('->>>>>>> testNovaAddFlavors ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/flavors/detail"
        addflavorsresponse = requests.post(url,
                                           data='{"flavor":{"name": "testFlavor", "vcpus": "test_vcpus", "ram": 1024, "disk": 10}}',
                                           headers=headers)
        self.assertEqual(addflavorsresponse.status_code, 200)
        self.assertIsNotNone(json.loads(
            addflavorsresponse.content)["flavor"]["id"])
        self.assertIsNotNone(json.loads(addflavorsresponse.content)[
                             "flavor"]["links"][0]['href'])
        print(" ")

        print('->>>>>>> test Nova List Flavor By Id ->>>>>>>>>>>>>>>')

        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/flavors/%s" % (
            json.loads(listflavorsdetailresponse.content)["flavors"][0]["name"])
        listflavorsbyidresponse = requests.get(url, headers=headers)
        self.assertEqual(listflavorsbyidresponse.status_code, 200)
        self.assertEqual(json.loads(listflavorsbyidresponse.content)[
                         "flavor"]["id"], json.loads(listflavorsdetailresponse.content)["flavors"][0]["id"])
        print(" ")

        print('->>>>>>> test Nova List Images ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/images"
        listimagesresponse = requests.get(url, headers=headers)
        self.assertEqual(listimagesresponse.status_code, 200)
        print(listimagesresponse.content)
        print(" ")

        print('->>>>>>> test Nova List Images Details ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/images/detail"
        listimagesdetailsresponse = requests.get(url, headers=headers)
        self.assertEqual(listimagesdetailsresponse.status_code, 200)
        self.assertEqual(json.loads(listimagesdetailsresponse.content)[
                         "images"][0]["metadata"]["architecture"], "x86_64")
        print(" ")

        print('->>>>>>> test Nova List Image By Id ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/images/%s" % (
            json.loads(listimagesdetailsresponse.content)["images"][0]["id"])
        listimagebyidresponse = requests.get(url, headers=headers)
        self.assertEqual(listimagebyidresponse.status_code, 200)
        self.assertEqual(json.loads(listimagebyidresponse.content)[
                         "image"]["id"], json.loads(listimagesdetailsresponse.content)["images"][0]["id"])
        print(" ")

        print('->>>>>>> test Nova List Image By Non-Existend Id ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/images/non_existing_id"
        listimagebynonexistingidresponse = requests.get(url, headers=headers)
        self.assertEqual(listimagebynonexistingidresponse.status_code, 404)
        print(" ")

        # find ubuntu id
        for image in json.loads(listimagesresponse.content)["images"]:
            if image["name"] == "ubuntu:trusty":
                ubuntu_image_id = image["id"]

        print('->>>>>>> test Nova Create Server Instance ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/servers"
        data = '{"server": {"name": "X", "flavorRef": "%s", "imageRef":"%s"}}' % (
            json.loads(listflavorsresponse.content)["flavors"][0]["id"], ubuntu_image_id)
        createserverinstance = requests.post(url, data=data, headers=headers)
        self.assertEqual(createserverinstance.status_code, 200)
        self.assertEqual(json.loads(createserverinstance.content)[
                         "server"]["image"]["id"], ubuntu_image_id)
        print(" ")

        print('->>>>>>> test Nova Create Server Instance With Already Existing Name ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/servers"
        data = '{"server": {"name": "X", "flavorRef": "%s", "imageRef":"%s"}}' % (
            json.loads(listflavorsresponse.content)["flavors"][0]["id"], ubuntu_image_id)
        createserverinstance = requests.post(url, data=data, headers=headers)
        self.assertEqual(createserverinstance.status_code, 409)
        print(" ")

        print('->>>>>>> test Nova Version List Server APIs Detailed ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/servers/detail"
        listserverapisdetailedresponse = requests.get(url, headers=headers)
        self.assertEqual(listserverapisdetailedresponse.status_code, 200)
        self.assertEqual(json.loads(listserverapisdetailedresponse.content)[
                         "servers"][0]["status"], "ACTIVE")
        print(" ")

        print('->>>>>>> test Nova Show Server Details ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/servers/%s" % (
            json.loads(listserverapisdetailedresponse.content)["servers"][0]["id"])
        listserverdetailsresponse = requests.get(url, headers=headers)
        self.assertEqual(listserverdetailsresponse.status_code, 200)
        self.assertEqual(json.loads(listserverdetailsresponse.content)[
                         "server"]["flavor"]["links"][0]["rel"], "bookmark")
        print(" ")

        print('->>>>>>> test Nova Show Non-Existing Server Details ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18774/v2.1/id_bla/servers/non_existing_server_id"
        listnonexistingserverdetailsresponse = requests.get(
            url, headers=headers)
        self.assertEqual(listnonexistingserverdetailsresponse.status_code, 404)
        print(" ")

    def testNeutronDummy(self):
        print('->>>>>>> test Neutron Dummy Class->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        print(" ")

        headers = {'Content-type': 'application/json'}
        test_heatapi_template_create_stack = open(os.path.join(os.path.dirname(
            __file__), "templates/test_heatapi_template_create_stack.yml")).read()
        url = "http://0.0.0.0:18004/v1/tenantabc123/stacks"
        requests.post(url, data=json.dumps(
            yaml.load(test_heatapi_template_create_stack)), headers=headers)
        # test_heatapi_keystone_get_token = open("test_heatapi_keystone_get_token.json").read()

        print('->>>>>>> test Neutron List Versions ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/"
        listapiversionstackresponse = requests.get(url, headers=headers)
        self.assertEqual(listapiversionstackresponse.status_code, 200)
        self.assertEqual(json.loads(listapiversionstackresponse.content)[
                         "versions"][0]["id"], "v2.0")
        print(" ")

        print('->>>>>>> test Neutron Show API v2.0 ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0"
        listapiversionv20response = requests.get(url, headers=headers)
        self.assertEqual(listapiversionv20response.status_code, 200)
        self.assertEqual(json.loads(listapiversionv20response.content)[
                         "resources"][0]["name"], "subnet")
        self.assertEqual(json.loads(listapiversionv20response.content)[
                         "resources"][1]["name"], "network")
        self.assertEqual(json.loads(listapiversionv20response.content)[
                         "resources"][2]["name"], "ports")
        print(" ")

        print('->>>>>>> test Neutron List Networks ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/networks"
        listnetworksesponse1 = requests.get(url, headers=headers)
        self.assertEqual(listnetworksesponse1.status_code, 200)
        self.assertEqual(json.loads(listnetworksesponse1.content)[
                         "networks"][0]["status"], "ACTIVE")
        listNetworksId = json.loads(listnetworksesponse1.content)[
            "networks"][0]["id"]
        listNetworksName = json.loads(listnetworksesponse1.content)[
            "networks"][0]["name"]
        listNetworksId2 = json.loads(listnetworksesponse1.content)[
            "networks"][1]["id"]
        print(" ")

        print('->>>>>>> test Neutron List Non-Existing Networks ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/networks?name=non_existent_network_name"
        listnetworksesponse2 = requests.get(url, headers=headers)
        self.assertEqual(listnetworksesponse2.status_code, 404)
        print(" ")

        print('->>>>>>> test Neutron List Networks By Name ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        # tcpdump-vnf:input:net:9df6a98f-9e11-4cb7-b3c0-InAdUnitTest
        url = "http://0.0.0.0:19696/v2.0/networks?name=" + listNetworksName
        listnetworksesponse3 = requests.get(url, headers=headers)
        self.assertEqual(listnetworksesponse3.status_code, 200)
        self.assertEqual(json.loads(listnetworksesponse3.content)[
                         "networks"][0]["name"], listNetworksName)
        print(" ")

        print('->>>>>>> test Neutron List Networks By Id ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        # tcpdump-vnf:input:net:9df6a98f-9e11-4cb7-b3c0-InAdUnitTest
        url = "http://0.0.0.0:19696/v2.0/networks?id=" + listNetworksId
        listnetworksesponse4 = requests.get(url, headers=headers)
        self.assertEqual(listnetworksesponse4.status_code, 200)
        self.assertEqual(json.loads(listnetworksesponse4.content)[
                         "networks"][0]["id"], listNetworksId)
        print(" ")

        print('->>>>>>> test Neutron List Networks By Multiple Ids ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/networks?id=" + listNetworksId + "&id=" + \
            listNetworksId2  # tcpdump-vnf:input:net:9df6a98f-9e11-4cb7-b3c0-InAdUnitTest
        listnetworksesponse5 = requests.get(url, headers=headers)
        self.assertEqual(listnetworksesponse5.status_code, 200)
        self.assertEqual(json.loads(listnetworksesponse5.content)[
                         "networks"][0]["id"], listNetworksId)
        self.assertEqual(json.loads(listnetworksesponse5.content)[
                         "networks"][1]["id"], listNetworksId2)
        print(" ")

        print('->>>>>>> test Neutron Show Network ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/networks/" + listNetworksId
        shownetworksesponse = requests.get(url, headers=headers)
        self.assertEqual(shownetworksesponse.status_code, 200)
        self.assertEqual(json.loads(shownetworksesponse.content)[
                         "network"]["status"], "ACTIVE")
        print(" ")

        print('->>>>>>> test Neutron Show Network Non-ExistendNetwork ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/networks/non_existent_network_id"
        shownetworksesponse2 = requests.get(url, headers=headers)
        self.assertEqual(shownetworksesponse2.status_code, 404)
        print(" ")

        print('->>>>>>> test Neutron Create Network ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/networks"
        createnetworkresponse = requests.post(
            url, data='{"network": {"name": "sample_network","admin_state_up": true}}', headers=headers)
        self.assertEqual(createnetworkresponse.status_code, 201)
        self.assertEqual(json.loads(createnetworkresponse.content)[
                         "network"]["status"], "ACTIVE")
        print(" ")

        print('->>>>>>> test Neutron Create Network With Existing Name ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/networks"
        createnetworkresponsefailure = requests.post(
            url, data='{"network": {"name": "sample_network","admin_state_up": true}}', headers=headers)
        self.assertEqual(createnetworkresponsefailure.status_code, 400)
        print(" ")

        print('->>>>>>> test Neutron Update Network ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/networks/%s" % (
            json.loads(createnetworkresponse.content)["network"]["id"])
        updatenetworkresponse = requests.put(
            url, data='{"network": {"status": "ACTIVE", "admin_state_up":true, "tenant_id":"abcd123", "name": "sample_network_new_name", "shared":false}}', headers=headers)
        self.assertEqual(updatenetworkresponse.status_code, 200)
        self.assertEqual(json.loads(updatenetworkresponse.content)[
                         "network"]["name"], "sample_network_new_name")
        self.assertEqual(json.loads(updatenetworkresponse.content)[
                         "network"]["tenant_id"], "abcd123")
        print(" ")

        print('->>>>>>> test Neutron Update Non-Existing Network ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/networks/non-existing-name123"
        updatenetworkresponse = requests.put(
            url, data='{"network": {"name": "sample_network_new_name"}}', headers=headers)
        self.assertEqual(updatenetworkresponse.status_code, 404)
        print(" ")

        print('->>>>>>> test Neutron List Subnets ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/subnets"
        listsubnetsresponse = requests.get(url, headers=headers)
        listSubnetName = json.loads(listsubnetsresponse.content)[
            "subnets"][0]["name"]
        listSubnetId = json.loads(listsubnetsresponse.content)[
            "subnets"][0]["id"]
        listSubnetId2 = json.loads(listsubnetsresponse.content)[
            "subnets"][1]["id"]
        self.assertEqual(listsubnetsresponse.status_code, 200)
        self.assertNotIn('None', listSubnetName)
        print(" ")

        print('->>>>>>> test Neutron List Subnets By Name ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/subnets?name=" + listSubnetName
        listsubnetByNameresponse = requests.get(url, headers=headers)
        self.assertEqual(listsubnetByNameresponse.status_code, 200)
        self.assertNotIn('None', json.loads(
            listsubnetByNameresponse.content)["subnets"][0]["name"])
        print(" ")

        print('->>>>>>> test Neutron List Subnets By Id ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/subnets?id=" + listSubnetId
        listsubnetsbyidresponse = requests.get(url, headers=headers)
        self.assertEqual(listsubnetsbyidresponse.status_code, 200)
        self.assertNotIn("None", json.loads(
            listsubnetsbyidresponse.content)["subnets"][0]["name"])
        print(" ")

        print('->>>>>>> test Neutron List Subnets By Multiple Id ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/subnets?id=" + \
            listSubnetId + "&id=" + listSubnetId2
        listsubnetsbymultipleidsresponse = requests.get(url, headers=headers)
        self.assertEqual(listsubnetsbymultipleidsresponse.status_code, 200)
        self.assertNotIn("None", json.loads(
            listsubnetsbymultipleidsresponse.content)["subnets"][0]["name"])
        print(" ")

        print('->>>>>>> test Neutron Show Subnet->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/subnets/%s" % (
            json.loads(listsubnetsresponse.content)["subnets"][0]["id"])
        showsubnetsresponse = requests.get(url, headers=headers)
        self.assertEqual(showsubnetsresponse.status_code, 200)
        self.assertNotIn("None", json.loads(
            showsubnetsresponse.content)["subnet"]["name"])
        print(" ")

        print('->>>>>>> test Neutron Show Non-Existing Subnet->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/subnets/non-existing-id123"
        showsubnetsresponse = requests.get(url, headers=headers)
        self.assertEqual(showsubnetsresponse.status_code, 404)
        print(" ")

        print('->>>>>>> test Neutron Create Subnet ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/subnets"
        createsubnetdata = '{"subnet": {"name": "new_subnet", "network_id": "%s","ip_version": 4,"cidr": "10.0.0.1/24"} }' % (
            json.loads(createnetworkresponse.content)["network"]["id"])
        createsubnetresponse = requests.post(
            url, data=createsubnetdata, headers=headers)
        self.assertEqual(createsubnetresponse.status_code, 201)
        self.assertEqual(json.loads(createsubnetresponse.content)[
                         "subnet"]["name"], "new_subnet")
        print(" ")

        print('->>>>>>> test Neutron Create Second Subnet ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/subnets"
        createsubnetdata = '{"subnet": {"name": "new_subnet", "network_id": "%s","ip_version": 4,"cidr": "10.0.0.1/24"} }' % (
            json.loads(createnetworkresponse.content)["network"]["id"])
        createsubnetfailureresponse = requests.post(
            url, data=createsubnetdata, headers=headers)
        self.assertEqual(createsubnetfailureresponse.status_code, 409)
        print(" ")

        print('->>>>>>> test Neutron Update Subnet ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/subnets/%s" % (
            json.loads(createsubnetresponse.content)["subnet"]["id"])
        updatesubnetdata = '{"subnet": {"name": "new_subnet_new_name", "network_id":"some_id", "tenant_id":"new_tenant_id", "allocation_pools":"change_me", "gateway_ip":"192.168.1.120", "ip_version":4, "cidr":"10.0.0.1/24", "id":"some_new_id", "enable_dhcp":true} }'
        updatesubnetresponse = requests.put(
            url, data=updatesubnetdata, headers=headers)
        self.assertEqual(updatesubnetresponse.status_code, 200)
        self.assertEqual(json.loads(updatesubnetresponse.content)[
                         "subnet"]["name"], "new_subnet_new_name")
        print(" ")

        print('->>>>>>> test Neutron Update Non-Existing Subnet ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/subnets/non-existing-subnet-12345"
        updatenonexistingsubnetdata = '{"subnet": {"name": "new_subnet_new_name"} }'
        updatenonexistingsubnetresponse = requests.put(
            url, data=updatenonexistingsubnetdata, headers=headers)
        self.assertEqual(updatenonexistingsubnetresponse.status_code, 404)
        print(" ")

        print('->>>>>>> test Neutron List Ports ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/ports"
        listportsesponse = requests.get(url, headers=headers)
        self.assertEqual(listportsesponse.status_code, 200)
        self.assertEqual(json.loads(listportsesponse.content)
                         ["ports"][0]["status"], "ACTIVE")
        listPortsName = json.loads(listportsesponse.content)[
            "ports"][0]["name"]
        listPortsId1 = json.loads(listportsesponse.content)["ports"][0]["id"]
        listPortsId2 = json.loads(listportsesponse.content)["ports"][1]["id"]
        print(" ")

        print('->>>>>>> test Neutron List Ports By Name ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/ports?name=" + listPortsName
        listportsbynameesponse = requests.get(url, headers=headers)
        self.assertEqual(listportsbynameesponse.status_code, 200)
        self.assertEqual(json.loads(listportsbynameesponse.content)[
                         "ports"][0]["name"], listPortsName)
        print(" ")

        print('->>>>>>> test Neutron List Ports By Id ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/ports?id=" + listPortsId1
        listportsbyidesponse = requests.get(url, headers=headers)
        self.assertEqual(listportsbyidesponse.status_code, 200)
        self.assertEqual(json.loads(listportsbyidesponse.content)[
                         "ports"][0]["id"], listPortsId1)
        print(" ")

        print('->>>>>>> test Neutron List Ports By Multiple Ids ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/ports?id=" + \
            listPortsId1 + "&id=" + listPortsId2
        listportsbymultipleidsesponse = requests.get(url, headers=headers)
        self.assertEqual(listportsbymultipleidsesponse.status_code, 200)
        self.assertEqual(json.loads(listportsbymultipleidsesponse.content)[
                         "ports"][0]["id"], listPortsId1)
        print(" ")

        print('->>>>>>> test Neutron List Ports By Device ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        server_url = "http://0.0.0.0:18774/v2.1/id_bla/servers/firewall1:9df6a98f-9e11-4cb7-b3c0-InAdUnitTest"
        server_response = requests.get(server_url, headers=headers)
        firewall1_server = json.loads(server_response.content)["server"]
        device_id = firewall1_server["id"]
        url = "http://0.0.0.0:19696/v2.0/ports?device_id=%s" % device_id
        list_ports_by_device_id_response = requests.get(url, headers=headers)
        self.assertEqual(list_ports_by_device_id_response.status_code, 200)
        list_ports_by_device_id_ports = json.loads(list_ports_by_device_id_response.content)["ports"]

        self.assertTrue(any(list_ports_by_device_id_ports), "Expected at least one port for device")
        for port in list_ports_by_device_id_ports:
            self.assertTrue(port["name"].startswith("firewall1:"), "Expected all ports to belong to firewall1")
        print(" ")

        print('->>>>>>> test Neutron List Non-Existing Ports ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/ports?id=non-existing-port-id"
        listportsbynonexistingidsesponse = requests.get(url, headers=headers)
        self.assertEqual(listportsbynonexistingidsesponse.status_code, 404)
        print(" ")

        print('->>>>>>> test Neutron Show Port ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/ports/%s" % (
            json.loads(listportsesponse.content)["ports"][0]["id"])
        showportresponse = requests.get(url, headers=headers)
        self.assertEqual(showportresponse.status_code, 200)
        self.assertEqual(json.loads(showportresponse.content)
                         ["port"]["status"], "ACTIVE")
        print(" ")

        print('->>>>>>> test Neutron Show Non-Existing Port ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/ports/non-existing-portid123"
        shownonexistingportresponse = requests.get(url, headers=headers)
        self.assertEqual(shownonexistingportresponse.status_code, 404)
        print(" ")

        print('->>>>>>> test Neutron Create Port In Non-Existing Network ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/ports"
        createnonexistingportdata = '{"port": {"name": "new_port", "network_id": "non-existing-id"} }'
        createnonexistingnetworkportresponse = requests.post(
            url, data=createnonexistingportdata, headers=headers)
        self.assertEqual(createnonexistingnetworkportresponse.status_code, 404)
        print(" ")

        print('->>>>>>> test Neutron Create Port ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/ports"
        createportdata = '{"port": {"name": "new_port", "network_id": "%s", "admin_state_up":true, "device_id":"device_id123", "device_owner":"device_owner123", "fixed_ips":"change_me","id":"new_id1234", "mac_address":"12:34:56:78:90", "status":"change_me", "tenant_id":"tenant_id123"} }' % (json.loads(createnetworkresponse.content)[
                                                                                "network"]["id"])
        createportresponse = requests.post(
            url, data=createportdata, headers=headers)
        self.assertEqual(createportresponse.status_code, 201)
        print(createportresponse.content)
        createport = json.loads(createportresponse.content)["port"]
        self.assertEqual(createport["name"], "new_port")
        print(" ")

        print('->>>>>>> test Neutron Create Port With Existing Name ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/ports"
        network_id = json.loads(createnetworkresponse.content)["network"]["id"]
        createportwithexistingnamedata = '{"port": {"name": "duplicate_port_name", "network_id": "%s"} }' % network_id
        createportwithexistingnameresponse1 = requests.post(
            url, data=createportwithexistingnamedata, headers=headers)
        createportwithexistingnameresponse2 = requests.post(
            url, data=createportwithexistingnamedata, headers=headers)
        createportwithexistingname1 = json.loads(createportwithexistingnameresponse1.content)["port"]
        createportwithexistingname2 = json.loads(createportwithexistingnameresponse2.content)["port"]
        self.assertEqual(createportwithexistingnameresponse1.status_code, 201)
        self.assertEqual(createportwithexistingnameresponse2.status_code, 201)
        self.assertEqual(createportwithexistingname1["name"], "duplicate_port_name")
        self.assertEqual(createportwithexistingname2["name"], "duplicate_port_name")
        self.assertNotEqual(createportwithexistingname1["id"], createportwithexistingname2["id"], "Duplicate port should have different id")
        print(" ")

        print('->>>>>>> test Neutron Create Port Without Name ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/ports"
        createportdatawithoutname = '{"port": {"network_id": "%s"} }' % (
            json.loads(createnetworkresponse.content)["network"]["id"])
        createportwithoutnameresponse = requests.post(
            url, data=createportdatawithoutname, headers=headers)
        self.assertEqual(createportwithoutnameresponse.status_code, 201)
        self.assertIn("port:cp", json.loads(
            createportwithoutnameresponse.content)["port"]["name"])
        print(" ")

        print('->>>>>>> test Neutron Update Port ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        print(json.loads(createportresponse.content)["port"]["name"])
        url = "http://0.0.0.0:19696/v2.0/ports/%s" % (
            json.loads(createportresponse.content)["port"]["name"])
        updateportdata = '{"port": {"name": "new_port_new_name", "admin_state_up":true, "device_id":"device_id123", "device_owner":"device_owner123", "fixed_ips":"change_me","mac_address":"12:34:56:78:90", "status":"change_me", "tenant_id":"tenant_id123", "network_id":"network_id123"} }'
        updateportresponse = requests.put(
            url, data=updateportdata, headers=headers)
        self.assertEqual(updateportresponse.status_code, 200)
        self.assertEqual(json.loads(updateportresponse.content)[
                         "port"]["name"], "new_port_new_name")
        print(" ")

        print('->>>>>>> test Neutron Update Non-Existing Port ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/ports/non-existing-port-ip"
        updatenonexistingportdata = '{"port": {"name": "new_port_new_name"} }'
        updatenonexistingportresponse = requests.put(
            url, data=updatenonexistingportdata, headers=headers)
        self.assertEqual(updatenonexistingportresponse.status_code, 404)
        print(" ")

        print('->>>>>>> test Neutron Delete Port ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        righturl = "http://0.0.0.0:19696/v2.0/ports/%s" % (
            json.loads(createportresponse.content)["port"]["id"])
        deleterightportresponse = requests.delete(righturl, headers=headers)
        self.assertEqual(deleterightportresponse.status_code, 204)
        print(" ")

        print('->>>>>>> test Neutron Delete Non-Existing Port ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        wrongurl = "http://0.0.0.0:19696/v2.0/ports/unknownid"
        deletewrongportresponse = requests.delete(wrongurl, headers=headers)
        self.assertEqual(deletewrongportresponse.status_code, 404)
        print(" ")

        print('->>>>>>> test Neutron Delete Subnet ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        wrongurl = "http://0.0.0.0:19696/v2.0/subnets/unknownid"
        righturl = "http://0.0.0.0:19696/v2.0/subnets/%s" % (
            json.loads(updatesubnetresponse.content)["subnet"]["id"])
        deletewrongsubnetresponse = requests.delete(wrongurl, headers=headers)
        deleterightsubnetresponse = requests.delete(righturl, headers=headers)
        self.assertEqual(deletewrongsubnetresponse.status_code, 404)
        self.assertEqual(deleterightsubnetresponse.status_code, 204)
        print(" ")

        print('->>>>>>> test Neutron Delete Network ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        righturl = "http://0.0.0.0:19696/v2.0/networks/%s" % (
            json.loads(createnetworkresponse.content)["network"]["id"])
        deleterightnetworkresponse = requests.delete(righturl, headers=headers)
        self.assertEqual(deleterightnetworkresponse.status_code, 204)
        print(" ")

        print('->>>>>>> test Neutron Delete Non-Existing Network ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        wrongurl = "http://0.0.0.0:19696/v2.0/networks/unknownid"
        deletewrongnetworkresponse = requests.delete(wrongurl, headers=headers)
        self.assertEqual(deletewrongnetworkresponse.status_code, 404)
        print(" ")

    def testKeystomeDummy(self):
        print('->>>>>>> test Keystone Dummy Class->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        print(" ")

        headers = {'Content-type': 'application/json'}
        test_heatapi_keystone_get_token = open(os.path.join(os.path.dirname(
            __file__), "templates/test_heatapi_keystone_get_token.yml")).read()

        print('->>>>>>> test Keystone List Versions ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:15000/"
        listapiversionstackresponse = requests.get(url, headers=headers)
        self.assertEqual(listapiversionstackresponse.status_code, 200)
        self.assertEqual(json.loads(listapiversionstackresponse.content)[
                         "versions"]["values"][0]["id"], "v2.0")
        print(" ")

        print('->>>>>>> test Keystone Show ApiV2 ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:15000/v2.0"
        showapiversionstackresponse = requests.get(url, headers=headers)
        self.assertEqual(showapiversionstackresponse.status_code, 200)
        self.assertEqual(json.loads(showapiversionstackresponse.content)[
                         "version"]["id"], "v2.0")
        print(" ")

        print('->>>>>>> test Keystone Get Token ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:15000/v2.0/tokens"
        gettokenstackresponse = requests.post(url, data=json.dumps(
            yaml.load(test_heatapi_keystone_get_token)), headers=headers)
        self.assertEqual(gettokenstackresponse.status_code, 200)
        self.assertEqual(json.loads(gettokenstackresponse.content)[
                         "access"]["user"]["name"], "tenantName")
        print(" ")

    def testHeatDummy(self):
        print('->>>>>>> test Heat Dummy Class->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        print(" ")

        headers = {'Content-type': 'application/json'}
        test_heatapi_template_create_stack = open(os.path.join(os.path.dirname(
            __file__), "templates/test_heatapi_template_create_stack.yml")).read()
        test_heatapi_template_update_stack = open(os.path.join(os.path.dirname(
            __file__), "templates/test_heatapi_template_update_stack.yml")).read()

        print('->>>>>>> test Heat List API Versions Stack ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18004/"
        listapiversionstackresponse = requests.get(url, headers=headers)
        self.assertEqual(listapiversionstackresponse.status_code, 200)
        self.assertEqual(json.loads(listapiversionstackresponse.content)[
                         "versions"][0]["id"], "v1.0")
        print(" ")

        print('->>>>>>> test Create Stack ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18004/v1/tenantabc123/stacks"
        createstackresponse = requests.post(url, data=json.dumps(
            yaml.load(test_heatapi_template_create_stack)), headers=headers)
        self.assertEqual(createstackresponse.status_code, 201)
        self.assertNotEqual(json.loads(
            createstackresponse.content)["stack"]["id"], "")
        print(" ")

        print('->>>>>>> test Create Stack With Existing Name ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18004/v1/tenantabc123/stacks"
        createstackwithexistingnameresponse = requests.post(
            url, data='{"stack_name" : "s1"}', headers=headers)
        self.assertEqual(createstackwithexistingnameresponse.status_code, 409)
        print(" ")

        print('->>>>>>> test Create Stack With Unsupported Version ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18004/v1/tenantabc123/stacks"
        createstackwitheunsupportedversionresponse = requests.post(
            url, data='{"stack_name" : "stackname123", "template" : {"heat_template_version": "2015-04-29"}}', headers=headers)
        self.assertEqual(
            createstackwitheunsupportedversionresponse.status_code, 400)
        print(" ")

        print('->>>>>>> test List Stack ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18004/v1/tenantabc123/stacks"
        liststackresponse = requests.get(url, headers=headers)
        self.assertEqual(liststackresponse.status_code, 200)
        self.assertEqual(json.loads(liststackresponse.content)[
                         "stacks"][0]["stack_status"], "CREATE_COMPLETE")
        print(" ")

        print('->>>>>>> test Show Stack ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18004/v1/tenantabc123showStack/stacks/%s" % json.loads(
            createstackresponse.content)['stack']['id']
        liststackdetailsresponse = requests.get(url, headers=headers)
        self.assertEqual(liststackdetailsresponse.status_code, 200)
        self.assertEqual(json.loads(liststackdetailsresponse.content)[
                         "stack"]["stack_status"], "CREATE_COMPLETE")
        print(" ")

        print('->>>>>>> test Show Non-Exisitng Stack ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18004/v1/tenantabc123showStack/stacks/non_exisitng_id123"
        listnonexistingstackdetailsresponse = requests.get(
            url, headers=headers)
        self.assertEqual(listnonexistingstackdetailsresponse.status_code, 404)
        print(" ")

        print('->>>>>>> test Update Stack ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18004/v1/tenantabc123updateStack/stacks/%s" % json.loads(
            createstackresponse.content)['stack']['id']
        updatestackresponse = requests.put(url, data=json.dumps(yaml.load(test_heatapi_template_update_stack)),
                                           headers=headers)
        self.assertEqual(updatestackresponse.status_code, 202)
        liststackdetailsresponse = requests.get(url, headers=headers)
        self.assertEqual(json.loads(liststackdetailsresponse.content)[
                         "stack"]["stack_status"], "UPDATE_COMPLETE")
        print(" ")

        print('->>>>>>> test Update Non-Existing Stack ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18004/v1/tenantabc123updateStack/stacks/non_existing_id_1234"
        updatenonexistingstackresponse = requests.put(
            url, data={"non": "sense"}, headers=headers)
        self.assertEqual(updatenonexistingstackresponse.status_code, 404)
        print(" ")

        print('->>>>>>> test Delete Stack ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:18004/v1/tenantabc123showStack/stacks/%s" % \
              json.loads(createstackresponse.content)['stack']['id']
        deletestackdetailsresponse = requests.delete(url, headers=headers)
        self.assertEqual(deletestackdetailsresponse.status_code, 204)
        print(" ")

    def testNeutronSFC(self):
        """
        Tests the Neutron Service Function Chaining implementation. As Some functions build up on others, a
        complete environment is created here:

        Ports:              p1, p2, p3, p4
        Port Pairs:         pp1(p1, p2), pp2(p3, p4)
        Port Pair Groups:   ppg1(pp1, pp2)
        Flow Classifiers:   fc1
        Port Chain:         pc1(ppg1, fc1)
        """

        headers = {'Content-type': 'application/json'}

        print('->>>>>>> Create ports p1 - p6 ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        # Get network id
        network_resp = requests.get(
            "http://0.0.0.0:19696/v2.0/networks?name=default", headers=headers)
        self.assertEqual(network_resp.status_code, 200)
        network_id = json.loads(network_resp.content)["networks"][0]["id"]

        port_responses = map(lambda name: requests.post("http://0.0.0.0:19696/v2.0/ports",
                                                        data='{"port": {"name": "%s", "network_id": "%s"}}' %
                                                             (name, network_id),
                                                        headers=headers),
                             ["p1", "p2", "p3", "p4", "p5", "p6"])

        for port in port_responses:
            self.assertEqual(port.status_code, 201)

        port_ids = map(lambda response: json.loads(response.content)["port"]["id"], port_responses)

        listflavorsresponse = requests.get("http://0.0.0.0:18774/v2.1/id_bla/flavors", headers=headers)
        self.assertEqual(listflavorsresponse.status_code, 200)
        flavors = json.loads(listflavorsresponse.content)["flavors"]
        m1_tiny_flavor = filter(lambda flavor: flavor["name"] == "m1.tiny", flavors)[0]

        listimagesdetailsresponse = requests.get("http://0.0.0.0:18774/v2.1/id_bla/images/detail", headers=headers)
        self.assertEqual(listimagesdetailsresponse.status_code, 200)
        images = json.loads(listimagesdetailsresponse.content)["images"]
        ubuntu_image = filter(lambda image: image["name"] == "ubuntu:trusty", images)[0]

        server_url = "http://0.0.0.0:18774/v2.1/id_bla/servers"
        server_template = \
            '{"server": {' \
            '"name": "%s",' \
            '"networks": [{"port": "%s"}, {"port": "%s"}],' \
            '"flavorRef": "%s",' \
            '"imageRef": "%s"' \
            '}}'
        server_responses = map(lambda spec: (
            requests.post(server_url,
                          data=server_template % (
                              spec["name"],
                              spec["ingress"],
                              spec["egress"],
                              m1_tiny_flavor["id"],
                              ubuntu_image["id"]
                          ),
                          headers=headers)
        ), [
            {"name": "s1", "ingress": "p1", "egress": "p2"},
            {"name": "s2", "ingress": "p3", "egress": "p4"},
            {"name": "s3", "ingress": "p5", "egress": "p6"},
        ])
        for response in server_responses:
            self.assertEqual(response.status_code, 200)

        print('->>>>>>> test Neutron SFC Port Pair Create ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_pairs"
        pp1_resp = requests.post(url, data='{"port_pair": {"name": "pp1", "ingress": "%s", "egress": "%s"}}' % (
            port_ids[0], port_ids[1]), headers=headers)
        self.assertEqual(pp1_resp.status_code, 201)
        pp2_resp = requests.post(url, data='{"port_pair": {"name": "pp2", "ingress": "%s", "egress": "%s"}}' % (
            port_ids[2], port_ids[3]), headers=headers)
        self.assertEqual(pp2_resp.status_code, 201)
        pp3_resp = requests.post(url, data='{"port_pair": {"name": "pp3", "ingress": "%s", "egress": "%s"}}' % (
            port_ids[4], port_ids[5]), headers=headers)
        self.assertEqual(pp3_resp.status_code, 201)

        pp1_id = json.loads(pp1_resp.content)["port_pair"]["id"]
        pp2_id = json.loads(pp2_resp.content)["port_pair"]["id"]
        pp3_id = json.loads(pp3_resp.content)["port_pair"]["id"]

        print('->>>>>>> test Neutron SFC Port Pair Update ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_pairs/%s" % pp3_id
        pp3_update_resp = requests.put(
            url, data='{"port_pair": {"description": "port_pair_update"}}', headers=headers)
        self.assertEqual(pp3_update_resp.status_code, 200)
        self.assertEqual(json.loads(pp3_update_resp.content)[
                         "port_pair"]["description"], "port_pair_update")

        print('->>>>>>> test Neutron SFC Port Pair Delete ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_pairs/%s" % pp3_id
        pp3_delete_resp = requests.delete(url, headers=headers)
        self.assertEqual(pp3_delete_resp.status_code, 204)

        print('->>>>>>> test Neutron SFC Port Pair List ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_pairs"
        pp_list_resp = requests.get(url, headers=headers)
        self.assertEqual(pp_list_resp.status_code, 200)
        pp_list = json.loads(pp_list_resp.content)["port_pairs"]
        # only pp1 and pp2 should be left
        self.assertEqual(len(pp_list), 2)

        print('->>>>>>> test Neutron SFC Port Pair List filtered by id ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_pairs?id=%s" % pp_list[0]["id"]
        pp_list_filtered_by_id_resp = requests.get(url, headers=headers)
        pp_list_filtered_by_id = json.loads(pp_list_filtered_by_id_resp.content)["port_pairs"]
        self.assertEqual(pp_list_filtered_by_id_resp.status_code, 200)
        self.assertEqual(len(pp_list_filtered_by_id), 1)
        self.assertEqual(pp_list_filtered_by_id[0], pp_list[0])

        print('->>>>>>> test Neutron SFC Port Pair Show ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_pairs/%s" % pp2_id
        pp2_show_resp = requests.get(url, headers=headers)
        self.assertEqual(pp2_show_resp.status_code, 200)
        self.assertEqual(json.loads(pp2_show_resp.content)
                         ["port_pair"]["name"], "pp2")

        print('->>>>>>> test Neutron SFC Port Pair Group Create ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_pair_groups"
        ppg1_resp = requests.post(
            url, data='{"port_pair_group": {"name": "ppg1", "port_pairs": ["%s"]}}' % (pp1_id), headers=headers)
        self.assertEqual(ppg1_resp.status_code, 201)
        ppg2_resp = requests.post(
            url, data='{"port_pair_group": {"name": "ppg2", "port_pairs": ["%s"]}}' % (pp2_id), headers=headers)
        self.assertEqual(ppg2_resp.status_code, 201)
        ppg3_resp = requests.post(
            url, data='{"port_pair_group": {"name": "ppg3", "port_pairs": ["%s"]}}' % (pp2_id), headers=headers)
        self.assertEqual(ppg3_resp.status_code, 201)

        ppg1_id = json.loads(ppg1_resp.content)["port_pair_group"]["id"]
        ppg2_id = json.loads(ppg2_resp.content)["port_pair_group"]["id"]
        ppg3_id = json.loads(ppg3_resp.content)["port_pair_group"]["id"]

        print('->>>>>>> test Neutron SFC Port Pair Group Update ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_pair_groups/%s" % ppg3_id
        ppg3_update_resp = requests.put(
            url, data='{"port_pair_group": {"description": "port_pair_group_update"}}', headers=headers)
        self.assertEqual(ppg3_update_resp.status_code, 200)
        self.assertEqual(json.loads(ppg3_update_resp.content)[
                         "port_pair_group"]["description"], "port_pair_group_update")

        print('->>>>>>> test Neutron SFC Port Pair Group Delete ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_pair_groups/%s" % ppg3_id
        ppg3_delete_resp = requests.delete(url, headers=headers)
        self.assertEqual(ppg3_delete_resp.status_code, 204)

        print('->>>>>>> test Neutron SFC Port Pair Group List ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_pair_groups"
        ppg_list_resp = requests.get(url, headers=headers)
        self.assertEqual(ppg_list_resp.status_code, 200)
        # only ppg1 and ppg2 should be left
        self.assertEqual(
            len(json.loads(ppg_list_resp.content)["port_pair_groups"]), 2)

        print('->>>>>>> test Neutron SFC Port Pair Group Show ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_pair_groups/%s" % ppg2_id
        ppg2_show_resp = requests.get(url, headers=headers)
        self.assertEqual(ppg2_show_resp.status_code, 200)
        self.assertEqual(json.loads(ppg2_show_resp.content)[
                         "port_pair_group"]["name"], "ppg2")

        print('->>>>>>> test Neutron SFC Flow Classifier Create ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/flow_classifiers"
        fc1_resp = requests.post(
            url, data='{"flow_classifier": {"name": "fc1", "logical_source_port": "p1", "source_port_range_min": 22, "source_port_range_max": 4000}}', headers=headers)
        self.assertEqual(fc1_resp.status_code, 201)
        fc2_resp = requests.post(
            url, data='{"flow_classifier": {"name": "fc2", "logical_source_port": "p2", "source_port_range_min": 22, "source_port_range_max": 4000}}', headers=headers)
        self.assertEqual(fc2_resp.status_code, 201)

        fc1_id = json.loads(fc1_resp.content)["flow_classifier"]["id"]
        fc2_id = json.loads(fc2_resp.content)["flow_classifier"]["id"]

        print('->>>>>>> test Neutron SFC Flow Classifier Update ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/flow_classifiers/%s" % fc2_id
        fc2_update_resp = requests.put(
            url, data='{"flow_classifier": {"description": "flow_classifier_update"}}', headers=headers)
        self.assertEqual(fc2_update_resp.status_code, 200)
        self.assertEqual(json.loads(fc2_update_resp.content)[
                         "flow_classifier"]["description"], "flow_classifier_update")

        print('->>>>>>> test Neutron SFC Flow Classifier Delete ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/flow_classifiers/%s" % fc2_id
        fc2_delete_resp = requests.delete(url, headers=headers)
        self.assertEqual(fc2_delete_resp.status_code, 204)

        print('->>>>>>> test Neutron SFC Flow Classifier List ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/flow_classifiers"
        fc_list_resp = requests.get(url, headers=headers)
        self.assertEqual(fc_list_resp.status_code, 200)
        self.assertEqual(len(json.loads(fc_list_resp.content)
                             ["flow_classifiers"]), 1)  # only fc1

        print('->>>>>>> test Neutron SFC Flow Classifier Show ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/flow_classifiers/%s" % fc1_id
        fc1_show_resp = requests.get(url, headers=headers)
        self.assertEqual(fc1_show_resp.status_code, 200)
        self.assertEqual(json.loads(fc1_show_resp.content)[
                         "flow_classifier"]["name"], "fc1")

        print('->>>>>>> test Neutron SFC Port Chain Create ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_chains"
        pc1_resp = requests.post(url, data='{"port_chain": {"name": "pc1", "port_pair_groups": ["%s"], "flow_classifiers": ["%s"]}}' % (
            ppg1_id, fc1_id), headers=headers)
        self.assertEqual(pc1_resp.status_code, 201)
        pc2_resp = requests.post(url, data='{"port_chain": {"name": "pc2", "port_pair_groups": ["%s"], "flow_classifiers": ["%s"]}}' % (
            ppg1_id, fc1_id), headers=headers)
        self.assertEqual(pc2_resp.status_code, 201)

        pc1_id = json.loads(pc1_resp.content)["port_chain"]["id"]
        pc2_id = json.loads(pc2_resp.content)["port_chain"]["id"]

        print('->>>>>>> test Neutron SFC Port Chain Update ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_chains/%s" % pc2_id
        pc2_update_resp = requests.put(
            url, data='{"port_chain": {"description": "port_chain_update"}}', headers=headers)
        self.assertEqual(pc2_update_resp.status_code, 200)
        self.assertEqual(json.loads(pc2_update_resp.content)[
                         "port_chain"]["description"], "port_chain_update")

        print('->>>>>>> test Neutron SFC Port Chain Delete ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_chains/%s" % pc2_id
        pc2_delete_resp = requests.delete(url, headers=headers)
        self.assertEqual(pc2_delete_resp.status_code, 204)

        print('->>>>>>> test Neutron SFC Port Chain List ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_chains"
        pc_list_resp = requests.get(url, headers=headers)
        self.assertEqual(pc_list_resp.status_code, 200)
        self.assertEqual(len(json.loads(pc_list_resp.content)
                             ["port_chains"]), 1)  # only pc1

        print('->>>>>>> test Neutron SFC Port Chain Show ->>>>>>>>>>>>>>>')
        print('->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
        url = "http://0.0.0.0:19696/v2.0/sfc/port_chains/%s" % pc1_id
        pc1_show_resp = requests.get(url, headers=headers)
        self.assertEqual(pc1_show_resp.status_code, 200)
        self.assertEqual(json.loads(pc1_show_resp.content)
                         ["port_chain"]["name"], "pc1")

if __name__ == '__main__':
    unittest.main()


text:
var Jimp = require('jimp'),
    StoreService = require('./StoreService');

var CARD_SIZE_LIST = [
  {index: "ss", size: {w: Jimp.AUTO, h: 61}},
  {index: "s", size: {w: 125, h: Jimp.AUTO}},
  {index: "m", size: {w: 250, h: Jimp.AUTO}},
  {index: "l", size: null}
]

var AVATAR_SIZE_LIST = [
  {index: "s", size: {w: 100, h: 100}},
  {index: "m", size: {w: 300, h: 300}}
]

/**
 * Get card image as binary data
 * @param {number} id Card id. It can be a string
 * @param {string} size Image size. Currently support "l", "m" ,"s" ,"ss"
 * @return {Promise<Buffer>} Binary data of the image
 */
exports.getCardImage = function(id, size) {
  return StoreService.getObject("9card-images-" + size, id + ".png");
}

/**
 * Create card image for each size. It can be used for update.
 * @param {number} id Card id. It can be a string
 * @param {string} path File path
 * @return {Promise<any[]>} Array of the response bodies from object store service
 */
exports.createCardImage = function(id, path) {
  return Jimp.read(path).then(function(originalImage) {
    var promises = [];
    CARD_SIZE_LIST.forEach(function(item) {
      var image = item.size ? originalImage.clone().resize(item.size.w, item.size.h) : originalImage;
      var promise = new Promise(function(resolve, reject) {
        image.getBuffer(Jimp.MIME_PNG, function(err, buf) {
          if (err) reject(err);
          else resolve(buf);
        });
      }).then(function(buf) {
        return StoreService.createObject("9card-images-" + item.index, id + ".png", buf, Jimp.MIME_PNG);
      });
      promises.push(promise);
    });
    return Promise.all(promises);
  });
}

/**
 * Update card image for each size.
 * @param {number} id Card id. It can be a string
 * @param {string} path File path
 * @return {Promise<any[]>} Array of the response bodies from object store service
 */
exports.updateCardImage = function(id, path) {
  return Jimp.read(path).then(function(originalImage) {
    var promises = [];
    CARD_SIZE_LIST.forEach(function(item) {
      var image = item.size ? originalImage.clone().resize(item.size.w, item.size.h) : originalImage;
      var promise = new Promise(function(resolve, reject) {
        image.getBuffer(Jimp.MIME_PNG, function(err, buf) {
          if (err) reject(err);
          else resolve(buf);
        });
      }).then(function(buf) {
        return StoreService.updateObject("9card-images-" + item.index, id + ".png", buf);
      });
      promises.push(promise);
    });
    return Promise.all(promises);
  });
}

/**
 * Delete card image for each size.
 * @param {number} id Card id. It can be a string
 * @return {Promise<any[]>} Array of response bodies from object store service
 */
exports.deleteCardImage = function(id) {
  var promises = [];
  CARD_SIZE_LIST.forEach(function(size) {
    promises.push(StoreService.deleteObject("9card-images-" + size.index, id + ".png"));
  });
  return Promise.all(promises);
}

/**
 * Get user avatar as binary data
 * @param {string} id User id
 * @param {string} size Image size. Currently supports "m" and "s"
 * @return {Promise<Buffer>} Binary data of the image
 */
exports.getAvatarImage = function(id, size) {
  return StoreService.getObject(`9card-avatars-${size}`, `${id}.png`);
}

/**
 * Create user avatar for each size. It also can be used for update.
 * @param {string} id User id
 * @param {string} path File path
 * @return {Promise<any[]>} Array of the response bodies from object store service
 */
exports.createAvatarImage = function(id, path) {
  return Jimp.read(path).then(function(originalImage) {
    var promises = [];
    AVATAR_SIZE_LIST.forEach(function(item) {
      var image = item.size ? originalImage.clone().resize(item.size.w, item.size.h) : originalImage;
      var promise = new Promise(function(resolve, reject) {
        image.getBuffer(Jimp.MIME_PNG, function(err, buf) {
          if (err) reject(err);
          else resolve(buf);
        });
      }).then(function(buf) {
        return StoreService.createObject(`9card-avatars-${size}`, `${id}.png`, buf, Jimp.MIME_PNG);
      });
      promises.push(promise);
    });
    return Promise.all(promises);
  });
}

/**
 * Update user avatar for each size.
 * @param {string} id User id
 * @param {string} path File path
 * @return {Promise<any[]>} Array of the response bodies from object store service
 */
exports.updateAvatarImage = function(id, path) {
  return Jimp.read(path).then(function(originalImage) {
    var promises = [];
    AVATAR_SIZE_LIST.forEach(function(item) {
      var image = item.size ? originalImage.clone().resize(item.size.w, item.size.h) : originalImage;
      var promise = new Promise(function(resolve, reject) {
        image.getBuffer(Jimp.MIME_PNG, function(err, buf) {
          if (err) reject(err);
          else resolve(buf);
        });
      }).then(function(buf) {
        return StoreService.updateObject(`9card-avatars-${size}`, `${id}.png`, buf);
      });
      promises.push(promise);
    });
    return Promise.all(promises);
  });
}

/**
 * Delete user avatar for each size.
 * @param {string} id User id
 * @return {Promise<any[]>} Array of response bodies from object store service
 */
exports.deleteAvatarImage = function(id) {
  var promises = [];
  AVATAR_SIZE_LIST.forEach(function(size) {
    promises.push(StoreService.deleteObject(`9card-avatars-${size}`, `${id}.png`));
  });
  return Promise.all(promises);
}

redpajama_set_name: RedPajamaGithub


text:
author: jpliew
title: "Arduino Exercises"
layout: guide
post-card-type: image
card-image: common_led.svg
lang: en
chapter : 4
description: LEDs (light-emitting diodes) are small and energy efficient lights that are used in many applications. In this Arduino blinking LED exercise, we will start with one of the easiest LED blinking circuit and learn how to blink an LED using the (STMB).
contents:
- Exercise 1 - Blinking LED
parts:
 RES_220R: 1
 LED_RED: 1
 JUMPER_WIRE: 2
schematic:
 exercise_01_schematic.svg
breadboard:
 exercise_01_breadboard.svg
---
## Exercise 1 - Blinking LED

{% include schematic.html %}LEDs (light-emitting diodes) are small and energy efficient lights that are used in many applications. In this exercise we will start with one of the easiest LED blinking circuit.

In this excercise, PIN3 is used to drive the LED on and off. The 220Ω resistor act as a current limiter to limit the current flowing through the LED. Depending on the specifications, LEDs need about 8mA to 20mA of current to light up.

{% include parts.html  %}

1. Connect a JUMPER WIRE to GND and 33J.
2. Connect a JUMPER WIRE to PIN3 and 38J.
3. Connect a 220Ω RESISTOR to 34H and 38H.
4. Connect the anode (longer) pin of the RED LED to 34G and cathode (shorter) pin to 33G.
{: .connections }

{% include breadboard.html %}

### Write and Upload the Blinking LED Sketch

In order to execute the sketch for this exercise, launch Arduino IDE then

Click ***File*** -> ***New***.
{: .mouse }

A new sketch editing window will appear. Copy the whole block of code below and paste it into the new sketch window, overwriting the empty `setup()` and `loop()` that was pre-created. Ensure that the board selected is Arduino Uno and the right COM port is chosen according to "Board Selection" chapter.

```c
void setup() {
    pinMode(3, OUTPUT);
}

void loop() {
    digitalWrite(3, HIGH);
    delay(1000);
    digitalWrite(3, LOW);
    delay(1000);
}
```

Click ![arduino_ide_upload button](img/arduino_ide_upload_icon.svg){: .sixteenth-w-w } Upload, and the Arduino IDE will prompt you to ***Save sketch folder as***. Enter `Excercise_1` into the filename field and click save. Once saved, the Arduino IDE will start to compile the sketch. After the compilation is completed, the Arduino IDE will start to upload the compiled sketch into the (STMB). During this stage both yellow LEDs on the (STMB) will start blinking indicating the Arduino IDE is uploading the sketch to the (STMB).
{: .mouse }

### Understanding the Blinking LED Sketch

From the circuit, we know that PIN3 of the (STMB) is connected to the 220Ω resistor and the Red LED. In order to turn on the LED, we need to instruct the (STMB) to set PIN3 to **OUTPUT** in the `setup()` function.

`pinMode(3, OUTPUT);`

The `pinMode()` function shown above takes two parameters. The first parameter is the pin number and the second parameter is the mode of the pin. The above code instructs the (STMB) to set PIN3 as **OUTPUT**.

Once PIN3 is configured as **OUTPUT**, we can then instruct the (STMB) to either set PIN3 **HIGH** or **LOW**.

`digitalWrite(3, HIGH);`

The `digitalWrite()` function shown above takes two parameters. The first parameter is the pin number and the second parameter is **HIGH** or **LOW**. When a PIN is set to **HIGH**, the PIN will **OUTPUT** 5V. When a PIN is set to **LOW**, the PIN will **OUTPUT** 0V (no voltage and connected to GROUND).

In order to set an ON time or OFF time, we can add a delay in between ON and OFF using the following line of code after setting a PIN **HIGH** or **LOW**.

`delay(1000);`

This line of code instruct the (STMB) to delay for **1000** ms (milliseconds).

When ON, DELAY, OFF, DELAY are executed in a loop, the result of this exercise is the LED blinking in 1000ms ON and 1000ms OFF pattern.
{: .success }


text:
<?xml version="1.0" ?>
<enemy>
    <behaviour>
        <root x="110" y="40">
            <normal>
                <condition id="checkCounter">
                    <string id="id">Toolkit_WaypointPlus_Trigger_PathLoader_PathStep</string>
                    <string id="value">0</string>
                    <string id="compare method" values="valuecompare">equal</string>
                    <string id="Comment">Starting step</string>
                    <normal>
                        <condition id="isFromTeam">
                            <string id="team" values="teamswithnumbers">ZERO_TEAM</string>
                            <string id="check on" values="targetself">self</string>
                            <string id="Comment">Am I on red?</string>
                            <normal>
                                <action id="adjustCounter">
                                    <string id="id">Toolkit_WaypointPlus_Trigger_TargetWaypoint</string>
                                    <string id="value">NEUTRALSIDESPOT_0</string>
                                    <string id="adjust method" values="valueadjust">set</string>
                                </action>
                            </normal>
                            <else>
                                <action id="adjustCounter">
                                    <string id="id">Toolkit_WaypointPlus_Trigger_TargetWaypoint</string>
                                    <string id="value">NEUTRALSIDESPOT_1</string>
                                    <string id="adjust method" values="valueadjust">set</string>
                                </action>
                            </else>
                        </condition>
                    </normal>
                    <else>
                        <condition id="checkCounter">
                            <string id="id">Toolkit_WaypointPlus_Trigger_PathLoader_PathStep</string>
                            <string id="value">1</string>
                            <string id="compare method" values="valuecompare">equal</string>
                            <string id="Comment">Ending step</string>
                            <normal>
                                <condition id="isFromTeam">
                                    <string id="team" values="teamswithnumbers">ZERO_TEAM</string>
                                    <string id="check on" values="targetself">self</string>
                                    <string id="Comment">Am I on red?</string>
                                    <normal>
                                        <action id="adjustCounter">
                                            <string id="id">Toolkit_WaypointPlus_Trigger_TargetWaypoint</string>
                                            <string id="value">UPPERLANESECOND_0</string>
                                            <string id="adjust method" values="valueadjust">set</string>
                                        </action>
                                    </normal>
                                    <else>
                                        <action id="adjustCounter">
                                            <string id="id">Toolkit_WaypointPlus_Trigger_TargetWaypoint</string>
                                            <string id="value">UPPERLANESECOND_1</string>
                                            <string id="adjust method" values="valueadjust">set</string>
                                        </action>
                                    </else>
                                </condition>
                            </normal>
                            <else>
                                <action id="setBool">
                                    <string id="id">Toolkit_WaypointPlus_Trigger_PathLoader_PathFinished</string>
                                    <string id="value" values="flagtoggle">yes</string>
                                    <string id="Comment">This path has nothing left to do!</string>
                                </action>
                            </else>
                        </condition>
                    </else>
                </condition>
            </normal>
        </root>
    </behaviour>
</enemy>


text:
<?php
namespace Ray\Adr;

use Radar\Adr\Adr;
use Ray\Adr\Module\AdrModule;
use Ray\Compiler\DiCompiler;
use Ray\Compiler\Exception\NotCompiled;
use Ray\Compiler\ScriptInjector;
use Ray\Di\Injector;

class Boot
{
    protected $tmpDir;

    public function __construct($tmpDir = null, $userModule = null)
    {
        $this->tmpDir = $tmpDir ?: sys_get_temp_dir();
    }

    public function adr()
    {
        try {
            $injector = new ScriptInjector($this->tmpDir);
            $adr = $injector->getInstance(Adr::class);
        } catch (NotCompiled $e) {
            $compiler = new DiCompiler(new AdrModule, $this->tmpDir);
            $compiler->compile();
            $adr = $compiler->getInstance(Adr::class);
        }

        return $adr;
    }
}


text:
namespace {

constexpr GLubyte *bufferOffset(size_t bytes)
{
    return static_cast<GLubyte *>(0) + bytes;
}

const char kVertexShader[] = R"(
#version 150

in vec4 vPosition;
in vec3 vColor;
uniform mat4 mModelViewProjection;

out vec4 fColor;

void main()
{
    gl_Position = mModelViewProjection * vPosition;
    fColor = vec4(vColor, 1.0);
}
)";
const char kFragmentShader[] = R"(
#version 150

in vec4 fColor;
out vec4 fragColor;

void main()
{
    fragColor = fColor;
}
)";

const int kWindowWidth = 800;
const int kWindowHeight = 600;

enum VAO_IDs { Triangles, NumVAOs };
enum Buffer_IDs { ArrayBuffer, ColorBuffer, NumBuffers };

GLuint VAOs[NumVAOs];
GLuint Buffers[NumBuffers];

const GLuint NumVertices = 6;

GLint vPositionIndex = -1;
GLint vColorIndex = -1;
GLint mModelViewProjectionIndex = -1;

const float squareWidth = 100.0f;
const float squareSpeed = 2 * squareWidth;
Eigen::Matrix4f squareTransform;
Eigen::Vector2f squareDirection;

void initSquare()
{
    glGenVertexArrays(NumVAOs, VAOs);
    glBindVertexArray(VAOs[Triangles]);

    Eigen::Vector3f vertices[NumVertices] = {
        { -0.5, -0.5, 0.0 },
        {  0.5, -0.5, 0.0 },
        { -0.5,  0.5, 0.0 },
        { -0.5,  0.5, 0.0 },
        {  0.5, -0.5, 0.0 },
        {  0.5,  0.5, 0.0 }
    };

    glGenBuffers(NumBuffers, Buffers);
    glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glVertexAttribPointer(vPositionIndex, 3, GL_FLOAT, GL_FALSE, 0, bufferOffset(0));
    glEnableVertexAttribArray(vPositionIndex);

    struct { float r, g, b; } colors[NumVertices] = {
        { 0.0, 0.0, 1.0 },
        { 0.0, 0.0, 1.0 },
        { 0.0, 0.0, 1.0 },
        { 0.0, 0.0, 1.0 },
        { 0.0, 0.0, 1.0 },
        { 0.0, 0.0, 1.0 }
    };

    glBindBuffer(GL_ARRAY_BUFFER, Buffers[ColorBuffer]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);

    glVertexAttribPointer(vColorIndex, 3, GL_FLOAT, GL_FALSE, 0, bufferOffset(0));
    glEnableVertexAttribArray(vColorIndex);

    squareDirection = Eigen::Vector2f::Zero();
    squareTransform << squareWidth,           0, 0, (kWindowWidth/2),
                                 0, squareWidth, 0, (kWindowHeight/2),
                                 0,           0, 1, 0,
                                 0,           0, 0, 1;
}

void init()
{
    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    GLuint vertexShader = loadShaderFromString(GL_VERTEX_SHADER, kVertexShader, "kVertexShader");
    GLuint fragmentShader = loadShaderFromString(GL_FRAGMENT_SHADER, kFragmentShader, "kFragmentShader");

    GLuint program = linkShader(vertexShader, fragmentShader);
    glUseProgram(program);

    vPositionIndex = glGetAttribLocation(program, "vPosition");
    vColorIndex = glGetAttribLocation(program, "vColor");
    mModelViewProjectionIndex = glGetUniformLocation(program, "mModelViewProjection");

    initSquare();
}

Eigen::Matrix4f createOrthographicProjection(float left, float right, float bottom, float top, float zNear, float zFar)
{
    float a = 2.0 / (right - left);
    float b = 2.0 / (top - bottom);
    float c = 2.0 / (zFar - zNear);
    float d = -(right + left) / (right - left);
    float e = -(top + bottom) / (top - bottom);
    float f = -(zFar + zNear) / (zFar - zNear);

    Eigen::Matrix4f result;
    result << a, 0, 0, d,
              0, b, 0, e,
              0, 0, c, f,
              0, 0, 0, 1;

    return result;
}

const Eigen::Matrix4f kProjection = createOrthographicProjection(0, kWindowWidth, 0, kWindowHeight, -1, 1);

uint32_t oldTime = 0;
uint32_t currentTime = 0;

void updateSquare()
{
    oldTime = currentTime;
    currentTime = SDL_GetTicks();
    float deltaTime = (currentTime - oldTime) / 1000.0f;

    const Uint8 *state = SDL_GetKeyboardState(NULL);

    squareDirection = Eigen::Vector2f::Zero();
    if (state[SDL_SCANCODE_UP]) {
        squareDirection += Eigen::Vector2f::UnitY();
    }
    if (state[SDL_SCANCODE_DOWN]) {
        squareDirection -= Eigen::Vector2f::UnitY();
    }
    if (state[SDL_SCANCODE_LEFT]) {
        squareDirection -= Eigen::Vector2f::UnitX();
    }
    if (state[SDL_SCANCODE_RIGHT]) {
        squareDirection += Eigen::Vector2f::UnitX();
    }

    if (squareDirection.squaredNorm()) {
        squareDirection.normalize();

        auto pos = squareTransform.topRightCorner<2, 1>();
        if (pos(0) <= (squareWidth/2) && squareDirection(0) < 0){
            squareDirection(0) = 0;
            pos(0) = (squareWidth/2);
        }
        if (pos(0) >= (kWindowWidth-(squareWidth/2)) && squareDirection(0) > 0) {
            squareDirection(0) = 0;
            pos(0) = (kWindowWidth-(squareWidth/2));
        }
        if (pos(1) <= (squareWidth/2) && squareDirection(1) < 0) {
            squareDirection(1) = 0;
            pos(1) = (squareWidth/2);
        }
        if (pos(1) >= (kWindowHeight-(squareWidth/2)) && squareDirection(1) > 0) {
            squareDirection(1) = 0;
            pos(1) = (kWindowHeight-(squareWidth/2));
        }

        if (squareDirection.squaredNorm()) {
            squareDirection.normalize();
            pos += squareDirection * squareSpeed * deltaTime;
        }
    }
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    updateSquare();

    Eigen::Matrix4f modelViewProjection = kProjection * squareTransform;
    glUniformMatrix4fv(mModelViewProjectionIndex, 1, GL_FALSE, modelViewProjection.data());

    glBindVertexArray(VAOs[Triangles]);
    glDrawArrays(GL_TRIANGLES, 0, NumVertices);
}

} // namespace

int main(int argc, char *argv[])
{
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        std::cerr << SDL_GetError() << std::endl;
        return -1;
    }

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

    // Create an OpenGL capable window
    SDL_Window *window = SDL_CreateWindow(
        "Assignment 1.2",
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        800, 600,
        SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE
    );
    if (!window) {
        std::cerr << SDL_GetError() << std::endl;
        SDL_Quit();
        return -1;
    }

    // Create an OpenGL context associated with the window.
    SDL_GLContext glcontext = SDL_GL_CreateContext(window);
    if (!glcontext) {
        std::cerr << SDL_GetError() << std::endl;
        SDL_Quit();
        return -1;
    }

    // Load extensions
    if (ogl_LoadFunctions() != ogl_LOAD_SUCCEEDED) {
        SDL_DestroyWindow(window);
        SDL_Quit();
        return -1;
    }

    // Initialize displayables
    init();

    SDL_Event event;
    bool keepRunning = true;
    while (keepRunning) {
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                keepRunning = false;
            }
        }

        // Render scene
        display();

        // Swap buffers
        SDL_GL_SwapWindow(window);
    }

    // Once finished with OpenGL functions, the SDL_GLContext can be deleted.
    SDL_GL_DeleteContext(glcontext);

    // Done! Close the window, clean-up and exit the program.
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}


text:
<body>
PostfixMathCommands which implement the group operations.
</body>


text:
class Profile;

namespace content {
class WebContents;
class WebIntentsDispatcher;
}

namespace extensions {
class Extension;

// The WebIntentCallbacks class tracks the pending callbacks for web intents
// that have been delivered to packaged apps (i.e., new-style apps containing
// shell windows), for a particular profile.
class WebIntentCallbacks : public ProfileKeyedService {
 public:
  WebIntentCallbacks();
  virtual ~WebIntentCallbacks();

  // Returns the instance for the given profile. This is a convenience wrapper
  // around WebIntentCallbacks::Factory::GetForProfile.
  static WebIntentCallbacks* Get(Profile* profile);

  // Registers the callback for the Web Intent we're about to dispatch to the
  // given extension. Returns an identifier that should later be dispatched to
  // RetrieveCallback in order to invoke the callback registered here.
  // This transfers ownership of WebIntentsDispatcher to this class.
  int RegisterCallback(const Extension* extension,
                       content::WebIntentsDispatcher* dispatcher,
                       content::WebContents* source);

  // Retrieves the callback for the given identifier, for a response from the
  // specified extension. This will clear the callback. If there is no callback
  // registered under this identifier, then this will return NULL. This
  // transfers ownership of WebIntentsDispatcher to the caller.
  content::WebIntentsDispatcher* RetrieveCallback(const Extension* extension,
                                                  int intent_id);

 private:
  typedef std::map<std::string, content::WebIntentsDispatcher*> CallbackMap;

  class Factory : public ProfileKeyedServiceFactory {
   public:
    static WebIntentCallbacks* GetForProfile(Profile* profile);

    static Factory* GetInstance();
   private:
    friend struct DefaultSingletonTraits<Factory>;

    Factory();
    virtual ~Factory();

    // ProfileKeyedServiceFactory
    virtual ProfileKeyedService* BuildServiceInstanceFor(
        Profile* profile) const OVERRIDE;
  };

  // Private method to get and clear the dispatcher for the given string key.
  // If there is no dispatcher available, this will return NULL. Otherwise, this
  // transfers ownership of the WebIntentsDispatcher to the caller.
  content::WebIntentsDispatcher* GetAndClear(const std::string& key);

  class SourceObserver;

  // Used as an incrementing ID for callback keys.
  int last_id_;

  // Stores all pending callbacks sent to platform apps.
  CallbackMap pending_;
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_WEB_INTENT_CALLBACKS_H_


text:
var settings=require('../settings');
var MongoClient = require('mongodb').MongoClient;
var crypto=require('crypto');

/**
 * 链接数据库
 * @param callback 链接之后的回调函数
 * @private
 */
function __connectDB(callback){
    var url=settings.dbUrl;
    MongoClient.connect(url,function(err,db){
        if(err){
            callback(err,null);
        }

        callback(err,db);

    })
}

/**
 * 插入操作
 * @param collectionName 要操作collection的名字
 * @param json 需要插入的数据
 * @param callback 插入之后的回调函数
 */
exports.insert=function(collectionName,json,callback){
        __connectDB(function(err,db){
            db.collection(collectionName).insertOne(json,function(err,result){
                callback(err,result);
                db.close();
            })
        })
}

/**
 * 花式查找数据
 * @param collectionName 要操作collection的名字
 * @param json 精确查找
 * @param C 如果参数是3个 C就是callback
 * @param D 如果参数是4个 D就是分页查找
 */
exports.find=function(collectionName,json,C,D){
    var result=[];
    if(arguments.length==3){
        var callback=C;
        var skipNumber=0;
        var limit=0;
    }else if(arguments.length==4){
        var callback=D;
        var args=C;
        var skipNumber=args.pageAmount * args.page || 0;
        var limit= args.pageAmount || 0;
        var sort=args.sort || {};
    }else{
        throw new Error('find函数的参数必须是3个或者4个');
        return;
    }

    __connectDB(function(err,db){
        var cursor=db.collection(collectionName).find(json).skip(skipNumber).limit(limit).sort(sort);
        cursor.each(function(err,doc){
            if(err){
                callback(err,null);
                db.close();
                return;
            }

            if(doc!=null){
                result.push(doc);
            }else{
                callback(null,result);
                db.close();
            }
        })
    })
}

/**
 * 删除数据操作
 * @param collectionName 要操作collection的名字
 * @param json 精确删除的对象
 * @param callback 删除之后的回调
 */
exports.delete=function(collectionName,json,callback){
    __connectDB(function(err,db){
        db.collection(collectionName).deleteMany(json,function(err,result){
            callback(err,result);
            db.close();
        })
    })
}

/**
 * 更新数据操作
 * @param collectionName 要操作collection的名字
 * @param json1 改什么
 * @param json2 怎么改
 * @param callback 更新之后的回调函数
 */
exports.update=function(collectionName,json1,json2,callback){
    __connectDB(function(err,db){
        db.collection(collectionName).updateMany(json1,json2,function(err,result){
            callback(err,result);
            db.close();
        })
    })
}

/**
 * 获取数据总数
 * @param collectionName 要操作collection的名字
 * @param callback 获取之后的回调函数
 */
exports.getAllCount=function(collectionName,callback){
    __connectDB(function (err, db) {
        db.collection(collectionName).count({}).then(function(count) {
            callback(count);
            db.close();
        });
    })
}

/**
 * MD5加密函数
 * @param password 需要加密的密码
 * @param callback  加密后的回调
 */
exports.md5=function(password,callback){
    var md5=crypto.createHash('md5');
    var password=md5.update(password).digest('base64');
    callback(password);
    return;
}

/**
 * 数据库初始化
 */
function init(){
    __connectDB(function(err,db){
        if(err){
            console.log(err);
            return;
        }
        db.collection('user').createIndex(
            {'username':1},
            null,
            function(err,result){
                console.log('索引建立成功');
            }
        )
    })
}
init();


text:
http://www.lintcode.com/en/problem/search-insert-position/

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume NO duplicates in the array.

**Example**

```[1,3,5,6]```, 5 -> 2
```[1,3,5,6]```, 7 -> 4

## Thoughts

- Binary Search
- start: 0, end: len(array) - 1
- mid: start + (end - start)/2
- If target doesn't exist in the array, insert position has three posibilities
  - on the left of start (smaller than start)
  - on the right of end (larger than end)
  - between start and end

## My Solution

```python
def searchInsert(self, A, target):
    if len(A) == 0:
        return 0

    start = 0
    end = len(A) - 1
    while start + 1 < end:
        mid = start + (end - start)/2
        if target < A[mid]:
            end = mid
        elif target > A[mid]:
            start = mid
        else:
            return mid

    if A[start] == target:
        return start
    elif A[end] == target:
        return end
    elif A[start] > target:
    # target is even smaller than the first
        return start
    elif A[end] < target:
    # target is even larger than the last
        return end + 1
    else:
    # target is in the range of the given array, start is the first element that is smaller than target
        return start + 1
```

## Reference


text:
var path = require('path'),
    _ = require('underscore');

module.exports = function (opts) {
    var app = require('../')(_.extend({
        path: path.join(__dirname, 'sample'),
        port: 8000 + (+_.uniqueId())
    }, opts));

    app.log.disable();

    return app;
};


text:
package edu.usc.softarch.disco.structs;

/**
 * @author mattmann
 * @version $Revision$
 *
 *
Describe your class here
.
 */
public class UserType {

	public static final int CONSUMER = -9383939;

	public static final int PRODUCER = -9388888;

	private boolean automated = false;

	private int type = -1;

	private long numInType = 0L;

	public UserType(){

	}

	/**
	 * @return the automated
	 */
	public boolean isAutomated() {
		return automated;
	}

	/**
	 * @param automated the automated to set
	 */
	public void setAutomated(boolean automated) {
		this.automated = automated;
	}

	/**
	 * @return the numInType
	 */
	public long getNumInType() {
		return numInType;
	}

	/**
	 * @param numInType the numInType to set
	 */
	public void setNumInType(long numInType) {
		this.numInType = numInType;
	}

	/**
	 * @return the type
	 */
	public int getType() {
		return type;
	}

	/**
	 * @param type the type to set
	 */
	public void setType(int type) {
		this.type = type;
	}

}


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

gulp.task('lint', function () {
    var eslint = require('gulp-eslint');
    return gulp.src(['index.js', 'test/*.js', 'gulpfile.js'])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('test', function () {
    var mocha = require('gulp-mocha');
    return gulp.src('test.js', { read: false })
        .pipe(mocha({ timeout: 60000 }));
});

gulp.task('default', ['lint', 'test']);


text:
var gulp = require('gulp');
var ts = require('gulp-typescript');
var merge = require('merge2');
var karma = require('gulp-karma');
var testFiles = [
    'release/js/**/*.js',
    'tests/**/*.js'
];
gulp.task('compile-typescript', function () {
    var tsProject = ts.createProject({
        declarationFiles: true,
        noExternalResolve: true
    });
    var tsResult = gulp.src('src/**/*.ts').pipe(ts(tsProject));
    return merge([
        tsResult.dts.pipe(gulp.dest('release/definitions')),
        tsResult.js.pipe(gulp.dest('release/js'))
    ]);
});
gulp.task('test', ['compile-typescript'], function () {
    // Be sure to return the stream
    return gulp.src(testFiles).pipe(karma({
        configFile: 'karma.conf.js',
        action: 'run'
    })).on('error', function (err) {
        throw err;
    });
});
gulp.task('watch', ['test'], function () {
    var paths = [
        "karma.conf.ts",
        "src/**/*.ts",
        "tests/**/*.ts",
        "typings/**/*.ts"
    ];
    gulp.watch(paths, ['test']);
});
gulp.task('default', ['test'], function () {
    // gulp.src(testFiles)
    // 	.pipe(karma({
    // 		configFile: 'karma.conf.js',
    // 		action: 'watch'
    // 	}));
});
//# sourceMappingURL=gulpfile.js.map


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>类 com.mastergaurav.android.mvc.common.Response的使用 (MVC-Android 0.0.1-SNAPSHOT API)</title>
<meta name="date" content="2014-06-27">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

类 com.mastergaurav.android.mvc.common.Response
的使用

使用Response的程序包

程序包
说明

com.mastergaurav.android.app.view

com.mastergaurav.android.common.view

com.mastergaurav.android.mvc.command

com.mastergaurav.android.mvc.common

com.mastergaurav.android.mvc.controller

com.mastergaurav.android.app.view中Response的使用

参数类型为Response的com.mastergaurav.android.app.view中的方法

限定符和类型
方法和说明

void
LoginActivity.onError(Response response)

void
LoginActivity.onSuccess(Response response)

com.mastergaurav.android.common.view中Response的使用

参数类型为Response的com.mastergaurav.android.common.view中的方法

限定符和类型
方法和说明

void
BaseActivity.onError(Response response)

void
BaseActivity.onSuccess(Response response)

void
IViewActivity.preProcessData(Response response)

void
BaseActivity.preProcessData(Response response)

void
IViewActivity.processData(Response response)

void
BaseActivity.processData(Response response)

com.mastergaurav.android.mvc.command中Response的使用

返回Response的com.mastergaurav.android.mvc.command中的方法

限定符和类型
方法和说明

Response
ICommand.getResponse()

Response
AbstractBaseCommand.getResponse()

参数类型为Response的com.mastergaurav.android.mvc.command中的方法

限定符和类型
方法和说明

void
ICommand.setResponse(Response response)

void
AbstractBaseCommand.setResponse(Response response)

com.mastergaurav.android.mvc.common中Response的使用

参数类型为Response的com.mastergaurav.android.mvc.common中的方法

限定符和类型
方法和说明

void
IResponseListener.onError(Response response)

void
IResponseListener.onSuccess(Response response)

com.mastergaurav.android.mvc.controller中Response的使用

返回Response的com.mastergaurav.android.mvc.controller中的方法

限定符和类型
方法和说明

Response
ActivityStackInfo.getResponse()

参数类型为Response的com.mastergaurav.android.mvc.controller中的方法

限定符和类型
方法和说明

void
Controller.onError(Response response)

void
Controller.onSuccess(Response response)

void
ActivityStackInfo.setResponse(Response response)

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

Copyright © 2014. All Rights Reserved.