text:
import sys
import uuid

import mock

import quantum.tests.unit.test_db_plugin as test_plugin

MIDOKURA_PKG_PATH = "quantum.plugins.midonet.plugin"

# Need to mock the midonetclient module since the plugin will try to load it.
sys.modules["midonetclient"] = mock.Mock()

class MidonetPluginV2TestCase(test_plugin.QuantumDbPluginV2TestCase):

    _plugin_name = ('%s.MidonetPluginV2' % MIDOKURA_PKG_PATH)

    def setUp(self):
        self.mock_api = mock.patch('midonetclient.api.MidonetApi')
        self.instance = self.mock_api.start()
        super(MidonetPluginV2TestCase, self).setUp(self._plugin_name)

    def tearDown(self):
        super(MidonetPluginV2TestCase, self).tearDown()
        self.mock_api.stop()

    def _setup_bridge_mock(self, bridge_id=str(uuid.uuid4()), name='net'):
        # Set up mocks needed for the parent network() method
        bridge = mock.Mock()
        bridge.get_id.return_value = bridge_id
        bridge.get_name.return_value = name

        self.instance.return_value.add_bridge.return_value.name.return_value\
            .tenant_id.return_value.create.return_value = bridge
        self.instance.return_value.get_bridges.return_value = [bridge]
        self.instance.return_value.get_bridge.return_value = bridge
        return bridge

    def _setup_subnet_mocks(self, subnet_id=str(uuid.uuid4()),
                            subnet_prefix='10.0.0.0', subnet_len=int(24)):
        # Set up mocks needed for the parent subnet() method
        bridge = self._setup_bridge_mock()
        subnet = mock.Mock()
        subnet.get_subnet_prefix.return_value = subnet_prefix
        subnet.get_subnet_length.return_value = subnet_len
        subnet.get_id.return_value = subnet_prefix + '/' + str(subnet_len)
        bridge.add_dhcp_subnet.return_value.default_gateway\
            .return_value.subnet_prefix.return_value.subnet_length\
            .return_value.create.return_value = subnet
        bridge.get_dhcp_subnets.return_value = [subnet]
        return (bridge, subnet)

    def _setup_port_mocks(self, port_id=str(uuid.uuid4())):
        # Set up mocks needed for the parent port() method
        bridge, subnet = self._setup_subnet_mocks()
        port = mock.Mock()
        port.get_id.return_value = port_id
        self.instance.return_value.create_port.return_value = port
        self.instance.return_value.get_port.return_value = port
        bridge.add_exterior_port.return_value.create.return_value = (
            port
        )

        dhcp_host = mock.Mock()
        rv1 = subnet.add_dhcp_host.return_value.ip_addr.return_value
        rv1.mac_addr.return_value.create.return_value = dhcp_host

        subnet.get_dhcp_hosts.return_value = [dhcp_host]
        return (bridge, subnet, port, dhcp_host)

class TestMidonetNetworksV2(test_plugin.TestNetworksV2,
                            MidonetPluginV2TestCase):

    def test_create_network(self):
        self._setup_bridge_mock()
        super(TestMidonetNetworksV2, self).test_create_network()

    def test_create_public_network(self):
        self._setup_bridge_mock()
        super(TestMidonetNetworksV2, self).test_create_public_network()

    def test_create_public_network_no_admin_tenant(self):
        self._setup_bridge_mock()
        super(TestMidonetNetworksV2,
              self).test_create_public_network_no_admin_tenant()

    def test_update_network(self):
        self._setup_bridge_mock()
        super(TestMidonetNetworksV2, self).test_update_network()

    def test_list_networks(self):
        self._setup_bridge_mock()
        with self.network(name='net1') as net1:
            req = self.new_list_request('networks')
            res = self.deserialize('json', req.get_response(self.api))
            self.assertEqual(res['networks'][0]['name'],
                             net1['network']['name'])

    def test_show_network(self):
        self._setup_bridge_mock()
        super(TestMidonetNetworksV2, self).test_show_network()

    def test_update_shared_network_noadmin_returns_403(self):
        self._setup_bridge_mock()
        super(TestMidonetNetworksV2,
              self).test_update_shared_network_noadmin_returns_403()

    def test_update_network_set_shared(self):
        pass

    def test_update_network_with_subnet_set_shared(self):
        pass

    def test_update_network_set_not_shared_single_tenant(self):
        pass

    def test_update_network_set_not_shared_other_tenant_returns_409(self):
        pass

    def test_update_network_set_not_shared_multi_tenants_returns_409(self):
        pass

    def test_update_network_set_not_shared_multi_tenants2_returns_409(self):
        pass

    def test_create_networks_bulk_native(self):
        pass

    def test_create_networks_bulk_native_quotas(self):
        pass

    def test_create_networks_bulk_tenants_and_quotas(self):
        pass

    def test_create_networks_bulk_tenants_and_quotas_fail(self):
        pass

    def test_create_networks_bulk_emulated(self):
        pass

    def test_create_networks_bulk_wrong_input(self):
        pass

    def test_create_networks_bulk_emulated_plugin_failure(self):
        pass

    def test_create_networks_bulk_native_plugin_failure(self):
        pass

    def test_list_networks_with_parameters(self):
        pass

    def test_list_networks_with_fields(self):
        pass

    def test_list_networks_with_parameters_invalid_values(self):
        pass

    def test_show_network_with_subnet(self):
        pass

    def test_invalid_admin_status(self):
        pass

    def test_list_networks_with_pagination_emulated(self):
        pass

    def test_list_networks_with_pagination_reverse_emulated(self):
        pass

    def test_list_networks_with_sort_emulated(self):
        pass

    def test_list_networks_without_pk_in_fields_pagination_emulated(self):
        pass

class TestMidonetSubnetsV2(test_plugin.TestSubnetsV2,
                           MidonetPluginV2TestCase):

    def test_create_subnet(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_subnet()

    def test_create_two_subnets(self):
        pass

    def test_create_two_subnets_same_cidr_returns_400(self):
        pass

    def test_create_subnet_bad_V4_cidr(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_subnet_bad_V4_cidr()

    def test_create_subnet_bad_V6_cidr(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_subnet_bad_V4_cidr()

    def test_create_2_subnets_overlapping_cidr_allowed_returns_200(self):
        pass

    def test_create_2_subnets_overlapping_cidr_not_allowed_returns_400(self):
        pass

    def test_create_subnets_bulk_native(self):
        pass

    def test_create_subnets_bulk_emulated(self):
        pass

    def test_create_subnets_bulk_emulated_plugin_failure(self):
        pass

    def test_create_subnets_bulk_native_plugin_failure(self):
        pass

    def test_delete_subnet(self):
        _bridge, subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_delete_subnet()
        subnet.delete.assert_called_once_with()

    def test_delete_subnet_port_exists_owned_by_network(self):
        _bridge, subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_delete_subnet_port_exists_owned_by_network()

    def test_delete_subnet_port_exists_owned_by_other(self):
        pass

    def test_delete_network(self):
        bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_delete_network()
        bridge.delete.assert_called_once_with()

    def test_create_subnet_bad_tenant(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_subnet_bad_tenant()

    def test_create_subnet_bad_ip_version(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_subnet_bad_ip_version()

    def test_create_subnet_bad_ip_version_null(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_create_subnet_bad_ip_version_null()

    def test_create_subnet_bad_uuid(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_subnet_bad_uuid()

    def test_create_subnet_bad_boolean(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_subnet_bad_boolean()

    def test_create_subnet_bad_pools(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_subnet_bad_pools()

    def test_create_subnet_bad_nameserver(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_subnet_bad_nameserver()

    def test_create_subnet_bad_hostroutes(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_subnet_bad_hostroutes()

    def test_create_subnet_defaults(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_subnet_defaults()

    def test_create_subnet_gw_values(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_subnet_gw_values()

    def test_create_force_subnet_gw_values(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_force_subnet_gw_values()

    def test_create_subnet_with_allocation_pool(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_create_subnet_with_allocation_pool()

    def test_create_subnet_with_none_gateway(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_create_subnet_with_none_gateway()

    def test_create_subnet_with_none_gateway_fully_allocated(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_create_subnet_with_none_gateway_fully_allocated()

    def test_subnet_with_allocation_range(self):
        pass

    def test_create_subnet_with_none_gateway_allocation_pool(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_create_subnet_with_none_gateway_allocation_pool()

    def test_create_subnet_with_v6_allocation_pool(self):
        pass

    def test_create_subnet_with_large_allocation_pool(self):
        pass

    def test_create_subnet_multiple_allocation_pools(self):
        pass

    def test_create_subnet_with_dhcp_disabled(self):
        pass

    def test_create_subnet_default_gw_conflict_allocation_pool_returns_409(
        self):
        pass

    def test_create_subnet_gateway_in_allocation_pool_returns_409(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self)\
            .test_create_subnet_gateway_in_allocation_pool_returns_409()

    def test_create_subnet_overlapping_allocation_pools_returns_409(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self)\
            .test_create_subnet_overlapping_allocation_pools_returns_409()

    def test_create_subnet_invalid_allocation_pool_returns_400(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_create_subnet_invalid_allocation_pool_returns_400()

    def test_create_subnet_out_of_range_allocation_pool_returns_400(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self)\
            .test_create_subnet_out_of_range_allocation_pool_returns_400()

    def test_create_subnet_shared_returns_400(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_create_subnet_shared_returns_400()

    def test_create_subnet_inconsistent_ipv6_cidrv4(self):
        pass

    def test_create_subnet_inconsistent_ipv4_cidrv6(self):
        pass

    def test_create_subnet_inconsistent_ipv4_gatewayv6(self):
        pass

    def test_create_subnet_inconsistent_ipv6_gatewayv4(self):
        pass

    def test_create_subnet_inconsistent_ipv6_dns_v4(self):
        pass

    def test_create_subnet_inconsistent_ipv4_hostroute_dst_v6(self):
        pass

    def test_create_subnet_inconsistent_ipv4_hostroute_np_v6(self):
        pass

    def test_update_subnet(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_update_subnet()

    def test_update_subnet_shared_returns_400(self):
        self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_update_subnet_shared_returns_400()

    def test_update_subnet_inconsistent_ipv4_gatewayv6(self):
        pass

    def test_update_subnet_inconsistent_ipv6_gatewayv4(self):
        pass

    def test_update_subnet_inconsistent_ipv4_dns_v6(self):
        pass

    def test_update_subnet_inconsistent_ipv6_hostroute_dst_v4(self):
        pass

    def test_update_subnet_inconsistent_ipv6_hostroute_np_v4(self):
        pass

    def test_show_subnet(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_show_subnet()

    def test_list_subnets(self):
        pass

    def test_list_subnets_shared(self):
        pass

    def test_list_subnets_with_parameter(self):
        pass

    def test_invalid_ip_version(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_invalid_ip_version()

    def test_invalid_subnet(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_invalid_subnet()

    def test_invalid_ip_address(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_invalid_ip_address()

    def test_invalid_uuid(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_invalid_uuid()

    def test_create_subnet_with_one_dns(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_subnet_with_one_dns()

    def test_create_subnet_with_two_dns(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_create_subnet_with_two_dns()

    def test_create_subnet_with_too_many_dns(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_create_subnet_with_too_many_dns()

    def test_create_subnet_with_one_host_route(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_create_subnet_with_one_host_route()

    def test_create_subnet_with_two_host_routes(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_create_subnet_with_two_host_routes()

    def test_create_subnet_with_too_many_routes(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_create_subnet_with_too_many_routes()

    def test_update_subnet_dns(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_update_subnet_dns()

    def test_update_subnet_dns_to_None(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_update_subnet_dns_to_None()

    def test_update_subnet_dns_with_too_many_entries(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_update_subnet_dns_with_too_many_entries()

    def test_update_subnet_route(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_update_subnet_route()

    def test_update_subnet_route_to_None(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_update_subnet_route_to_None()

    def test_update_subnet_route_with_too_many_entries(self):
        _bridge, _subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_update_subnet_route_with_too_many_entries()

    def test_delete_subnet_with_dns(self):
        _bridge, subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_delete_subnet_with_dns()
        subnet.delete.assert_called_once_with()

    def test_delete_subnet_with_route(self):
        _bridge, subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2, self).test_delete_subnet_with_route()
        subnet.delete.assert_called_once_with()

    def test_delete_subnet_with_dns_and_route(self):
        _bridge, subnet = self._setup_subnet_mocks()
        super(TestMidonetSubnetsV2,
              self).test_delete_subnet_with_dns_and_route()
        subnet.delete.assert_called_once_with()

    def test_update_subnet_gateway_in_allocation_pool_returns_409(self):
        self._setup_port_mocks()
        super(TestMidonetSubnetsV2, self)\
            .test_update_subnet_gateway_in_allocation_pool_returns_409()

    def test_list_subnets_with_pagination_emulated(self):
        pass

    def test_list_subnets_with_pagination_reverse_emulated(self):
        pass

    def test_list_subnets_with_sort_emulated(self):
        pass

class TestMidonetPortsV2(test_plugin.TestPortsV2,
                         MidonetPluginV2TestCase):

    def test_create_port_json(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_create_port_json()

    def test_create_port_bad_tenant(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_create_port_bad_tenant()

    def test_create_port_public_network(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_create_port_public_network()

    def test_create_port_public_network_with_ip(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2,
              self).test_create_port_public_network_with_ip()

    def test_create_ports_bulk_native(self):
        pass

    def test_create_ports_bulk_emulated(self):
        pass

    def test_create_ports_bulk_wrong_input(self):
        pass

    def test_create_ports_bulk_emulated_plugin_failure(self):
        pass

    def test_create_ports_bulk_native_plugin_failure(self):
        pass

    def test_list_ports(self):
        pass

    def test_list_ports_filtered_by_fixed_ip(self):
        pass

    def test_list_ports_public_network(self):
        pass

    def test_show_port(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_show_port()

    def test_delete_port(self):
        _bridge, _subnet, port, _dhcp = self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_delete_port()
        port.delete.assert_called_once_with()

    def test_delete_port_public_network(self):
        _bridge, _subnet, port, _dhcp = self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_delete_port_public_network()
        port.delete.assert_called_once_with()

    def test_update_port(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_update_port()

    def test_update_device_id_null(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_update_device_id_null()

    def test_delete_network_if_port_exists(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_delete_network_if_port_exists()

    def test_delete_network_port_exists_owned_by_network(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2,
              self).test_delete_network_port_exists_owned_by_network()

    def test_update_port_delete_ip(self):
        pass

    def test_no_more_port_exception(self):
        pass

    def test_update_port_update_ip(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_update_port_update_ip()

    def test_update_port_update_ip_address_only(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2,
              self).test_update_port_update_ip_address_only()

    def test_update_port_update_ips(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_update_port_update_ips()

    def test_update_port_add_additional_ip(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_update_port_add_additional_ip()

    def test_requested_duplicate_mac(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_requested_duplicate_mac()

    def test_mac_generation(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_mac_generation()

    def test_mac_generation_4octet(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_mac_generation_4octet()

    def test_bad_mac_format(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_bad_mac_format()

    def test_mac_exhaustion(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_mac_exhaustion()

    def test_requested_duplicate_ip(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_requested_duplicate_ip()

    def test_requested_subnet_delete(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_requested_subnet_delete()

    def test_requested_subnet_id(self):
        pass

    def test_requested_subnet_id_not_on_network(self):
        pass

    def test_overlapping_subnets(self):
        pass

    def test_requested_subnet_id_v4_and_v6(self):
        pass

    def test_range_allocation(self):
        pass

    def test_requested_invalid_fixed_ips(self):
        pass

    def test_invalid_ip(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_invalid_ip()

    def test_requested_split(self):
        pass

    def test_duplicate_ips(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_duplicate_ips()

    def test_fixed_ip_invalid_subnet_id(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_fixed_ip_invalid_subnet_id()

    def test_fixed_ip_invalid_ip(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_fixed_ip_invalid_ip()

    def test_requested_ips_only(self):
        pass

    def test_recycling(self):
        pass

    def test_invalid_admin_state(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_invalid_admin_state()

    def test_invalid_mac_address(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_invalid_mac_address()

    def test_default_allocation_expiration(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_default_allocation_expiration()

    def test_update_fixed_ip_lease_expiration(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2,
              self).test_update_fixed_ip_lease_expiration()

    def test_port_delete_holds_ip(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_port_delete_holds_ip()

    def test_update_fixed_ip_lease_expiration_invalid_address(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2,
              self).test_update_fixed_ip_lease_expiration_invalid_address()

    def test_hold_ip_address(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_hold_ip_address()

    def test_recycle_held_ip_address(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_recycle_held_ip_address()

    def test_recycle_expired_previously_run_within_context(self):
        pass

    def test_update_port_not_admin(self):
        self._setup_port_mocks()
        super(TestMidonetPortsV2, self).test_update_port_not_admin()

    def test_list_ports_with_pagination_emulated(self):
        pass

    def test_list_ports_with_pagination_reverse_emulated(self):
        pass

    def test_list_ports_with_sort_emulated(self):
        pass

    def test_max_fixed_ips_exceeded(self):
        pass

    def test_update_max_fixed_ips_exceeded(self):
        pass


text:
[![No Maintenance Intended](http://unmaintained.tech/badge.svg)](http://unmaintained.tech/)

----

Howdy!

So far this is really, nothing.

redpajama_set_name: RedPajamaGithub


text:
"""Run the API."""

from flask import Flask
import requests

app = Flask(__name__)
app.config.from_pyfile("config.py", True)

from views import *

if __name__ == "__main__":
    app.run(port=8000, host="0.0.0.0", debug=True)


text:
#ifndef LinearGradientAttributes_h
#define LinearGradientAttributes_h

#include "core/svg/GradientAttributes.h"
#include "platform/heap/Handle.h"

namespace blink {

struct LinearGradientAttributes : GradientAttributes {
    DISALLOW_ALLOCATION();
public:
    LinearGradientAttributes()
        : m_x1(SVGLength::create(LengthModeWidth))
        , m_y1(SVGLength::create(LengthModeWidth))
        , m_x2(SVGLength::create(LengthModeWidth))
        , m_y2(SVGLength::create(LengthModeWidth))
        , m_x1Set(false)
        , m_y1Set(false)
        , m_x2Set(false)
        , m_y2Set(false)
    {
        m_x2->setValueAsString("100%", ASSERT_NO_EXCEPTION);
    }

    SVGLength* x1() const { return m_x1.get(); }
    SVGLength* y1() const { return m_y1.get(); }
    SVGLength* x2() const { return m_x2.get(); }
    SVGLength* y2() const { return m_y2.get(); }

    void setX1(PassRefPtrWillBeRawPtr<SVGLength> value) { m_x1 = value; m_x1Set = true; }
    void setY1(PassRefPtrWillBeRawPtr<SVGLength> value) { m_y1 = value; m_y1Set = true; }
    void setX2(PassRefPtrWillBeRawPtr<SVGLength> value) { m_x2 = value; m_x2Set = true; }
    void setY2(PassRefPtrWillBeRawPtr<SVGLength> value) { m_y2 = value; m_y2Set = true; }

    bool hasX1() const { return m_x1Set; }
    bool hasY1() const { return m_y1Set; }
    bool hasX2() const { return m_x2Set; }
    bool hasY2() const { return m_y2Set; }

    void trace(Visitor* visitor)
    {
        visitor->trace(m_x1);
        visitor->trace(m_y1);
        visitor->trace(m_x2);
        visitor->trace(m_y2);
    }

private:
    // Properties
    RefPtrWillBeMember<SVGLength> m_x1;
    RefPtrWillBeMember<SVGLength> m_y1;
    RefPtrWillBeMember<SVGLength> m_x2;
    RefPtrWillBeMember<SVGLength> m_y2;

    // Property states
    bool m_x1Set : 1;
    bool m_y1Set : 1;
    bool m_x2Set : 1;
    bool m_y2Set : 1;
};

} // namespace blink

#endif

// vim:ts=4:noet


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `/home/jacob/.cargo/registry/src/github.com-1ecc6299db9ec823/typenum-1.8.0/src/array.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>array.rs.html -- source</title>

    <link rel="stylesheet" type="text/css" href="../../normalize.css">
    <link rel="stylesheet" type="text/css" href="../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../main.css">

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269

//! This module provides a type-level array of type-level numbers.
//!
//! It is not very featureful right now, and should be considered a work in progress.

use core::marker::PhantomData;
use core::ops::{Add, Sub, Mul, Div};

use super::*;

/// The terminating type for type arrays.
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Hash, Debug)]
pub struct ATerm;

impl TypeArray for ATerm {}

/// `TArr` is a type that acts as an array of types. It is defined similarly to `UInt`, only its
/// values can be more than bits, and it is designed to act as an array. So you can only add two if
/// they have the same number of elements, for example.
///
/// This array is only really designed to contain `Integer` types. If you use it with others, you
/// may find it lacking functionality.
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Hash, Debug)]
pub struct TArr<V, A> {
    _marker: PhantomData<(V, A)>,
}

impl<V, A> TypeArray for TArr<V, A> {}

/// Create a new type-level arrray. Only usable on Rust 1.13.0 or newer.
///
/// There's not a whole lot you can do with it right now.
///
/// # Example
/// ```rust
/// #[macro_use]
/// extern crate typenum;
/// use typenum::consts::*;
///
/// type Array = tarr![P3, N4, Z0, P38];
/// # fn main() {}
#[macro_export]
macro_rules! tarr {
    () => ( $crate::ATerm );
    ($n:ty) => ( $crate::TArr<$n, $crate::ATerm> );
    ($n:ty,) => ( $crate::TArr<$n, $crate::ATerm> );
    ($n:ty, $($tail:ty),+) => ( $crate::TArr<$n, tarr![$($tail),+]> );
    ($n:ty, $($tail:ty),+,) => ( $crate::TArr<$n, tarr![$($tail),+]> );
}

// ---------------------------------------------------------------------------------------
// Length

/// Length of `ATerm` by itself is 0
impl Len for ATerm {
    type Output = U0;
    fn len(&self) -> Self::Output {
        UTerm
    }
}

/// Size of a `TypeArray`
impl<V, A> Len for TArr<V, A>
    where A: Len,
          Length<A>: Add<B1>,
          Sum<Length<A>, B1>: Unsigned
{
    type Output = Add1<Length<A>>;
    fn len(&self) -> Self::Output {
        unsafe { ::core::mem::uninitialized() }
    }
}

// ---------------------------------------------------------------------------------------
// Add arrays
// Note that two arrays are only addable if they are the same length.

impl Add<ATerm> for ATerm {
    type Output = ATerm;
    fn add(self, _: ATerm) -> Self::Output {
        ATerm
    }
}

impl<Al, Vl, Ar, Vr> Add<TArr<Vr, Ar>> for TArr<Vl, Al>
    where Al: Add<Ar>,
          Vl: Add<Vr>
{
    type Output = TArr<Sum<Vl, Vr>, Sum<Al, Ar>>;
    fn add(self, _: TArr<Vr, Ar>) -> Self::Output {
        unsafe { ::core::mem::uninitialized() }
    }
}

// ---------------------------------------------------------------------------------------
// Subtract arrays
// Note that two arrays are only subtractable if they are the same length.

impl Sub<ATerm> for ATerm {
    type Output = ATerm;
    fn sub(self, _: ATerm) -> Self::Output {
        ATerm
    }
}

impl<Vl, Al, Vr, Ar> Sub<TArr<Vr, Ar>> for TArr<Vl, Al>
    where Vl: Sub<Vr>,
          Al: Sub<Ar>
{
    type Output = TArr<Diff<Vl, Vr>, Diff<Al, Ar>>;
    fn sub(self, _: TArr<Vr, Ar>) -> Self::Output {
        unsafe { ::core::mem::uninitialized() }
    }
}

// ---------------------------------------------------------------------------------------
// Multiply an array by a scalar

impl<Rhs> Mul<Rhs> for ATerm {
    type Output = ATerm;
    fn mul(self, _: Rhs) -> Self::Output {
        ATerm
    }
}

impl<V, A, Rhs> Mul<Rhs> for TArr<V, A>
    where V: Mul<Rhs>,
          A: Mul<Rhs>
{
    type Output = TArr<Prod<V, Rhs>, Prod<A, Rhs>>;
    fn mul(self, _: Rhs) -> Self::Output {
        unsafe { ::core::mem::uninitialized() }
    }
}

impl Mul<ATerm> for Z0 {
    type Output = ATerm;
    fn mul(self, _: ATerm) -> Self::Output {
        ATerm
    }
}

impl<U> Mul<ATerm> for PInt<U>
    where U: Unsigned + NonZero
{
    type Output = ATerm;
    fn mul(self, _: ATerm) -> Self::Output {
        ATerm
    }
}

impl<U> Mul<ATerm> for NInt<U>
    where U: Unsigned + NonZero
{
    type Output = ATerm;
    fn mul(self, _: ATerm) -> Self::Output {
        ATerm
    }
}

impl<V, A> Mul<TArr<V, A>> for Z0
    where Z0: Mul<A>
{
    type Output = TArr<Z0, Prod<Z0, A>>;
    fn mul(self, _: TArr<V, A>) -> Self::Output {
        unsafe { ::core::mem::uninitialized() }
    }
}

impl<V, A, U> Mul<TArr<V, A>> for PInt<U>
    where U: Unsigned + NonZero,
          PInt<U>: Mul<A> + Mul<V>
{
    type Output = TArr<Prod<PInt<U>, V>, Prod<PInt<U>, A>>;
    fn mul(self, _: TArr<V, A>) -> Self::Output {
        unsafe { ::core::mem::uninitialized() }
    }
}

impl<V, A, U> Mul<TArr<V, A>> for NInt<U>
    where U: Unsigned + NonZero,
          NInt<U>: Mul<A> + Mul<V>
{
    type Output = TArr<Prod<NInt<U>, V>, Prod<NInt<U>, A>>;
    fn mul(self, _: TArr<V, A>) -> Self::Output {
        unsafe { ::core::mem::uninitialized() }
    }
}

// ---------------------------------------------------------------------------------------
// Divide an array by a scalar

impl<Rhs> Div<Rhs> for ATerm {
    type Output = ATerm;
    fn div(self, _: Rhs) -> Self::Output {
        ATerm
    }
}

impl<V, A, Rhs> Div<Rhs> for TArr<V, A>
    where V: Div<Rhs>,
          A: Div<Rhs>
{
    type Output = TArr<Quot<V, Rhs>, Quot<A, Rhs>>;
    fn div(self, _: Rhs) -> Self::Output {
        unsafe { ::core::mem::uninitialized() }
    }
}

// ---------------------------------------------------------------------------------------
// Partial Divide an array by a scalar

impl<Rhs> PartialDiv<Rhs> for ATerm {
    type Output = ATerm;
    fn partial_div(self, _: Rhs) -> Self::Output {
        ATerm
    }
}

impl<V, A, Rhs> PartialDiv<Rhs> for TArr<V, A>
    where V: PartialDiv<Rhs>,
          A: PartialDiv<Rhs>
{
    type Output = TArr<PartialQuot<V, Rhs>, PartialQuot<A, Rhs>>;
    fn partial_div(self, _: Rhs) -> Self::Output {
        unsafe { ::core::mem::uninitialized() }
    }
}

// ---------------------------------------------------------------------------------------
// Modulo an array by a scalar
use core::ops::Rem;

impl<Rhs> Rem<Rhs> for ATerm {
    type Output = ATerm;
    fn rem(self, _: Rhs) -> Self::Output {
        ATerm
    }
}

impl<V, A, Rhs> Rem<Rhs> for TArr<V, A>
    where V: Rem<Rhs>,
          A: Rem<Rhs>
{
    type Output = TArr<Mod<V, Rhs>, Mod<A, Rhs>>;
    fn rem(self, _: Rhs) -> Self::Output {
        unsafe { ::core::mem::uninitialized() }
    }
}

// ---------------------------------------------------------------------------------------
// Negate an array
use core::ops::Neg;

impl Neg for ATerm {
    type Output = ATerm;
    fn neg(self) -> Self::Output {
        ATerm
    }
}

impl<V, A> Neg for TArr<V, A>
    where V: Neg,
          A: Neg
{
    type Output = TArr<Negate<V>, Negate<A>>;
    fn neg(self) -> Self::Output {
        unsafe { ::core::mem::uninitialized() }
    }
}

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
#ifndef _WX_GTKDCCLIENT_H_
#define _WX_GTKDCCLIENT_H_

#include "wx/gtk/dc.h"
#include "wx/dcclient.h"
#include "wx/region.h"

class WXDLLIMPEXP_FWD_CORE wxWindow;

//-----------------------------------------------------------------------------
// wxWindowDCImpl
//-----------------------------------------------------------------------------

class WXDLLIMPEXP_CORE wxWindowDCImpl : public wxGTKDCImpl
{
public:
    wxWindowDCImpl( wxDC *owner );
    wxWindowDCImpl( wxDC *owner, wxWindow *win );

    virtual ~wxWindowDCImpl();

    virtual bool CanDrawBitmap() const { return true; }
    virtual bool CanGetTextExtent() const { return true; }

    virtual void DoGetSize(int *width, int *height) const;
    virtual bool DoFloodFill( wxCoord x, wxCoord y, const wxColour& col,
                              wxFloodFillStyle style=wxFLOOD_SURFACE );
    virtual bool DoGetPixel( wxCoord x1, wxCoord y1, wxColour *col ) const;

    virtual void DoDrawLine( wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2 );
    virtual void DoCrossHair( wxCoord x, wxCoord y );
    virtual void DoDrawArc( wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2,
                            wxCoord xc, wxCoord yc );
    virtual void DoDrawEllipticArc( wxCoord x, wxCoord y, wxCoord width, wxCoord height,
                                    double sa, double ea );
    virtual void DoDrawPoint( wxCoord x, wxCoord y );

    virtual void DoDrawLines(int n, wxPoint points[],
                             wxCoord xoffset, wxCoord yoffset);
    virtual void DoDrawPolygon(int n, wxPoint points[],
                               wxCoord xoffset, wxCoord yoffset,
                               wxPolygonFillMode fillStyle = wxODDEVEN_RULE);

    virtual void DoDrawRectangle( wxCoord x, wxCoord y, wxCoord width, wxCoord height );
    virtual void DoDrawRoundedRectangle( wxCoord x, wxCoord y, wxCoord width, wxCoord height, double radius = 20.0 );
    virtual void DoDrawEllipse( wxCoord x, wxCoord y, wxCoord width, wxCoord height );

    virtual void DoDrawIcon( const wxIcon &icon, wxCoord x, wxCoord y );
    virtual void DoDrawBitmap( const wxBitmap &bitmap, wxCoord x, wxCoord y,
                               bool useMask = false );

    virtual bool DoBlit( wxCoord xdest, wxCoord ydest,
                         wxCoord width, wxCoord height,
                         wxDC *source, wxCoord xsrc, wxCoord ysrc,
                         wxRasterOperationMode logical_func = wxCOPY,
                         bool useMask = false,
                         wxCoord xsrcMask = -1, wxCoord ysrcMask = -1 );

    virtual void DoDrawText( const wxString &text, wxCoord x, wxCoord y );
    virtual void DoDrawRotatedText(const wxString& text, wxCoord x, wxCoord y,
                                   double angle);
    virtual void DoGetTextExtent( const wxString &string,
                                wxCoord *width, wxCoord *height,
                                wxCoord *descent = NULL,
                                wxCoord *externalLeading = NULL,
                                const wxFont *theFont = NULL) const;
    virtual bool DoGetPartialTextExtents(const wxString& text, wxArrayInt& widths) const;
    virtual void DoSetClippingRegion( wxCoord x, wxCoord y, wxCoord width, wxCoord height );
    virtual void DoSetDeviceClippingRegion( const wxRegion &region );

    virtual wxCoord GetCharWidth() const;
    virtual wxCoord GetCharHeight() const;

    virtual void Clear();

    virtual void SetFont( const wxFont &font );
    virtual void SetPen( const wxPen &pen );
    virtual void SetBrush( const wxBrush &brush );
    virtual void SetBackground( const wxBrush &brush );
    virtual void SetLogicalFunction( wxRasterOperationMode function );
    virtual void SetTextForeground( const wxColour &col );
    virtual void SetTextBackground( const wxColour &col );
    virtual void SetBackgroundMode( int mode );
    virtual void SetPalette( const wxPalette& palette );

    virtual void DestroyClippingRegion();

    // Resolution in pixels per logical inch
    virtual wxSize GetPPI() const;
    virtual int GetDepth() const;

    // overrriden here for RTL
    virtual void SetDeviceOrigin( wxCoord x, wxCoord y );
    virtual void SetAxisOrientation( bool xLeftRight, bool yBottomUp );

// protected:
    // implementation
    // --------------

    GdkWindow    *m_gdkwindow;
    GdkGC        *m_penGC;
    GdkGC        *m_brushGC;
    GdkGC        *m_textGC;
    GdkGC        *m_bgGC;
    GdkColormap  *m_cmap;
    bool          m_isScreenDC;
    wxRegion      m_currentClippingRegion;
    wxRegion      m_paintClippingRegion;

    // PangoContext stuff for GTK 2.0
    PangoContext *m_context;
    PangoLayout *m_layout;
    PangoFontDescription *m_fontdesc;

    void SetUpDC( bool ismem = false );
    void Destroy();

    virtual void ComputeScaleAndOrigin();

    virtual GdkWindow *GetGDKWindow() const { return m_gdkwindow; }

private:
    void DrawingSetup(GdkGC*& gc, bool& originChanged);
    GdkPixmap* MonoToColor(GdkPixmap* monoPixmap, int x, int y, int w, int h) const;

    DECLARE_ABSTRACT_CLASS(wxWindowDCImpl)
};

//-----------------------------------------------------------------------------
// wxClientDCImpl
//-----------------------------------------------------------------------------

class WXDLLIMPEXP_CORE wxClientDCImpl : public wxWindowDCImpl
{
public:
    wxClientDCImpl( wxDC *owner );
    wxClientDCImpl( wxDC *owner, wxWindow *win );

    virtual void DoGetSize(int *width, int *height) const;

    DECLARE_ABSTRACT_CLASS(wxClientDCImpl)
};

//-----------------------------------------------------------------------------
// wxPaintDCImpl
//-----------------------------------------------------------------------------

class WXDLLIMPEXP_CORE wxPaintDCImpl : public wxClientDCImpl
{
public:
    wxPaintDCImpl( wxDC *owner );
    wxPaintDCImpl( wxDC *owner, wxWindow *win );

    DECLARE_ABSTRACT_CLASS(wxPaintDCImpl)
};

#endif // _WX_GTKDCCLIENT_H_


text:
#include <sys/time.h>
#include <math.h>
#include <time.h>

#include "rtpp_time.h"

static double
_getdtime(clockid_t clock_id)
{
    struct timespec tp;

    if (clock_gettime(clock_id, &tp) == -1)
        return (-1);

    return timespec2dtime(&tp);
}

double
getdtime(void)
{

    return (_getdtime(RTPP_CLOCK_MONO));
}

void
rtpp_timestamp_get(struct rtpp_timestamp *tp)
{

    tp->wall = _getdtime(RTPP_CLOCK_REAL);
    tp->mono = _getdtime(RTPP_CLOCK_MONO);
}

void
dtime2mtimespec(double dtime, struct timespec *mtime)
{

    SEC(mtime) = trunc(dtime);
    NSEC(mtime) = round((double)NSEC_MAX * (dtime - (double)SEC(mtime)));
}

void
dtime2timeval(double dtime, struct timeval *tvp)
{

    SEC(tvp) = trunc(dtime);
    USEC(tvp) = round((double)USEC_MAX * (dtime - (double)SEC(tvp)));
}

const char *
get_mclock_name(void)
{

    return (RTPP_MCLOCK_NAME);
}


text:
    {{_internalModelValue}}{{unit}}
    <input ng-show="editable" class="form-control" type="number" ng-model="_internalModelValue" min="{{min}}" max="{{max}}" step="{{step}}" style="width: 100%;" placeholder="{{placeholder}}">
    {{unit}}


text:
package pl.exsio.ck.entrytable.view;

import javax.swing.JPanel;
import javax.swing.JTable;
import pl.exsio.ck.entrytable.presenter.EntryTablePresenter;

/**
 *
 * @author exsio
 */
public abstract class AbstractEntryTablePanel extends JPanel {

    protected EntryTablePresenter presenter;

    public void setPresenter(EntryTablePresenter presenter) {
        this.presenter = presenter;
    }

    public abstract JTable getEntryTable();
}


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

    <string name="app_name">ADB_WIFI_For_Eclipse</string>
    <string name="hello_world">Powered By oneym</string>
    <string name="action_settings">Settings</string>
    <string name="start_but">Start</string>
    <string name="stop_but">Stop</string>

</resources>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WhereToMeet.Transporters.Input
{
    public class PlacesQueryTransporter
    {
        public double Latitude { get; set; }
        public double Longitude { get; set; }

        public int Radius { get; set; }
        public IEnumerable<string>  PlacesTypes { get; set; }
    }
}


text:
Authentication
==============

There are two approaches for handing authentication. One is provided by the URL
loading system through classes like `NSURLCredential`, `NSURLProtectionSpace`,
`NSURLAuthenticationChallenge`, etc. The other is to prepare the request manually
or through Processor objects.

Authentication through URL loading system
-----------------------------------------

To add authentication support through URL loading system, you can create an
object of `Authentication` subclass, like `BasicAuthentication`. Add this
`Authentication` subclass object in an array and pass the array to the convenient
method as parameter `authentications`, or assign the array to property
`authentications` if you are creating a `Cycle` manually::

  var auth = BasicAuthentication(username: "test", password: "12345")
  Cycle.get("http://127.0.0.1:8000/test/hello_with_basic_auth",
      authentications: [auth],
      completionHandler: {
          (cycle, error) in
          println("\(cycle.response.text)") // Hello World
      })

The `BasicAuthentication` object can handle three authentication methods: Basic,
Digest and NTLM.

Prepare request manually for authentication
-------------------------------------------

There are authentication methods the `Authentication` classes don't support. And
in some situations, preparing requests manually is the only option. Take GitHub
API's Basic Authentication as an example, for unauthenticated requests, the
GitHub API responds with `404 Not Found`, instead of `401 Unauthorized`. In such
case, URL loading system's authentication routes won't be triggered.

The solution is to manually craft the `Authorization` header. Using Processor
objects can be a perfect choice for this task::

  Cycle.get("https://api.github.com/user/",
      requestProcessors: [BasicAuthProcessor(username: "user", password: "pass")],
      responseProcessors: [JSONProcessor()],
      completionHandler: { (cycle, error) in
          println("\(cycle.response.statusCode)") // 200
          var header = cycle.response.valueForHTTPHeaderField("content-type")
          println("\(header)") // application/json; charset=utf-8
          println("\(cycle.response.textEncoding)") // 4
          println("\(cycle.response.text)") // {"login":"user","id":3 ...
          println("\(cycle.response.object)") // {"avatar_url" = ...
      })

In this code snippet, a BasicAuthProcessor object was created and passed into
the convenient method as parameter `requestProcessors`. Before the request is
sent, the BasicAuthProcessor object will craft and set the `Authorization`
header.


text:
title: Reactのイベントコールバックで非同期にeventオブジェクトを参照する
date: 2016-10-12 19:30 JST
tags: React
description: Reactのイベントコールバックにおいて、非同期的にeventオブジェクトを参照しようとするとエラーが出て怒られる。その原因と解決法について。
published: true
---

Reactでイベントコールバックの`event`オブジェクトに非同期でアクセスしようとするとエラーが出て怒られる。例えば、`setState`の第二引数のコールバック内で`event`を参照しようとした時とか。

function clickHandler(event) {
  this.setState({
    foo: 'bar'
  }, function () {
    console.log(event.target.value); // error
  });
}

## なぜ参照できないか

Reactのドキュメントの[Event pooling](https://facebook.github.io/react/docs/events.html#event-pooling)に書いてあった。

> The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.

簡単に説明すると、`event`オブジェクトはReactによって`SyntheticEvent`オブジェクトとしてラップされていて、パフォーマンスのために使いまわしてますよ。その関係で、イベントコールバックが実行され終わったら全てのプロパティを`null`にするから、非同期ではアクセスできませんよ、ということらしい。

## 解決策

これもドキュメントの同じ項に書かれている。

> If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

非同期でアクセスしたかったら`event.persist()`使ってくれ、と書かれている。なのでイベントコールバックの中で呼んであげれば非同期で`event`を参照することができる。

function clickHandler(event) {
  event.persist();

  this.setState({
    foo: 'bar'
  }, function () {
    console.log(event.target.value); // ok
  });
}


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="generator" content="ApiGen 2.8.0" />

	<title>Package RestApi\Objects | Demo Json Service</title>

	<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360" />

		Overview

Packages

RestApi

Objects

Services

Classes

ManufacturerJson

ProductCategoryJson

ProductJson

ProductQueryJson

	<form id="search">
		<input type="hidden" name="cx" value="" />
		<input type="hidden" name="ie" value="UTF-8" />
		<input type="text" name="q" class="text" />
		<input type="submit" value="Search" />
	</form>

				Overview

Package

Class

				Tree

				Todo

Package RestApi\Objects

Classes summary

	ManufacturerJson
	Json representation of the Manufacturer AR model.

	ProductCategoryJson
	Json representation of the Product Category AR model.

	ProductJson
	Json representation of the Product AR model.

	ProductQueryJson
	Product query object.

		Demo Json Service API documentation generated by ApiGen 2.8.0


text:
Kanban: Choose your own adventure

Audience led talk for [BCS Lean/Kanban Day 2014](http://www.bcs.org/category/18004)


text:
import copy
import random
from typing import Dict, Tuple, List

import math

from customCsvReader import CustomCSVReader
from decisionTree import ID3, Node

class ID3Pruning:

    def prune(self, tree, validation_set):
        """
        Main algorithm for doing Reduced error pruning
        This is a bottom up algorithm that starts at the bottom of the tree and replaces
        nodes with the majority label.
        The new tree is tested to see if the error rate has improved. If so, keep the change, if not revert.

        Psuedo code:

        change_made_to_tree = false
        while change_made_to_tree true && tree(root).class_label is None
            change_made_to_tree = false
            get leaf node parents
            for each leaf node parent
                get the majority label for that node
                replace the node with majority class label

                Test tree on validation set
                If improved accuracy (or same), keep
                    change_made_to_tree = true

        """
        best_error_rate = self.get_error_rate(tree, validation_set)

        change_made_to_tree = True
        while change_made_to_tree and tree.class_label is None:

            change_made_to_tree = False
            nodes_to_remove = self.get_leaf_parents(tree)

            for node in nodes_to_remove:
                majority_label = self.get_majority_label(node)

                node.class_label = majority_label
                node.is_terminal = True

                error_rate = self.get_error_rate(tree, validation_set)
                if error_rate <= best_error_rate:
                    best_error_rate = error_rate
                    change_made_to_tree = True
                    node.children = []
                else:
                    node.class_label = None
                    node.is_terminal = False

        return tree

    def get_leaf_parents(self, tree):
        """
        A BFS algorithm that searches to find all parents of leaf nodes.
        returns a list of nodes that are parents of leaf nodes.
        """
        current_node = tree
        frontier = [current_node]
        explored = []

        list_of_leaf_parents = []

        while frontier:

            current_node = frontier.pop(0)

            if self.is_parent_of_only_leaf_nodes(current_node):
                list_of_leaf_parents.append(current_node)
            else:
                frontier += current_node.children

            explored.append(current_node)

        return list_of_leaf_parents

    def is_parent_of_only_leaf_nodes(self, node: Node):
        """
        A helper function to check if a node is a parent of only leaf nodes.
        This is important so that we do not get intermediate nodes to try and replace.
        """
        if node.is_terminal:
            return False

        for child in node.children:
            if not child.is_terminal:
                return False
        return True

    def get_majority_label(self, node: Node) -> str:
        """
        returns the majority for a node that is a likely a parent node of a leaf
        Uses a BFS

        """
        num_label = {}

        current_node = node
        frontier = [current_node]
        explored = []

        while frontier:
            current_node = frontier.pop(0)

            if current_node.is_terminal:
                label = current_node.class_label
                if label not in num_label.keys():
                    num_label[label] = 1
                else:
                    num_label[label] += 1
            else:
                frontier += current_node.children

        return max(num_label, key=num_label.get)

    def get_error_rate(self, tree: Node, validation_set: List[list]) -> float:
        """
        A helper function that calculates the error rate of a tree.
        Uses the ID3 classificaiton and evaluation function to get the results.

        Used to determine if a tree got bettter of not.
        """
        id3 = ID3()
        classifications = id3.classify(tree, validation_set)
        error_rate = id3.evaluate(validation_set, classifications)
        # print(error_rate)
        return error_rate

""" Local Test for correctness """
# reader = CustomCSVReader()
# # data = reader.read_file('data/segmentation.data.new.txt', float)
# data = reader.read_file('data/car.data.txt', str)
# # data = reader.read_file('data/abalone.data.txt', float)
#
# random.shuffle(data)
#
# half_way = int(math.floor(len(data)/3)) * 2
# set_1 = data[:half_way]
# set_2 = data[half_way:]
#
# id3 = ID3()
#
# tree_1 = id3.learn(set_1)
# tree1_dot = id3.view(tree_1)
# tree1_dot.render('test_original', view=True)
# # print("Original Tree Node Count = {}".format(id3.node_count(tree_1)))
#
# prune = ID3Pruning()
# pruned_tree = prune.prune(copy.deepcopy(tree_1), set_2)
#
# classification_original = id3.classify(tree_1, set_2)
# classification_pruned = id3.classify(pruned_tree, set_2)
#
# error_rate_original = id3.evaluate(set_2, classification_original)
# error_rate_pruned = id3.evaluate(set_2, classification_pruned)
#
# print(error_rate_original)
# print(error_rate_pruned)

# pruned_tree_dot = id3.view(pruned_tree)
# pruned_tree_dot.render('test_pruned', view=True)
#
# print("Original Tree Node Count = {}".format(id3.node_count(tree_1)))
# print("Pruned Tree Node Count = {}".format(id3.node_count(pruned_tree)))


text:
"""Unit test runner for Web Development Style Guide checks."""

from web_dev_style import css_checker_test, \
                          html_checker_test, \
                          js_checker_test, \
                          resource_checker_test

_TEST_MODULES = [
    css_checker_test,
    html_checker_test,
    js_checker_test,
    resource_checker_test
]

for test_module in _TEST_MODULES:
  test_module.unittest.main(test_module)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Arbiter: Arbiter::Requirement::Visitor Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Arbiter

Dependency manager library that supports decentralization

Arbiter

Requirement

Visitor

Public Member Functions |
List of all members

Arbiter::Requirement::Visitor Class Referenceabstract

Base class for objects that want to visit requirements.
 More...

Public Member Functions

virtual 	~Visitor ()=default

virtual void 	operator() (const ArbiterRequirement &requirement)=0

Detailed Description

Base class for objects that want to visit requirements.

Definition at line 71 of file Requirement.h.

Constructor & Destructor Documentation

§ ~Visitor()

          virtual Arbiter::Requirement::Visitor::~Visitor
          (
          	)

virtualdefault

Member Function Documentation

§ operator()()

          virtual void Arbiter::Requirement::Visitor::operator()
          (
          const ArbiterRequirement &
          requirement	)

pure virtual

The documentation for this class was generated from the following file:

src/Requirement.h

<address class="footer">
Generated on Mon Sep 26 2016 15:09:08 for Arbiter by

 1.8.12
</address>


text:
title: Destructuring Assignment
---

## Destructuring Assignment

Destructuring Assignment syntax is a Javascript expression that makes it possible to unpack values or properties from arrays or objects.

Lets say that you have an array that contains a first name and last name as it's two values, but you want to reassign those values to something more descriptive. You can use Destructuring to accomplish this.

**ES5 Destructuring**

```js
var fullName = ["John", "Smith"];
var firstName = fullName[0];
var lastName = fullName[1];

console.log(firstName, lastName); // John Smith

```

**ES6 Destructuring**

```js
const fullName = ["John", "Smith"];
const [firstName, lastName] = fullName;

console.log(firstName, lastName); // John Smith

```

The examples above show the benefit of using the ES6 Destructuring Assignment.

You can also use Destructuring on objects using a similar syntax

```js
const fullName = { first: "John", last: "Smith"};
const {first, last} = fullName;

console.log(first, last); // John Smith
```

Object Destructuring Assignment is a little bit different because the object must have properties with the names you are assigning. Therefore the code below would not work as intended.

```js
const fullName = { first: "John", last: "Smith"};
const {firstName, lastName} = fullName;

console.log(firstName, lastName); // undefined undefined
```

You can still achieve the desired result using the following syntax.
```js
const obj = {propertyName: value}
const {propertyName: desiredVariableName} = obj
```

Our previous example would be rewritten as follows:
```js
const fullName = { first: "John", last: "Smith"};
const {first: firstName, last: lastName} = fullName;

console.log(firstName, lastName); // John Smith
```
**Array Destructuring with rest**
When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:
```js
const [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]
```


text:
import { Meteor } from 'meteor/meteor';

Meteor.startup(() => {
   Meteor.startup(function() {
     SSLProxy({
        port: 3100, //or 443 (normal port/requires sudo)
        ssl : {
             key: Assets.getText("server.key"),
             cert: Assets.getText("server.crt"),

             //Optional CA
             //Assets.getText("ca.pem")
        }
     });
 });
});


text:
package ua.com.fielden.platform.web.menu;

import ua.com.fielden.platform.web.menu.module.IModuleConfigDone;

public interface IModuleMenuConfigWithDone extends IModuleMenuConfig {

    IModuleConfigDone done();
}


text:
function _resamplerJs() {

    function Resampler(fromSampleRate, toSampleRate, channels, outputBufferSize, noReturn) {
        this.fromSampleRate = fromSampleRate;
        this.toSampleRate = toSampleRate;
        this.channels = channels | 0;
        this.outputBufferSize = outputBufferSize;
        this.noReturn = !!noReturn;
        this.initialize();
    }

    Resampler.prototype.initialize = function () {
        //Perform some checks:
        if (this.fromSampleRate <= 0 || this.toSampleRate <= 0 || this.channels <= 0) {
            throw(new Error("Invalid settings specified for the resampler."));
        }

        if (this.fromSampleRate == this.toSampleRate) {
            //Setup a resampler bypass:
            this.resampler = this.bypassResampler;    	//Resampler just returns what was passed through.
            this.ratioWeight = 1;
        } else {

            //Resampler is a custom quality interpolation algorithm.
            this.resampler = function (buffer) {
                var bufferLength = Math.min(buffer.length, this.outputBufferSize);

                if ((bufferLength % this.channels) != 0) {
                    throw(new Error("Buffer was of incorrect sample length."));
                }

                if (bufferLength <= 0) {
                    return (this.noReturn) ? 0 : [];
                }

                var weight = 0;
                var output = new Array(this.channels);
                for (var channel = 0; channel < this.channels; ++channel) {
                    output[channel] = 0;
                }
                var actualPosition = 0;
                var amountToNext = 0;
                var alreadyProcessedTail = !this.tailExists;
                this.tailExists = false;
                var outputBuffer = this.outputBuffer;
                var outputOffset = 0;
                var currentPosition = 0;
                var ratioWeight = this.ratioWeight;
                do {
                    if (alreadyProcessedTail) {
                        weight = ratioWeight;
                        for (channel = 0; channel < this.channels; ++channel) {
                            output[channel] = 0;
                        }
                    } else {
                        weight = this.lastWeight;
                        for (channel = 0; channel < this.channels; ++channel) {
                            output[channel] = this.lastOutput[channel];
                        }
                        alreadyProcessedTail = true;
                    }

                    while (weight > 0 && actualPosition < bufferLength) {
                        amountToNext = 1 + actualPosition - currentPosition;
                        if (weight >= amountToNext) {
                            for (channel = 0; channel < this.channels; ++channel) {
                                output[channel] += buffer[actualPosition++] * amountToNext;
                            }
                            currentPosition = actualPosition;
                            weight -= amountToNext;
                        } else {
                            for (channel = 0; channel < this.channels; ++channel) {
                                output[channel] += buffer[actualPosition + ((channel > 0) ? channel : 0)] * weight;
                            }
                            currentPosition += weight;
                            weight = 0;
                            break;
                        }
                    }

                    if (weight == 0) {
                        for (channel = 0; channel < this.channels; ++channel) {
                            outputBuffer[outputOffset++] = output[channel] / ratioWeight;
                        }
                    } else {
                        this.lastWeight = weight;
                        for (channel = 0; channel < this.channels; ++channel) {
                            this.lastOutput[channel] = output[channel];
                        }
                        this.tailExists = true;
                        break;
                    }
                } while (actualPosition < bufferLength);

                return this.bufferSlice(outputOffset);
            };
            this.ratioWeight = this.fromSampleRate / this.toSampleRate;
            this.tailExists = false;
            this.lastWeight = 0;
            this.initializeBuffers();
        }
    };
    Resampler.prototype.bypassResampler = function (buffer) {
        if (this.noReturn) {
            //Set the buffer passed as our own, as we don't need to resample it:
            this.outputBuffer = buffer;
            return buffer.length;
        } else {
            //Just return the buffer passsed:
            return buffer;
        }
    };
    Resampler.prototype.bufferSlice = function (sliceAmount) {
        if (this.noReturn) {
            //If we're going to access the properties directly from this object:
            return sliceAmount;
        } else {
            //Typed array and normal array buffer section referencing:
            try {
                return this.outputBuffer.subarray(0, sliceAmount);
            }
            catch (error) {
                try {
                    //Regular array pass:
                    this.outputBuffer.length = sliceAmount;
                    return this.outputBuffer;
                }
                catch (error) {
                    //Nightly Firefox 4 used to have the subarray function named as slice:
                    return this.outputBuffer.slice(0, sliceAmount);
                }
            }
        }
    };
    Resampler.prototype.initializeBuffers = function () {
        //Initialize the internal buffer:
        try {
            this.outputBuffer = new Float32Array(this.outputBufferSize);
            this.lastOutput = new Float32Array(this.channels);
        }
        catch (error) {
            this.outputBuffer = [];
            this.lastOutput = [];
        }
    };

    navigator.Resampler = Resampler;

}

_resamplerJs();
function _recorderWorkerJs() {

    var recLength = 0,
        recBuffers = [],
        sampleRate,
        resampler;

    this.onmessage = function (e) {
        switch (e.data.command) {
            case 'init':
                init(e.data.config);
                break;
            case 'record':
                record(e.data.buffer);
                break;
            case 'export16kMono':
                export16kMono(e.data.type);
                break;
            case 'getBuffer':
                getBuffer();
                break;
            case 'clear':
                clear();
                break;
        }
    };

    function init(config) {
        // Invoke initializer to register Resampler within navigator object
        (new Function(config.resamplerInitializerBody))();

        sampleRate = config.sampleRate;
        resampler = new navigator.Resampler(sampleRate, 16000, 1, 50 * 1024);
    }

    function record(inputBuffer) {
        recBuffers.push(inputBuffer[0]);
        recLength += inputBuffer[0].length;
    }

    function export16kMono(type) {
        var buffer = mergeBuffers(recBuffers, recLength);
        var samples = resampler.resampler(buffer);
        var dataview = encodeRAW(samples);
        var audioBlob = new Blob([dataview], {type: type});

        this.postMessage(audioBlob);
    }

    function getBuffer() {
        var buffers = [];
        buffers.push(mergeBuffers(recBuffers, recLength));
        this.postMessage(buffers);
    }

    function clear() {
        recLength = 0;
        recBuffers = [];
    }

    function mergeBuffers(recBuffers, recLength) {
        var result = new Float32Array(recLength);
        var offset = 0;
        for (var i = 0; i < recBuffers.length; i++) {
            result.set(recBuffers[i], offset);
            offset += recBuffers[i].length;
        }
        return result;
    }

    function _floatTo16BitPCM(output, offset, input) {
        for (var i = 0; i < input.length; i++, offset += 2) {
            var s = Math.max(-1, Math.min(1, input[i]));
            output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
        }
    }

    function _writeString(view, offset, string) {
        for (var i = 0; i < string.length; i++) {
            view.setUint8(offset + i, string.charCodeAt(i));
        }
    }

    function encodeWAV(samples) {
        var buffer = new ArrayBuffer(44 + samples.length * 2);
        var view = new DataView(buffer);

        /* RIFF identifier */
        _writeString(view, 0, 'RIFF');
        /* file length */
        view.setUint32(4, 32 + samples.length * 2, true);
        /* RIFF type */
        _writeString(view, 8, 'WAVE');
        /* format chunk identifier */
        _writeString(view, 12, 'fmt ');
        /* format chunk length */
        view.setUint32(16, 16, true);
        /* sample format (raw) */
        view.setUint16(20, 1, true);
        /* channel count */
        view.setUint16(22, 2, true);
        /* sample rate */
        view.setUint32(24, sampleRate, true);
        /* byte rate (sample rate * block align) */
        view.setUint32(28, sampleRate * 4, true);
        /* block align (channel count * bytes per sample) */
        view.setUint16(32, 4, true);
        /* bits per sample */
        view.setUint16(34, 16, true);
        /* data chunk identifier */
        _writeString(view, 36, 'data');
        /* data chunk length */
        view.setUint32(40, samples.length * 2, true);

        _floatTo16BitPCM(view, 44, samples);

        return view;
    }

    function encodeRAW(samples) {
        var buffer = new ArrayBuffer(samples.length * 2);
        var view = new DataView(buffer);
        _floatTo16BitPCM(view, 0, samples);
        return view;
    }

}
(function () {

    function Recorder(source, cfg) {
        var config = cfg || {};
        var bufferLen = config.bufferLen || 4096;
        this.context = source.context;
        this.node = this.context.createScriptProcessor(bufferLen, 1, 1);
        var worker = new Worker(_getRecorderWorkerUrl());
        worker.postMessage({
            command: 'init',
            config: {
                sampleRate: this.context.sampleRate,
                resamplerInitializerBody: _getFuntionBody(_resamplerJs)
            }
        });
        var recording = false,
            currCallback;

        this.node.onaudioprocess = function (e) {
            if (!recording) return;
            worker.postMessage({
                command: 'record',
                buffer: [
                    e.inputBuffer.getChannelData(0)
                ]
            });
        };

        this.configure = function (cfg) {
            for (var prop in cfg) {
                if (cfg.hasOwnProperty(prop)) {
                    config[prop] = cfg[prop];
                }
            }
        };

        this.record = function () {
            recording = true;
        };

        this.stop = function () {
            recording = false;
        };

        this.clear = function () {
            worker.postMessage({command: 'clear'});
        };

        this.getBuffer = function (cb) {
            currCallback = cb || config.callback;
            worker.postMessage({command: 'getBuffer'})
        };

        this.export16kMono = function (cb, type) {
            currCallback = cb || config.callback;
            type = type || config.type || 'audio/raw';
            if (!currCallback) throw new Error('Callback not set');
            worker.postMessage({
                command: 'export16kMono',
                type: type
            });
        };

        worker.onmessage = function (e) {
            currCallback(e.data);
        };

        source.connect(this.node);
        this.node.connect(this.context.destination);
    }

    function _getRecorderWorkerUrl() {
        var getBlobUrl = (window.URL && URL.createObjectURL.bind(URL)) ||
            (window.webkitURL && webkitURL.createObjectURL.bind(webkitURL)) ||
            window.createObjectURL;

        return getBlobUrl(new Blob([_getFuntionBody(_recorderWorkerJs)], {type: 'text/javascript'}));
    }

    function _getFuntionBody(fn) {
        if (typeof fn !== 'function') {
            throw new Error("Illegal argument exception: argument is not a funtion: " + fn);
        }
        var fnStr = fn.toString(),
            start = fnStr.indexOf('{'),
            fin = fnStr.lastIndexOf('}');

        return (start > 0 && fin > 0) ? fnStr.substring(start + 1, fin) : fnStr;
    }

    window.Recorder = Recorder;

})();(function () {

    window.AudioContext = window.AudioContext || window.webkitAudioContext;

    AudioContext.prototype.createResampleProcessor = function (bufferSize, numberOfInputChannels, numberOfOutputChannels, destinationSampleRate) {
        var script_processor = this.createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels);
        var resampler = new navigator.Resampler(this.sampleRate, destinationSampleRate, numberOfInputChannels, bufferSize, true);

        script_processor.onaudioprocess = function (event) {
            var inp = event.inputBuffer.getChannelData(0);
            var out = event.outputBuffer.getChannelData(0);
            var l = resampler.resampler(inp);
            for (var i = 0; i < l; ++i) {
                out[i] = resampler.outputBuffer[i];
            }
        };

        return script_processor;
    };

    function MagicBuffer(chunkSize) {
        this.chunkSize = chunkSize;
        this.array_data = [];

        this.callback = null;
    }

    MagicBuffer.prototype.push = function (array) {
        var l = array.length;
        var new_array = new Array(Math.ceil(l / 2));

        for (var i = 0; i < l; i += 2) {
            new_array[i / 2] = array[i];
        }

        Array.prototype.push.apply(this.array_data, new_array);
        this.process();
    };

    MagicBuffer.prototype.process = function () {
        var elements;
        while (this.array_data.length > this.chunkSize) {
            elements = this.array_data.splice(0, this.chunkSize);

            if (this.callback) {
                this.callback(elements);
            }
        }
    };

    MagicBuffer.prototype.drop = function () {
        this.array_data.splice(0, this.array_data.length);
    };

    AudioContext.prototype.createEndOfSpeechProcessor = function (bufferSize) {
        var script_processor = this.createScriptProcessor(bufferSize, 1, 1);

        script_processor.endOfSpeechCallback = null;

        var vad = new VAD();

        script_processor.vad = vad;

        var buffer = new MagicBuffer(160);

        buffer.callback = function (elements) {
            var vad_result = vad.process(elements);

            if (vad_result !== 'CONTINUE' && script_processor.endOfSpeechCallback) {
                script_processor.endOfSpeechCallback();
                buffer.drop();
            }
        };

        script_processor.onaudioprocess = function (event) {
            var inp = event.inputBuffer.getChannelData(0);
            var out = event.outputBuffer.getChannelData(0);
            buffer.push(inp);

            for (var i = 0; i < inp.length; i++) {
                out[i] = inp[i];
            }
        };

        return script_processor;
    };

})();(function () {

    function VAD() {
        this.reset()
    }

    VAD.prototype.process = function (frame) {
        var active = this.frameActive(frame);
        this.time = this.frameNumber * 160.0 / 16000.0;

        if (active) {
            if (this.lastActiveTime >= 0 && (this.time - this.lastActiveTime) < this.silenceLengthMilis) {
                this.sequenceCounter++;
                if (this.sequenceCounter >= this.minSequenceCount) {
                    this.lastSequenceTime = this.time;
                    this.silenceLengthMilis = Math.max(this.minSilenceLengthMilis, this.silenceLengthMilis - (this.maxSilenceLengthMilis - this.minSilenceLengthMilis) / 4.0);
                }
            } else {
                this.sequenceCounter = 1;
            }

            this.lastSequenceTime = this.time;
        } else {
            if (this.time - this.lastSequenceTime > this.silenceLengthMilis) {
                if (this.lastSequenceTime > 0) {
                    return 'TERMINATE';
                } else {
                    return 'NO_SPEECH';
                }
            }
        }

        return 'CONTINUE';
    };

    VAD.prototype.frameActive = function (frame) {
        var energy = 0;
        var czCount = 0;

        var lastsign = 0;
        var frame_length = frame.length;

        for (var i = 0; i < frame_length; i++) {
            energy += (frame[i] * frame[i]) / 160.0;

            var sign = 0;
            if (frame[i] > 0) {
                sign = 1;
            } else {
                sign = -1;
            }

            if (lastsign != 0 && sign != lastsign) {
                czCount++;
            }

            lastsign = sign;
        }

        this.frameNumber += 1;

        var result = false;

        if (this.frameNumber < this.noiseFrames) {
            this.noiseEnergy += energy / this.noiseFrames;
            console.log('noiseEnergy=', this.noiseEnergy);
        } else {
            if (czCount >= this.minCZ && czCount <= this.maxCZ) {
                if (energy > /*this.noiseEnergy*/ Math.max(0.01, this.noiseEnergy) * this.energyFactor) {
                    result = true;
                }
            }
        }

        return result;
    };

    VAD.prototype.reset = function () {
        this.minCZ = 5;
        this.maxCZ = 15;

        this.frameLengthMilis = 10.0;
        this.maxSilenceLengthMilis = 3.5;
        this.minSilenceLengthMilis = 0.8;
        this.silenceLengthMilis = this.maxSilenceLengthMilis;
        this.sequenceLengthMilis = 0.03;
        this.minSequenceCount = 3;
        this.energyFactor = 3.1;

        this.noiseFrames = Math.round(150. / this.frameLengthMilis);
        this.noiseEnergy = 0.0;
        this.frameNumber = 0;
        this.lastActiveTime = -1.0;
        this.lastSequenceTime = 0.0;
        this.sequenceCounter = 0;
        this.time = 0.0;
    };

    window.VAD = VAD;

})();(function () {

    function TTS(server, access_token, audio_context) {
        if (!(server && access_token)) {
            throw 'Illegal TTS arguments: server and access_token are required.';
        }

        this.access_token = access_token;
        this.server = server;

        if (audio_context) {
            this.audio_context = audio_context;
        } else {
            var AudioContext = window.AudioContext || window.webkitAudioContext;
            this.audio_context = new AudioContext();
        }
    }

    TTS.prototype.tts = function (text, onended) {
        if (!text) {
            return;
        }
        var _this = this;

        text = encodeURIComponent(encodeURIComponent(text));// hack for platform's tts.

        var XHR = ("onload" in new XMLHttpRequest()) ? XMLHttpRequest : XDomainRequest;
        var xhr = new XHR();

        xhr.open('GET', 'http://' + _this.server + '/api/tts?access_token=' + _this.access_token + '&lang=en-US&text=' + text, true);
        xhr.responseType = 'arraybuffer';

        xhr.onload = function (response) {
            var data = this.response;
            //data = response.currentTarget.response;
            speek(data, onended);
        };
        xhr.onerror = function (error) {
            console.log('HttpRequest: Status:', this.status, 'Reason:', error);
        };

        xhr.send();

        function speek(data, onended) {
            var audio_context = _this.audio_context;

            audio_context.decodeAudioData(data, playSound, handleError);

            function playSound(buffer) {
                console.log('play speech...');
                var source = audio_context.createBufferSource(); // creates a sound source
                source.buffer = buffer;                    // tell the source which sound to play
                source.connect(audio_context.destination);       // connect the source to the context's destination (the speakers)
                source.onended = onended;
                source.start(0);                           // play the source now
                                                           // note: on older systems, may have to use deprecated noteOn(time);
            }

            function handleError(error) {
                console.log('TTS decodeAudioData error is', error);
            }
        }

    };

    window.TTS = TTS;

})();
(function () {

    // Defaults
    var CONTENT_TYPE = "content-type=audio/x-raw,+layout=(string)interleaved,+rate=(int)16000,+format=(string)S16LE,+channels=(int)1";
    // Send blocks 4 x per second as recommended in the server doc.
    var INTERVAL = 250;
    var TAG_END_OF_SENTENCE = "EOS";

    // Error codes (mostly following Android error names and codes)
    var ERR_NETWORK = 2;
    var ERR_AUDIO = 3;
    var ERR_SERVER = 4;
    var ERR_CLIENT = 5;

    // Event codes
    var MSG_WAITING_MICROPHONE = 1;
    var MSG_MEDIA_STREAM_CREATED = 2;
    var MSG_INIT_RECORDER = 3;
    var MSG_RECORDING = 4;
    var MSG_SEND = 5;
    var MSG_SEND_EMPTY = 6;
    var MSG_SEND_EOS_OR_JSON = 7;
    var MSG_WEB_SOCKET = 8;
    var MSG_WEB_SOCKET_OPEN = 9;
    var MSG_WEB_SOCKET_CLOSE = 10;
    var MSG_STOP = 11;
    var MSG_CONFIG_CHANGED = 12;

    function ApiAi(cfg) {
        var config = cfg || {};
        var _this = this;

        //var resample_processor;
        //var mediaStreamSource;
        //var audio_context;
        //var recorder;
        //var ws;
        //var intervalKey;

        _this.server = config.server || '';
        _this.token = config.token || '';
        _this.sessionId = config.sessionId || '';
        _this.contentType = config.contentType || CONTENT_TYPE;
        _this.readingInterval = config.readingInterval || INTERVAL;

        _this.onOpen = config.onOpen && config.onOpen.bind(_this) || _noop;
        _this.onClose = config.onClose && config.onClose.bind(_this) || _noop;
        _this.onInit = config.onInit && config.onInit.bind(_this) || _noop;
        _this.onStartListening = config.onStartListening && config.onStartListening.bind(_this) || _noop;
        _this.onStopListening = config.onStopListening && config.onStopListening.bind(_this) || _noop;
        _this.onResults = config.onResults && config.onResults.bind(_this) || _noop;
        _this.onEvent = config.onEvent && config.onEvent.bind(_this) || _noop;
        _this.onError = config.onError && config.onError.bind(_this) || _noop;

        function _noop() {
        }
    }

    /**
     * Initializes audioContext
     * Set up the recorder (incl. asking permission)
     * Can be called multiple times.
     */
    ApiAi.prototype.init = function () {
        var _this = this;

        _this.onEvent(MSG_WAITING_MICROPHONE, "Waiting for approval to access your microphone ...");
        try {
            window.AudioContext = window.AudioContext || window.webkitAudioContext;
            navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
            window.URL = window.URL || window.webkitURL;
            _this.audio_context = new AudioContext();
        } catch (e) {
            // Firefox 24: TypeError: AudioContext is not a constructor
            // Set media.webaudio.enabled = true (in about:config) to fix this.
            _this.onError(ERR_CLIENT, "Error initializing Web Audio browser: " + JSON.stringify(e));
        }

        if (navigator.getUserMedia) {
            navigator.getUserMedia({audio: true}, _startUserMedia.bind(null, _this.onInit), function (e) {
                _this.onError(ERR_CLIENT, "No live audio input in this browser: " + JSON.stringify(e));
            });
        } else {
            _this.onError(ERR_CLIENT, "No user media support");
        }

        function _startUserMedia(onInit, stream) {
            _this.mediaStreamSource = _this.audio_context.createMediaStreamSource(stream);
            _this.onEvent(MSG_MEDIA_STREAM_CREATED, 'Media stream created');

            // make the analyser available in window context
            window.userSpeechAnalyser = _this.audio_context.createAnalyser();

            _this.mediaStreamSource.connect(window.userSpeechAnalyser);

            _this.recorder = new Recorder(_this.mediaStreamSource);
            _this.onEvent(MSG_INIT_RECORDER, 'Recorder initialized');

            onInit && onInit();
        }

    };

    /**
     * Chck if recorder is initialise.
     * @returns {boolean}
     */
    ApiAi.prototype.isInitialise = function () {
        return !!this.recorder;
    };

    /**
     * Send object as json
     * @param json - javascript map.
     */
    ApiAi.prototype.sendJson = function (json) {
        this._socketSend(JSON.stringify(json));
        this._socketSend(TAG_END_OF_SENTENCE);
    };

    /**
     * Start recording and transcribing
     */
    ApiAi.prototype.startListening = function () {
        var _this = this;
        var recorder = _this.recorder;
        if (!recorder) {
            _this.onError(ERR_AUDIO, 'Recorder undefined');
            return;
        }
        if (!_this.ws) {
            _this.onError(ERR_AUDIO, 'No web socket connection');
            return;
        }

        _useVad(function () {
            _this.stopListening();
        });

        _this.ws.send("{'timezone':'America/New_York', 'lang':'en', 'sessionId':'" + _this.sessionId + "'}");

        _this.intervalKey = setInterval(function () {
            recorder.export16kMono(function (blob) {
                _this._socketSend(blob);
                recorder.clear();
            }, 'audio/x-raw');
        }, _this.readingInterval);
        // Start recording
        recorder.record();
        _this.onStartListening();// call interface method

        function _useVad(endOfSpeechCallback) {
            _this.resample_processor = _this.audio_context.createResampleProcessor(256, 1, 1, 16000);

            _this.mediaStreamSource.connect(_this.resample_processor);

            var endOfSpeechProcessor = _this.audio_context.createEndOfSpeechProcessor(256);
            endOfSpeechProcessor.endOfSpeechCallback = endOfSpeechCallback;
            _this.resample_processor.connect(endOfSpeechProcessor);
        }
    };

    /**
     * Stop listening, i.e. recording and sending of new input.
     */
    ApiAi.prototype.stopListening = function () {
        var _this = this;

        _this.resample_processor && _this.resample_processor.disconnect();

        // Stop the regular sending of audio
        clearInterval(_this.intervalKey);

        var recorder = _this.recorder;
        if (!recorder) {
            _this.onError(ERR_AUDIO, 'Recorder undefined');
            return;
        }

        // Stop recording
        recorder.stop();
        _this.onEvent(MSG_STOP, 'Stopped recording');
        // Push the remaining audio to the server
        recorder.export16kMono(function (blob) {
            _this._socketSend(blob);
            _this._socketSend(TAG_END_OF_SENTENCE);
            recorder.clear();
        }, 'audio/x-raw');
        _this.onStopListening();// call interface method
    };

    /**
     * Check if websocket is open
     */
    ApiAi.prototype.isOpen = function () {
        return !!this.ws;
    };
    /**
     * Open websocket
     */
    ApiAi.prototype.open = function () {
        var _this = this;

        if (!this.recorder) {
            this.init(_openWebSocket);
        } else {
            _openWebSocket();
        }

        function _openWebSocket() {
            if (!_this.recorder) {
                _this.onError(ERR_AUDIO, "Recorder undefined");
                return;
            }

            if (_this.ws) {
                _this.close();
            }

            try {
                _this.ws = _createWebSocket();
            } catch (e) {
                _this.onError(ERR_CLIENT, "No web socket support in this browser!");
            }

            function _createWebSocket() {
                var url = _this.server + '?' + _this.contentType + '&access_token=' + _this.token;
                var ws = new WebSocket(url);

                ws.onmessage = function (e) {
                    var data = e.data;
                    _this.onEvent(MSG_WEB_SOCKET, data);

                    if (data instanceof Object && !(data instanceof Blob)) {
                        _this.onError(ERR_SERVER, 'WebSocket: onEvent: got Object that is not a Blob');
                    } else if (data instanceof Blob) {
                        _this.onError(ERR_SERVER, 'WebSocket: got Blob');
                    } else {
                        _this.onResults(JSON.parse(data));// call interface method
                    }
                };

                // Start recording only if the socket becomes open
                ws.onopen = function (e) {
                    // send first request for initialisation dialogue
                    //ws.send("{'timezone':'America/New_York', 'lang':'en'}");
                    _this.onOpen();// call interface method
                    _this.onEvent(MSG_WEB_SOCKET_OPEN, e);
                };

                // This can happen if the blob was too big
                // E.g. "Frame size of 65580 bytes exceeds maximum accepted frame size"
                // Status codes
                // http://tools.ietf.org/html/rfc6455#section-7.4.1
                // 1005:
                // 1006:
                ws.onclose = function (e) {
                    // The server closes the connection (only?)
                    // when its endpointer triggers.
                    _this.onClose();// call interface method
                    _this.onEvent(MSG_WEB_SOCKET_CLOSE, e.code + "/" + e.reason + "/" + e.wasClean);
                };

                ws.onerror = function (e) {
                    _this.onError(ERR_NETWORK, JSON.stringify(e.data));
                };

                return ws;
            }
        }

    };

    /**
     * Cancel everything without waiting on the server
     */
    ApiAi.prototype.close = function () {
        var _this = this;
        // Stop the regular sending of audio (if present)
        clearInterval(_this.intervalKey);
        if (_this.recorder) {
            _this.recorder.stop();
            _this.recorder.clear();
            _this.onEvent(MSG_STOP, 'Stopped recording');
        }
        if (_this.ws) {
            _this.ws.close();
            _this.ws = null;
        }
    };

    ApiAi.prototype._socketSend = function (item) {
        var _this = this;
        if (!_this.ws) {
            _this.onError(ERR_CLIENT, 'No web socket connection: failed to send: ' + item);
            return;
        }

        var state = _this.ws.readyState;
        if (state != 1) {
            var errorMsg = 'WebSocket: ';
            switch (state) {
                case 0: // CONNECTING
                    errorMsg += 'The connection is not yet open.';
                    break;
                //case 1:break;// OPEN
                case 2:// CLOSING
                    errorMsg += 'The connection is in the process of closing.';
                    break;
                case 3:// CLOSED
                    errorMsg += 'The connection is closed or couldn\'t be opened.';
                    break;
            }
            errorMsg += ' readyState=' + state + ' (!=1) failed to send: ' + item;
            _this.onError(ERR_NETWORK, errorMsg);
        }

        // If item isn't an audio blob it's the EOS tag or json data (string)
        if (!(item instanceof Blob)) {
            _this.ws.send(item);
            _this.onEvent(MSG_SEND_EOS_OR_JSON, 'Send string: ' + item);
        } else if (item.size > 0) {
            _this.ws.send(item);
            _this.onEvent(MSG_SEND, 'Send: blob: ' + item.type + ', ' + item.size);
        } else {
            _this.onEvent(MSG_SEND_EMPTY, 'Send: blob: ' + item.type + ', EMPTY');
        }
    };

    window.ApiAi = ApiAi;

})();


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb
 Copyright (C) 2005 StatPro Italia srl

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

/*! \file trinomialtree.hpp
    \brief Trinomial tree class
*/

#ifndef quantlib_trinomial_tree_hpp
#define quantlib_trinomial_tree_hpp

#include <ql/methods/lattices/tree.hpp>
#include <ql/timegrid.hpp>

namespace QuantLib {
    class StochasticProcess1D;
    //! Recombining trinomial tree class
    /*! This class defines a recombining trinomial tree approximating a
        1-D stochastic process.
        \warning The diffusion term of the SDE must be independent of the
                 underlying process.

        \ingroup lattices
    */
    class TrinomialTree : public Tree<TrinomialTree> {
        class Branching;
      public:
        enum Branches { branches = 3 };
        TrinomialTree(const boost::shared_ptr<StochasticProcess1D>& process,
                      const TimeGrid& timeGrid,
                      bool isPositive = false);
        Real dx(Size i) const { return dx_[i]; }
        const TimeGrid& timeGrid() const { return timeGrid_; }

        Size size(Size i) const;
        Real underlying(Size i, Size index) const;
        Size descendant(Size i, Size index, Size branch) const;
        Real probability(Size i, Size index, Size branch) const;

      protected:
        std::vector<Branching> branchings_;
        Real x0_;
        std::vector<Real> dx_;
        TimeGrid timeGrid_;

      private:
        /* Branching scheme for a trinomial node.  Each node has three
           descendants, with the middle branch linked to the node
           which is closest to the expectation of the variable. */
        class Branching {
          public:
            Branching();
            Size descendant(Size index, Size branch) const;
            Real probability(Size index, Size branch) const;
            Size size() const;
            Integer jMin() const;
            Integer jMax() const;
            void add(Integer k, Real p1, Real p2, Real p3);
          private:
            std::vector<Integer> k_;
            std::vector<std::vector<Real> > probs_;
            Integer kMin_, jMin_, kMax_, jMax_;
        };
    };

    // inline definitions

    inline Size TrinomialTree::size(Size i) const {
        return i==0 ? 1 : branchings_[i-1].size();
    }

    inline Real TrinomialTree::underlying(Size i, Size index) const {
        if (i==0)
            return x0_;
        else
            return x0_ + (branchings_[i-1].jMin() +
                          static_cast<Real>(index))*dx(i);
    }

    inline Size TrinomialTree::descendant(Size i, Size index,
                                          Size branch) const {
        return branchings_[i].descendant(index, branch);
    }

    inline Real TrinomialTree::probability(Size i, Size j, Size b) const {
        return branchings_[i].probability(j, b);
    }

    inline TrinomialTree::Branching::Branching()
    : probs_(3), kMin_(QL_MAX_INTEGER), jMin_(QL_MAX_INTEGER),
                 kMax_(QL_MIN_INTEGER), jMax_(QL_MIN_INTEGER) {}

    inline Size TrinomialTree::Branching::descendant(Size index,
                                                     Size branch) const {
        return k_[index] - jMin_ - 1 + branch;
    }

    inline Real TrinomialTree::Branching::probability(Size index,
                                                      Size branch) const {
        return probs_[branch][index];
    }

    inline Size TrinomialTree::Branching::size() const {
        return jMax_ - jMin_ + 1;
    }

    inline Integer TrinomialTree::Branching::jMin() const {
        return jMin_;
    }

    inline Integer TrinomialTree::Branching::jMax() const {
        return jMax_;
    }

    inline void TrinomialTree::Branching::add(Integer k,
                                              Real p1, Real p2, Real p3) {
        // store
        k_.push_back(k);
        probs_[0].push_back(p1);
        probs_[1].push_back(p2);
        probs_[2].push_back(p3);
        // maintain invariants
        kMin_ = std::min(kMin_, k);
        jMin_ = kMin_ - 1;
        kMax_ = std::max(kMax_, k);
        jMax_ = kMax_ + 1;
    }

}

#endif


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Chapter 08 - CSRF</title>
    <link rel="stylesheet" type="text/css" href="resources/css/styles.css" />

Chapter 08 - CSRF: Hidden Image

Back


text:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Passenger.Infrastructure.Commands;
using Passenger.Infrastructure.Commands.Users;

namespace Passenger.Api.Controllers
{
    public class AccountController : ApiControllerBase
    {
        public AccountController(ICommandDispatcher commandDispatcher)
            : base(commandDispatcher)
        {
        }

        [HttpPut]
        [Route("password")]
        public async Task<IActionResult> Put([FromBody]ChangeUserPassword command)
        {
            await DispatchAsync(command);

            return NoContent();
        }
    }
}