hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f719bf0a49a2168cb3b4abfd826a62d6032ed825 | 7,399 | py | Python | nova/api/openstack/compute/plugins/v3/cloudpipe.py | zaina/nova | 181358c172d606b23c9cc14b58d677d911013c02 | [
"Apache-2.0"
] | null | null | null | nova/api/openstack/compute/plugins/v3/cloudpipe.py | zaina/nova | 181358c172d606b23c9cc14b58d677d911013c02 | [
"Apache-2.0"
] | null | null | null | nova/api/openstack/compute/plugins/v3/cloudpipe.py | zaina/nova | 181358c172d606b23c9cc14b58d677d911013c02 | [
"Apache-2.0"
] | null | null | null | # Copyright 2011 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Connect your vlan to the world."""
from oslo_config import cfg
from oslo_utils import fileutils
from oslo_utils import timeutils
from webob import exc
from nova.api.openstack.compute.schemas.v3 import cloudpipe
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova.cloudpipe import pipelib
from nova import compute
from nova.compute import utils as compute_utils
from nova.compute import vm_states
from nova import exception
from nova.i18n import _
from nova import network
from nova import objects
from nova import utils
CONF = cfg.CONF
CONF.import_opt('keys_path', 'nova.crypto')
ALIAS = 'os-cloudpipe'
authorize = extensions.os_compute_authorizer(ALIAS)
class CloudpipeController(wsgi.Controller):
"""Handle creating and listing cloudpipe instances."""
def __init__(self):
self.compute_api = compute.API(skip_policy_check=True)
self.network_api = network.API(skip_policy_check=True)
self.cloudpipe = pipelib.CloudPipe(skip_policy_check=True)
self.setup()
def setup(self):
"""Ensure the keychains and folders exist."""
# NOTE(vish): One of the drawbacks of doing this in the api is
# the keys will only be on the api node that launched
# the cloudpipe.
fileutils.ensure_tree(CONF.keys_path)
def _get_all_cloudpipes(self, context):
"""Get all cloudpipes."""
instances = self.compute_api.get_all(context,
search_opts={'deleted': False},
want_objects=True)
return [instance for instance in instances
if pipelib.is_vpn_image(instance.image_ref)
and instance.vm_state != vm_states.DELETED]
def _get_cloudpipe_for_project(self, context):
"""Get the cloudpipe instance for a project from context."""
cloudpipes = self._get_all_cloudpipes(context) or [None]
return cloudpipes[0]
def _vpn_dict(self, context, project_id, instance):
elevated = context.elevated()
rv = {'project_id': project_id}
if not instance:
rv['state'] = 'pending'
return rv
rv['instance_id'] = instance.uuid
rv['created_at'] = timeutils.isotime(instance.created_at)
nw_info = compute_utils.get_nw_info_for_instance(instance)
if not nw_info:
return rv
vif = nw_info[0]
ips = [ip for ip in vif.fixed_ips() if ip['version'] == 4]
if ips:
rv['internal_ip'] = ips[0]['address']
# NOTE(vish): Currently network_api.get does an owner check on
# project_id. This is probably no longer necessary
# but rather than risk changes in the db layer,
# we are working around it here by changing the
# project_id in the context. This can be removed
# if we remove the project_id check in the db.
elevated.project_id = project_id
network = self.network_api.get(elevated, vif['network']['id'])
if network:
vpn_ip = network['vpn_public_address']
vpn_port = network['vpn_public_port']
rv['public_ip'] = vpn_ip
rv['public_port'] = vpn_port
if vpn_ip and vpn_port:
if utils.vpn_ping(vpn_ip, vpn_port):
rv['state'] = 'running'
else:
rv['state'] = 'down'
else:
rv['state'] = 'invalid'
return rv
@extensions.expected_errors((400, 403))
@validation.schema(cloudpipe.create)
def create(self, req, body):
"""Create a new cloudpipe instance, if none exists.
Parameters: {cloudpipe: {'project_id': ''}}
"""
context = req.environ['nova.context']
authorize(context)
params = body.get('cloudpipe', {})
project_id = params.get('project_id', context.project_id)
# NOTE(vish): downgrade to project context. Note that we keep
# the same token so we can still talk to glance
context.project_id = project_id
context.user_id = 'project-vpn'
context.is_admin = False
context.roles = []
instance = self._get_cloudpipe_for_project(context)
if not instance:
try:
result = self.cloudpipe.launch_vpn_instance(context)
instance = result[0][0]
except exception.NoMoreNetworks:
msg = _("Unable to claim IP for VPN instances, ensure it "
"isn't running, and try again in a few minutes")
raise exc.HTTPBadRequest(explanation=msg)
return {'instance_id': instance.uuid}
@extensions.expected_errors((400, 403, 404))
def index(self, req):
"""List running cloudpipe instances."""
context = req.environ['nova.context']
authorize(context)
vpns = [self._vpn_dict(context, x['project_id'], x)
for x in self._get_all_cloudpipes(context)]
return {'cloudpipes': vpns}
@wsgi.response(202)
@extensions.expected_errors(400)
@validation.schema(cloudpipe.update)
def update(self, req, id, body):
"""Configure cloudpipe parameters for the project."""
context = req.environ['nova.context']
authorize(context)
if id != "configure-project":
msg = _("Unknown action %s") % id
raise exc.HTTPBadRequest(explanation=msg)
project_id = context.project_id
networks = objects.NetworkList.get_by_project(context, project_id)
params = body['configure_project']
vpn_ip = params['vpn_ip']
vpn_port = params['vpn_port']
for nw in networks:
nw.vpn_public_address = vpn_ip
nw.vpn_public_port = vpn_port
nw.save()
class Cloudpipe(extensions.V3APIExtensionBase):
"""Adds actions to create cloudpipe instances.
When running with the Vlan network mode, you need a mechanism to route
from the public Internet to your vlans. This mechanism is known as a
cloudpipe.
At the time of creating this class, only OpenVPN is supported. Support for
a SSH Bastion host is forthcoming.
"""
name = "Cloudpipe"
alias = ALIAS
version = 1
def get_resources(self):
resource = [extensions.ResourceExtension(ALIAS,
CloudpipeController())]
return resource
def get_controller_extensions(self):
"""It's an abstract function V3APIExtensionBase and the extension
will not be loaded without it.
"""
return []
| 37.368687 | 79 | 0.629274 |
from oslo_config import cfg
from oslo_utils import fileutils
from oslo_utils import timeutils
from webob import exc
from nova.api.openstack.compute.schemas.v3 import cloudpipe
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova.cloudpipe import pipelib
from nova import compute
from nova.compute import utils as compute_utils
from nova.compute import vm_states
from nova import exception
from nova.i18n import _
from nova import network
from nova import objects
from nova import utils
CONF = cfg.CONF
CONF.import_opt('keys_path', 'nova.crypto')
ALIAS = 'os-cloudpipe'
authorize = extensions.os_compute_authorizer(ALIAS)
class CloudpipeController(wsgi.Controller):
def __init__(self):
self.compute_api = compute.API(skip_policy_check=True)
self.network_api = network.API(skip_policy_check=True)
self.cloudpipe = pipelib.CloudPipe(skip_policy_check=True)
self.setup()
def setup(self):
fileutils.ensure_tree(CONF.keys_path)
def _get_all_cloudpipes(self, context):
instances = self.compute_api.get_all(context,
search_opts={'deleted': False},
want_objects=True)
return [instance for instance in instances
if pipelib.is_vpn_image(instance.image_ref)
and instance.vm_state != vm_states.DELETED]
def _get_cloudpipe_for_project(self, context):
cloudpipes = self._get_all_cloudpipes(context) or [None]
return cloudpipes[0]
def _vpn_dict(self, context, project_id, instance):
elevated = context.elevated()
rv = {'project_id': project_id}
if not instance:
rv['state'] = 'pending'
return rv
rv['instance_id'] = instance.uuid
rv['created_at'] = timeutils.isotime(instance.created_at)
nw_info = compute_utils.get_nw_info_for_instance(instance)
if not nw_info:
return rv
vif = nw_info[0]
ips = [ip for ip in vif.fixed_ips() if ip['version'] == 4]
if ips:
rv['internal_ip'] = ips[0]['address']
elevated.project_id = project_id
network = self.network_api.get(elevated, vif['network']['id'])
if network:
vpn_ip = network['vpn_public_address']
vpn_port = network['vpn_public_port']
rv['public_ip'] = vpn_ip
rv['public_port'] = vpn_port
if vpn_ip and vpn_port:
if utils.vpn_ping(vpn_ip, vpn_port):
rv['state'] = 'running'
else:
rv['state'] = 'down'
else:
rv['state'] = 'invalid'
return rv
@extensions.expected_errors((400, 403))
@validation.schema(cloudpipe.create)
def create(self, req, body):
context = req.environ['nova.context']
authorize(context)
params = body.get('cloudpipe', {})
project_id = params.get('project_id', context.project_id)
context.project_id = project_id
context.user_id = 'project-vpn'
context.is_admin = False
context.roles = []
instance = self._get_cloudpipe_for_project(context)
if not instance:
try:
result = self.cloudpipe.launch_vpn_instance(context)
instance = result[0][0]
except exception.NoMoreNetworks:
msg = _("Unable to claim IP for VPN instances, ensure it "
"isn't running, and try again in a few minutes")
raise exc.HTTPBadRequest(explanation=msg)
return {'instance_id': instance.uuid}
@extensions.expected_errors((400, 403, 404))
def index(self, req):
context = req.environ['nova.context']
authorize(context)
vpns = [self._vpn_dict(context, x['project_id'], x)
for x in self._get_all_cloudpipes(context)]
return {'cloudpipes': vpns}
@wsgi.response(202)
@extensions.expected_errors(400)
@validation.schema(cloudpipe.update)
def update(self, req, id, body):
context = req.environ['nova.context']
authorize(context)
if id != "configure-project":
msg = _("Unknown action %s") % id
raise exc.HTTPBadRequest(explanation=msg)
project_id = context.project_id
networks = objects.NetworkList.get_by_project(context, project_id)
params = body['configure_project']
vpn_ip = params['vpn_ip']
vpn_port = params['vpn_port']
for nw in networks:
nw.vpn_public_address = vpn_ip
nw.vpn_public_port = vpn_port
nw.save()
class Cloudpipe(extensions.V3APIExtensionBase):
name = "Cloudpipe"
alias = ALIAS
version = 1
def get_resources(self):
resource = [extensions.ResourceExtension(ALIAS,
CloudpipeController())]
return resource
def get_controller_extensions(self):
return []
| true | true |
f719bfc6c7c129776e3b9c9595c4c130931fdd2d | 15,240 | py | Python | tempest/api/compute/servers/test_create_server.py | xavpaice/tempest | 958bd694df27511e0346d799876fe49331b8145c | [
"Apache-2.0"
] | 3 | 2016-07-15T12:27:23.000Z | 2021-04-23T04:41:10.000Z | tempest/api/compute/servers/test_create_server.py | LIS/lis-tempest | 8e6403b2d6de81c5d18ed867b4977385c8278b75 | [
"Apache-2.0"
] | null | null | null | tempest/api/compute/servers/test_create_server.py | LIS/lis-tempest | 8e6403b2d6de81c5d18ed867b4977385c8278b75 | [
"Apache-2.0"
] | 12 | 2016-07-14T18:13:05.000Z | 2017-07-08T18:45:42.000Z | # Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import netaddr
import testtools
from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest.common.utils.linux import remote_client
from tempest.common import waiters
from tempest import config
from tempest import test
CONF = config.CONF
class ServersTestJSON(base.BaseV2ComputeTest):
disk_config = 'AUTO'
@classmethod
def setup_credentials(cls):
cls.prepare_instance_network()
super(ServersTestJSON, cls).setup_credentials()
@classmethod
def setup_clients(cls):
super(ServersTestJSON, cls).setup_clients()
cls.client = cls.servers_client
cls.network_client = cls.os.network_client
cls.networks_client = cls.os.networks_client
cls.subnets_client = cls.os.subnets_client
@classmethod
def resource_setup(cls):
cls.set_validation_resources()
super(ServersTestJSON, cls).resource_setup()
cls.meta = {'hello': 'world'}
cls.accessIPv4 = '1.1.1.1'
cls.accessIPv6 = '0000:0000:0000:0000:0000:babe:220.12.22.2'
cls.name = data_utils.rand_name('server')
cls.password = data_utils.rand_password()
disk_config = cls.disk_config
cls.server_initial = cls.create_test_server(
validatable=True,
wait_until='ACTIVE',
name=cls.name,
metadata=cls.meta,
accessIPv4=cls.accessIPv4,
accessIPv6=cls.accessIPv6,
disk_config=disk_config,
adminPass=cls.password)
cls.server = (cls.client.show_server(cls.server_initial['id'])
['server'])
def _create_net_subnet_ret_net_from_cidr(self, cidr):
name_net = data_utils.rand_name(self.__class__.__name__)
net = self.networks_client.create_network(name=name_net)
self.addCleanup(self.networks_client.delete_network,
net['network']['id'])
subnet = self.subnets_client.create_subnet(
network_id=net['network']['id'],
cidr=cidr,
ip_version=4)
self.addCleanup(self.subnets_client.delete_subnet,
subnet['subnet']['id'])
return net
@test.attr(type='smoke')
@test.idempotent_id('5de47127-9977-400a-936f-abcfbec1218f')
def test_verify_server_details(self):
# Verify the specified server attributes are set correctly
self.assertEqual(self.accessIPv4, self.server['accessIPv4'])
# NOTE(maurosr): See http://tools.ietf.org/html/rfc5952 (section 4)
# Here we compare directly with the canonicalized format.
self.assertEqual(self.server['accessIPv6'],
str(netaddr.IPAddress(self.accessIPv6)))
self.assertEqual(self.name, self.server['name'])
self.assertEqual(self.image_ref, self.server['image']['id'])
self.assertEqual(self.flavor_ref, self.server['flavor']['id'])
self.assertEqual(self.meta, self.server['metadata'])
@test.attr(type='smoke')
@test.idempotent_id('9a438d88-10c6-4bcd-8b5b-5b6e25e1346f')
def test_list_servers(self):
# The created server should be in the list of all servers
body = self.client.list_servers()
servers = body['servers']
found = any([i for i in servers if i['id'] == self.server['id']])
self.assertTrue(found)
@test.idempotent_id('585e934c-448e-43c4-acbf-d06a9b899997')
def test_list_servers_with_detail(self):
# The created server should be in the detailed list of all servers
body = self.client.list_servers(detail=True)
servers = body['servers']
found = any([i for i in servers if i['id'] == self.server['id']])
self.assertTrue(found)
@test.idempotent_id('cbc0f52f-05aa-492b-bdc1-84b575ca294b')
@testtools.skipUnless(CONF.validation.run_validation,
'Instance validation tests are disabled.')
def test_verify_created_server_vcpus(self):
# Verify that the number of vcpus reported by the instance matches
# the amount stated by the flavor
flavor = self.flavors_client.show_flavor(self.flavor_ref)['flavor']
linux_client = remote_client.RemoteClient(
self.get_server_ip(self.server),
self.ssh_user,
self.password,
self.validation_resources['keypair']['private_key'])
self.assertEqual(flavor['vcpus'], linux_client.get_number_of_vcpus())
@test.idempotent_id('ac1ad47f-984b-4441-9274-c9079b7a0666')
@testtools.skipUnless(CONF.validation.run_validation,
'Instance validation tests are disabled.')
def test_host_name_is_same_as_server_name(self):
# Verify the instance host name is the same as the server name
linux_client = remote_client.RemoteClient(
self.get_server_ip(self.server),
self.ssh_user,
self.password,
self.validation_resources['keypair']['private_key'])
self.assertTrue(linux_client.hostname_equals_servername(self.name))
@test.idempotent_id('ed20d3fb-9d1f-4329-b160-543fbd5d9811')
def test_create_server_with_scheduler_hint_group(self):
# Create a server with the scheduler hint "group".
name = data_utils.rand_name('server_group')
policies = ['affinity']
body = self.server_groups_client.create_server_group(
name=name, policies=policies)['server_group']
group_id = body['id']
self.addCleanup(self.server_groups_client.delete_server_group,
group_id)
hints = {'group': group_id}
server = self.create_test_server(scheduler_hints=hints,
wait_until='ACTIVE')
# Check a server is in the group
server_group = (self.server_groups_client.show_server_group(group_id)
['server_group'])
self.assertIn(server['id'], server_group['members'])
@test.idempotent_id('0578d144-ed74-43f8-8e57-ab10dbf9b3c2')
@testtools.skipUnless(CONF.service_available.neutron,
'Neutron service must be available.')
def test_verify_multiple_nics_order(self):
# Verify that the networks order given at the server creation is
# preserved within the server.
net1 = self._create_net_subnet_ret_net_from_cidr('19.80.0.0/24')
net2 = self._create_net_subnet_ret_net_from_cidr('19.86.0.0/24')
networks = [{'uuid': net1['network']['id']},
{'uuid': net2['network']['id']}]
server_multi_nics = self.create_test_server(
networks=networks, wait_until='ACTIVE')
# Cleanup server; this is needed in the test case because with the LIFO
# nature of the cleanups, if we don't delete the server first, the port
# will still be part of the subnet and we'll get a 409 from Neutron
# when trying to delete the subnet. The tear down in the base class
# will try to delete the server and get a 404 but it's ignored so
# we're OK.
def cleanup_server():
self.client.delete_server(server_multi_nics['id'])
waiters.wait_for_server_termination(self.client,
server_multi_nics['id'])
self.addCleanup(cleanup_server)
addresses = (self.client.list_addresses(server_multi_nics['id'])
['addresses'])
# We can't predict the ip addresses assigned to the server on networks.
# Sometimes the assigned addresses are ['19.80.0.2', '19.86.0.2'], at
# other times ['19.80.0.3', '19.86.0.3']. So we check if the first
# address is in first network, similarly second address is in second
# network.
addr = [addresses[net1['network']['name']][0]['addr'],
addresses[net2['network']['name']][0]['addr']]
networks = [netaddr.IPNetwork('19.80.0.0/24'),
netaddr.IPNetwork('19.86.0.0/24')]
for address, network in zip(addr, networks):
self.assertIn(address, network)
@test.idempotent_id('1678d144-ed74-43f8-8e57-ab10dbf9b3c2')
@testtools.skipUnless(CONF.service_available.neutron,
'Neutron service must be available.')
# The below skipUnless should be removed once Kilo-eol happens.
@testtools.skipUnless(CONF.compute_feature_enabled.
allow_duplicate_networks,
'Duplicate networks must be allowed')
def test_verify_duplicate_network_nics(self):
# Verify that server creation does not fail when more than one nic
# is created on the same network.
net1 = self._create_net_subnet_ret_net_from_cidr('19.80.0.0/24')
net2 = self._create_net_subnet_ret_net_from_cidr('19.86.0.0/24')
networks = [{'uuid': net1['network']['id']},
{'uuid': net2['network']['id']},
{'uuid': net1['network']['id']}]
server_multi_nics = self.create_test_server(
networks=networks, wait_until='ACTIVE')
def cleanup_server():
self.client.delete_server(server_multi_nics['id'])
waiters.wait_for_server_termination(self.client,
server_multi_nics['id'])
self.addCleanup(cleanup_server)
addresses = (self.client.list_addresses(server_multi_nics['id'])
['addresses'])
addr = [addresses[net1['network']['name']][0]['addr'],
addresses[net2['network']['name']][0]['addr'],
addresses[net1['network']['name']][1]['addr']]
networks = [netaddr.IPNetwork('19.80.0.0/24'),
netaddr.IPNetwork('19.86.0.0/24'),
netaddr.IPNetwork('19.80.0.0/24')]
for address, network in zip(addr, networks):
self.assertIn(address, network)
class ServersWithSpecificFlavorTestJSON(base.BaseV2ComputeAdminTest):
disk_config = 'AUTO'
@classmethod
def setup_credentials(cls):
cls.prepare_instance_network()
super(ServersWithSpecificFlavorTestJSON, cls).setup_credentials()
@classmethod
def setup_clients(cls):
super(ServersWithSpecificFlavorTestJSON, cls).setup_clients()
cls.flavor_client = cls.os_adm.flavors_client
cls.client = cls.servers_client
@classmethod
def resource_setup(cls):
cls.set_validation_resources()
super(ServersWithSpecificFlavorTestJSON, cls).resource_setup()
@test.idempotent_id('b3c7bcfc-bb5b-4e22-b517-c7f686b802ca')
@testtools.skipUnless(CONF.validation.run_validation,
'Instance validation tests are disabled.')
def test_verify_created_server_ephemeral_disk(self):
# Verify that the ephemeral disk is created when creating server
flavor_base = self.flavors_client.show_flavor(
self.flavor_ref)['flavor']
def create_flavor_with_extra_specs():
flavor_with_eph_disk_name = data_utils.rand_name('eph_flavor')
flavor_with_eph_disk_id = data_utils.rand_int_id(start=1000)
ram = flavor_base['ram']
vcpus = flavor_base['vcpus']
disk = flavor_base['disk']
# Create a flavor with extra specs
flavor = (self.flavor_client.
create_flavor(name=flavor_with_eph_disk_name,
ram=ram, vcpus=vcpus, disk=disk,
id=flavor_with_eph_disk_id,
ephemeral=1))['flavor']
self.addCleanup(flavor_clean_up, flavor['id'])
return flavor['id']
def create_flavor_without_extra_specs():
flavor_no_eph_disk_name = data_utils.rand_name('no_eph_flavor')
flavor_no_eph_disk_id = data_utils.rand_int_id(start=1000)
ram = flavor_base['ram']
vcpus = flavor_base['vcpus']
disk = flavor_base['disk']
# Create a flavor without extra specs
flavor = (self.flavor_client.
create_flavor(name=flavor_no_eph_disk_name,
ram=ram, vcpus=vcpus, disk=disk,
id=flavor_no_eph_disk_id))['flavor']
self.addCleanup(flavor_clean_up, flavor['id'])
return flavor['id']
def flavor_clean_up(flavor_id):
self.flavor_client.delete_flavor(flavor_id)
self.flavor_client.wait_for_resource_deletion(flavor_id)
flavor_with_eph_disk_id = create_flavor_with_extra_specs()
flavor_no_eph_disk_id = create_flavor_without_extra_specs()
admin_pass = self.image_ssh_password
server_no_eph_disk = self.create_test_server(
validatable=True,
wait_until='ACTIVE',
adminPass=admin_pass,
flavor=flavor_no_eph_disk_id)
# Get partition number of server without extra specs.
server_no_eph_disk = self.client.show_server(
server_no_eph_disk['id'])['server']
linux_client = remote_client.RemoteClient(
self.get_server_ip(server_no_eph_disk),
self.ssh_user,
admin_pass,
self.validation_resources['keypair']['private_key'])
partition_num = len(linux_client.get_partitions().split('\n'))
# Explicit server deletion necessary for Juno compatibility
self.client.delete_server(server_no_eph_disk['id'])
server_with_eph_disk = self.create_test_server(
validatable=True,
wait_until='ACTIVE',
adminPass=admin_pass,
flavor=flavor_with_eph_disk_id)
server_with_eph_disk = self.client.show_server(
server_with_eph_disk['id'])['server']
linux_client = remote_client.RemoteClient(
self.get_server_ip(server_with_eph_disk),
self.ssh_user,
admin_pass,
self.validation_resources['keypair']['private_key'])
partition_num_emph = len(linux_client.get_partitions().split('\n'))
self.assertEqual(partition_num + 1, partition_num_emph)
class ServersTestManualDisk(ServersTestJSON):
disk_config = 'MANUAL'
@classmethod
def skip_checks(cls):
super(ServersTestManualDisk, cls).skip_checks()
if not CONF.compute_feature_enabled.disk_config:
msg = "DiskConfig extension not enabled."
raise cls.skipException(msg)
| 42.569832 | 79 | 0.639764 |
import netaddr
import testtools
from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest.common.utils.linux import remote_client
from tempest.common import waiters
from tempest import config
from tempest import test
CONF = config.CONF
class ServersTestJSON(base.BaseV2ComputeTest):
disk_config = 'AUTO'
@classmethod
def setup_credentials(cls):
cls.prepare_instance_network()
super(ServersTestJSON, cls).setup_credentials()
@classmethod
def setup_clients(cls):
super(ServersTestJSON, cls).setup_clients()
cls.client = cls.servers_client
cls.network_client = cls.os.network_client
cls.networks_client = cls.os.networks_client
cls.subnets_client = cls.os.subnets_client
@classmethod
def resource_setup(cls):
cls.set_validation_resources()
super(ServersTestJSON, cls).resource_setup()
cls.meta = {'hello': 'world'}
cls.accessIPv4 = '1.1.1.1'
cls.accessIPv6 = '0000:0000:0000:0000:0000:babe:220.12.22.2'
cls.name = data_utils.rand_name('server')
cls.password = data_utils.rand_password()
disk_config = cls.disk_config
cls.server_initial = cls.create_test_server(
validatable=True,
wait_until='ACTIVE',
name=cls.name,
metadata=cls.meta,
accessIPv4=cls.accessIPv4,
accessIPv6=cls.accessIPv6,
disk_config=disk_config,
adminPass=cls.password)
cls.server = (cls.client.show_server(cls.server_initial['id'])
['server'])
def _create_net_subnet_ret_net_from_cidr(self, cidr):
name_net = data_utils.rand_name(self.__class__.__name__)
net = self.networks_client.create_network(name=name_net)
self.addCleanup(self.networks_client.delete_network,
net['network']['id'])
subnet = self.subnets_client.create_subnet(
network_id=net['network']['id'],
cidr=cidr,
ip_version=4)
self.addCleanup(self.subnets_client.delete_subnet,
subnet['subnet']['id'])
return net
@test.attr(type='smoke')
@test.idempotent_id('5de47127-9977-400a-936f-abcfbec1218f')
def test_verify_server_details(self):
self.assertEqual(self.accessIPv4, self.server['accessIPv4'])
self.assertEqual(self.server['accessIPv6'],
str(netaddr.IPAddress(self.accessIPv6)))
self.assertEqual(self.name, self.server['name'])
self.assertEqual(self.image_ref, self.server['image']['id'])
self.assertEqual(self.flavor_ref, self.server['flavor']['id'])
self.assertEqual(self.meta, self.server['metadata'])
@test.attr(type='smoke')
@test.idempotent_id('9a438d88-10c6-4bcd-8b5b-5b6e25e1346f')
def test_list_servers(self):
body = self.client.list_servers()
servers = body['servers']
found = any([i for i in servers if i['id'] == self.server['id']])
self.assertTrue(found)
@test.idempotent_id('585e934c-448e-43c4-acbf-d06a9b899997')
def test_list_servers_with_detail(self):
body = self.client.list_servers(detail=True)
servers = body['servers']
found = any([i for i in servers if i['id'] == self.server['id']])
self.assertTrue(found)
@test.idempotent_id('cbc0f52f-05aa-492b-bdc1-84b575ca294b')
@testtools.skipUnless(CONF.validation.run_validation,
'Instance validation tests are disabled.')
def test_verify_created_server_vcpus(self):
flavor = self.flavors_client.show_flavor(self.flavor_ref)['flavor']
linux_client = remote_client.RemoteClient(
self.get_server_ip(self.server),
self.ssh_user,
self.password,
self.validation_resources['keypair']['private_key'])
self.assertEqual(flavor['vcpus'], linux_client.get_number_of_vcpus())
@test.idempotent_id('ac1ad47f-984b-4441-9274-c9079b7a0666')
@testtools.skipUnless(CONF.validation.run_validation,
'Instance validation tests are disabled.')
def test_host_name_is_same_as_server_name(self):
linux_client = remote_client.RemoteClient(
self.get_server_ip(self.server),
self.ssh_user,
self.password,
self.validation_resources['keypair']['private_key'])
self.assertTrue(linux_client.hostname_equals_servername(self.name))
@test.idempotent_id('ed20d3fb-9d1f-4329-b160-543fbd5d9811')
def test_create_server_with_scheduler_hint_group(self):
name = data_utils.rand_name('server_group')
policies = ['affinity']
body = self.server_groups_client.create_server_group(
name=name, policies=policies)['server_group']
group_id = body['id']
self.addCleanup(self.server_groups_client.delete_server_group,
group_id)
hints = {'group': group_id}
server = self.create_test_server(scheduler_hints=hints,
wait_until='ACTIVE')
server_group = (self.server_groups_client.show_server_group(group_id)
['server_group'])
self.assertIn(server['id'], server_group['members'])
@test.idempotent_id('0578d144-ed74-43f8-8e57-ab10dbf9b3c2')
@testtools.skipUnless(CONF.service_available.neutron,
'Neutron service must be available.')
def test_verify_multiple_nics_order(self):
net1 = self._create_net_subnet_ret_net_from_cidr('19.80.0.0/24')
net2 = self._create_net_subnet_ret_net_from_cidr('19.86.0.0/24')
networks = [{'uuid': net1['network']['id']},
{'uuid': net2['network']['id']}]
server_multi_nics = self.create_test_server(
networks=networks, wait_until='ACTIVE')
# will still be part of the subnet and we'll get a 409 from Neutron
# we're OK.
def cleanup_server():
self.client.delete_server(server_multi_nics['id'])
waiters.wait_for_server_termination(self.client,
server_multi_nics['id'])
self.addCleanup(cleanup_server)
addresses = (self.client.list_addresses(server_multi_nics['id'])
['addresses'])
# Sometimes the assigned addresses are ['19.80.0.2', '19.86.0.2'], at
# other times ['19.80.0.3', '19.86.0.3']. So we check if the first
# address is in first network, similarly second address is in second
# network.
addr = [addresses[net1['network']['name']][0]['addr'],
addresses[net2['network']['name']][0]['addr']]
networks = [netaddr.IPNetwork('19.80.0.0/24'),
netaddr.IPNetwork('19.86.0.0/24')]
for address, network in zip(addr, networks):
self.assertIn(address, network)
@test.idempotent_id('1678d144-ed74-43f8-8e57-ab10dbf9b3c2')
@testtools.skipUnless(CONF.service_available.neutron,
'Neutron service must be available.')
# The below skipUnless should be removed once Kilo-eol happens.
@testtools.skipUnless(CONF.compute_feature_enabled.
allow_duplicate_networks,
'Duplicate networks must be allowed')
def test_verify_duplicate_network_nics(self):
# Verify that server creation does not fail when more than one nic
# is created on the same network.
net1 = self._create_net_subnet_ret_net_from_cidr('19.80.0.0/24')
net2 = self._create_net_subnet_ret_net_from_cidr('19.86.0.0/24')
networks = [{'uuid': net1['network']['id']},
{'uuid': net2['network']['id']},
{'uuid': net1['network']['id']}]
server_multi_nics = self.create_test_server(
networks=networks, wait_until='ACTIVE')
def cleanup_server():
self.client.delete_server(server_multi_nics['id'])
waiters.wait_for_server_termination(self.client,
server_multi_nics['id'])
self.addCleanup(cleanup_server)
addresses = (self.client.list_addresses(server_multi_nics['id'])
['addresses'])
addr = [addresses[net1['network']['name']][0]['addr'],
addresses[net2['network']['name']][0]['addr'],
addresses[net1['network']['name']][1]['addr']]
networks = [netaddr.IPNetwork('19.80.0.0/24'),
netaddr.IPNetwork('19.86.0.0/24'),
netaddr.IPNetwork('19.80.0.0/24')]
for address, network in zip(addr, networks):
self.assertIn(address, network)
class ServersWithSpecificFlavorTestJSON(base.BaseV2ComputeAdminTest):
disk_config = 'AUTO'
@classmethod
def setup_credentials(cls):
cls.prepare_instance_network()
super(ServersWithSpecificFlavorTestJSON, cls).setup_credentials()
@classmethod
def setup_clients(cls):
super(ServersWithSpecificFlavorTestJSON, cls).setup_clients()
cls.flavor_client = cls.os_adm.flavors_client
cls.client = cls.servers_client
@classmethod
def resource_setup(cls):
cls.set_validation_resources()
super(ServersWithSpecificFlavorTestJSON, cls).resource_setup()
@test.idempotent_id('b3c7bcfc-bb5b-4e22-b517-c7f686b802ca')
@testtools.skipUnless(CONF.validation.run_validation,
'Instance validation tests are disabled.')
def test_verify_created_server_ephemeral_disk(self):
# Verify that the ephemeral disk is created when creating server
flavor_base = self.flavors_client.show_flavor(
self.flavor_ref)['flavor']
def create_flavor_with_extra_specs():
flavor_with_eph_disk_name = data_utils.rand_name('eph_flavor')
flavor_with_eph_disk_id = data_utils.rand_int_id(start=1000)
ram = flavor_base['ram']
vcpus = flavor_base['vcpus']
disk = flavor_base['disk']
# Create a flavor with extra specs
flavor = (self.flavor_client.
create_flavor(name=flavor_with_eph_disk_name,
ram=ram, vcpus=vcpus, disk=disk,
id=flavor_with_eph_disk_id,
ephemeral=1))['flavor']
self.addCleanup(flavor_clean_up, flavor['id'])
return flavor['id']
def create_flavor_without_extra_specs():
flavor_no_eph_disk_name = data_utils.rand_name('no_eph_flavor')
flavor_no_eph_disk_id = data_utils.rand_int_id(start=1000)
ram = flavor_base['ram']
vcpus = flavor_base['vcpus']
disk = flavor_base['disk']
# Create a flavor without extra specs
flavor = (self.flavor_client.
create_flavor(name=flavor_no_eph_disk_name,
ram=ram, vcpus=vcpus, disk=disk,
id=flavor_no_eph_disk_id))['flavor']
self.addCleanup(flavor_clean_up, flavor['id'])
return flavor['id']
def flavor_clean_up(flavor_id):
self.flavor_client.delete_flavor(flavor_id)
self.flavor_client.wait_for_resource_deletion(flavor_id)
flavor_with_eph_disk_id = create_flavor_with_extra_specs()
flavor_no_eph_disk_id = create_flavor_without_extra_specs()
admin_pass = self.image_ssh_password
server_no_eph_disk = self.create_test_server(
validatable=True,
wait_until='ACTIVE',
adminPass=admin_pass,
flavor=flavor_no_eph_disk_id)
# Get partition number of server without extra specs.
server_no_eph_disk = self.client.show_server(
server_no_eph_disk['id'])['server']
linux_client = remote_client.RemoteClient(
self.get_server_ip(server_no_eph_disk),
self.ssh_user,
admin_pass,
self.validation_resources['keypair']['private_key'])
partition_num = len(linux_client.get_partitions().split('\n'))
# Explicit server deletion necessary for Juno compatibility
self.client.delete_server(server_no_eph_disk['id'])
server_with_eph_disk = self.create_test_server(
validatable=True,
wait_until='ACTIVE',
adminPass=admin_pass,
flavor=flavor_with_eph_disk_id)
server_with_eph_disk = self.client.show_server(
server_with_eph_disk['id'])['server']
linux_client = remote_client.RemoteClient(
self.get_server_ip(server_with_eph_disk),
self.ssh_user,
admin_pass,
self.validation_resources['keypair']['private_key'])
partition_num_emph = len(linux_client.get_partitions().split('\n'))
self.assertEqual(partition_num + 1, partition_num_emph)
class ServersTestManualDisk(ServersTestJSON):
disk_config = 'MANUAL'
@classmethod
def skip_checks(cls):
super(ServersTestManualDisk, cls).skip_checks()
if not CONF.compute_feature_enabled.disk_config:
msg = "DiskConfig extension not enabled."
raise cls.skipException(msg)
| true | true |
f719c272300d7b8fc3f56eac0566b018ef20c845 | 1,313 | py | Python | ooobuild/dyn/i18n/x_calendar4.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | ooobuild/dyn/i18n/x_calendar4.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | ooobuild/dyn/i18n/x_calendar4.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http: // www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Interface Class
# this is a auto generated file generated by Cheetah
# Libre Office Version: 7.3
# Namespace: com.sun.star.i18n
from typing import TYPE_CHECKING
from ooo.oenv.env_const import UNO_ENVIRONMENT, UNO_RUNTIME
_DYNAMIC = False
if (not TYPE_CHECKING) and UNO_RUNTIME and UNO_ENVIRONMENT:
_DYNAMIC = True
if not TYPE_CHECKING and _DYNAMIC:
from com.sun.star.i18n import XCalendar4 as XCalendar4
setattr(XCalendar4, '__ooo_ns__', 'com.sun.star.i18n')
setattr(XCalendar4, '__ooo_full_ns__', 'com.sun.star.i18n.XCalendar4')
setattr(XCalendar4, '__ooo_type_name__', 'interface')
else:
from ...lo.i18n.x_calendar4 import XCalendar4 as XCalendar4
__all__ = ['XCalendar4']
| 35.486486 | 74 | 0.760091 |
from typing import TYPE_CHECKING
from ooo.oenv.env_const import UNO_ENVIRONMENT, UNO_RUNTIME
_DYNAMIC = False
if (not TYPE_CHECKING) and UNO_RUNTIME and UNO_ENVIRONMENT:
_DYNAMIC = True
if not TYPE_CHECKING and _DYNAMIC:
from com.sun.star.i18n import XCalendar4 as XCalendar4
setattr(XCalendar4, '__ooo_ns__', 'com.sun.star.i18n')
setattr(XCalendar4, '__ooo_full_ns__', 'com.sun.star.i18n.XCalendar4')
setattr(XCalendar4, '__ooo_type_name__', 'interface')
else:
from ...lo.i18n.x_calendar4 import XCalendar4 as XCalendar4
__all__ = ['XCalendar4']
| true | true |
f719c298d161b599d989c8e2337e4c83af090b4b | 1,483 | py | Python | test/test_binary.py | teristam/openephys-fileIO | 8089e7c4aff829c13a79656b8812a3d3e68eb1eb | [
"MIT"
] | 1 | 2020-08-16T21:52:10.000Z | 2020-08-16T21:52:10.000Z | test/test_binary.py | teristam/openephys-fileIO | 8089e7c4aff829c13a79656b8812a3d3e68eb1eb | [
"MIT"
] | null | null | null | test/test_binary.py | teristam/openephys-fileIO | 8089e7c4aff829c13a79656b8812a3d3e68eb1eb | [
"MIT"
] | null | null | null | import numpy as np
from openephys_fileIO.fileIO import *
from openephys_fileIO.Binary import *
def test_write_binary_data():
# Test writing of binary data
dataFolder = 'test/data'
# Read the data in original int16 format
data,headers = load_OpenEphysRecording4BinaryFile(dataFolder,
num_data_channel=1,num_aux_channel=1, num_adc_channel=1)
print(headers)
# Write to binary file
writeBinaryData(dataFolder+'/experiment1/recording1/',data)
writeStructFile(dataFolder+'/experiment1/recording1/structure.oebin',headers)
#load the data in float format (take care of the bit per volt)
data,headers = load_OpenEphysRecording4BinaryFile(dataFolder,
num_data_channel=1,num_aux_channel=1, num_adc_channel=1,dtype=float)
# Load binary file using the offical function
data2, rate2 = Load('test/data')
np.allclose(data.T,data2['100']['0']['0'])
def test_numpy2binary():
# test write of numpy data
Fs = 30000
x = np.random.randn(3*Fs,4)
bitVolts = 0.195
dataFolder = 'test/data2'
channel_names = [f'CH{i}' for i in range(x.shape[1])]
writeBinaryData(dataFolder+'/experiment1/recording1/', x, bitVolts)
writeStructFile(dataFolder+'/experiment1/recording1/structure.oebin',samplerate=30000,
num_channels= x.shape[1], bit_volts=bitVolts,channel_names=channel_names)
# load the binary file
data, rate = Load(dataFolder)
np.allclose(x, data['100']['0']['0'])
| 29.66 | 90 | 0.710722 | import numpy as np
from openephys_fileIO.fileIO import *
from openephys_fileIO.Binary import *
def test_write_binary_data():
dataFolder = 'test/data'
data,headers = load_OpenEphysRecording4BinaryFile(dataFolder,
num_data_channel=1,num_aux_channel=1, num_adc_channel=1)
print(headers)
writeBinaryData(dataFolder+'/experiment1/recording1/',data)
writeStructFile(dataFolder+'/experiment1/recording1/structure.oebin',headers)
data,headers = load_OpenEphysRecording4BinaryFile(dataFolder,
num_data_channel=1,num_aux_channel=1, num_adc_channel=1,dtype=float)
data2, rate2 = Load('test/data')
np.allclose(data.T,data2['100']['0']['0'])
def test_numpy2binary():
Fs = 30000
x = np.random.randn(3*Fs,4)
bitVolts = 0.195
dataFolder = 'test/data2'
channel_names = [f'CH{i}' for i in range(x.shape[1])]
writeBinaryData(dataFolder+'/experiment1/recording1/', x, bitVolts)
writeStructFile(dataFolder+'/experiment1/recording1/structure.oebin',samplerate=30000,
num_channels= x.shape[1], bit_volts=bitVolts,channel_names=channel_names)
data, rate = Load(dataFolder)
np.allclose(x, data['100']['0']['0'])
| true | true |
f719c2d3c90414ada7ec442b5268bf062e2a60e0 | 23,986 | py | Python | ckan/logic/__init__.py | robbi5/ckan | e89ca125dc68ddb9fe9bad68a401404146ba90c7 | [
"BSD-3-Clause"
] | 6 | 2015-11-09T00:44:51.000Z | 2019-11-21T14:56:01.000Z | ckan/logic/__init__.py | robbi5/ckan | e89ca125dc68ddb9fe9bad68a401404146ba90c7 | [
"BSD-3-Clause"
] | 39 | 2015-02-18T17:32:23.000Z | 2022-03-11T18:03:36.000Z | ckan/logic/__init__.py | robbi5/ckan | e89ca125dc68ddb9fe9bad68a401404146ba90c7 | [
"BSD-3-Clause"
] | 17 | 2015-03-13T18:05:05.000Z | 2020-11-06T13:55:32.000Z | # encoding: utf-8
import inspect
import functools
import logging
import re
import importlib
import inspect
from collections import defaultdict
from werkzeug.utils import import_string
import six
from six import string_types, text_type
import ckan.model as model
import ckan.authz as authz
import ckan.lib.navl.dictization_functions as df
import ckan.plugins as p
from ckan.common import _, c
log = logging.getLogger(__name__)
_validate = df.validate
class NameConflict(Exception):
pass
class UsernamePasswordError(Exception):
pass
class ActionError(Exception):
def __init__(self, message=''):
self.message = message
super(ActionError, self).__init__(message)
def __str__(self):
msg = self.message
if not isinstance(msg, six.string_types):
msg = str(msg)
return six.ensure_text(msg)
class NotFound(ActionError):
'''Exception raised by logic functions when a given object is not found.
For example :py:func:`~ckan.logic.action.get.package_show` raises
:py:exc:`~ckan.plugins.toolkit.ObjectNotFound` if no package with the
given ``id`` exists.
'''
pass
class NotAuthorized(ActionError):
'''Exception raised when the user is not authorized to call the action.
For example :py:func:`~ckan.logic.action.create.package_create` raises
:py:exc:`~ckan.plugins.toolkit.NotAuthorized` if the user is not authorized
to create packages.
'''
pass
class ValidationError(ActionError):
'''Exception raised by action functions when validating their given
``data_dict`` fails.
'''
def __init__(self, error_dict, error_summary=None, extra_msg=None):
if not isinstance(error_dict, dict):
error_dict = {'message': error_dict}
# tags errors are a mess so let's clean them up
if 'tags' in error_dict:
tag_errors = []
for error in error_dict['tags']:
try:
tag_errors.append(', '.join(error['name']))
except KeyError:
# e.g. if it is a vocabulary_id error
if error:
tag_errors.append(error)
error_dict['tags'] = tag_errors
self.error_dict = error_dict
self._error_summary = error_summary
super(ValidationError, self).__init__(extra_msg)
@property
def error_summary(self):
''' autogenerate the summary if not supplied '''
def summarise(error_dict):
''' Do some i18n stuff on the error_dict keys '''
def prettify(field_name):
field_name = re.sub(r'(?<!\w)[Uu]rl(?!\w)', 'URL',
field_name.replace('_', ' ').capitalize())
return _(field_name.replace('_', ' '))
summary = {}
for key, error in six.iteritems(error_dict):
if key == 'resources':
summary[_('Resources')] = _('Package resource(s) invalid')
elif key == 'extras':
errors_extras = []
for item in error:
if (item.get('key') and
item['key'][0] not in errors_extras):
errors_extras.append(item.get('key')[0])
summary[_('Extras')] = ', '.join(errors_extras)
elif key == 'extras_validation':
summary[_('Extras')] = error[0]
elif key == 'tags':
summary[_('Tags')] = error[0]
else:
summary[_(prettify(key))] = error[0]
return summary
if self._error_summary:
return self._error_summary
return summarise(self.error_dict)
def __str__(self):
err_msgs = (super(ValidationError, self).__str__(),
self.error_dict)
return ' - '.join([str(err_msg) for err_msg in err_msgs if err_msg])
log = logging.getLogger(__name__)
def parse_params(params, ignore_keys=None):
'''Takes a dict and returns it with some values standardised.
This is done on a dict before calling tuplize_dict on it.
'''
parsed = {}
for key in params:
if ignore_keys and key in ignore_keys:
continue
# flask request has `getlist` instead of pylons' `getall`
if hasattr(params, 'getall'):
value = params.getall(key)
else:
value = params.getlist(key)
# Blank values become ''
if not value:
value = ''
# A list with only one item is stripped of being a list
if len(value) == 1:
value = value[0]
parsed[key] = value
return parsed
def clean_dict(data_dict):
'''Takes a dict and if any of the values are lists of dicts,
the empty dicts are stripped from the lists (recursive).
e.g.
>>> clean_dict(
{'name': u'testgrp4',
'title': u'',
'description': u'',
'packages': [{'name': u'testpkg'}, {'name': u'testpkg'}],
'extras': [{'key': u'packages', 'value': u'["testpkg"]'},
{'key': u'', 'value': u''},
{'key': u'', 'value': u''}],
'state': u'active'}
{'name': u'testgrp4',
'title': u'',
'description': u'',
'packages': [{'name': u'testpkg'}, {'name': u'testpkg'}],
'extras': [{'key': u'packages', 'value': u'["testpkg"]'}],
'state': u'active'}
'''
for key, value in data_dict.items():
if not isinstance(value, list):
continue
for inner_dict in value[:]:
if isinstance(inner_dict, string_types):
break
if not any(inner_dict.values()):
value.remove(inner_dict)
else:
clean_dict(inner_dict)
return data_dict
def tuplize_dict(data_dict):
'''Takes a dict with keys of the form 'table__0__key' and converts them
to a tuple like ('table', 0, 'key').
Dict should be put through parse_dict before this function, to have
values standardized.
May raise a DataError if the format of the key is incorrect.
'''
tuplized_dict = {}
for key, value in six.iteritems(data_dict):
key_list = key.split('__')
for num, key in enumerate(key_list):
if num % 2 == 1:
try:
key_list[num] = int(key)
except ValueError:
raise df.DataError('Bad key')
tuplized_dict[tuple(key_list)] = value
return tuplized_dict
def untuplize_dict(tuplized_dict):
data_dict = {}
for key, value in six.iteritems(tuplized_dict):
new_key = '__'.join([str(item) for item in key])
data_dict[new_key] = value
return data_dict
def flatten_to_string_key(dict):
flattented = df.flatten_dict(dict)
return untuplize_dict(flattented)
def _prepopulate_context(context):
if context is None:
context = {}
context.setdefault('model', model)
context.setdefault('session', model.Session)
try:
context.setdefault('user', c.user)
except AttributeError:
# c.user not set
pass
except RuntimeError:
# Outside of request context
pass
except TypeError:
# c not registered
pass
return context
def check_access(action, context, data_dict=None):
'''Calls the authorization function for the provided action
This is the only function that should be called to determine whether a
user (or an anonymous request) is allowed to perform a particular action.
The function accepts a context object, which should contain a 'user' key
with the name of the user performing the action, and optionally a
dictionary with extra data to be passed to the authorization function.
For example::
check_access('package_update', context, data_dict)
If not already there, the function will add an `auth_user_obj` key to the
context object with the actual User object (in case it exists in the
database). This check is only performed once per context object.
Raise :py:exc:`~ckan.plugins.toolkit.NotAuthorized` if the user is not
authorized to call the named action function.
If the user *is* authorized to call the action, return ``True``.
:param action: the name of the action function, eg. ``'package_create'``
:type action: string
:param context:
:type context: dict
:param data_dict:
:type data_dict: dict
:raises: :py:exc:`~ckan.plugins.toolkit.NotAuthorized` if the user is not
authorized to call the named action
'''
# Auth Auditing. We remove this call from the __auth_audit stack to show
# we have called the auth function
try:
audit = context.get('__auth_audit', [])[-1]
except IndexError:
audit = ''
if audit and audit[0] == action:
context['__auth_audit'].pop()
user = context.get('user')
try:
if 'auth_user_obj' not in context:
context['auth_user_obj'] = None
if not context.get('ignore_auth'):
if not context.get('__auth_user_obj_checked'):
if context.get('user') and not context.get('auth_user_obj'):
context['auth_user_obj'] = \
model.User.by_name(context['user'])
context['__auth_user_obj_checked'] = True
context = _prepopulate_context(context)
logic_authorization = authz.is_authorized(action, context,
data_dict)
if not logic_authorization['success']:
msg = logic_authorization.get('msg', '')
raise NotAuthorized(msg)
except NotAuthorized as e:
log.debug(u'check access NotAuthorized - %s user=%s "%s"',
action, user, text_type(e))
raise
log.debug('check access OK - %s user=%s', action, user)
return True
_actions = {}
def clear_actions_cache():
_actions.clear()
def chained_action(func):
func.chained_action = True
return func
def _is_chained_action(func):
return getattr(func, 'chained_action', False)
def get_action(action):
'''Return the named :py:mod:`ckan.logic.action` function.
For example ``get_action('package_create')`` will normally return the
:py:func:`ckan.logic.action.create.package_create()` function.
For documentation of the available action functions, see
:ref:`api-reference`.
You should always use ``get_action()`` instead of importing an action
function directly, because :py:class:`~ckan.plugins.interfaces.IActions`
plugins can override action functions, causing ``get_action()`` to return a
plugin-provided function instead of the default one.
Usage::
import ckan.plugins.toolkit as toolkit
# Call the package_create action function:
toolkit.get_action('package_create')(context, data_dict)
As the context parameter passed to an action function is commonly::
context = {'model': ckan.model, 'session': ckan.model.Session,
'user': pylons.c.user}
an action function returned by ``get_action()`` will automatically add
these parameters to the context if they are not defined. This is
especially useful for plugins as they should not really be importing parts
of ckan eg :py:mod:`ckan.model` and as such do not have access to ``model``
or ``model.Session``.
If a ``context`` of ``None`` is passed to the action function then the
default context dict will be created.
.. note::
Many action functions modify the context dict. It can therefore
not be reused for multiple calls of the same or different action
functions.
:param action: name of the action function to return,
eg. ``'package_create'``
:type action: string
:returns: the named action function
:rtype: callable
'''
if _actions:
if action not in _actions:
raise KeyError("Action '%s' not found" % action)
return _actions.get(action)
# Otherwise look in all the plugins to resolve all possible First
# get the default ones in the ckan/logic/action directory Rather
# than writing them out in full will use importlib.import_module
# to load anything from ckan.logic.action that looks like it might
# be an action
for action_module_name in ['get', 'create', 'update', 'delete', 'patch']:
module = importlib.import_module(
'.' + action_module_name, 'ckan.logic.action')
for k, v in authz.get_local_functions(module):
_actions[k] = v
# Whitelist all actions defined in logic/action/get.py as
# being side-effect free.
if action_module_name == 'get' and \
not hasattr(v, 'side_effect_free'):
v.side_effect_free = True
# Then overwrite them with any specific ones in the plugins:
resolved_action_plugins = {}
fetched_actions = {}
chained_actions = defaultdict(list)
for plugin in p.PluginImplementations(p.IActions):
for name, action_function in plugin.get_actions().items():
if _is_chained_action(action_function):
chained_actions[name].append(action_function)
elif name in resolved_action_plugins:
raise NameConflict(
'The action %r is already implemented in %r' % (
name,
resolved_action_plugins[name]
)
)
else:
resolved_action_plugins[name] = plugin.name
# Extensions are exempted from the auth audit for now
# This needs to be resolved later
action_function.auth_audit_exempt = True
fetched_actions[name] = action_function
for name, func_list in six.iteritems(chained_actions):
if name not in fetched_actions and name not in _actions:
# nothing to override from plugins or core
raise NotFound('The action %r is not found for chained action' % (
name))
for func in reversed(func_list):
# try other plugins first, fall back to core
prev_func = fetched_actions.get(name, _actions.get(name))
new_func = functools.partial(func, prev_func)
# persisting attributes to the new partial function
for attribute, value in six.iteritems(func.__dict__):
setattr(new_func, attribute, value)
fetched_actions[name] = new_func
# Use the updated ones in preference to the originals.
_actions.update(fetched_actions)
# wrap the functions
for action_name, _action in _actions.items():
def make_wrapped(_action, action_name):
def wrapped(context=None, data_dict=None, **kw):
if kw:
log.critical('%s was passed extra keywords %r'
% (_action.__name__, kw))
context = _prepopulate_context(context)
# Auth Auditing - checks that the action function did call
# check_access (unless there is no accompanying auth function).
# We push the action name and id onto the __auth_audit stack
# before calling the action, and check_access removes it.
# (We need the id of the action in case the action is wrapped
# inside an action of the same name, which happens in the
# datastore)
context.setdefault('__auth_audit', [])
context['__auth_audit'].append((action_name, id(_action)))
# check_access(action_name, context, data_dict=None)
result = _action(context, data_dict, **kw)
try:
audit = context['__auth_audit'][-1]
if audit[0] == action_name and audit[1] == id(_action):
if action_name not in authz.auth_functions_list():
log.debug('No auth function for %s' % action_name)
elif not getattr(_action, 'auth_audit_exempt', False):
raise Exception(
'Action function {0} did not call its '
'auth function'
.format(action_name))
# remove from audit stack
context['__auth_audit'].pop()
except IndexError:
pass
return result
return wrapped
fn = make_wrapped(_action, action_name)
# we need to mirror the docstring
fn.__doc__ = _action.__doc__
# we need to retain the side effect free behaviour
if getattr(_action, 'side_effect_free', False):
fn.side_effect_free = True
_actions[action_name] = fn
return _actions.get(action)
def get_or_bust(data_dict, keys):
'''Return the value(s) from the given data_dict for the given key(s).
Usage::
single_value = get_or_bust(data_dict, 'a_key')
value_1, value_2 = get_or_bust(data_dict, ['key1', 'key2'])
:param data_dict: the dictionary to return the values from
:type data_dict: dictionary
:param keys: the key(s) for the value(s) to return
:type keys: either a string or a list
:returns: a single value from the dict if a single key was given,
or a tuple of values if a list of keys was given
:raises: :py:exc:`ckan.logic.ValidationError` if one of the given keys is
not in the given dictionary
'''
if isinstance(keys, string_types):
keys = [keys]
import ckan.logic.schema as schema
schema = schema.create_schema_for_required_keys(keys)
data_dict, errors = _validate(data_dict, schema)
if errors:
raise ValidationError(errors)
# preserve original key order
values = [data_dict[key] for key in keys]
if len(values) == 1:
return values[0]
return tuple(values)
def validate(schema_func, can_skip_validator=False):
''' A decorator that validates an action function against a given schema
'''
def action_decorator(action):
@functools.wraps(action)
def wrapper(context, data_dict):
if can_skip_validator:
if context.get('skip_validation'):
return action(context, data_dict)
schema = context.get('schema', schema_func())
data_dict, errors = _validate(data_dict, schema, context)
if errors:
raise ValidationError(errors)
return action(context, data_dict)
return wrapper
return action_decorator
def side_effect_free(action):
'''A decorator that marks the given action function as side-effect-free.
Action functions decorated with this decorator can be called with an HTTP
GET request to the :doc:`Action API </api/index>`. Action functions that
don't have this decorator must be called with a POST request.
If your CKAN extension defines its own action functions using the
:py:class:`~ckan.plugins.interfaces.IActions` plugin interface, you can use
this decorator to make your actions available with GET requests instead of
just with POST requests.
Example::
import ckan.plugins.toolkit as toolkit
@toolkit.side_effect_free
def my_custom_action_function(context, data_dict):
...
(Then implement :py:class:`~ckan.plugins.interfaces.IActions` to register
your action function with CKAN.)
'''
action.side_effect_free = True
return action
def auth_sysadmins_check(action):
'''A decorator that prevents sysadmins from being automatically authorized
to call an action function.
Normally sysadmins are allowed to call any action function (for example
when they're using the :doc:`Action API </api/index>` or the web
interface), if the user is a sysadmin the action function's authorization
function will not even be called.
If an action function is decorated with this decorator, then its
authorization function will always be called, even if the user is a
sysadmin.
'''
action.auth_sysadmins_check = True
return action
def auth_audit_exempt(action):
''' Dirty hack to stop auth audit being done '''
action.auth_audit_exempt = True
return action
def auth_allow_anonymous_access(action):
''' Flag an auth function as not requiring a logged in user
This means that check_access won't automatically raise a NotAuthorized
exception if an authenticated user is not provided in the context. (The
auth function can still return False if for some reason access is not
granted).
'''
action.auth_allow_anonymous_access = True
return action
def auth_disallow_anonymous_access(action):
''' Flag an auth function as requiring a logged in user
This means that check_access will automatically raise a NotAuthorized
exception if an authenticated user is not provided in the context, without
calling the actual auth function.
'''
action.auth_allow_anonymous_access = False
return action
def chained_auth_function(func):
'''
Decorator function allowing authentication functions to be chained.
'''
func.chained_auth_function = True
return func
class UnknownValidator(Exception):
'''Exception raised when a requested validator function cannot be found.
'''
pass
_validators_cache = {}
def clear_validators_cache():
_validators_cache.clear()
# This function exists mainly so that validators can be made available to
# extensions via ckan.plugins.toolkit.
def get_validator(validator):
'''Return a validator function by name.
:param validator: the name of the validator function to return,
eg. ``'package_name_exists'``
:type validator: string
:raises: :py:exc:`~ckan.plugins.toolkit.UnknownValidator` if the named
validator is not found
:returns: the named validator function
:rtype: ``types.FunctionType``
'''
if not _validators_cache:
validators = _import_module_functions('ckan.lib.navl.validators')
_validators_cache.update(validators)
validators = _import_module_functions('ckan.logic.validators')
_validators_cache.update(validators)
converters = _import_module_functions('ckan.logic.converters')
_validators_cache.update(converters)
_validators_cache.update({'OneOf': _validators_cache['one_of']})
for plugin in reversed(list(p.PluginImplementations(p.IValidators))):
for name, fn in plugin.get_validators().items():
log.debug('Validator function {0} from plugin {1} was inserted'
.format(name, plugin.name))
_validators_cache[name] = fn
try:
return _validators_cache[validator]
except KeyError:
raise UnknownValidator('Validator `%s` does not exist' % validator)
def model_name_to_class(model_module, model_name):
'''Return the class in model_module that has the same name as the
received string.
Raises AttributeError if there's no model in model_module named model_name.
'''
try:
model_class_name = model_name.title()
return getattr(model_module, model_class_name)
except AttributeError:
raise ValidationError("%s isn't a valid model" % model_class_name)
def _import_module_functions(module_path):
'''Import a module and get the functions and return them in a dict'''
module = importlib.import_module(module_path)
return {
k: v
for k, v in authz.get_local_functions(module)
}
| 33.688202 | 79 | 0.627741 |
import inspect
import functools
import logging
import re
import importlib
import inspect
from collections import defaultdict
from werkzeug.utils import import_string
import six
from six import string_types, text_type
import ckan.model as model
import ckan.authz as authz
import ckan.lib.navl.dictization_functions as df
import ckan.plugins as p
from ckan.common import _, c
log = logging.getLogger(__name__)
_validate = df.validate
class NameConflict(Exception):
pass
class UsernamePasswordError(Exception):
pass
class ActionError(Exception):
def __init__(self, message=''):
self.message = message
super(ActionError, self).__init__(message)
def __str__(self):
msg = self.message
if not isinstance(msg, six.string_types):
msg = str(msg)
return six.ensure_text(msg)
class NotFound(ActionError):
pass
class NotAuthorized(ActionError):
pass
class ValidationError(ActionError):
def __init__(self, error_dict, error_summary=None, extra_msg=None):
if not isinstance(error_dict, dict):
error_dict = {'message': error_dict}
if 'tags' in error_dict:
tag_errors = []
for error in error_dict['tags']:
try:
tag_errors.append(', '.join(error['name']))
except KeyError:
# e.g. if it is a vocabulary_id error
if error:
tag_errors.append(error)
error_dict['tags'] = tag_errors
self.error_dict = error_dict
self._error_summary = error_summary
super(ValidationError, self).__init__(extra_msg)
@property
def error_summary(self):
def summarise(error_dict):
def prettify(field_name):
field_name = re.sub(r'(?<!\w)[Uu]rl(?!\w)', 'URL',
field_name.replace('_', ' ').capitalize())
return _(field_name.replace('_', ' '))
summary = {}
for key, error in six.iteritems(error_dict):
if key == 'resources':
summary[_('Resources')] = _('Package resource(s) invalid')
elif key == 'extras':
errors_extras = []
for item in error:
if (item.get('key') and
item['key'][0] not in errors_extras):
errors_extras.append(item.get('key')[0])
summary[_('Extras')] = ', '.join(errors_extras)
elif key == 'extras_validation':
summary[_('Extras')] = error[0]
elif key == 'tags':
summary[_('Tags')] = error[0]
else:
summary[_(prettify(key))] = error[0]
return summary
if self._error_summary:
return self._error_summary
return summarise(self.error_dict)
def __str__(self):
err_msgs = (super(ValidationError, self).__str__(),
self.error_dict)
return ' - '.join([str(err_msg) for err_msg in err_msgs if err_msg])
log = logging.getLogger(__name__)
def parse_params(params, ignore_keys=None):
parsed = {}
for key in params:
if ignore_keys and key in ignore_keys:
continue
# flask request has `getlist` instead of pylons' `getall`
if hasattr(params, 'getall'):
value = params.getall(key)
else:
value = params.getlist(key)
if not value:
value = ''
if len(value) == 1:
value = value[0]
parsed[key] = value
return parsed
def clean_dict(data_dict):
for key, value in data_dict.items():
if not isinstance(value, list):
continue
for inner_dict in value[:]:
if isinstance(inner_dict, string_types):
break
if not any(inner_dict.values()):
value.remove(inner_dict)
else:
clean_dict(inner_dict)
return data_dict
def tuplize_dict(data_dict):
tuplized_dict = {}
for key, value in six.iteritems(data_dict):
key_list = key.split('__')
for num, key in enumerate(key_list):
if num % 2 == 1:
try:
key_list[num] = int(key)
except ValueError:
raise df.DataError('Bad key')
tuplized_dict[tuple(key_list)] = value
return tuplized_dict
def untuplize_dict(tuplized_dict):
data_dict = {}
for key, value in six.iteritems(tuplized_dict):
new_key = '__'.join([str(item) for item in key])
data_dict[new_key] = value
return data_dict
def flatten_to_string_key(dict):
flattented = df.flatten_dict(dict)
return untuplize_dict(flattented)
def _prepopulate_context(context):
if context is None:
context = {}
context.setdefault('model', model)
context.setdefault('session', model.Session)
try:
context.setdefault('user', c.user)
except AttributeError:
pass
except RuntimeError:
pass
except TypeError:
pass
return context
def check_access(action, context, data_dict=None):
try:
audit = context.get('__auth_audit', [])[-1]
except IndexError:
audit = ''
if audit and audit[0] == action:
context['__auth_audit'].pop()
user = context.get('user')
try:
if 'auth_user_obj' not in context:
context['auth_user_obj'] = None
if not context.get('ignore_auth'):
if not context.get('__auth_user_obj_checked'):
if context.get('user') and not context.get('auth_user_obj'):
context['auth_user_obj'] = \
model.User.by_name(context['user'])
context['__auth_user_obj_checked'] = True
context = _prepopulate_context(context)
logic_authorization = authz.is_authorized(action, context,
data_dict)
if not logic_authorization['success']:
msg = logic_authorization.get('msg', '')
raise NotAuthorized(msg)
except NotAuthorized as e:
log.debug(u'check access NotAuthorized - %s user=%s "%s"',
action, user, text_type(e))
raise
log.debug('check access OK - %s user=%s', action, user)
return True
_actions = {}
def clear_actions_cache():
_actions.clear()
def chained_action(func):
func.chained_action = True
return func
def _is_chained_action(func):
return getattr(func, 'chained_action', False)
def get_action(action):
if _actions:
if action not in _actions:
raise KeyError("Action '%s' not found" % action)
return _actions.get(action)
for action_module_name in ['get', 'create', 'update', 'delete', 'patch']:
module = importlib.import_module(
'.' + action_module_name, 'ckan.logic.action')
for k, v in authz.get_local_functions(module):
_actions[k] = v
if action_module_name == 'get' and \
not hasattr(v, 'side_effect_free'):
v.side_effect_free = True
resolved_action_plugins = {}
fetched_actions = {}
chained_actions = defaultdict(list)
for plugin in p.PluginImplementations(p.IActions):
for name, action_function in plugin.get_actions().items():
if _is_chained_action(action_function):
chained_actions[name].append(action_function)
elif name in resolved_action_plugins:
raise NameConflict(
'The action %r is already implemented in %r' % (
name,
resolved_action_plugins[name]
)
)
else:
resolved_action_plugins[name] = plugin.name
action_function.auth_audit_exempt = True
fetched_actions[name] = action_function
for name, func_list in six.iteritems(chained_actions):
if name not in fetched_actions and name not in _actions:
raise NotFound('The action %r is not found for chained action' % (
name))
for func in reversed(func_list):
prev_func = fetched_actions.get(name, _actions.get(name))
new_func = functools.partial(func, prev_func)
for attribute, value in six.iteritems(func.__dict__):
setattr(new_func, attribute, value)
fetched_actions[name] = new_func
_actions.update(fetched_actions)
for action_name, _action in _actions.items():
def make_wrapped(_action, action_name):
def wrapped(context=None, data_dict=None, **kw):
if kw:
log.critical('%s was passed extra keywords %r'
% (_action.__name__, kw))
context = _prepopulate_context(context)
context.setdefault('__auth_audit', [])
context['__auth_audit'].append((action_name, id(_action)))
result = _action(context, data_dict, **kw)
try:
audit = context['__auth_audit'][-1]
if audit[0] == action_name and audit[1] == id(_action):
if action_name not in authz.auth_functions_list():
log.debug('No auth function for %s' % action_name)
elif not getattr(_action, 'auth_audit_exempt', False):
raise Exception(
'Action function {0} did not call its '
'auth function'
.format(action_name))
context['__auth_audit'].pop()
except IndexError:
pass
return result
return wrapped
fn = make_wrapped(_action, action_name)
fn.__doc__ = _action.__doc__
if getattr(_action, 'side_effect_free', False):
fn.side_effect_free = True
_actions[action_name] = fn
return _actions.get(action)
def get_or_bust(data_dict, keys):
if isinstance(keys, string_types):
keys = [keys]
import ckan.logic.schema as schema
schema = schema.create_schema_for_required_keys(keys)
data_dict, errors = _validate(data_dict, schema)
if errors:
raise ValidationError(errors)
values = [data_dict[key] for key in keys]
if len(values) == 1:
return values[0]
return tuple(values)
def validate(schema_func, can_skip_validator=False):
def action_decorator(action):
@functools.wraps(action)
def wrapper(context, data_dict):
if can_skip_validator:
if context.get('skip_validation'):
return action(context, data_dict)
schema = context.get('schema', schema_func())
data_dict, errors = _validate(data_dict, schema, context)
if errors:
raise ValidationError(errors)
return action(context, data_dict)
return wrapper
return action_decorator
def side_effect_free(action):
action.side_effect_free = True
return action
def auth_sysadmins_check(action):
action.auth_sysadmins_check = True
return action
def auth_audit_exempt(action):
action.auth_audit_exempt = True
return action
def auth_allow_anonymous_access(action):
action.auth_allow_anonymous_access = True
return action
def auth_disallow_anonymous_access(action):
action.auth_allow_anonymous_access = False
return action
def chained_auth_function(func):
func.chained_auth_function = True
return func
class UnknownValidator(Exception):
pass
_validators_cache = {}
def clear_validators_cache():
_validators_cache.clear()
def get_validator(validator):
if not _validators_cache:
validators = _import_module_functions('ckan.lib.navl.validators')
_validators_cache.update(validators)
validators = _import_module_functions('ckan.logic.validators')
_validators_cache.update(validators)
converters = _import_module_functions('ckan.logic.converters')
_validators_cache.update(converters)
_validators_cache.update({'OneOf': _validators_cache['one_of']})
for plugin in reversed(list(p.PluginImplementations(p.IValidators))):
for name, fn in plugin.get_validators().items():
log.debug('Validator function {0} from plugin {1} was inserted'
.format(name, plugin.name))
_validators_cache[name] = fn
try:
return _validators_cache[validator]
except KeyError:
raise UnknownValidator('Validator `%s` does not exist' % validator)
def model_name_to_class(model_module, model_name):
try:
model_class_name = model_name.title()
return getattr(model_module, model_class_name)
except AttributeError:
raise ValidationError("%s isn't a valid model" % model_class_name)
def _import_module_functions(module_path):
module = importlib.import_module(module_path)
return {
k: v
for k, v in authz.get_local_functions(module)
}
| true | true |
f719c3d21c3cbd95489d2ede11b990e85803833d | 79 | py | Python | Chapter03/circle_call.py | PacktPublishing/Secret-Recipes-of-the-Python-Ninja | 805d00c7a54927ba94c9077e9a580508ee3c5e56 | [
"MIT"
] | 13 | 2018-06-21T01:44:49.000Z | 2021-12-01T10:49:53.000Z | Chapter03/circle_call.py | PacktPublishing/Secret-Recipes-of-the-Python-Ninja | 805d00c7a54927ba94c9077e9a580508ee3c5e56 | [
"MIT"
] | null | null | null | Chapter03/circle_call.py | PacktPublishing/Secret-Recipes-of-the-Python-Ninja | 805d00c7a54927ba94c9077e9a580508ee3c5e56 | [
"MIT"
] | 6 | 2018-10-05T08:29:24.000Z | 2022-01-11T14:49:50.000Z | r = input("Input radius: ")
diameter, circumference, area = circle_measures(r)
| 26.333333 | 50 | 0.734177 | r = input("Input radius: ")
diameter, circumference, area = circle_measures(r)
| true | true |
f719c48b433034a6d2941656747bb299c65248d8 | 9,652 | py | Python | QLearning.py | FlowerForAlgernon/ai_tetris | 7ac0d3875ad9b31fb260f7567a218e0de340c4e4 | [
"Apache-2.0"
] | 1 | 2021-12-19T14:07:37.000Z | 2021-12-19T14:07:37.000Z | QLearning.py | FlowerForAlgernon/ai_tetris | 7ac0d3875ad9b31fb260f7567a218e0de340c4e4 | [
"Apache-2.0"
] | null | null | null | QLearning.py | FlowerForAlgernon/ai_tetris | 7ac0d3875ad9b31fb260f7567a218e0de340c4e4 | [
"Apache-2.0"
] | null | null | null | """
这份代码使用 Q learning 算法训练并运行俄罗斯方块游戏 ai。其中简化状态空间的方法可参考论文 Adapting Reinforcement Learning to Tetris
"""
import numpy as np
from game import *
sub_well = 4
base = 7
def getStateIndex(field_width, field_height, field_map):
"""
因为每一列有 7 种不同的情况,所以采用七进制数来作为状态索引
"""
temp = [0 for _ in range(field_width)]
convert = {}
for i in range(-(base - 1)//2, (base - 1)//2 + 1):
convert[i] = i + (base - 1)//2
for x in range(field_width):
while temp[x] < field_height and field_map[temp[x]][x] == 0:
temp[x] += 1
index = 0
for i in range(field_width-1):
if temp[i+1] - temp[i] > (base - 1)//2:
index += base**i * convert[(base - 1)//2]
elif temp[i+1] - temp[i] < -(base - 1)//2:
index += base**i * convert[-(base - 1)//2]
else:
index += base**i * convert[temp[i+1] - temp[i]]
return index
def getAllPossibleLocation(field_width, field_map, block, layout):
all_possible_position = []
for x in range(field_width):
if block.isLegal(layout, (x, -4), field_map) is not State.Middle:
all_possible_position.append(x)
return all_possible_position
def findBottomPosition(field_map, block, x, layout):
y = -4
while block.isLegal(layout, (x, y), field_map) is not State.Bottom:
y += 1
return y - 1
def dropBlock(field_height, field_map, x0, y0, layout):
for (x, y) in layout:
if 0 <= y0 + y < field_height:
field_map[y0 + y][x0 + x] = 1
if y0 + y < 0:
return False
return True
def resetMap(field_width, field_height, field_map):
count = 0
for y in range(field_height):
for x in range(field_width):
if field_map[y][x] == 1:
field_map[y][x] = 0
count += 1
if count == 4:
return
def getNewMap(block, position, direction, field_map):
while block.direction is not direction:
block.rotate(field_map)
while block.position[0] > position[0]:
block.left(field_map)
while block.position[0] < position[0]:
block.right(field_map)
while not block.is_stop:
block.down(field_map)
class QLearning(Game):
def __init__(self):
super(QLearning, self).__init__(sub_well, 1000)
self.repeat_num = 200
self.alpha = 0.2
self.gamma = 0.8
self.lambda_ = 0.3
self.epsilon = 0.01
self.key = [((s, b), (p, d)) for s in range(base**(self.field_width-1)) for b in range(7) for p in range(self.field_width) for d in range(4)]
self.V = [0 for _ in range(len(self.key))]
self.Q = dict(zip(self.key, self.V))
#self.Q = np.load('QL.npy').item()
def checkEvents(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
def getBlock(self, block):
for x in range(len(Blocks_color)):
if block.color == Blocks_color[x]:
return x
def getReward(self):
temp = [0 for _ in range(self.field_width)]
for x in range(self.field_width):
while temp[x] < self.field_height and self.field_map[temp[x]][x] == 0:
temp[x] += 1
buried_holes = 0
block = self.block_factory.cur_block
for (x, y) in block.layout:
i = 1
while block.position[1]+y+i < self.field_height and self.field_map[block.position[1]+y+i][x] == 0:
buried_holes += 1
i += 1
return np.var(temp)*(-2) + buried_holes*(-1)
def getAllActions(self, block):
actions = []
for direction in range(len(block.layouts)):
for x in getAllPossibleLocation(self.field_width, self.field_map, block, block.layouts[direction]):
y = findBottomPosition(self.field_map, block, x, block.layouts[direction])
if dropBlock(self.field_height, self.field_map, x, y, block.layouts[direction]):
actions.append((x, direction))
resetMap(self.field_width, self.field_height, self.field_map)
return actions
def getBestActionWithGreedy(self, block):
block_type = self.getBlock(block)
state = getStateIndex(self.field_width, self.field_height, self.field_map)
actions = self.getAllActions(block)
actions_value = {}
for action in actions:
actions_value[action] = self.Q[((state, block_type), action)]
if actions_value == {}:
return None
elif random.random() > self.epsilon:
return max(actions_value, key=actions_value.get)
else:
return list(actions_value.keys())[random.randint(0, len(actions_value)-1)]
def getBestAction(self, block):
block_type = self.getBlock(block)
state = getStateIndex(self.field_width, self.field_height, self.field_map)
actions = self.getAllActions(block)
actions_value = {}
for action in actions:
actions_value[action] = self.Q[((state, block_type), action)]
if actions_value == {}:
return None
return max(actions_value, key=actions_value.get)
def train(self):
record = []
for i in range(1, self.repeat_num+1):
self.initialize()
while not self.block_factory.is_failed:
cur_state = getStateIndex(self.field_width, self.field_height, self.field_map)
cur_block = self.getBlock(self.block_factory.cur_block)
cur_action = self.getBestActionWithGreedy(self.block_factory.cur_block)
cur_index = ((cur_state, cur_block), cur_action)
if cur_action == None: break
getNewMap(self.block_factory.cur_block, cur_action, cur_action[1], self.field_map)
next_state = getStateIndex(self.field_width, self.field_height, self.field_map)
next_block = self.getBlock(self.block_factory.next_block)
next_action = self.getBestAction(self.block_factory.next_block)
next_index = ((next_state, next_block), next_action)
if next_action == None: break
self.Q[cur_index] += self.alpha*(self.getReward()+self.gamma*self.Q[next_index] - self.Q[cur_index])
self.update()
print("Epoch:"+str(i)+"/"+str(self.repeat_num)+" Lines:"+ str(self.lines_num)+" Alpha:"+str(self.alpha))
record.append(self.lines_num)
if i % 100 == 0:
self.alpha *= 0.5
np.save('QL.npy', {"V": self.V})
np.save('record_QL.npy', {"record": record})
np.save('QL.npy', self.Q)
np.save('record_QL.npy', {"record": record})
class QLGame(Game):
def __init__(self):
super(QLGame, self).__init__(10, 20)
self.Q = np.load('QL.npy', allow_pickle=True).item()
self.col = 0
def checkEvents(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
def getBlock(self, block):
for x in range(len(Blocks_color)):
if block.color == Blocks_color[x]:
return x
def cutFieldMap(self, position):
new_field_map = [[0]*sub_well for _ in range(self.field_height)]
for y in range(self.field_height):
for x in range(sub_well):
new_field_map[y][x] = self.field_map[y][position+x]
return new_field_map
def getAllActions(self, field_width, field_height, block, field_map, init_pos):
actions = {}
for direction in range(len(block.layouts)):
for x in getAllPossibleLocation(field_width, field_map, block, block.layouts[direction]):
y = findBottomPosition(field_map, block, x, block.layouts[direction])
if dropBlock(field_height, field_map, x, y, block.layouts[direction]):
block_type = self.getBlock(block)
state = getStateIndex(field_width, field_height, field_map)
actions[(x + init_pos, direction)] = self.Q[((state, block_type), (x, direction))]
resetMap(field_width, field_height, field_map)
return actions
def getBestAction(self):
actions = {}
cur_block = Block(self.block_factory.cur_block.screen, sub_well, self.field_height, self.block_factory.cur_block.layouts, self.block_factory.cur_block.direction, self.block_factory.cur_block.color, (0, -4))
for x in range(self.field_width - sub_well + 1):
loc_actions = self.getAllActions(sub_well, self.field_height, cur_block, self.cutFieldMap(x), x)
for k, v in loc_actions.items():
if k in actions:
actions[k].append(v)
else:
actions[k] = [v]
for k, v in actions.items():
actions[k] = max(v)
return max(actions, key=actions.get) if actions != {} else None
def start(self):
self.initialize()
self.initializePygame()
while not self.block_factory.is_failed:
self.checkEvents()
action = self.getBestAction()
if action == None:
break
getNewMap(self.block_factory.cur_block, action, action[1], self.field_map)
self.update()
self.draw()
return self.lines_num
if __name__ == '__main__':
train = QLearning()
train.train()
game = QLGame()
game.start()
| 38 | 214 | 0.585993 |
import numpy as np
from game import *
sub_well = 4
base = 7
def getStateIndex(field_width, field_height, field_map):
temp = [0 for _ in range(field_width)]
convert = {}
for i in range(-(base - 1)//2, (base - 1)//2 + 1):
convert[i] = i + (base - 1)//2
for x in range(field_width):
while temp[x] < field_height and field_map[temp[x]][x] == 0:
temp[x] += 1
index = 0
for i in range(field_width-1):
if temp[i+1] - temp[i] > (base - 1)//2:
index += base**i * convert[(base - 1)//2]
elif temp[i+1] - temp[i] < -(base - 1)//2:
index += base**i * convert[-(base - 1)//2]
else:
index += base**i * convert[temp[i+1] - temp[i]]
return index
def getAllPossibleLocation(field_width, field_map, block, layout):
all_possible_position = []
for x in range(field_width):
if block.isLegal(layout, (x, -4), field_map) is not State.Middle:
all_possible_position.append(x)
return all_possible_position
def findBottomPosition(field_map, block, x, layout):
y = -4
while block.isLegal(layout, (x, y), field_map) is not State.Bottom:
y += 1
return y - 1
def dropBlock(field_height, field_map, x0, y0, layout):
for (x, y) in layout:
if 0 <= y0 + y < field_height:
field_map[y0 + y][x0 + x] = 1
if y0 + y < 0:
return False
return True
def resetMap(field_width, field_height, field_map):
count = 0
for y in range(field_height):
for x in range(field_width):
if field_map[y][x] == 1:
field_map[y][x] = 0
count += 1
if count == 4:
return
def getNewMap(block, position, direction, field_map):
while block.direction is not direction:
block.rotate(field_map)
while block.position[0] > position[0]:
block.left(field_map)
while block.position[0] < position[0]:
block.right(field_map)
while not block.is_stop:
block.down(field_map)
class QLearning(Game):
def __init__(self):
super(QLearning, self).__init__(sub_well, 1000)
self.repeat_num = 200
self.alpha = 0.2
self.gamma = 0.8
self.lambda_ = 0.3
self.epsilon = 0.01
self.key = [((s, b), (p, d)) for s in range(base**(self.field_width-1)) for b in range(7) for p in range(self.field_width) for d in range(4)]
self.V = [0 for _ in range(len(self.key))]
self.Q = dict(zip(self.key, self.V))
def checkEvents(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
def getBlock(self, block):
for x in range(len(Blocks_color)):
if block.color == Blocks_color[x]:
return x
def getReward(self):
temp = [0 for _ in range(self.field_width)]
for x in range(self.field_width):
while temp[x] < self.field_height and self.field_map[temp[x]][x] == 0:
temp[x] += 1
buried_holes = 0
block = self.block_factory.cur_block
for (x, y) in block.layout:
i = 1
while block.position[1]+y+i < self.field_height and self.field_map[block.position[1]+y+i][x] == 0:
buried_holes += 1
i += 1
return np.var(temp)*(-2) + buried_holes*(-1)
def getAllActions(self, block):
actions = []
for direction in range(len(block.layouts)):
for x in getAllPossibleLocation(self.field_width, self.field_map, block, block.layouts[direction]):
y = findBottomPosition(self.field_map, block, x, block.layouts[direction])
if dropBlock(self.field_height, self.field_map, x, y, block.layouts[direction]):
actions.append((x, direction))
resetMap(self.field_width, self.field_height, self.field_map)
return actions
def getBestActionWithGreedy(self, block):
block_type = self.getBlock(block)
state = getStateIndex(self.field_width, self.field_height, self.field_map)
actions = self.getAllActions(block)
actions_value = {}
for action in actions:
actions_value[action] = self.Q[((state, block_type), action)]
if actions_value == {}:
return None
elif random.random() > self.epsilon:
return max(actions_value, key=actions_value.get)
else:
return list(actions_value.keys())[random.randint(0, len(actions_value)-1)]
def getBestAction(self, block):
block_type = self.getBlock(block)
state = getStateIndex(self.field_width, self.field_height, self.field_map)
actions = self.getAllActions(block)
actions_value = {}
for action in actions:
actions_value[action] = self.Q[((state, block_type), action)]
if actions_value == {}:
return None
return max(actions_value, key=actions_value.get)
def train(self):
record = []
for i in range(1, self.repeat_num+1):
self.initialize()
while not self.block_factory.is_failed:
cur_state = getStateIndex(self.field_width, self.field_height, self.field_map)
cur_block = self.getBlock(self.block_factory.cur_block)
cur_action = self.getBestActionWithGreedy(self.block_factory.cur_block)
cur_index = ((cur_state, cur_block), cur_action)
if cur_action == None: break
getNewMap(self.block_factory.cur_block, cur_action, cur_action[1], self.field_map)
next_state = getStateIndex(self.field_width, self.field_height, self.field_map)
next_block = self.getBlock(self.block_factory.next_block)
next_action = self.getBestAction(self.block_factory.next_block)
next_index = ((next_state, next_block), next_action)
if next_action == None: break
self.Q[cur_index] += self.alpha*(self.getReward()+self.gamma*self.Q[next_index] - self.Q[cur_index])
self.update()
print("Epoch:"+str(i)+"/"+str(self.repeat_num)+" Lines:"+ str(self.lines_num)+" Alpha:"+str(self.alpha))
record.append(self.lines_num)
if i % 100 == 0:
self.alpha *= 0.5
np.save('QL.npy', {"V": self.V})
np.save('record_QL.npy', {"record": record})
np.save('QL.npy', self.Q)
np.save('record_QL.npy', {"record": record})
class QLGame(Game):
def __init__(self):
super(QLGame, self).__init__(10, 20)
self.Q = np.load('QL.npy', allow_pickle=True).item()
self.col = 0
def checkEvents(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
def getBlock(self, block):
for x in range(len(Blocks_color)):
if block.color == Blocks_color[x]:
return x
def cutFieldMap(self, position):
new_field_map = [[0]*sub_well for _ in range(self.field_height)]
for y in range(self.field_height):
for x in range(sub_well):
new_field_map[y][x] = self.field_map[y][position+x]
return new_field_map
def getAllActions(self, field_width, field_height, block, field_map, init_pos):
actions = {}
for direction in range(len(block.layouts)):
for x in getAllPossibleLocation(field_width, field_map, block, block.layouts[direction]):
y = findBottomPosition(field_map, block, x, block.layouts[direction])
if dropBlock(field_height, field_map, x, y, block.layouts[direction]):
block_type = self.getBlock(block)
state = getStateIndex(field_width, field_height, field_map)
actions[(x + init_pos, direction)] = self.Q[((state, block_type), (x, direction))]
resetMap(field_width, field_height, field_map)
return actions
def getBestAction(self):
actions = {}
cur_block = Block(self.block_factory.cur_block.screen, sub_well, self.field_height, self.block_factory.cur_block.layouts, self.block_factory.cur_block.direction, self.block_factory.cur_block.color, (0, -4))
for x in range(self.field_width - sub_well + 1):
loc_actions = self.getAllActions(sub_well, self.field_height, cur_block, self.cutFieldMap(x), x)
for k, v in loc_actions.items():
if k in actions:
actions[k].append(v)
else:
actions[k] = [v]
for k, v in actions.items():
actions[k] = max(v)
return max(actions, key=actions.get) if actions != {} else None
def start(self):
self.initialize()
self.initializePygame()
while not self.block_factory.is_failed:
self.checkEvents()
action = self.getBestAction()
if action == None:
break
getNewMap(self.block_factory.cur_block, action, action[1], self.field_map)
self.update()
self.draw()
return self.lines_num
if __name__ == '__main__':
train = QLearning()
train.train()
game = QLGame()
game.start()
| true | true |
f719c4a70ee2814bd930a3c19d9d0b1401f193f9 | 834 | py | Python | pyvat/result.py | Alex-Espressone/pyvat | 266559c9d8af2aee7ecea3aed52a517181a412c8 | [
"Apache-2.0"
] | 48 | 2015-07-22T12:02:20.000Z | 2022-02-07T16:54:13.000Z | pyvat/result.py | Alex-Espressone/pyvat | 266559c9d8af2aee7ecea3aed52a517181a412c8 | [
"Apache-2.0"
] | 34 | 2015-03-27T17:47:38.000Z | 2022-02-08T18:14:55.000Z | pyvat/result.py | Alex-Espressone/pyvat | 266559c9d8af2aee7ecea3aed52a517181a412c8 | [
"Apache-2.0"
] | 40 | 2015-04-08T14:03:06.000Z | 2022-02-09T12:29:04.000Z | class VatNumberCheckResult(object):
"""Result of a VAT number validation check.
:ivar is_valid:
Boolean value indicating if the checked VAT number was deemed to be
valid. ``True`` if the VAT number is valid or ``False`` if the VAT
number is positively invalid.
:ivar log_lines:
Check log lines.
:ivar business_name: Optional business name retrieved for the VAT number.
:ivar business_address: Optional address retrieved for the VAT number.
"""
def __init__(self,
is_valid=None,
log_lines=None,
business_name=None,
business_address=None):
self.is_valid = is_valid
self.log_lines = log_lines or []
self.business_name = business_name
self.business_address = business_address
| 36.26087 | 77 | 0.641487 | class VatNumberCheckResult(object):
def __init__(self,
is_valid=None,
log_lines=None,
business_name=None,
business_address=None):
self.is_valid = is_valid
self.log_lines = log_lines or []
self.business_name = business_name
self.business_address = business_address
| true | true |
f719c4d93ac3ade1ce4c3daeee9db9db01e404b2 | 2,209 | py | Python | source code/Data Visualization.py | starkworld/Python-Course-work | 28715f079939129b442aedcd7edb2e0838886ba0 | [
"Apache-2.0"
] | null | null | null | source code/Data Visualization.py | starkworld/Python-Course-work | 28715f079939129b442aedcd7edb2e0838886ba0 | [
"Apache-2.0"
] | null | null | null | source code/Data Visualization.py | starkworld/Python-Course-work | 28715f079939129b442aedcd7edb2e0838886ba0 | [
"Apache-2.0"
] | null | null | null | """
Author : nkalyan🤠
implementing Python Scripts on reading and returning the name no of mails that sent each day in week
and plot/display them in bar graph
I wrote code In counting to count the number of emails sent by each distinct user. That code may be helpful for this assignment.
"""
import matplotlib.pyplot as plt
from os import getcwd
def file_path():
"""Method that ask the users file name and returns it"""
file_name = input("Enter the file name:")
return file_name
def pop_values(filename):
"""Method the reads file and returning value"""
file_name = filename
try: # look for exception
fp = open(file_name, "r")
except FileNotFoundError: # if found exception display error
print("File Does not exist, please check your file name")
exit()
else: # if no exceptions thrown then performs this block
with fp:
for line in fp:
line = line.strip("\n")
offset = line.find("From")
offset1 = line.find("@")
line = line[-24:]
offset3 = line.find("@")
if offset == 0 and offset1 > 0 and offset3 == -1:
line = line[:-21]
yield line
def main():
"""Calls the all functions that necessary to get the output"""
name = file_path() # calls the file path method
dictionary = {'Sun': 0, 'Mon': 0, 'Tue': 0, 'Wed': 0, 'Thu': 0, 'Fri': 0, 'Sat': 0} # store the day val in dict
value = pop_values(name)
count = 0
for i in value:
if i in dictionary:
dictionary[i] += 1
count += len(i)
val = dictionary.values()
keys = dictionary.keys()
zp = zip(dictionary.keys(), dictionary.values())
for item in val:
i = val
j = keys
plt.bar(j, i, align='center', alpha=0.5)
plt.ylabel('Number of messages')
plt.title('Emails per day')
plt.show() # method that shows the bar graph of our code result
if __name__ == '__main__':
"""calls the main method"""
main()
| 32.970149 | 132 | 0.557718 |
import matplotlib.pyplot as plt
from os import getcwd
def file_path():
file_name = input("Enter the file name:")
return file_name
def pop_values(filename):
file_name = filename
try:
fp = open(file_name, "r")
except FileNotFoundError:
print("File Does not exist, please check your file name")
exit()
else:
with fp:
for line in fp:
line = line.strip("\n")
offset = line.find("From")
offset1 = line.find("@")
line = line[-24:]
offset3 = line.find("@")
if offset == 0 and offset1 > 0 and offset3 == -1:
line = line[:-21]
yield line
def main():
name = file_path()
dictionary = {'Sun': 0, 'Mon': 0, 'Tue': 0, 'Wed': 0, 'Thu': 0, 'Fri': 0, 'Sat': 0}
value = pop_values(name)
count = 0
for i in value:
if i in dictionary:
dictionary[i] += 1
count += len(i)
val = dictionary.values()
keys = dictionary.keys()
zp = zip(dictionary.keys(), dictionary.values())
for item in val:
i = val
j = keys
plt.bar(j, i, align='center', alpha=0.5)
plt.ylabel('Number of messages')
plt.title('Emails per day')
plt.show()
if __name__ == '__main__':
main()
| true | true |
f719c4fee092036cf2a37dc220d4280aca8e4828 | 665 | py | Python | full-problems/studentRecord.py | vikas-t/DS-Algo | ea654d1cad5374c824c52da9d3815a9546eb43fa | [
"Apache-2.0"
] | null | null | null | full-problems/studentRecord.py | vikas-t/DS-Algo | ea654d1cad5374c824c52da9d3815a9546eb43fa | [
"Apache-2.0"
] | null | null | null | full-problems/studentRecord.py | vikas-t/DS-Algo | ea654d1cad5374c824c52da9d3815a9546eb43fa | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python3
#https://practice.geeksforgeeks.org/problems/student-record/0
def sol(records, n):
mx = 0
res = []
for ni in range(0, n*4, 4):
am = sum(map(int, records[ni+1:ni+4]))//3
if am > mx:
# If we find a better average overwrite the result list
# with the name of the student and the average
mx = am
res = [(records[ni], am)]
elif am == mx:
# If the averages are same append in the result list
res.append((records[ni], am))
for name, marks in res:
print(name, end=" ")
print(marks)
# print the result as stated in the problem | 33.25 | 67 | 0.557895 |
def sol(records, n):
mx = 0
res = []
for ni in range(0, n*4, 4):
am = sum(map(int, records[ni+1:ni+4]))//3
if am > mx:
mx = am
res = [(records[ni], am)]
elif am == mx:
res.append((records[ni], am))
for name, marks in res:
print(name, end=" ")
print(marks)
| true | true |
f719c541df617120f9d4a9a665699e9251dae5ac | 1,425 | py | Python | angrmanagement/plugins/bughouse/data/component_tree.py | DennyDai/angr-management | 8a4ba5dafbf2f4d2ba558528a0d1ae099a199a04 | [
"BSD-2-Clause"
] | 474 | 2015-08-10T17:47:15.000Z | 2022-03-31T21:10:55.000Z | angrmanagement/plugins/bughouse/data/component_tree.py | DennyDai/angr-management | 8a4ba5dafbf2f4d2ba558528a0d1ae099a199a04 | [
"BSD-2-Clause"
] | 355 | 2015-08-17T09:35:53.000Z | 2022-03-31T21:29:52.000Z | angrmanagement/plugins/bughouse/data/component_tree.py | DennyDai/angr-management | 8a4ba5dafbf2f4d2ba558528a0d1ae099a199a04 | [
"BSD-2-Clause"
] | 95 | 2015-08-11T14:36:12.000Z | 2022-03-31T23:01:01.000Z | from typing import List, Optional
class ComponentFunction:
__slots__ = ('mapped_base', 'virtual_addr', 'symbol_name', )
def __init__(self, mapped_base: int, virtual_addr: int, symbol_name: Optional[str]=None):
self.mapped_base = mapped_base
self.virtual_addr = virtual_addr
self.symbol_name = symbol_name
def __eq__(self, other):
return isinstance(other, ComponentFunction) and \
self.mapped_base == other.mapped_base and \
self.virtual_addr == other.virtual_addr
def __hash__(self):
return hash((ComponentFunction, self.mapped_base, self.virtual_addr))
class ComponentTreeNode:
def __init__(self, name=None):
self.name = name
self.components: List['ComponentTreeNode'] = [ ]
self.functions: List[ComponentFunction] = [ ]
def __eq__(self, other):
return isinstance(other, ComponentTreeNode) \
and self.components == other.components \
and set(self.functions) == set(other.functions)
def __hash__(self):
return hash((ComponentTreeNode,
hash(tuple(self.components)),
hash(tuple(sorted((f.mapped_base + f.virtual_addr) for f in self.functions))),
)
)
class ComponentTree:
def __init__(self, root: Optional[ComponentTreeNode]=None):
self.root = root
| 32.386364 | 99 | 0.627368 | from typing import List, Optional
class ComponentFunction:
__slots__ = ('mapped_base', 'virtual_addr', 'symbol_name', )
def __init__(self, mapped_base: int, virtual_addr: int, symbol_name: Optional[str]=None):
self.mapped_base = mapped_base
self.virtual_addr = virtual_addr
self.symbol_name = symbol_name
def __eq__(self, other):
return isinstance(other, ComponentFunction) and \
self.mapped_base == other.mapped_base and \
self.virtual_addr == other.virtual_addr
def __hash__(self):
return hash((ComponentFunction, self.mapped_base, self.virtual_addr))
class ComponentTreeNode:
def __init__(self, name=None):
self.name = name
self.components: List['ComponentTreeNode'] = [ ]
self.functions: List[ComponentFunction] = [ ]
def __eq__(self, other):
return isinstance(other, ComponentTreeNode) \
and self.components == other.components \
and set(self.functions) == set(other.functions)
def __hash__(self):
return hash((ComponentTreeNode,
hash(tuple(self.components)),
hash(tuple(sorted((f.mapped_base + f.virtual_addr) for f in self.functions))),
)
)
class ComponentTree:
def __init__(self, root: Optional[ComponentTreeNode]=None):
self.root = root
| true | true |
f719c5dcecb268d37900df93c57ea65672756916 | 2,829 | py | Python | analysis/stats.py | jasonrute/puzzle_cube | 7e05a21acd26cb30e729ba6a95e14e16c76c1780 | [
"MIT"
] | 81 | 2018-06-17T17:02:24.000Z | 2021-11-05T07:16:12.000Z | analysis/stats.py | jasonrute/puzzle_cube | 7e05a21acd26cb30e729ba6a95e14e16c76c1780 | [
"MIT"
] | 1 | 2018-09-20T08:04:19.000Z | 2018-09-20T12:14:55.000Z | analysis/stats.py | jasonrute/puzzle_cube | 7e05a21acd26cb30e729ba6a95e14e16c76c1780 | [
"MIT"
] | 23 | 2018-02-20T21:19:49.000Z | 2022-03-05T18:05:10.000Z | """
Training Statics Tools
A class for loading statistics related to a particular rutraiining session.
"""
import numpy as np
#from scipy import stats
import pandas as pd
import os
def str_between(s, start, end):
return (s.split(start))[1].split(end)[0]
def is_stat_file_version(file_name, version):
return file_name.startswith("stats_{}_gen".format(version)) and file_name.endswith(".h5")
class TrainingStates:
def __init__(self, versions, directory, verbose=True):
self.stats_files = self.get_stat_files(versions, directory)
if verbose:
print("Loading files:")
for f in self.stats_files:
print(directory + f)
self.generation_stats = self.load_stats('generation_stats')
self.game_stats = self.load_stats('game_stats')
self.move_stats = self.load_stats('self_play_stats')
def get_stat_files(self, versions, directory):
stat_files = []
for version in reversed(versions):
files = [directory + f for f in os.listdir(directory) if is_stat_file_version(f, version)]
stat_files += list(sorted(files))
return stat_files
def load_stats(self, key_name):
df_list = []
for f in self.stats_files:
path = f
generation = str_between(f, "_gen", ".h5")
df = pd.read_hdf(path, key=key_name)
df['_generation'] = int(generation)
df_list.append(df)
if df_list:
stats = pd.concat(df_list, ignore_index=True)
else:
return pd.DataFrame()
return stats
def first_move_stats(self):
"""
Note: There is an indexing issue (the index of first_play_stats is the orginal index
while the index of game_stats is the game number). The easiest fix is to just use
the values (an array) of the series and not the series itself.
"""
return self.move_stats[self.move_stats['_step_id'] == 0]
def found_target_on_first_move(self):
return (self.first_move_stats()['shortest_path'] >= 0).values
def lost_but_found_target_on_first_move(self):
return self.found_target_on_first_move() & ~self.game_stats['win']
def win_but_did_not_find_target_on_first_move(self):
return ~self.found_target_on_first_move() & self.game_stats['win']
if __name__ == '__main__':
from pprint import pprint
versions = ['v0.9.3']
save_dir = '../save/stats_v0.9.3/'
#VERSIONS = ['v0.9.2.1', 'v0.9.2']
#SAVE_DIR = '../save/stats_archive/'
cube_stats = TrainingStates(versions, save_dir)
pprint(cube_stats.generation_stats)
pprint(np.mean(cube_stats.lost_but_found_target_on_first_move()))
pprint(np.mean(cube_stats.win_but_did_not_find_target_on_first_move()))
| 32.147727 | 102 | 0.655355 |
import numpy as np
import pandas as pd
import os
def str_between(s, start, end):
return (s.split(start))[1].split(end)[0]
def is_stat_file_version(file_name, version):
return file_name.startswith("stats_{}_gen".format(version)) and file_name.endswith(".h5")
class TrainingStates:
def __init__(self, versions, directory, verbose=True):
self.stats_files = self.get_stat_files(versions, directory)
if verbose:
print("Loading files:")
for f in self.stats_files:
print(directory + f)
self.generation_stats = self.load_stats('generation_stats')
self.game_stats = self.load_stats('game_stats')
self.move_stats = self.load_stats('self_play_stats')
def get_stat_files(self, versions, directory):
stat_files = []
for version in reversed(versions):
files = [directory + f for f in os.listdir(directory) if is_stat_file_version(f, version)]
stat_files += list(sorted(files))
return stat_files
def load_stats(self, key_name):
df_list = []
for f in self.stats_files:
path = f
generation = str_between(f, "_gen", ".h5")
df = pd.read_hdf(path, key=key_name)
df['_generation'] = int(generation)
df_list.append(df)
if df_list:
stats = pd.concat(df_list, ignore_index=True)
else:
return pd.DataFrame()
return stats
def first_move_stats(self):
return self.move_stats[self.move_stats['_step_id'] == 0]
def found_target_on_first_move(self):
return (self.first_move_stats()['shortest_path'] >= 0).values
def lost_but_found_target_on_first_move(self):
return self.found_target_on_first_move() & ~self.game_stats['win']
def win_but_did_not_find_target_on_first_move(self):
return ~self.found_target_on_first_move() & self.game_stats['win']
if __name__ == '__main__':
from pprint import pprint
versions = ['v0.9.3']
save_dir = '../save/stats_v0.9.3/'
cube_stats = TrainingStates(versions, save_dir)
pprint(cube_stats.generation_stats)
pprint(np.mean(cube_stats.lost_but_found_target_on_first_move()))
pprint(np.mean(cube_stats.win_but_did_not_find_target_on_first_move()))
| true | true |
f719c6c53b95cb7f32858726c85cf496a8c0b670 | 1,192 | py | Python | lantz/drivers/thorlabs/pm100d.py | ZixiLi0520/lantz | a67120a65e6b66f394965ef0100529db7be3df0a | [
"BSD-3-Clause"
] | 6 | 2016-04-13T12:59:18.000Z | 2020-06-24T17:43:04.000Z | lantz/drivers/thorlabs/pm100d.py | awsch/lantz | 717f6962a471be7ceb61d1d8f6c6f381553df9c4 | [
"BSD-3-Clause"
] | null | null | null | lantz/drivers/thorlabs/pm100d.py | awsch/lantz | 717f6962a471be7ceb61d1d8f6c6f381553df9c4 | [
"BSD-3-Clause"
] | 6 | 2015-12-14T19:30:36.000Z | 2020-06-29T21:16:01.000Z | # -*- coding: utf-8 -*-
"""
To connect the power meter you'll need to use the "Power meter driver switcher" application to switch to the PM100D (Ni-Visa) drivers.
Then the resource name should show up when exceuting:
import visa
visa.ResourceManager().list_resources()
"""
from lantz.messagebased import MessageBasedDriver
from lantz import Feat
class PM100D(MessageBasedDriver):
DEFAULTS = {
'COMMON': {
'read_termination': '\n',
'write_termination': '\n',
},
}
@Feat(read_once=True)
def idn(self):
return self.query('*IDN?')
@Feat(units='W')
def power(self):
return float(self.query('MEAS:POWER?'))
@Feat(units='nm')
def correction_wavelength(self):
return float(self.query('SENSE:CORRECTION:WAVELENGTH?'))
@correction_wavelength.setter
def correction_wavelength(self, wavelength):
self.write('SENSE:CORRECTION:WAVELENGTH {}'.format(wavelength))
@Feat()
def correction_wavelength_range(self):
cmd = 'SENSE:CORRECTION:WAVELENGTH? {}'
cmd_vals = ['MIN', 'MAX']
return tuple(float(self.query(cmd.format(cmd_val))) for cmd_val in cmd_vals)
| 27.090909 | 134 | 0.655201 |
from lantz.messagebased import MessageBasedDriver
from lantz import Feat
class PM100D(MessageBasedDriver):
DEFAULTS = {
'COMMON': {
'read_termination': '\n',
'write_termination': '\n',
},
}
@Feat(read_once=True)
def idn(self):
return self.query('*IDN?')
@Feat(units='W')
def power(self):
return float(self.query('MEAS:POWER?'))
@Feat(units='nm')
def correction_wavelength(self):
return float(self.query('SENSE:CORRECTION:WAVELENGTH?'))
@correction_wavelength.setter
def correction_wavelength(self, wavelength):
self.write('SENSE:CORRECTION:WAVELENGTH {}'.format(wavelength))
@Feat()
def correction_wavelength_range(self):
cmd = 'SENSE:CORRECTION:WAVELENGTH? {}'
cmd_vals = ['MIN', 'MAX']
return tuple(float(self.query(cmd.format(cmd_val))) for cmd_val in cmd_vals)
| true | true |
f719c7438aaad15d2be4ec5a66891319541f52ff | 1,767 | py | Python | Scripts/reader/gpro_corpus.py | lasigeBioTM/ULISBOA-at-SemEval-2017 | 415dc3ebbd2365aa7620a9b4feb1218fa837d7d5 | [
"MIT"
] | 8 | 2018-05-10T10:27:18.000Z | 2021-08-30T02:55:54.000Z | Scripts/reader/gpro_corpus.py | lasigeBioTM/ULISBOA-at-SemEval-2017 | 415dc3ebbd2365aa7620a9b4feb1218fa837d7d5 | [
"MIT"
] | 4 | 2018-10-24T13:32:45.000Z | 2021-02-05T11:48:04.000Z | Scripts/reader/gpro_corpus.py | lasigeBioTM/ULISBOA-at-SemEval-2017 | 415dc3ebbd2365aa7620a9b4feb1218fa837d7d5 | [
"MIT"
] | 5 | 2020-07-22T06:13:56.000Z | 2020-11-18T14:48:39.000Z | import codecs
import logging
import pickle
from chemdner_corpus import ChemdnerCorpus
class GproCorpus(ChemdnerCorpus):
"""Chemdner GPRO corpus from BioCreative V"""
def __init__(self, corpusdir, **kwargs):
super(GproCorpus, self).__init__(corpusdir, **kwargs)
self.subtypes = ["NESTED", "IDENTIFIER", "FULL_NAME", "ABBREVIATION"]
def load_corpus(self, corenlpserver):
"""
Assume the corpus is already loaded as a ChemdnerCorpus
Load the pickle and get the docs
:param corenlpserver:
:return:
"""
ps = self.path.split("/")
cemp_path = "data/chemdner_" + "_".join(ps[-1].split("_")[1:]) + ".pickle"
corpus = pickle.load(open(cemp_path, 'rb'))
self.documents = corpus.documents
def load_annotations(self, ann_dir, etype="protein"):
logging.info("loading annotations file {}...".format(ann_dir))
with codecs.open(ann_dir, 'r', "utf-8") as inputfile:
for line in inputfile:
# logging.info("processing annotation %s/%s" % (n_lines, total_lines))
pmid, doct, start, end, text, t, dbid = line.strip().split('\t')
if dbid != "GPRO_TYPE_2" and pmid in self.documents:
#if pmid in self.documents:
#pmid = "PMID" + pmid
# For now, ignore the database ID information
#logging.debug("using this annotation: {}".format(text.encode("utf8")))
self.documents[pmid].tag_chemdner_entity(int(start), int(end),
t, text=text, doct=doct)
elif pmid not in self.documents:
logging.info("%s not found!" % pmid)
| 43.097561 | 91 | 0.57442 | import codecs
import logging
import pickle
from chemdner_corpus import ChemdnerCorpus
class GproCorpus(ChemdnerCorpus):
def __init__(self, corpusdir, **kwargs):
super(GproCorpus, self).__init__(corpusdir, **kwargs)
self.subtypes = ["NESTED", "IDENTIFIER", "FULL_NAME", "ABBREVIATION"]
def load_corpus(self, corenlpserver):
ps = self.path.split("/")
cemp_path = "data/chemdner_" + "_".join(ps[-1].split("_")[1:]) + ".pickle"
corpus = pickle.load(open(cemp_path, 'rb'))
self.documents = corpus.documents
def load_annotations(self, ann_dir, etype="protein"):
logging.info("loading annotations file {}...".format(ann_dir))
with codecs.open(ann_dir, 'r', "utf-8") as inputfile:
for line in inputfile:
pmid, doct, start, end, text, t, dbid = line.strip().split('\t')
if dbid != "GPRO_TYPE_2" and pmid in self.documents:
self.documents[pmid].tag_chemdner_entity(int(start), int(end),
t, text=text, doct=doct)
elif pmid not in self.documents:
logging.info("%s not found!" % pmid)
| true | true |
f719c759c9af0450e25345c13d5b68b9e3d98654 | 788 | py | Python | model.py | OrBin/N-Gram-Language-Model | e196758083bbed386dd1a24733cb956c8a36aa79 | [
"MIT"
] | null | null | null | model.py | OrBin/N-Gram-Language-Model | e196758083bbed386dd1a24733cb956c8a36aa79 | [
"MIT"
] | null | null | null | model.py | OrBin/N-Gram-Language-Model | e196758083bbed386dd1a24733cb956c8a36aa79 | [
"MIT"
] | null | null | null | import utils
class Model:
def __init__(self, file_path):
with open(file_path, 'r', encoding="utf8") as model_file:
self.model_tree = {}
for line in model_file:
chars, minus_log_p = utils.parse_model_file_line(line)
n_1_gram = ''.join(chars[:-1])
last_char = chars[-1]
if n_1_gram not in self.model_tree:
self.model_tree[n_1_gram] = {}
self.model_tree[n_1_gram][last_char] = minus_log_p
for n_1_gram in self.model_tree:
min_n_char, min_value = next(iter(self.model_tree[n_1_gram].items()))
for n_char, value in self.model_tree[n_1_gram].items():
if value < min_value:
min_n_char, min_value = n_char, value
self.model_tree[n_1_gram] = min_n_char
def __getitem__(self, n_1_gram):
return self.model_tree[n_1_gram] | 28.142857 | 72 | 0.695431 | import utils
class Model:
def __init__(self, file_path):
with open(file_path, 'r', encoding="utf8") as model_file:
self.model_tree = {}
for line in model_file:
chars, minus_log_p = utils.parse_model_file_line(line)
n_1_gram = ''.join(chars[:-1])
last_char = chars[-1]
if n_1_gram not in self.model_tree:
self.model_tree[n_1_gram] = {}
self.model_tree[n_1_gram][last_char] = minus_log_p
for n_1_gram in self.model_tree:
min_n_char, min_value = next(iter(self.model_tree[n_1_gram].items()))
for n_char, value in self.model_tree[n_1_gram].items():
if value < min_value:
min_n_char, min_value = n_char, value
self.model_tree[n_1_gram] = min_n_char
def __getitem__(self, n_1_gram):
return self.model_tree[n_1_gram] | true | true |
f719c75eed3a13b4d4eda1dd71c9f05b6e0ba238 | 349 | py | Python | tools/PRESUBMIT.py | RiyoCoder/v8 | e073edfc7dc990cc5f71c4e51ac27b19be16fcb7 | [
"BSD-3-Clause"
] | 2 | 2020-08-27T09:36:44.000Z | 2020-09-23T14:01:12.000Z | tools/PRESUBMIT.py | RiyoCoder/v8 | e073edfc7dc990cc5f71c4e51ac27b19be16fcb7 | [
"BSD-3-Clause"
] | null | null | null | tools/PRESUBMIT.py | RiyoCoder/v8 | e073edfc7dc990cc5f71c4e51ac27b19be16fcb7 | [
"BSD-3-Clause"
] | 1 | 2019-10-08T06:20:30.000Z | 2019-10-08T06:20:30.000Z | # Copyright 2018 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def CheckChangeOnCommit(input_api, output_api):
tests = input_api.canned_checks.GetUnitTestsInDirectory(
input_api, output_api, 'unittests')
return input_api.RunTests(tests)
| 38.777778 | 72 | 0.782235 |
def CheckChangeOnCommit(input_api, output_api):
tests = input_api.canned_checks.GetUnitTestsInDirectory(
input_api, output_api, 'unittests')
return input_api.RunTests(tests)
| true | true |
f719c7a7aac77a98a8d3c8df7aaf015dd69b5b0b | 1,102 | py | Python | ch_06/std_from_mean_kde.py | ags-ds/Hands-On-Data-Analysis-with-Pandas-By-Ags | f4ae6e3c3ef3c9ed9b11185724e1ea70a2f63f14 | [
"MIT"
] | 260 | 2019-01-21T01:38:39.000Z | 2022-03-26T18:49:21.000Z | ch_06/std_from_mean_kde.py | ags-ds/Hands-On-Data-Analysis-with-Pandas-By-Ags | f4ae6e3c3ef3c9ed9b11185724e1ea70a2f63f14 | [
"MIT"
] | 8 | 2020-03-13T15:48:56.000Z | 2021-08-23T21:43:44.000Z | ch_06/std_from_mean_kde.py | ags-ds/Hands-On-Data-Analysis-with-Pandas-By-Ags | f4ae6e3c3ef3c9ed9b11185724e1ea70a2f63f14 | [
"MIT"
] | 665 | 2019-07-27T18:28:20.000Z | 2022-03-23T08:20:35.000Z | import itertools
def std_from_mean_kde(data):
"""
Plot the KDE of the pandas series along with vertical
reference lines for each standard deviation from the mean.
Parameters:
- data: pandas Series with numeric data
Returns:
Matplotlib Axes object.
"""
mean_mag, std_mean = data.mean(), data.std()
ax = data.plot(kind='kde')
ax.axvline(mean_mag, color='b', alpha=0.2, label='mean')
colors = ['green', 'orange', 'red']
multipliers = [1, 2, 3]
signs = ['-', '+']
for sign, (color, multiplier) in itertools.product(
signs, zip(colors, multipliers)
):
adjustment = multiplier * std_mean
if sign == '-':
value = mean_mag - adjustment
label = '{} {}{}{}'.format(
r'$\mu$',
r'$\pm$',
multiplier,
r'$\sigma$'
)
else:
value = mean_mag + adjustment
label = None
ax.axvline(value, color=color, label=label, alpha=0.5)
ax.legend()
return ax | 26.878049 | 62 | 0.520871 | import itertools
def std_from_mean_kde(data):
mean_mag, std_mean = data.mean(), data.std()
ax = data.plot(kind='kde')
ax.axvline(mean_mag, color='b', alpha=0.2, label='mean')
colors = ['green', 'orange', 'red']
multipliers = [1, 2, 3]
signs = ['-', '+']
for sign, (color, multiplier) in itertools.product(
signs, zip(colors, multipliers)
):
adjustment = multiplier * std_mean
if sign == '-':
value = mean_mag - adjustment
label = '{} {}{}{}'.format(
r'$\mu$',
r'$\pm$',
multiplier,
r'$\sigma$'
)
else:
value = mean_mag + adjustment
label = None
ax.axvline(value, color=color, label=label, alpha=0.5)
ax.legend()
return ax | true | true |
f719c8336db951828b5e48810801b98858d489e2 | 1,559 | py | Python | ladder/urls.py | jzahedieh/django-tennis-ladder | 03a9fc9ec6d0830ac1d6648428eca11755eabb00 | [
"MIT"
] | 13 | 2015-04-30T21:07:20.000Z | 2021-01-08T13:52:14.000Z | ladder/urls.py | jzahedieh/django-tennis-ladder | 03a9fc9ec6d0830ac1d6648428eca11755eabb00 | [
"MIT"
] | 13 | 2015-04-05T22:48:14.000Z | 2021-12-12T17:29:16.000Z | ladder/urls.py | jzahedieh/django-tennis-ladder | 03a9fc9ec6d0830ac1d6648428eca11755eabb00 | [
"MIT"
] | 5 | 2016-10-12T16:24:09.000Z | 2019-11-26T10:16:44.000Z | from django.urls import re_path
from ladder import views
urlpatterns = [
re_path(r'^$', views.index, name='index'),
re_path(r'^list/$', views.list_rounds, name='list'),
re_path(r'^current/$', views.current_season_redirect, name='current'),
# ex: /2013/round/1/
re_path(r'^(?P<year>\d+)/round/(?P<season_round>\d+)/$', views.season, name='season'),
# ex: /2013/round/1/division/1-n
re_path(r'^(?P<year>\d+)/round/(?P<season_round>\d+)/division/(?P<division_id>\w+)/$', views.ladder, name='ladder'),
# ex: /2013/round/1/division/1-n/add/
re_path(r'^(?P<year>\d+)/round/(?P<season_round>\d+)/division/(?P<division_id>\w+)/add/$', views.add, name='add'),
# ex: /head_to_head/1/vs/2
re_path(r'^head_to_head/(?P<player_id>\d+)/vs/(?P<opponent_id>\w+)/$', views.head_to_head, name='head_to_head'),
# ex: /player/1/
re_path(r'^player/(?P<player_id>\d+)/$', views.player_history, name='player_history'),
# ex: /player/
re_path(r'^player/search/$', views.player_search, name='player_search'),
re_path(r'^player/h2h/(?P<player_id>\d+)/$', views.h2h_search, name='h2h_search'),
re_path(r'^player/results/$', views.player_result, name='player_result'),
re_path(r'^season/ajax/stats/$', views.season_ajax_stats, name='season_ajax_stats'),
re_path(r'^season/ajax/progress/$', views.season_ajax_progress, name='season_ajax_progress'),
re_path(r'^result/entry/$', views.result_entry, name='result_entry'),
re_path(r'^result/entry/add/$', views.result_entry_add, name='result_entry_add'),
]
| 55.678571 | 120 | 0.664529 | from django.urls import re_path
from ladder import views
urlpatterns = [
re_path(r'^$', views.index, name='index'),
re_path(r'^list/$', views.list_rounds, name='list'),
re_path(r'^current/$', views.current_season_redirect, name='current'),
re_path(r'^(?P<year>\d+)/round/(?P<season_round>\d+)/$', views.season, name='season'),
re_path(r'^(?P<year>\d+)/round/(?P<season_round>\d+)/division/(?P<division_id>\w+)/$', views.ladder, name='ladder'),
re_path(r'^(?P<year>\d+)/round/(?P<season_round>\d+)/division/(?P<division_id>\w+)/add/$', views.add, name='add'),
re_path(r'^head_to_head/(?P<player_id>\d+)/vs/(?P<opponent_id>\w+)/$', views.head_to_head, name='head_to_head'),
re_path(r'^player/(?P<player_id>\d+)/$', views.player_history, name='player_history'),
re_path(r'^player/search/$', views.player_search, name='player_search'),
re_path(r'^player/h2h/(?P<player_id>\d+)/$', views.h2h_search, name='h2h_search'),
re_path(r'^player/results/$', views.player_result, name='player_result'),
re_path(r'^season/ajax/stats/$', views.season_ajax_stats, name='season_ajax_stats'),
re_path(r'^season/ajax/progress/$', views.season_ajax_progress, name='season_ajax_progress'),
re_path(r'^result/entry/$', views.result_entry, name='result_entry'),
re_path(r'^result/entry/add/$', views.result_entry_add, name='result_entry_add'),
]
| true | true |
f719c848267dc37edb40ddf8031a05c5fa16b620 | 3,306 | py | Python | myFileClass.py | saewoonam/thorium_daq_uqd | 249ab89338591c833009711e2f7997dbe2898fbc | [
"MIT"
] | null | null | null | myFileClass.py | saewoonam/thorium_daq_uqd | 249ab89338591c833009711e2f7997dbe2898fbc | [
"MIT"
] | null | null | null | myFileClass.py | saewoonam/thorium_daq_uqd | 249ab89338591c833009711e2f7997dbe2898fbc | [
"MIT"
] | null | null | null | import sys
import sqlite3
import hashlib
import time
import logging
import os.path
logger = logging.getLogger(__name__)
logpath = os.path.dirname(__file__)
logpath = os.path.join(logpath, 'logs/')
fileHandler = logging.FileHandler(logpath + __name__ + '.log')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileHandler.setFormatter(formatter)
fileHandler.setLevel(logging.INFO)
logger.addHandler(fileHandler)
def create(fname='hashes.sqlite'):
conn = sqlite3.connect(fname)
c = conn.cursor()
# Create table
c.execute(
'CREATE TABLE hashes(filename text, md5 text, sha1 text, hashtime real)'
)
conn.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
# based on
# http://stackoverflow.com/questions/16085292/subclassing-file-objects-to-extend-open-and-close-operations-in-python-3
class _file_obj(object):
"""Check if `f` is a file name and open the file in `mode`.
A context manager."""
hashdb = None
def __init__(self, f, mode):
if f is None:
self.file = {
'r': sys.stdin,
'a': sys.stdout,
'w': sys.stdout
}[mode[0]]
self.none = True
elif isinstance(f, str):
self.file = open(f, mode)
else:
self.file = f
self.close_file = (self.file is not f)
self.md5 = hashlib.md5()
self.sha1 = hashlib.sha1()
# self.hashdb = None
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
if (not self.close_file) or hasattr(self, 'none'):
return # do nothing
# clean up
exit = getattr(self.file, '__exit__', None)
if exit is not None:
return exit(*args, **kwargs)
else:
exit = getattr(self.file, 'close', None)
if exit is not None:
exit()
def write(self, rawdata):
byteswritten = self.file.tell()
res = self.file.write(rawdata)
# if res is not None: # It is None in python2
# logger.error('Problem with writing to file, res: %r' % res)
byteswritten = self.file.tell() - byteswritten
self.md5.update(rawdata)
self.sha1.update(rawdata)
# if self.hashdb is not None:
# print('md5: %s, sha1: %s'%(self.md5.hexdigest(),
# self.sha1.hexdigest()))
# self.updatehashdb()
return byteswritten
def close(self):
if self.hashdb is not None:
logger.info('md5: %s, sha1: %s' % (self.md5.hexdigest(),
self.sha1.hexdigest()))
self.updatehashdb()
return self.file.close()
def updatehashdb(self):
conn = sqlite3.connect(self.hashdb)
c = conn.cursor()
c.execute("INSERT INTO hashes VALUES (?,?,?,?)",
(self.file.name, self.md5.hexdigest(), self.sha1.hexdigest(),
time.time()))
conn.commit()
conn.close()
def __getattr__(self, attr):
return getattr(self.file, attr)
def __iter__(self):
return iter(self.file)
| 30.611111 | 119 | 0.575015 | import sys
import sqlite3
import hashlib
import time
import logging
import os.path
logger = logging.getLogger(__name__)
logpath = os.path.dirname(__file__)
logpath = os.path.join(logpath, 'logs/')
fileHandler = logging.FileHandler(logpath + __name__ + '.log')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileHandler.setFormatter(formatter)
fileHandler.setLevel(logging.INFO)
logger.addHandler(fileHandler)
def create(fname='hashes.sqlite'):
conn = sqlite3.connect(fname)
c = conn.cursor()
c.execute(
'CREATE TABLE hashes(filename text, md5 text, sha1 text, hashtime real)'
)
conn.commit()
conn.close()
class _file_obj(object):
hashdb = None
def __init__(self, f, mode):
if f is None:
self.file = {
'r': sys.stdin,
'a': sys.stdout,
'w': sys.stdout
}[mode[0]]
self.none = True
elif isinstance(f, str):
self.file = open(f, mode)
else:
self.file = f
self.close_file = (self.file is not f)
self.md5 = hashlib.md5()
self.sha1 = hashlib.sha1()
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
if (not self.close_file) or hasattr(self, 'none'):
return
exit = getattr(self.file, '__exit__', None)
if exit is not None:
return exit(*args, **kwargs)
else:
exit = getattr(self.file, 'close', None)
if exit is not None:
exit()
def write(self, rawdata):
byteswritten = self.file.tell()
res = self.file.write(rawdata)
written = self.file.tell() - byteswritten
self.md5.update(rawdata)
self.sha1.update(rawdata)
return byteswritten
def close(self):
if self.hashdb is not None:
logger.info('md5: %s, sha1: %s' % (self.md5.hexdigest(),
self.sha1.hexdigest()))
self.updatehashdb()
return self.file.close()
def updatehashdb(self):
conn = sqlite3.connect(self.hashdb)
c = conn.cursor()
c.execute("INSERT INTO hashes VALUES (?,?,?,?)",
(self.file.name, self.md5.hexdigest(), self.sha1.hexdigest(),
time.time()))
conn.commit()
conn.close()
def __getattr__(self, attr):
return getattr(self.file, attr)
def __iter__(self):
return iter(self.file)
| true | true |
f719c9d44f62e65378d7e3d7e79d5a07e67b6c18 | 1,925 | py | Python | tests/test_swf/models/test_generic_type.py | symroe/moto | 4e106995af6f2820273528fca8a4e9ee288690a5 | [
"Apache-2.0"
] | 5,460 | 2015-01-01T01:11:17.000Z | 2022-03-31T23:45:38.000Z | tests/test_swf/models/test_generic_type.py | symroe/moto | 4e106995af6f2820273528fca8a4e9ee288690a5 | [
"Apache-2.0"
] | 4,475 | 2015-01-05T19:37:30.000Z | 2022-03-31T13:55:12.000Z | tests/test_swf/models/test_generic_type.py | symroe/moto | 4e106995af6f2820273528fca8a4e9ee288690a5 | [
"Apache-2.0"
] | 1,831 | 2015-01-14T00:00:44.000Z | 2022-03-31T20:30:04.000Z | from moto.swf.models import GenericType
import sure # noqa # pylint: disable=unused-import
# Tests for GenericType (ActivityType, WorkflowType)
class FooType(GenericType):
@property
def kind(self):
return "foo"
@property
def _configuration_keys(self):
return ["justAnExampleTimeout"]
def test_type_short_dict_representation():
_type = FooType("test-foo", "v1.0")
_type.to_short_dict().should.equal({"name": "test-foo", "version": "v1.0"})
def test_type_medium_dict_representation():
_type = FooType("test-foo", "v1.0")
_type.to_medium_dict()["fooType"].should.equal(_type.to_short_dict())
_type.to_medium_dict()["status"].should.equal("REGISTERED")
_type.to_medium_dict().should.contain("creationDate")
_type.to_medium_dict().should_not.contain("deprecationDate")
_type.to_medium_dict().should_not.contain("description")
_type.description = "foo bar"
_type.to_medium_dict()["description"].should.equal("foo bar")
_type.status = "DEPRECATED"
_type.to_medium_dict().should.contain("deprecationDate")
def test_type_full_dict_representation():
_type = FooType("test-foo", "v1.0")
_type.to_full_dict()["typeInfo"].should.equal(_type.to_medium_dict())
_type.to_full_dict()["configuration"].should.equal({})
_type.task_list = "foo"
_type.to_full_dict()["configuration"]["defaultTaskList"].should.equal(
{"name": "foo"}
)
_type.just_an_example_timeout = "60"
_type.to_full_dict()["configuration"]["justAnExampleTimeout"].should.equal("60")
_type.non_whitelisted_property = "34"
keys = _type.to_full_dict()["configuration"].keys()
sorted(keys).should.equal(["defaultTaskList", "justAnExampleTimeout"])
def test_type_string_representation():
_type = FooType("test-foo", "v1.0")
str(_type).should.equal(
"FooType(name: test-foo, version: v1.0, status: REGISTERED)"
)
| 32.627119 | 84 | 0.701299 | from moto.swf.models import GenericType
import sure
@property
def kind(self):
return "foo"
@property
def _configuration_keys(self):
return ["justAnExampleTimeout"]
def test_type_short_dict_representation():
_type = FooType("test-foo", "v1.0")
_type.to_short_dict().should.equal({"name": "test-foo", "version": "v1.0"})
def test_type_medium_dict_representation():
_type = FooType("test-foo", "v1.0")
_type.to_medium_dict()["fooType"].should.equal(_type.to_short_dict())
_type.to_medium_dict()["status"].should.equal("REGISTERED")
_type.to_medium_dict().should.contain("creationDate")
_type.to_medium_dict().should_not.contain("deprecationDate")
_type.to_medium_dict().should_not.contain("description")
_type.description = "foo bar"
_type.to_medium_dict()["description"].should.equal("foo bar")
_type.status = "DEPRECATED"
_type.to_medium_dict().should.contain("deprecationDate")
def test_type_full_dict_representation():
_type = FooType("test-foo", "v1.0")
_type.to_full_dict()["typeInfo"].should.equal(_type.to_medium_dict())
_type.to_full_dict()["configuration"].should.equal({})
_type.task_list = "foo"
_type.to_full_dict()["configuration"]["defaultTaskList"].should.equal(
{"name": "foo"}
)
_type.just_an_example_timeout = "60"
_type.to_full_dict()["configuration"]["justAnExampleTimeout"].should.equal("60")
_type.non_whitelisted_property = "34"
keys = _type.to_full_dict()["configuration"].keys()
sorted(keys).should.equal(["defaultTaskList", "justAnExampleTimeout"])
def test_type_string_representation():
_type = FooType("test-foo", "v1.0")
str(_type).should.equal(
"FooType(name: test-foo, version: v1.0, status: REGISTERED)"
)
| true | true |
f719ca25ac5cfde9937fa4a3c1d7f11e2bc44eb3 | 427 | py | Python | data/scripts/templates/object/mobile/shared_r2_space.py | obi-two/GameServer | 7d37024e2291a97d49522610cd8f1dbe5666afc2 | [
"MIT"
] | 20 | 2015-02-23T15:11:56.000Z | 2022-03-18T20:56:48.000Z | data/scripts/templates/object/mobile/shared_r2_space.py | apathyboy/swganh | 665128efe9154611dec4cb5efc61d246dd095984 | [
"MIT"
] | null | null | null | data/scripts/templates/object/mobile/shared_r2_space.py | apathyboy/swganh | 665128efe9154611dec4cb5efc61d246dd095984 | [
"MIT"
] | 20 | 2015-04-04T16:35:59.000Z | 2022-03-24T14:54:37.000Z | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_r2_space.iff"
result.attribute_template_id = 9
result.stfName("droid_name","r2_base")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | 25.117647 | 54 | 0.71897 | true | true | |
f719cc3064aeb246e474124454e307d2ac046ca9 | 4,087 | py | Python | tests/unit_tests/routes_test.py | schmidtbri/rest-model-service | 0d1705cb62e6a942f90150da3bcf51e3e1265a25 | [
"BSD-3-Clause"
] | 1 | 2021-11-10T19:48:35.000Z | 2021-11-10T19:48:35.000Z | tests/unit_tests/routes_test.py | schmidtbri/rest-model-service | 0d1705cb62e6a942f90150da3bcf51e3e1265a25 | [
"BSD-3-Clause"
] | 1 | 2022-03-15T12:36:46.000Z | 2022-03-15T12:36:46.000Z | tests/unit_tests/routes_test.py | schmidtbri/rest-model-service | 0d1705cb62e6a942f90150da3bcf51e3e1265a25 | [
"BSD-3-Clause"
] | null | null | null | import os
from pathlib import Path
import unittest
import json
from starlette.testclient import TestClient
from ml_base.utilities import ModelManager
os.chdir(Path(__file__).resolve().parent.parent.parent)
os.environ["REST_CONFIG"] = "examples/rest_config.yaml"
from rest_model_service.main import app, create_app
from rest_model_service.configuration import Model
class RoutesTests(unittest.TestCase):
def test_root(self):
# arrange
client = TestClient(app)
# act
response = client.get("/")
# assert
self.assertTrue(response.status_code == 200)
# cleanup
model_manager = ModelManager()
model_manager.clear_instance()
def test_get_models(self):
# arrange
client = TestClient(app)
# act
response = client.get("/api/models")
# assert
self.assertTrue(response.status_code == 200)
self.assertTrue(response.json() == {
"models":
[
{
"display_name": "Iris Model",
"qualified_name": "iris_model",
"description": "Model for predicting the species of a flower based on its measurements.",
"version": "1.0.0"
}
]
})
# cleanup
model_manager = ModelManager()
model_manager.clear_instance()
def test_prediction(self):
# arrange
client = TestClient(app)
# act
response = client.post("/api/models/iris_model/prediction", data=json.dumps({
"sepal_length": 6.0,
"sepal_width": 5.0,
"petal_length": 3.0,
"petal_width": 2.0
}))
# assert
self.assertTrue(response.status_code == 200)
self.assertTrue(response.json() == {
"species": "Iris setosa"
})
# cleanup
model_manager = ModelManager()
model_manager.clear_instance()
def test_prediction_with_bad_data(self):
# arrange
app = create_app("REST Model Service", [Model(qualified_name="iris_model",
class_path="tests.mocks.IrisModel",
create_endpoint=True)])
client = TestClient(app)
# act
response = client.post("/api/models/iris_model/prediction", data=json.dumps({
"sepal_length": 16.0,
"sepal_width": 5.0,
"petal_length": 3.0,
"petal_width": 2.0
}))
# assert
self.assertTrue(response.status_code == 422)
# cleanup
model_manager = ModelManager()
model_manager.clear_instance()
def test_prediction_with_bad_configuration(self):
# arrange, act, assert
with self.assertRaises(ValueError) as e:
app = create_app("REST Model Service", [Model(qualified_name="asdf",
class_path="tests.mocks.IrisModel",
create_endpoint=True)])
# cleanup
model_manager = ModelManager()
model_manager.clear_instance()
def test_prediction_with_no_endpoint(self):
# arrange
app = create_app("REST Model Service", [Model(qualified_name="iris_model",
class_path="tests.mocks.IrisModel",
create_endpoint=False)])
client = TestClient(app)
# act
response = client.post("/api/models/iris_model/prediction", data=json.dumps({
"sepal_length": 16.0,
"sepal_width": 5.0,
"petal_length": 3.0,
"petal_width": 2.0
}))
# assert
self.assertTrue(response.status_code == 404)
# cleanup
model_manager = ModelManager()
model_manager.clear_instance()
if __name__ == '__main__':
unittest.main()
| 29.402878 | 113 | 0.54025 | import os
from pathlib import Path
import unittest
import json
from starlette.testclient import TestClient
from ml_base.utilities import ModelManager
os.chdir(Path(__file__).resolve().parent.parent.parent)
os.environ["REST_CONFIG"] = "examples/rest_config.yaml"
from rest_model_service.main import app, create_app
from rest_model_service.configuration import Model
class RoutesTests(unittest.TestCase):
def test_root(self):
client = TestClient(app)
response = client.get("/")
self.assertTrue(response.status_code == 200)
model_manager = ModelManager()
model_manager.clear_instance()
def test_get_models(self):
client = TestClient(app)
response = client.get("/api/models")
self.assertTrue(response.status_code == 200)
self.assertTrue(response.json() == {
"models":
[
{
"display_name": "Iris Model",
"qualified_name": "iris_model",
"description": "Model for predicting the species of a flower based on its measurements.",
"version": "1.0.0"
}
]
})
model_manager = ModelManager()
model_manager.clear_instance()
def test_prediction(self):
client = TestClient(app)
response = client.post("/api/models/iris_model/prediction", data=json.dumps({
"sepal_length": 6.0,
"sepal_width": 5.0,
"petal_length": 3.0,
"petal_width": 2.0
}))
self.assertTrue(response.status_code == 200)
self.assertTrue(response.json() == {
"species": "Iris setosa"
})
model_manager = ModelManager()
model_manager.clear_instance()
def test_prediction_with_bad_data(self):
app = create_app("REST Model Service", [Model(qualified_name="iris_model",
class_path="tests.mocks.IrisModel",
create_endpoint=True)])
client = TestClient(app)
response = client.post("/api/models/iris_model/prediction", data=json.dumps({
"sepal_length": 16.0,
"sepal_width": 5.0,
"petal_length": 3.0,
"petal_width": 2.0
}))
self.assertTrue(response.status_code == 422)
model_manager = ModelManager()
model_manager.clear_instance()
def test_prediction_with_bad_configuration(self):
with self.assertRaises(ValueError) as e:
app = create_app("REST Model Service", [Model(qualified_name="asdf",
class_path="tests.mocks.IrisModel",
create_endpoint=True)])
model_manager = ModelManager()
model_manager.clear_instance()
def test_prediction_with_no_endpoint(self):
app = create_app("REST Model Service", [Model(qualified_name="iris_model",
class_path="tests.mocks.IrisModel",
create_endpoint=False)])
client = TestClient(app)
response = client.post("/api/models/iris_model/prediction", data=json.dumps({
"sepal_length": 16.0,
"sepal_width": 5.0,
"petal_length": 3.0,
"petal_width": 2.0
}))
self.assertTrue(response.status_code == 404)
model_manager = ModelManager()
model_manager.clear_instance()
if __name__ == '__main__':
unittest.main()
| true | true |
f719cd368c417026551c16e8dd7e7961bff48f66 | 7,466 | py | Python | inverted-index/src/test_inverted_index.py | Illumaria/made-python-2020 | 7ec219ff1a5116925027646810ca4b294b1080d9 | [
"MIT"
] | 2 | 2021-07-08T10:59:44.000Z | 2021-09-06T07:44:24.000Z | inverted-index/src/test_inverted_index.py | Illumaria/made-python | 7ec219ff1a5116925027646810ca4b294b1080d9 | [
"MIT"
] | null | null | null | inverted-index/src/test_inverted_index.py | Illumaria/made-python | 7ec219ff1a5116925027646810ca4b294b1080d9 | [
"MIT"
] | null | null | null | from argparse import Namespace
from textwrap import dedent
import pytest
from inverted_index import InvertedIndex
from inverted_index import build_inverted_index
from inverted_index import DEFAULT_INVERTED_INDEX_SAVE_PATH
from inverted_index import callback_query, process_queries
from inverted_index import callback_build, process_build
from inverted_index import load_documents
from storage_policy import ArrayStoragePolicy
DATASET_BIG_FPATH = "../resources/wikipedia_sample"
DATASET_SMALL_FPATH = "../resources/small_wikipedia_sample"
DATASET_TINY_FPATH = "../resources/tiny_wikipedia_sample"
def test_can_load_documents_v1():
documents = load_documents(DATASET_TINY_FPATH)
etalon_documents = {
123: "some words A_word and nothing",
2: "some word B_word in this dataset",
5: "famous_phrases to be or not to be",
37: "all words such as A_word and B_word are here",
}
assert etalon_documents == documents, (
"load_documents incorrectly loaded dataset"
)
def test_can_load_documents_v2(tmpdir):
dataset_str = dedent("""\
123\tsome words A_word and nothing
2\tsome word B_word in this dataset
5\tfamous_phrases to be or not to be
37\tall words such as A_word and B_word are here
""")
dataset_fio = tmpdir.join("tiny.dataset")
dataset_fio.write(dataset_str)
documents = load_documents(dataset_fio)
etalon_documents = {
123: "some words A_word and nothing",
2: "some word B_word in this dataset",
5: "famous_phrases to be or not to be",
37: "all words such as A_word and B_word are here",
}
assert etalon_documents == documents, (
"load_documents incorrectly loaded dataset"
)
DATASET_TINY_STR = dedent("""\
123\tsome words A_word and nothing
2\tsome word B_word in this dataset
5\tfamous_phrases to be or not to be
37\tall words such as A_word and B_word are here
""")
@pytest.fixture()
def tiny_dataset_fio(tmpdir):
dataset_fio = tmpdir.join("dataset.txt")
dataset_fio.write(DATASET_TINY_STR)
return dataset_fio
def test_can_load_documents(tiny_dataset_fio):
documents = load_documents(tiny_dataset_fio)
etalon_documents = {
123: "some words A_word and nothing",
2: "some word B_word in this dataset",
5: "famous_phrases to be or not to be",
37: "all words such as A_word and B_word are here",
}
assert etalon_documents == documents, (
"load_documents incorrectly loaded dataset"
)
@pytest.mark.parametrize(
"query, etalon_answer",
[
pytest.param(["A_word"], [123, 37], id="A_word"),
pytest.param(["B_word"], [2, 37], id="B_word"),
pytest.param(["A_word", "B_word"], [37], id="both_words"),
pytest.param(["word_does_not_exist"], [], id="word does not exist"),
],
)
def test_query_inverted_index_intersect_results(tiny_dataset_fio, query, etalon_answer):
documents = load_documents(tiny_dataset_fio)
tiny_inverted_index = build_inverted_index(documents)
answer = tiny_inverted_index.query(query)
assert sorted(answer) == sorted(etalon_answer), (
f"Expected answer is {etalon_answer}, but you got {answer}"
)
# @pytest.mark.skip
def test_can_load_wikipedia_sample():
documents = load_documents(DATASET_BIG_FPATH)
assert len(documents) == 4100, (
"you incorrectly loaded Wikipedia sample"
)
@pytest.fixture()
def wikipedia_documents():
# documents = load_documents(DATASET_BIG_FPATH)
documents = load_documents(DATASET_SMALL_FPATH)
# documents = load_documents(DATASET_TINY_FPATH)
return documents
@pytest.fixture()
def small_sample_wikipedia_documents():
documents = load_documents(DATASET_SMALL_FPATH)
return documents
# @pytest.mark.skip
def test_can_build_and_query_inverted_index(wikipedia_documents):
wikipedia_inverted_index = build_inverted_index(wikipedia_documents)
doc_ids = wikipedia_inverted_index.query(["wikipedia"])
assert isinstance(doc_ids, list), "inverted index query should return list"
@pytest.fixture()
def wikipedia_inverted_index(wikipedia_documents):
wikipedia_inverted_index = build_inverted_index(wikipedia_documents)
return wikipedia_inverted_index
@pytest.fixture()
def small_wikipedia_inverted_index(small_sample_wikipedia_documents):
wikipedia_inverted_index = build_inverted_index(small_sample_wikipedia_documents)
return wikipedia_inverted_index
# @pytest.mark.skip
def test_can_dump_and_load_inverted_index(tmpdir, wikipedia_inverted_index):
index_fio = tmpdir.join("index.dump")
wikipedia_inverted_index.dump(index_fio)
loaded_inverted_index = InvertedIndex.load(index_fio)
assert wikipedia_inverted_index == loaded_inverted_index, (
"load should return the same inverted index"
)
# @pytest.mark.parametrize(
# ("filepath",),
# [
# pytest.param(DATASET_SMALL_FPATH, id="small dataset"),
# # pytest.param(DATASET_BIG_FPATH, marks=[pytest.mark.slow], id="big dataset"),
# ],
# )
# @pytest.mark.skip
# def test_can_dump_and_load_inverted_index_with_array_policy_parametrized(filepath, tmpdir):
# index_fio = tmpdir.join("index.dump")
#
# documents = load_documents(filepath)
# etalon_inverted_index = build_inverted_index(documents)
#
# # class StoragePolicy:
# # @staticmethod
# # def dump(word_to_docs_mapping, filepath):
# # pass
# #
# # @staticmethod
# # def load(filepath):# pass
#
# etalon_inverted_index.dump(index_fio, storage_policy=ArrayStoragePolicy)
# loaded_inverted_index = InvertedIndex.load(index_fio, storage_policy=ArrayStoragePolicy)
# assert etalon_inverted_index == loaded_inverted_index, (
# "load should return the same inverted index"
# )
@pytest.mark.parametrize(
"dataset_filepath",
[
DATASET_TINY_FPATH,
DATASET_SMALL_FPATH,
# pytest.param(DATASET_BIG_FPATH, marks=[pytest.mark.slow]),
],
)
def test_process_build_can_load_documents(dataset_filepath):
process_build(dataset_filepath, "inverted.index")
@pytest.mark.parametrize(
"dataset_filepath",
[
DATASET_TINY_FPATH,
DATASET_SMALL_FPATH,
# pytest.param(DATASET_BIG_FPATH, marks=[pytest.mark.slow]),
],
)
def test_callback_build_can_build_inverted_index_from_provided_file(dataset_filepath):
build_arguments = Namespace(
dataset_filepath=dataset_filepath,
inverted_index_filepath=DEFAULT_INVERTED_INDEX_SAVE_PATH,
)
callback_build(build_arguments)
def test_process_queries_can_process_queries_from_provided_file(capsys):
with open("queries-utf8.txt") as queries_fin:
process_queries(
inverted_index_filepath=DEFAULT_INVERTED_INDEX_SAVE_PATH,
query_file=queries_fin,
)
captured = capsys.readouterr()
assert "load inverted index" not in captured.out
assert "load inverted index" in captured.err
assert "two words" in captured.out
assert "two words" not in captured.err
def test_callback_query_can_process_queries_from_provided_file():
with open("queries-utf8.txt") as queries_fin:
query_arguments = Namespace(
inverted_index_filepath=DEFAULT_INVERTED_INDEX_SAVE_PATH,
query_file=queries_fin,
)
callback_query(query_arguments)
| 32.889868 | 94 | 0.721939 | from argparse import Namespace
from textwrap import dedent
import pytest
from inverted_index import InvertedIndex
from inverted_index import build_inverted_index
from inverted_index import DEFAULT_INVERTED_INDEX_SAVE_PATH
from inverted_index import callback_query, process_queries
from inverted_index import callback_build, process_build
from inverted_index import load_documents
from storage_policy import ArrayStoragePolicy
DATASET_BIG_FPATH = "../resources/wikipedia_sample"
DATASET_SMALL_FPATH = "../resources/small_wikipedia_sample"
DATASET_TINY_FPATH = "../resources/tiny_wikipedia_sample"
def test_can_load_documents_v1():
documents = load_documents(DATASET_TINY_FPATH)
etalon_documents = {
123: "some words A_word and nothing",
2: "some word B_word in this dataset",
5: "famous_phrases to be or not to be",
37: "all words such as A_word and B_word are here",
}
assert etalon_documents == documents, (
"load_documents incorrectly loaded dataset"
)
def test_can_load_documents_v2(tmpdir):
dataset_str = dedent("""\
123\tsome words A_word and nothing
2\tsome word B_word in this dataset
5\tfamous_phrases to be or not to be
37\tall words such as A_word and B_word are here
""")
dataset_fio = tmpdir.join("tiny.dataset")
dataset_fio.write(dataset_str)
documents = load_documents(dataset_fio)
etalon_documents = {
123: "some words A_word and nothing",
2: "some word B_word in this dataset",
5: "famous_phrases to be or not to be",
37: "all words such as A_word and B_word are here",
}
assert etalon_documents == documents, (
"load_documents incorrectly loaded dataset"
)
DATASET_TINY_STR = dedent("""\
123\tsome words A_word and nothing
2\tsome word B_word in this dataset
5\tfamous_phrases to be or not to be
37\tall words such as A_word and B_word are here
""")
@pytest.fixture()
def tiny_dataset_fio(tmpdir):
dataset_fio = tmpdir.join("dataset.txt")
dataset_fio.write(DATASET_TINY_STR)
return dataset_fio
def test_can_load_documents(tiny_dataset_fio):
documents = load_documents(tiny_dataset_fio)
etalon_documents = {
123: "some words A_word and nothing",
2: "some word B_word in this dataset",
5: "famous_phrases to be or not to be",
37: "all words such as A_word and B_word are here",
}
assert etalon_documents == documents, (
"load_documents incorrectly loaded dataset"
)
@pytest.mark.parametrize(
"query, etalon_answer",
[
pytest.param(["A_word"], [123, 37], id="A_word"),
pytest.param(["B_word"], [2, 37], id="B_word"),
pytest.param(["A_word", "B_word"], [37], id="both_words"),
pytest.param(["word_does_not_exist"], [], id="word does not exist"),
],
)
def test_query_inverted_index_intersect_results(tiny_dataset_fio, query, etalon_answer):
documents = load_documents(tiny_dataset_fio)
tiny_inverted_index = build_inverted_index(documents)
answer = tiny_inverted_index.query(query)
assert sorted(answer) == sorted(etalon_answer), (
f"Expected answer is {etalon_answer}, but you got {answer}"
)
def test_can_load_wikipedia_sample():
documents = load_documents(DATASET_BIG_FPATH)
assert len(documents) == 4100, (
"you incorrectly loaded Wikipedia sample"
)
@pytest.fixture()
def wikipedia_documents():
documents = load_documents(DATASET_SMALL_FPATH)
return documents
@pytest.fixture()
def small_sample_wikipedia_documents():
documents = load_documents(DATASET_SMALL_FPATH)
return documents
def test_can_build_and_query_inverted_index(wikipedia_documents):
wikipedia_inverted_index = build_inverted_index(wikipedia_documents)
doc_ids = wikipedia_inverted_index.query(["wikipedia"])
assert isinstance(doc_ids, list), "inverted index query should return list"
@pytest.fixture()
def wikipedia_inverted_index(wikipedia_documents):
wikipedia_inverted_index = build_inverted_index(wikipedia_documents)
return wikipedia_inverted_index
@pytest.fixture()
def small_wikipedia_inverted_index(small_sample_wikipedia_documents):
wikipedia_inverted_index = build_inverted_index(small_sample_wikipedia_documents)
return wikipedia_inverted_index
def test_can_dump_and_load_inverted_index(tmpdir, wikipedia_inverted_index):
index_fio = tmpdir.join("index.dump")
wikipedia_inverted_index.dump(index_fio)
loaded_inverted_index = InvertedIndex.load(index_fio)
assert wikipedia_inverted_index == loaded_inverted_index, (
"load should return the same inverted index"
)
"inverted.index")
@pytest.mark.parametrize(
"dataset_filepath",
[
DATASET_TINY_FPATH,
DATASET_SMALL_FPATH,
],
)
def test_callback_build_can_build_inverted_index_from_provided_file(dataset_filepath):
build_arguments = Namespace(
dataset_filepath=dataset_filepath,
inverted_index_filepath=DEFAULT_INVERTED_INDEX_SAVE_PATH,
)
callback_build(build_arguments)
def test_process_queries_can_process_queries_from_provided_file(capsys):
with open("queries-utf8.txt") as queries_fin:
process_queries(
inverted_index_filepath=DEFAULT_INVERTED_INDEX_SAVE_PATH,
query_file=queries_fin,
)
captured = capsys.readouterr()
assert "load inverted index" not in captured.out
assert "load inverted index" in captured.err
assert "two words" in captured.out
assert "two words" not in captured.err
def test_callback_query_can_process_queries_from_provided_file():
with open("queries-utf8.txt") as queries_fin:
query_arguments = Namespace(
inverted_index_filepath=DEFAULT_INVERTED_INDEX_SAVE_PATH,
query_file=queries_fin,
)
callback_query(query_arguments)
| true | true |
f719ce9774a010e3d05576a84a6bbe9fff496778 | 3,460 | py | Python | purity_fb/purity_fb_1dot6/models/object_response.py | mabdelhafez/purity_fb_python_client | a9856875b3df43b4302a2e4addd1a6b71f51f5ce | [
"Apache-2.0"
] | null | null | null | purity_fb/purity_fb_1dot6/models/object_response.py | mabdelhafez/purity_fb_python_client | a9856875b3df43b4302a2e4addd1a6b71f51f5ce | [
"Apache-2.0"
] | null | null | null | purity_fb/purity_fb_1dot6/models/object_response.py | mabdelhafez/purity_fb_python_client | a9856875b3df43b4302a2e4addd1a6b71f51f5ce | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
"""
Pure Storage FlashBlade REST 1.6 Python SDK
Pure Storage FlashBlade REST 1.6 Python SDK, developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/).
OpenAPI spec version: 1.6
Contact: info@purestorage.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class ObjectResponse(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'pagination_info': 'PaginationInfo'
}
attribute_map = {
'pagination_info': 'pagination_info'
}
def __init__(self, pagination_info=None):
"""
ObjectResponse - a model defined in Swagger
"""
self._pagination_info = None
if pagination_info is not None:
self.pagination_info = pagination_info
@property
def pagination_info(self):
"""
Gets the pagination_info of this ObjectResponse.
pagination information, only available in GET requests
:return: The pagination_info of this ObjectResponse.
:rtype: PaginationInfo
"""
return self._pagination_info
@pagination_info.setter
def pagination_info(self, pagination_info):
"""
Sets the pagination_info of this ObjectResponse.
pagination information, only available in GET requests
:param pagination_info: The pagination_info of this ObjectResponse.
:type: PaginationInfo
"""
self._pagination_info = pagination_info
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, ObjectResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| 27.460317 | 204 | 0.578324 |
from pprint import pformat
from six import iteritems
import re
class ObjectResponse(object):
swagger_types = {
'pagination_info': 'PaginationInfo'
}
attribute_map = {
'pagination_info': 'pagination_info'
}
def __init__(self, pagination_info=None):
self._pagination_info = None
if pagination_info is not None:
self.pagination_info = pagination_info
@property
def pagination_info(self):
return self._pagination_info
@pagination_info.setter
def pagination_info(self, pagination_info):
self._pagination_info = pagination_info
def to_dict(self):
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
return pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, ObjectResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
f719cf9df16d97ce0c0637dc8db52aa8046af0f1 | 6,350 | py | Python | deeppages/utils.py | ricardofalasca/deep-pages | d1b2a48f62c31e20d767df5c6345e07e4d05290d | [
"MIT"
] | null | null | null | deeppages/utils.py | ricardofalasca/deep-pages | d1b2a48f62c31e20d767df5c6345e07e4d05290d | [
"MIT"
] | null | null | null | deeppages/utils.py | ricardofalasca/deep-pages | d1b2a48f62c31e20d767df5c6345e07e4d05290d | [
"MIT"
] | null | null | null | from django.template import Template, Context
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.db.models import Q
from django.urls import reverse, NoReverseMatch
from django.core.exceptions import ObjectDoesNotExist
from .signals import page_found, page_not_found, page_requested
from .exceptions import InvalidPathException, PageNotFoundException
from .models import Page
import re
def normalize_path(path):
''' Remove duplicated slashes and reverse mode with/wo slash in the end '''
from .urls import get_deeppages_path
new_path = re.sub(r'[\/]{2,}', '/', path)
try:
# check if deeppages' path isn't the root path
deeppages_path = reverse('deeppages:{}'.format(get_deeppages_path()))
except NoReverseMatch:
pass
else:
if deeppages_path != '/':
if new_path.startswith(deeppages_path):
new_path = new_path.replace(deeppages_path, '')
if not new_path.startswith('/'):
new_path = '/{}'.format(new_path)
return new_path[:-1] if new_path.endswith('/') else '{}/'.format(new_path)
def render_content(content, context):
''' Render page content '''
ctx = Context(context or {})
return Template(content).render(ctx)
def render_page(page, context, callback):
''' Render page '''
if callback:
page_content = callback(page, context)
else:
page_content = page.content
return render_content(page_content, context)
def render_requested_page_content(sender, request, page):
''' Render page requested by Middleware or PageView '''
content = page.content
ctx = {'request': request}
page_found.send_robust(
sender=sender.__class__,
page=page,
path=page.path,
request=request,
content=content,
context=ctx)
# So, if content and/or context was changed inside the signal receiver,
# we'll render with the new values.
return render_content(content, ctx)
def is_acceptable_file_type(path):
''' Only text-based content can be accepted, any other will be ignored. '''
filename = path.strip('/').split('/')[-1]
accepted_exts = ['.html', '.htm', '.css', '.js', '.svg', '.txt']
max_ext_len = max(map(len, accepted_exts))
try:
has_extension = filename.index('.') >= (len(filename) - max_ext_len)
except ValueError:
has_extension = False
is_accepted = not has_extension or len([a for a in accepted_exts
if filename.endswith(a)]) > 0
return is_accepted
def get_page_by_path(sender, request, logger):
''' Get page by path and return a rendered and processed template.
Arguments:
sender -- object sender
request -- WSGIRequest object
logger -- logger instance
Also, three robust signals can be dispatched from here:
1. page_requested (after a page request, ha!)
2. page_not_found (for non-existent pages! O'really?)
3. and, mainly, page_found (When a page exists AND is active! Ha!
Could you imagine that?)
Both signals: 'page_request' and 'page_not_found' these keyword
arguments will be received: 'path' and 'request'.
For 'page_found':
- path: the path (URL) requested
- page: a deeppages.models.Page() model's instance that was found
by its PATH
- request: WSGIRequest object
- context: a context dictionary (with request inside)
- content: the page content (you can change it as you wish)
In case of 'page_not_found', after robust signal callback has been
returned, Django's will follow its normal flow.
ps.: if settings.DEBUG is True, you can handle some logs for debug
purposes.
'''
path = normalize_path(request.path)
if not is_acceptable_file_type(path):
return
if settings.DEBUG and logger:
logger.debug('DeepPage Path Requested: [{}]'.format(path))
# dispatch page requested signal
page_requested.send_robust(
sender=sender.__class__, path=path, request=request)
if not path:
# Is called from an instance subclass of TemplateView ?
if issubclass(sender.__class__, MiddlewareMixin):
return
else:
raise InvalidPathException
try:
# try to get page directly
page = Page.objects.exclude(is_active=False).get(
Q(path__iexact=path) | Q(path__iexact=request.path))
except Page.DoesNotExist:
if settings.DEBUG and logger:
logger.exception('DeepPage Not Found: [{}]'.format(path))
page_not_found.send_robust(
sender=sender.__class__,
path=path,
request=request)
if issubclass(sender.__class__, MiddlewareMixin):
return
else:
raise PageNotFoundException
else:
return render_requested_page_content(sender, request, page)
def get_page_by_name(name, context=None, callback=None):
''' Get page by its name and render it.
Arguments:
name -- Page name
Keyword arguments:
context -- dictionary with additional key/values that
will be used for page content rendering (default: None)
callback -- callback function - will be called before render the
page content (default: None)
'''
if not name:
return
try:
# try to get page directly
page = Page.objects.exclude(is_active=False).get(name__iexact=name)
except ObjectDoesNotExist:
return
else:
return render_page(page, context, callback)
def get_page_by_slug(slug, context=None, callback=None):
''' Get page by its slug and render it.
Arguments:
slug -- Page's slug
Keyword arguments:
context -- dictionary with additional key/values that
will be used for page content rendering (default: None)
callback -- callback function - will be called before render the
page content (default: None)
'''
if not slug:
return
try:
page = Page.objects.exclude(is_active=False).get(slug__iexact=slug)
except ObjectDoesNotExist:
return
else:
return render_page(page, context, callback)
| 29.398148 | 79 | 0.649291 | from django.template import Template, Context
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.db.models import Q
from django.urls import reverse, NoReverseMatch
from django.core.exceptions import ObjectDoesNotExist
from .signals import page_found, page_not_found, page_requested
from .exceptions import InvalidPathException, PageNotFoundException
from .models import Page
import re
def normalize_path(path):
from .urls import get_deeppages_path
new_path = re.sub(r'[\/]{2,}', '/', path)
try:
deeppages_path = reverse('deeppages:{}'.format(get_deeppages_path()))
except NoReverseMatch:
pass
else:
if deeppages_path != '/':
if new_path.startswith(deeppages_path):
new_path = new_path.replace(deeppages_path, '')
if not new_path.startswith('/'):
new_path = '/{}'.format(new_path)
return new_path[:-1] if new_path.endswith('/') else '{}/'.format(new_path)
def render_content(content, context):
ctx = Context(context or {})
return Template(content).render(ctx)
def render_page(page, context, callback):
if callback:
page_content = callback(page, context)
else:
page_content = page.content
return render_content(page_content, context)
def render_requested_page_content(sender, request, page):
content = page.content
ctx = {'request': request}
page_found.send_robust(
sender=sender.__class__,
page=page,
path=page.path,
request=request,
content=content,
context=ctx)
return render_content(content, ctx)
def is_acceptable_file_type(path):
filename = path.strip('/').split('/')[-1]
accepted_exts = ['.html', '.htm', '.css', '.js', '.svg', '.txt']
max_ext_len = max(map(len, accepted_exts))
try:
has_extension = filename.index('.') >= (len(filename) - max_ext_len)
except ValueError:
has_extension = False
is_accepted = not has_extension or len([a for a in accepted_exts
if filename.endswith(a)]) > 0
return is_accepted
def get_page_by_path(sender, request, logger):
path = normalize_path(request.path)
if not is_acceptable_file_type(path):
return
if settings.DEBUG and logger:
logger.debug('DeepPage Path Requested: [{}]'.format(path))
# dispatch page requested signal
page_requested.send_robust(
sender=sender.__class__, path=path, request=request)
if not path:
# Is called from an instance subclass of TemplateView ?
if issubclass(sender.__class__, MiddlewareMixin):
return
else:
raise InvalidPathException
try:
# try to get page directly
page = Page.objects.exclude(is_active=False).get(
Q(path__iexact=path) | Q(path__iexact=request.path))
except Page.DoesNotExist:
if settings.DEBUG and logger:
logger.exception('DeepPage Not Found: [{}]'.format(path))
page_not_found.send_robust(
sender=sender.__class__,
path=path,
request=request)
if issubclass(sender.__class__, MiddlewareMixin):
return
else:
raise PageNotFoundException
else:
return render_requested_page_content(sender, request, page)
def get_page_by_name(name, context=None, callback=None):
if not name:
return
try:
# try to get page directly
page = Page.objects.exclude(is_active=False).get(name__iexact=name)
except ObjectDoesNotExist:
return
else:
return render_page(page, context, callback)
def get_page_by_slug(slug, context=None, callback=None):
if not slug:
return
try:
page = Page.objects.exclude(is_active=False).get(slug__iexact=slug)
except ObjectDoesNotExist:
return
else:
return render_page(page, context, callback)
| true | true |
f719cfd1f03d71fd7a99b8b868b8442eb5dcb3c5 | 26,423 | py | Python | cabot_ui/src/cabot_ui/geojson.py | kufusha/cabot | 52a40a39a29f0bd79b6fdd8f961708e09fda9a51 | [
"MIT"
] | null | null | null | cabot_ui/src/cabot_ui/geojson.py | kufusha/cabot | 52a40a39a29f0bd79b6fdd8f961708e09fda9a51 | [
"MIT"
] | null | null | null | cabot_ui/src/cabot_ui/geojson.py | kufusha/cabot | 52a40a39a29f0bd79b6fdd8f961708e09fda9a51 | [
"MIT"
] | null | null | null | # Copyright (c) 2020 Carnegie Mellon University
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
MapService GeoJson mapper
MapService: https://github.com/hulop/MapService
Author: Daisuke Sato<daisukes@cmu.edu>
"""
# -*- coding: utf-8 -*-
import sys
import traceback
import copy
import math
import json
import scipy
import scipy.spatial
import numpy
import numpy.linalg
import rospy
import tf
import angles
import geometry_msgs.msg
from cabot_ui import geoutil, i18n
class Geometry(object):
"""Geometry class"""
@classmethod
def marshal(cls, dic):
"""marshal Geometry subclasses object"""
if 'type' in dic:
if dic['type'] == "Point":
cls = Point
elif dic['type'] == "LineString":
cls = LineString
if cls == Geometry:
return cls(**dic)
return cls.marshal(dic)
def __init__(self, **dic):
s = super(Geometry, self)
if self.__class__.mro()[-2] == s.__thisclass__:
s.__init__()
else:
s.__init__(**dic)
if 'coordinates' in dic:
self.coordinates = dic['coordinates']
if 'type' in dic:
self.geometry_type = dic['type']
class Point(Geometry, geoutil.Latlng):
"""Point class representing global point"""
@classmethod
def marshal(cls, dic):
"""marshal Point object"""
return cls(**dic)
def __init__(self, **dic):
c = dic['coordinates']
super(Point, self).__init__(lat=c[1], lng=c[0], **dic)
class LineString(Geometry):
"""Point class representing global line (start to end)"""
@classmethod
def marshal(cls, dic):
"""marshal LineString object"""
return cls(**dic)
def __init__(self, **dic):
super(LineString, self).__init__(**dic)
self.start = geoutil.Latlng(lat=self.coordinates[0][1], lng=self.coordinates[0][0])
self.end = geoutil.Latlng(lat=self.coordinates[1][1], lng=self.coordinates[1][0])
def distance_to(self, point):
if isinstance(point, Point):
return self.nearest_point_on_line(point).distance_to(point)
raise RuntimeError("Need to pass a Point object (%s)"%(type(point)))
def nearest_point_on_line(self, point):
A = geoutil.latlng2mercator(self.start)
B = geoutil.latlng2mercator(self.end)
C = geoutil.latlng2mercator(point)
# Distance between A and B
distAB = math.sqrt(math.pow(A.x - B.x, 2) + math.pow(A.y - B.y, 2));
# Direction vector from A to B
vecABx = (B.x - A.x) / distAB;
vecABy = (B.y - A.y) / distAB;
# Time from A to C
timeAC = max(0, min(distAB, vecABx * (C.x - A.x) + vecABy * (C.y - A.y)));
# LatLng of the point
x = timeAC * vecABx + A.x;
y = timeAC * vecABy + A.y;
return geoutil.mercator2latlng(geoutil.Point(x=x, y=y))
class Properties(object):
@classmethod
def marshal(cls, dic):
"""marshal Properties object"""
return cls(**dic)
DEFAULT_VALUES = {
"hulop_building": None,
"hulop_major_category": None,
"hulop_sub_category": None,
"hulop_minor_category": None,
"hulop_heading": 0,
"hulop_angle": 180,
"hulop_height": 0,
"hulop_long_description": None,
"hulop_short_description": None,
"hulop_description": None,
"hulop_location_description": None,
"hulop_content": None,
"hulop_tags": None,
"hulop_poi_external_category": None,
"hulop_show_labels_zoomlevel": None
}
def __getattr__(self, name):
value = self.__dict__.get(name)
if not value:
if name in Properties.DEFAULT_VALUES:
return Properties.DEFAULT_VALUES[name]
raise AttributeError("%s.%s is invalid"%(self.__class__.__name__, name))
return value
def __init__(self, **dic):
for key in dic:
try:
setattr(self, key, dic[key])
except:
print("Cannot use unicode string for a property name: \"{}\"".format(key.encode('utf8')))
def __str__(self):
return json.dumps(self.__dict__, sort_keys=True, indent=2)
class Object(object):
"""Object class"""
@classmethod
def marshal_list(cls, objects):
"""marshal list of Object subclasses objects"""
temp = []
for obj in objects:
temp.append(cls.marshal(obj))
return temp
@classmethod
def marshal_dict(cls, objects):
"""marshal dict of Object subclasses objects"""
temp = {}
for key in objects.keys():
temp[key] = cls.marshal(objects[key])
return temp
@classmethod
def marshal(cls, dic):
"""marshal Object subclasses object"""
if 'node' in dic:
cls = Landmark
else:
prop = dic['properties'] if 'properties' in dic else None
if prop is not None:
if 'node_id' in prop:
cls = Node
if 'link_id' in prop:
cls = Link
if 'facil_id' in prop:
cls = Facility
if cls == Object:
return cls(**dic)
return cls.marshal(dic)
_id_map = {}
_all_objects = []
@staticmethod
def get_object_by_id(_id, func=None):
"""get object having id by callback function, it can be defered"""
if _id in Object._id_map:
if isinstance(Object._id_map[_id], list):
Object._id_map[_id].append(func)
else:
if func is not None and callable(func):
func(Object._id_map[_id])
return None
return Object._id_map[_id]
else:
Object._id_map[_id] = [func]
return None
@staticmethod
def get_objects_by_type(_type):
"""get objects of specified type"""
temp = []
for obj in Object._all_objects:
if isinstance(obj, _type):
temp.append(obj)
return temp
@staticmethod
def get_all_objects():
return Object._all_objects
@staticmethod
def _register(obj):
"""store object with id and type"""
# register with id
_id = obj._id
if _id in Object._id_map:
if isinstance(Object._id_map[_id], list):
for func in Object._id_map[_id]:
if callable(func):
func(obj)
Object._id_map[_id] = obj
Object._all_objects.append(obj)
else:
#raise RuntimeError("duplicate id")
pass
else:
Object._id_map[_id] = obj
Object._all_objects.append(obj)
@staticmethod
def reset_all_objects():
"""reset all state in the objects"""
for obj in Object._all_objects:
obj.reset()
@staticmethod
def _reset_link_index():
Object._link_index = []
Object._link_points = []
Object._link_kdtree = None
_link_index = []
_link_points = []
_link_kdtree = None
@staticmethod
def _build_link_index():
for obj in Object.get_objects_by_type(Link):
if obj.start_node and obj.end_node:
sp = numpy.array([obj.start_node.local_geometry.x, obj.start_node.local_geometry.y])
ep = numpy.array([obj.end_node.local_geometry.x, obj.end_node.local_geometry.y])
Object._add_link_index(sp, ep, obj)
if Object._link_points:
Object._link_kdtree = scipy.spatial.KDTree(Object._link_points)
@staticmethod
def _add_link_index(sp, ep, obj):
mp = (sp+ep)/2.0
Object._link_points.append(mp)
Object._link_index.append(obj)
if numpy.linalg.norm(sp-ep) > 1:
Object._add_link_index(sp, mp, obj)
Object._add_link_index(mp, ep, obj)
@staticmethod
def get_nearest_link(node, exclude=None):
point = node.local_geometry
latlng = node.geometry
_, index = Object._link_kdtree.query([point.x, point.y], 50)
min_index = None
min_dist = 1000
for i in index:
link = Object._link_index[i]
if exclude is not None and exclude(link):
continue
dist = link.geometry.distance_to(latlng)
if node.floor is not None:
if link.start_node.floor != node.floor and \
link.end_node.floor != node.floor:
dist += 1000
if dist < min_dist:
min_dist = dist
min_index = i
if min_index is None:
return None
return Object._link_index[min_index]
@staticmethod
def update_anchor_all(anchor):
"""update anchor of all object"""
Object._reset_link_index()
for obj in Object._all_objects:
obj.update_anchor(anchor)
Object._build_link_index()
def __init__(self, **dic):
s = super(Object, self)
if self.__class__.mro()[-2] == s.__thisclass__:
s.__init__()
else:
s.__init__(**dic)
if 'geometry' in dic:
self.geometry = Geometry.marshal(dic['geometry'])
if 'properties' in dic:
self.properties = Properties.marshal(dic['properties'])
if '_id' in dic:
self._id = dic['_id']
if 'no_registration' not in dic or not dic['no_registration']:
Object._register(self)
self.anchor = None
self.local_geometry = None
def __str__(self):
ret = "%s, (%s)\n" % (type(self), hex(id(self)))
for key in self.__dict__:
value = getattr(self, key)
if isinstance(value, Object):
ret += "%s: %s<%s>\n"%(key, type(value), value._id)
else:
ret += "%s: %s\n"%(key, str(value))
import inspect
for method in inspect.getmembers(type(self), predicate=lambda o: isinstance(o, property)):
ret += "%s: %s\n"%(method[0], method[1].__get__(self, type(self)))
return ret
def __repr__(self):
return "%s<%s>"%(type(self), self._id)
def update_anchor(self, anchor):
self.anchor = anchor
if anchor is not None:
try:
self.local_geometry = geoutil.global2local(self.geometry, anchor)
except:
print("Could not convert geometry: {}".format(self.local_geometry))
def distance_to(self, point):
if isinstance(point, geoutil.Point):
return self.local_geometry.distance_to(point)
if isinstance(point, geoutil.Latlng):
return self.geometry.distance_to(point)
def reset(self):
pass
class Link(Object):
"""Link class"""
ROUTE_TYPE_WALKWAY = 1
ROUTE_TYPE_MOVING_WALKWAY = 2
ROUTE_TYPE_RAILROAD_CROSSING = 3
ROUTE_TYPE_ELEVATOR = 4
ROUTE_TYPE_ESCALATOR = 5
ROUTE_TYPE_STAIRS = 6
ROUTE_TYPE_SLOPE = 7
ROUTE_TYPE_UNKNOWN = 99
@classmethod
def marshal(cls, dic):
"""marshal Link subclasses object"""
if 'properties' in dic:
prop = dic['properties']
if 'sourceNode' in prop:
cls = RouteLink
if cls == Link:
return cls(**dic)
return cls.marshal(dic)
def __init__(self, **dic):
super(Link, self).__init__(**dic)
self.start_node = None
self.end_node = None
self.pois = []
self.floor = 0
Object.get_object_by_id(self.properties.start_id, self._set_start_node)
Object.get_object_by_id(self.properties.end_id, self._set_end_node)
def _set_start_node(self, node):
self.start_node = node
self._update()
def _set_end_node(self, node):
self.end_node = node
self._update()
def _update(self):
if self.start_node is not None and \
self.end_node is not None:
self.floor = (self.start_node.floor + self.end_node.floor)/2.0
@property
def is_elevator(self):
"""wheather this links is an elevator or not"""
return self.properties.route_type == Link.ROUTE_TYPE_ELEVATOR
@property
def is_escalator(self):
"""wheather this links is an escalator or not"""
return self.properties.route_type == Link.ROUTE_TYPE_ESCALATOR
@property
def is_leaf(self):
"""wheather this links is a leaf or not"""
if self.start_node is None or self.end_node is None:
return False
return self.start_node.is_leaf or self.end_node.is_leaf
@property
def length(self):
"""distance from start to end"""
if self.start_node is None or self.end_node is None:
return float('nan')
return self.start_node.geometry.distance_to(self.end_node.geometry)
def register_poi(self, poi):
self.pois.append(poi)
def update_anchor(self, anchor):
self.anchor = anchor
#TODO
class RouteLink(Link):
"""Route Link class"""
@classmethod
def marshal(cls, dic):
"""marshal Directed Link object"""
return cls(**dic)
def __init__(self, **dic):
super(RouteLink, self).__init__(no_registration=True, **dic)
self.source_node = None
self.target_node = None
Object.get_object_by_id(self.properties.sourceNode, self._set_source_node)
Object.get_object_by_id(self.properties.targetNode, self._set_target_node)
Object.get_object_by_id(self._id, self._found_link)
def _set_source_node(self, node):
self.source_node = node
def _set_target_node(self, node):
self.target_node = node
def _found_link(self, link):
self.pois = link.pois
@property
def is_temp(self):
return self._id.startswith("_TEMP_LINK")
class Node(Object):
"""Node class"""
@classmethod
def marshal(cls, dic):
"""marshal Node object"""
return cls(**dic)
def __init__(self, **dic):
super(Node, self).__init__(**dic)
self.links = []
for i in range(1, 100):
attr = "link%d_id"%(i)
if hasattr(self.properties, attr):
Object.get_object_by_id(getattr(self.properties, attr), self._add_link)
if hasattr(self.properties, 'floor'):
self.floor = self.properties.floor
else:
self.floor = 0
self.facility = None
Facility.get_facility_by_id(self._id, self._set_facility)
def _add_link(self, link):
self.links.append(link)
def _set_facility(self, facility):
self.facility = facility
@property
def is_leaf(self):
"""wheather this node is the end of leaf link"""
return len(self.links) == 1
@property
def is_elevator(self):
"""wheather this node is connected to elevator link"""
res = False
for link in self.links:
res = res or link.is_elevator
return res
class Facility(Object):
"""Facility class"""
@classmethod
def marshal(cls, dic):
"""marshal Facility subclasses object"""
if 'properties' in dic:
prop = dic['properties']
if 'hulop_major_category' in prop:
category = prop['hulop_major_category']
if category == '_nav_poi_':
cls = POI
if cls == Facility:
return cls(**dic)
return cls.marshal(dic)
def __init__(self, **dic):
super(Facility, self).__init__(**dic)
self.entrances = []
for i in range(1, 100):
attr = "ent%d_node"%(i)
if hasattr(self.properties, attr):
Facility._id_map[getattr(self.properties, attr)] = self
Object.get_object_by_id(getattr(self.properties, attr), self._add_facility)
self.name = i18n.localized_attr(self.properties, "name")
self.name_pron = i18n.localized_attr(self.properties, "name_hira", only_if="ja") ## special case
self.long_description = i18n.localized_attr(self.properties, "hulop_long_description")
def _add_facility(self, node):
self.entrances.append(node)
_id_map = {}
@staticmethod
def get_facility_by_id(_id, func=None):
"""get facility having id by callback function, it can be defered"""
if _id in Facility._id_map:
if isinstance(Facility._id_map[_id], list):
Facility._id_map[_id].append(func)
else:
if func is not None and callable(func):
func(Facility._id_map[_id])
return None
return Facility._id_map[_id]
else:
Facility._id_map[_id] = [func]
return None
class POI(Facility, geoutil.TargetPlace):
"""POI class"""
@classmethod
def marshal(cls, dic):
"""marshal POI object"""
if 'properties' in dic:
prop = dic['properties']
if 'hulop_sub_category' in prop:
category = prop['hulop_sub_category']
if category == '_nav_door_':
cls = DoorPOI
if category == '_nav_info_':
cls = InfoPOI
if category == '_cabot_speed_':
cls = SpeedPOI
if category == '_nav_elevator_cab_':
cls = ElevatorCabPOI
if category == '_nav_queue_wait_':
cls = QueueWaitPOI
if category == '_nav_queue_target_':
cls = QueueTargetPOI
if cls == POI:
return cls(**dic)
return cls.marshal(dic)
def __init__(self, **dic):
if 'properties' in dic:
prop = dic['properties']
get_prop = lambda prop, key: prop[key] if key in prop else Properties.DEFAULT_VALUES[key]
r = (-get_prop(prop, 'hulop_heading') + 90) / 180.0 * math.pi
angle = get_prop(prop, 'hulop_angle')
self.floor = get_prop(prop, 'hulop_height')
super(POI, self).__init__(r=r, x=0, y=0, angle=angle, floor=self.floor, **dic)
self.sub_category = self.properties.hulop_sub_category \
if hasattr(self.properties, 'hulop_sub_category') else ""
self.minor_category = self.properties.hulop_minor_category \
if hasattr(self.properties, 'hulop_minor_category') else ""
#backward compatibility
self.local_pose = self
def approaching_statement(self):
return None
def approached_statement(self):
return None
def passed_statement(self):
return None
def update_anchor(self, anchor):
super(POI, self).update_anchor(anchor)
if anchor is not None:
rad = (-self.properties.hulop_heading + 90 + anchor.rotate) / 180.0 * math.pi
self.update_pose(self.local_geometry, rad)
def reset(self):
self.reset_target()
class DoorPOI(POI):
"""POI class"""
@classmethod
def marshal(cls, dic):
"""marshal Door POI object"""
return cls(**dic)
def __init__(self, **dic):
super(DoorPOI, self).__init__(**dic)
@property
def title(self):
if self.is_auto:
return i18n.localized_string("AUTO_DOOR")
else:
return i18n.localized_string("DOOR")
@property
def is_auto(self):
"""wheather this is auto door or not"""
return self.minor_category is not None and \
'_flag_auto_' in self.minor_category
def approaching_statement(self):
return i18n.localized_string("DOOR_POI_APPROACHING", self.title)
class InfoPOI(POI):
"""Nav Info POI class"""
@classmethod
def marshal(cls, dic):
"""marshal Info POI object"""
return cls(**dic)
def __init__(self, **dic):
super(InfoPOI, self).__init__(**dic)
def approached_statement(self):
return self.name
class SpeedPOI(POI):
"""Cabot Speed POI class"""
@classmethod
def marshal(cls, dic):
"""marshal Speed POI object"""
return cls(**dic)
def __init__(self, **dic):
super(SpeedPOI, self).__init__(**dic)
self.limit = float(self.properties.hulop_content)
class ElevatorCabPOI(POI):
"""Elevator Cab POI class"""
@classmethod
def marshal(cls, dic):
"""marshal Elevator Cab POI object"""
return cls(**dic)
def __init__(self, **dic):
super(ElevatorCabPOI, self).__init__(**dic)
self.set_back = (3.0, 0.0)
self.set_forward = (3.0, 0.0)
self.door = (1.0, 0.0)
if self.properties.hulop_content:
try:
hulop_content_json = json.loads(self.properties.hulop_content)
if "set_back" in hulop_content_json:
self.set_back = hulop_content_json["set_back"]
if "set_forward" in hulop_content_json:
self.set_forward = hulop_content_json["set_forward"]
if "door" in hulop_content_json:
self.door = hulop_content_json["door"]
if "buttons" in hulop_content_json:
self.buttons = hulop_content_json["buttons"]
except:
traceback.print_exc(file=sys.std_out)
@property
def door_geometry(self):
x = self.x + math.cos(self.r) * self.door[0] - math.sin(self.r) * self.door[1]
y = self.y + math.sin(self.r) * self.door[0] + math.cos(self.r) * self.door[1]
return geoutil.Point(x=x, y=y)
def where_is_buttons(self, pose):
x = self.x + math.cos(self.r) * self.buttons[0] - math.sin(self.r) * self.buttons[1]
y = self.y + math.sin(self.r) * self.buttons[0] + math.cos(self.r) * self.buttons[1]
b_pos = geoutil.Point(x=x,y=y)
b_pose = geoutil.Pose.pose_from_points(b_pos, pose)
dir = angles.shortest_angular_distance(pose.r, b_pose.r)
print(pose, b_pos, b_pose, dir)
if abs(dir) > math.pi / 3 * 2:
return "BACK"
elif abs(dir) > math.pi / 3:
if dir > 0:
return "LEFT"
elif dir < 0:
return "RIGHT"
elif abs(dir) < math.pi / 10:
return "FRONT"
elif dir > 0:
return "FRONT_LEFT"
elif dir < 0:
return "FRONT_RIGHT"
rospy.logerror("should not happen")
return None
class QueueWaitPOI(POI):
"""Queue Wait POI class"""
@classmethod
def marshal(cls, dic):
"""marshal Queue TaWaitrget POI object"""
return cls(**dic)
def __init__(self, **dic):
super(QueueWaitPOI, self).__init__(**dic)
self.interval = 1.0
hulop_content_json = json.loads(self.properties.hulop_content)
if "interval" in hulop_content_json:
self.interval = float(hulop_content_json["interval"])
self.is_copied = False
self.link_orientation = None
# def approached_statement(self):
# return "queue wait point"
def register_link(self, link):
end_pose = geoutil.Pose.pose_from_points(link.end_node.local_geometry, link.start_node.local_geometry)
quat = tf.transformations.quaternion_from_euler(0, 0, end_pose.r)
self.link_orientation = geometry_msgs.msg.Quaternion()
self.link_orientation.x = quat[0]
self.link_orientation.y = quat[1]
self.link_orientation.z = quat[2]
self.link_orientation.w = quat[3]
def copy_to_link(self, link, local_geometry_x, local_geometry_y):
copied_poi = copy.deepcopy(self)
copied_poi.x = local_geometry_x
copied_poi.y = local_geometry_y
copied_poi.local_geometry.x = local_geometry_x
copied_poi.local_geometry.y = local_geometry_y
copied_poi.geometry = geoutil.local2global(copied_poi.local_geometry, copied_poi.anchor)
link.register_poi(copied_poi)
copied_poi.register_link(link)
self.is_copied = True
return copied_poi
class QueueTargetPOI(POI):
"""Queue Target POI class"""
@classmethod
def marshal(cls, dic):
"""marshal Queue Target POI object"""
return cls(**dic)
def __init__(self, **dic):
super(QueueTargetPOI, self).__init__(**dic)
self.enter_node = None
self.exit_node = None
hulop_content_json = json.loads(self.properties.hulop_content)
Object.get_object_by_id(hulop_content_json["enter"], self._set_enter_node)
Object.get_object_by_id(hulop_content_json["exit"], self._set_exit_node)
def _set_enter_node(self, node):
self.enter_node = node
def _set_exit_node(self, node):
self.exit_node = node
class Landmark(Facility):
"""Landmark class"""
@classmethod
def marshal(cls, dic):
"""marshal Landmark object"""
return cls(**dic)
def __init__(self, **dic):
self._id = dic['node']+"_landmark"
super(Landmark, self).__init__(**dic)
| 32.027879 | 110 | 0.590357 |
import sys
import traceback
import copy
import math
import json
import scipy
import scipy.spatial
import numpy
import numpy.linalg
import rospy
import tf
import angles
import geometry_msgs.msg
from cabot_ui import geoutil, i18n
class Geometry(object):
@classmethod
def marshal(cls, dic):
if 'type' in dic:
if dic['type'] == "Point":
cls = Point
elif dic['type'] == "LineString":
cls = LineString
if cls == Geometry:
return cls(**dic)
return cls.marshal(dic)
def __init__(self, **dic):
s = super(Geometry, self)
if self.__class__.mro()[-2] == s.__thisclass__:
s.__init__()
else:
s.__init__(**dic)
if 'coordinates' in dic:
self.coordinates = dic['coordinates']
if 'type' in dic:
self.geometry_type = dic['type']
class Point(Geometry, geoutil.Latlng):
@classmethod
def marshal(cls, dic):
return cls(**dic)
def __init__(self, **dic):
c = dic['coordinates']
super(Point, self).__init__(lat=c[1], lng=c[0], **dic)
class LineString(Geometry):
@classmethod
def marshal(cls, dic):
return cls(**dic)
def __init__(self, **dic):
super(LineString, self).__init__(**dic)
self.start = geoutil.Latlng(lat=self.coordinates[0][1], lng=self.coordinates[0][0])
self.end = geoutil.Latlng(lat=self.coordinates[1][1], lng=self.coordinates[1][0])
def distance_to(self, point):
if isinstance(point, Point):
return self.nearest_point_on_line(point).distance_to(point)
raise RuntimeError("Need to pass a Point object (%s)"%(type(point)))
def nearest_point_on_line(self, point):
A = geoutil.latlng2mercator(self.start)
B = geoutil.latlng2mercator(self.end)
C = geoutil.latlng2mercator(point)
distAB = math.sqrt(math.pow(A.x - B.x, 2) + math.pow(A.y - B.y, 2));
vecABx = (B.x - A.x) / distAB;
vecABy = (B.y - A.y) / distAB;
timeAC = max(0, min(distAB, vecABx * (C.x - A.x) + vecABy * (C.y - A.y)));
x = timeAC * vecABx + A.x;
y = timeAC * vecABy + A.y;
return geoutil.mercator2latlng(geoutil.Point(x=x, y=y))
class Properties(object):
@classmethod
def marshal(cls, dic):
return cls(**dic)
DEFAULT_VALUES = {
"hulop_building": None,
"hulop_major_category": None,
"hulop_sub_category": None,
"hulop_minor_category": None,
"hulop_heading": 0,
"hulop_angle": 180,
"hulop_height": 0,
"hulop_long_description": None,
"hulop_short_description": None,
"hulop_description": None,
"hulop_location_description": None,
"hulop_content": None,
"hulop_tags": None,
"hulop_poi_external_category": None,
"hulop_show_labels_zoomlevel": None
}
def __getattr__(self, name):
value = self.__dict__.get(name)
if not value:
if name in Properties.DEFAULT_VALUES:
return Properties.DEFAULT_VALUES[name]
raise AttributeError("%s.%s is invalid"%(self.__class__.__name__, name))
return value
def __init__(self, **dic):
for key in dic:
try:
setattr(self, key, dic[key])
except:
print("Cannot use unicode string for a property name: \"{}\"".format(key.encode('utf8')))
def __str__(self):
return json.dumps(self.__dict__, sort_keys=True, indent=2)
class Object(object):
@classmethod
def marshal_list(cls, objects):
temp = []
for obj in objects:
temp.append(cls.marshal(obj))
return temp
@classmethod
def marshal_dict(cls, objects):
temp = {}
for key in objects.keys():
temp[key] = cls.marshal(objects[key])
return temp
@classmethod
def marshal(cls, dic):
if 'node' in dic:
cls = Landmark
else:
prop = dic['properties'] if 'properties' in dic else None
if prop is not None:
if 'node_id' in prop:
cls = Node
if 'link_id' in prop:
cls = Link
if 'facil_id' in prop:
cls = Facility
if cls == Object:
return cls(**dic)
return cls.marshal(dic)
_id_map = {}
_all_objects = []
@staticmethod
def get_object_by_id(_id, func=None):
if _id in Object._id_map:
if isinstance(Object._id_map[_id], list):
Object._id_map[_id].append(func)
else:
if func is not None and callable(func):
func(Object._id_map[_id])
return None
return Object._id_map[_id]
else:
Object._id_map[_id] = [func]
return None
@staticmethod
def get_objects_by_type(_type):
temp = []
for obj in Object._all_objects:
if isinstance(obj, _type):
temp.append(obj)
return temp
@staticmethod
def get_all_objects():
return Object._all_objects
@staticmethod
def _register(obj):
_id = obj._id
if _id in Object._id_map:
if isinstance(Object._id_map[_id], list):
for func in Object._id_map[_id]:
if callable(func):
func(obj)
Object._id_map[_id] = obj
Object._all_objects.append(obj)
else:
pass
else:
Object._id_map[_id] = obj
Object._all_objects.append(obj)
@staticmethod
def reset_all_objects():
for obj in Object._all_objects:
obj.reset()
@staticmethod
def _reset_link_index():
Object._link_index = []
Object._link_points = []
Object._link_kdtree = None
_link_index = []
_link_points = []
_link_kdtree = None
@staticmethod
def _build_link_index():
for obj in Object.get_objects_by_type(Link):
if obj.start_node and obj.end_node:
sp = numpy.array([obj.start_node.local_geometry.x, obj.start_node.local_geometry.y])
ep = numpy.array([obj.end_node.local_geometry.x, obj.end_node.local_geometry.y])
Object._add_link_index(sp, ep, obj)
if Object._link_points:
Object._link_kdtree = scipy.spatial.KDTree(Object._link_points)
@staticmethod
def _add_link_index(sp, ep, obj):
mp = (sp+ep)/2.0
Object._link_points.append(mp)
Object._link_index.append(obj)
if numpy.linalg.norm(sp-ep) > 1:
Object._add_link_index(sp, mp, obj)
Object._add_link_index(mp, ep, obj)
@staticmethod
def get_nearest_link(node, exclude=None):
point = node.local_geometry
latlng = node.geometry
_, index = Object._link_kdtree.query([point.x, point.y], 50)
min_index = None
min_dist = 1000
for i in index:
link = Object._link_index[i]
if exclude is not None and exclude(link):
continue
dist = link.geometry.distance_to(latlng)
if node.floor is not None:
if link.start_node.floor != node.floor and \
link.end_node.floor != node.floor:
dist += 1000
if dist < min_dist:
min_dist = dist
min_index = i
if min_index is None:
return None
return Object._link_index[min_index]
@staticmethod
def update_anchor_all(anchor):
Object._reset_link_index()
for obj in Object._all_objects:
obj.update_anchor(anchor)
Object._build_link_index()
def __init__(self, **dic):
s = super(Object, self)
if self.__class__.mro()[-2] == s.__thisclass__:
s.__init__()
else:
s.__init__(**dic)
if 'geometry' in dic:
self.geometry = Geometry.marshal(dic['geometry'])
if 'properties' in dic:
self.properties = Properties.marshal(dic['properties'])
if '_id' in dic:
self._id = dic['_id']
if 'no_registration' not in dic or not dic['no_registration']:
Object._register(self)
self.anchor = None
self.local_geometry = None
def __str__(self):
ret = "%s, (%s)\n" % (type(self), hex(id(self)))
for key in self.__dict__:
value = getattr(self, key)
if isinstance(value, Object):
ret += "%s: %s<%s>\n"%(key, type(value), value._id)
else:
ret += "%s: %s\n"%(key, str(value))
import inspect
for method in inspect.getmembers(type(self), predicate=lambda o: isinstance(o, property)):
ret += "%s: %s\n"%(method[0], method[1].__get__(self, type(self)))
return ret
def __repr__(self):
return "%s<%s>"%(type(self), self._id)
def update_anchor(self, anchor):
self.anchor = anchor
if anchor is not None:
try:
self.local_geometry = geoutil.global2local(self.geometry, anchor)
except:
print("Could not convert geometry: {}".format(self.local_geometry))
def distance_to(self, point):
if isinstance(point, geoutil.Point):
return self.local_geometry.distance_to(point)
if isinstance(point, geoutil.Latlng):
return self.geometry.distance_to(point)
def reset(self):
pass
class Link(Object):
ROUTE_TYPE_WALKWAY = 1
ROUTE_TYPE_MOVING_WALKWAY = 2
ROUTE_TYPE_RAILROAD_CROSSING = 3
ROUTE_TYPE_ELEVATOR = 4
ROUTE_TYPE_ESCALATOR = 5
ROUTE_TYPE_STAIRS = 6
ROUTE_TYPE_SLOPE = 7
ROUTE_TYPE_UNKNOWN = 99
@classmethod
def marshal(cls, dic):
if 'properties' in dic:
prop = dic['properties']
if 'sourceNode' in prop:
cls = RouteLink
if cls == Link:
return cls(**dic)
return cls.marshal(dic)
def __init__(self, **dic):
super(Link, self).__init__(**dic)
self.start_node = None
self.end_node = None
self.pois = []
self.floor = 0
Object.get_object_by_id(self.properties.start_id, self._set_start_node)
Object.get_object_by_id(self.properties.end_id, self._set_end_node)
def _set_start_node(self, node):
self.start_node = node
self._update()
def _set_end_node(self, node):
self.end_node = node
self._update()
def _update(self):
if self.start_node is not None and \
self.end_node is not None:
self.floor = (self.start_node.floor + self.end_node.floor)/2.0
@property
def is_elevator(self):
return self.properties.route_type == Link.ROUTE_TYPE_ELEVATOR
@property
def is_escalator(self):
return self.properties.route_type == Link.ROUTE_TYPE_ESCALATOR
@property
def is_leaf(self):
if self.start_node is None or self.end_node is None:
return False
return self.start_node.is_leaf or self.end_node.is_leaf
@property
def length(self):
if self.start_node is None or self.end_node is None:
return float('nan')
return self.start_node.geometry.distance_to(self.end_node.geometry)
def register_poi(self, poi):
self.pois.append(poi)
def update_anchor(self, anchor):
self.anchor = anchor
class RouteLink(Link):
@classmethod
def marshal(cls, dic):
return cls(**dic)
def __init__(self, **dic):
super(RouteLink, self).__init__(no_registration=True, **dic)
self.source_node = None
self.target_node = None
Object.get_object_by_id(self.properties.sourceNode, self._set_source_node)
Object.get_object_by_id(self.properties.targetNode, self._set_target_node)
Object.get_object_by_id(self._id, self._found_link)
def _set_source_node(self, node):
self.source_node = node
def _set_target_node(self, node):
self.target_node = node
def _found_link(self, link):
self.pois = link.pois
@property
def is_temp(self):
return self._id.startswith("_TEMP_LINK")
class Node(Object):
@classmethod
def marshal(cls, dic):
return cls(**dic)
def __init__(self, **dic):
super(Node, self).__init__(**dic)
self.links = []
for i in range(1, 100):
attr = "link%d_id"%(i)
if hasattr(self.properties, attr):
Object.get_object_by_id(getattr(self.properties, attr), self._add_link)
if hasattr(self.properties, 'floor'):
self.floor = self.properties.floor
else:
self.floor = 0
self.facility = None
Facility.get_facility_by_id(self._id, self._set_facility)
def _add_link(self, link):
self.links.append(link)
def _set_facility(self, facility):
self.facility = facility
@property
def is_leaf(self):
return len(self.links) == 1
@property
def is_elevator(self):
res = False
for link in self.links:
res = res or link.is_elevator
return res
class Facility(Object):
@classmethod
def marshal(cls, dic):
if 'properties' in dic:
prop = dic['properties']
if 'hulop_major_category' in prop:
category = prop['hulop_major_category']
if category == '_nav_poi_':
cls = POI
if cls == Facility:
return cls(**dic)
return cls.marshal(dic)
def __init__(self, **dic):
super(Facility, self).__init__(**dic)
self.entrances = []
for i in range(1, 100):
attr = "ent%d_node"%(i)
if hasattr(self.properties, attr):
Facility._id_map[getattr(self.properties, attr)] = self
Object.get_object_by_id(getattr(self.properties, attr), self._add_facility)
self.name = i18n.localized_attr(self.properties, "name")
self.name_pron = i18n.localized_attr(self.properties, "name_hira", only_if="ja") long_description = i18n.localized_attr(self.properties, "hulop_long_description")
def _add_facility(self, node):
self.entrances.append(node)
_id_map = {}
@staticmethod
def get_facility_by_id(_id, func=None):
if _id in Facility._id_map:
if isinstance(Facility._id_map[_id], list):
Facility._id_map[_id].append(func)
else:
if func is not None and callable(func):
func(Facility._id_map[_id])
return None
return Facility._id_map[_id]
else:
Facility._id_map[_id] = [func]
return None
class POI(Facility, geoutil.TargetPlace):
@classmethod
def marshal(cls, dic):
if 'properties' in dic:
prop = dic['properties']
if 'hulop_sub_category' in prop:
category = prop['hulop_sub_category']
if category == '_nav_door_':
cls = DoorPOI
if category == '_nav_info_':
cls = InfoPOI
if category == '_cabot_speed_':
cls = SpeedPOI
if category == '_nav_elevator_cab_':
cls = ElevatorCabPOI
if category == '_nav_queue_wait_':
cls = QueueWaitPOI
if category == '_nav_queue_target_':
cls = QueueTargetPOI
if cls == POI:
return cls(**dic)
return cls.marshal(dic)
def __init__(self, **dic):
if 'properties' in dic:
prop = dic['properties']
get_prop = lambda prop, key: prop[key] if key in prop else Properties.DEFAULT_VALUES[key]
r = (-get_prop(prop, 'hulop_heading') + 90) / 180.0 * math.pi
angle = get_prop(prop, 'hulop_angle')
self.floor = get_prop(prop, 'hulop_height')
super(POI, self).__init__(r=r, x=0, y=0, angle=angle, floor=self.floor, **dic)
self.sub_category = self.properties.hulop_sub_category \
if hasattr(self.properties, 'hulop_sub_category') else ""
self.minor_category = self.properties.hulop_minor_category \
if hasattr(self.properties, 'hulop_minor_category') else ""
self.local_pose = self
def approaching_statement(self):
return None
def approached_statement(self):
return None
def passed_statement(self):
return None
def update_anchor(self, anchor):
super(POI, self).update_anchor(anchor)
if anchor is not None:
rad = (-self.properties.hulop_heading + 90 + anchor.rotate) / 180.0 * math.pi
self.update_pose(self.local_geometry, rad)
def reset(self):
self.reset_target()
class DoorPOI(POI):
@classmethod
def marshal(cls, dic):
return cls(**dic)
def __init__(self, **dic):
super(DoorPOI, self).__init__(**dic)
@property
def title(self):
if self.is_auto:
return i18n.localized_string("AUTO_DOOR")
else:
return i18n.localized_string("DOOR")
@property
def is_auto(self):
return self.minor_category is not None and \
'_flag_auto_' in self.minor_category
def approaching_statement(self):
return i18n.localized_string("DOOR_POI_APPROACHING", self.title)
class InfoPOI(POI):
@classmethod
def marshal(cls, dic):
return cls(**dic)
def __init__(self, **dic):
super(InfoPOI, self).__init__(**dic)
def approached_statement(self):
return self.name
class SpeedPOI(POI):
@classmethod
def marshal(cls, dic):
return cls(**dic)
def __init__(self, **dic):
super(SpeedPOI, self).__init__(**dic)
self.limit = float(self.properties.hulop_content)
class ElevatorCabPOI(POI):
@classmethod
def marshal(cls, dic):
return cls(**dic)
def __init__(self, **dic):
super(ElevatorCabPOI, self).__init__(**dic)
self.set_back = (3.0, 0.0)
self.set_forward = (3.0, 0.0)
self.door = (1.0, 0.0)
if self.properties.hulop_content:
try:
hulop_content_json = json.loads(self.properties.hulop_content)
if "set_back" in hulop_content_json:
self.set_back = hulop_content_json["set_back"]
if "set_forward" in hulop_content_json:
self.set_forward = hulop_content_json["set_forward"]
if "door" in hulop_content_json:
self.door = hulop_content_json["door"]
if "buttons" in hulop_content_json:
self.buttons = hulop_content_json["buttons"]
except:
traceback.print_exc(file=sys.std_out)
@property
def door_geometry(self):
x = self.x + math.cos(self.r) * self.door[0] - math.sin(self.r) * self.door[1]
y = self.y + math.sin(self.r) * self.door[0] + math.cos(self.r) * self.door[1]
return geoutil.Point(x=x, y=y)
def where_is_buttons(self, pose):
x = self.x + math.cos(self.r) * self.buttons[0] - math.sin(self.r) * self.buttons[1]
y = self.y + math.sin(self.r) * self.buttons[0] + math.cos(self.r) * self.buttons[1]
b_pos = geoutil.Point(x=x,y=y)
b_pose = geoutil.Pose.pose_from_points(b_pos, pose)
dir = angles.shortest_angular_distance(pose.r, b_pose.r)
print(pose, b_pos, b_pose, dir)
if abs(dir) > math.pi / 3 * 2:
return "BACK"
elif abs(dir) > math.pi / 3:
if dir > 0:
return "LEFT"
elif dir < 0:
return "RIGHT"
elif abs(dir) < math.pi / 10:
return "FRONT"
elif dir > 0:
return "FRONT_LEFT"
elif dir < 0:
return "FRONT_RIGHT"
rospy.logerror("should not happen")
return None
class QueueWaitPOI(POI):
@classmethod
def marshal(cls, dic):
return cls(**dic)
def __init__(self, **dic):
super(QueueWaitPOI, self).__init__(**dic)
self.interval = 1.0
hulop_content_json = json.loads(self.properties.hulop_content)
if "interval" in hulop_content_json:
self.interval = float(hulop_content_json["interval"])
self.is_copied = False
self.link_orientation = None
def register_link(self, link):
end_pose = geoutil.Pose.pose_from_points(link.end_node.local_geometry, link.start_node.local_geometry)
quat = tf.transformations.quaternion_from_euler(0, 0, end_pose.r)
self.link_orientation = geometry_msgs.msg.Quaternion()
self.link_orientation.x = quat[0]
self.link_orientation.y = quat[1]
self.link_orientation.z = quat[2]
self.link_orientation.w = quat[3]
def copy_to_link(self, link, local_geometry_x, local_geometry_y):
copied_poi = copy.deepcopy(self)
copied_poi.x = local_geometry_x
copied_poi.y = local_geometry_y
copied_poi.local_geometry.x = local_geometry_x
copied_poi.local_geometry.y = local_geometry_y
copied_poi.geometry = geoutil.local2global(copied_poi.local_geometry, copied_poi.anchor)
link.register_poi(copied_poi)
copied_poi.register_link(link)
self.is_copied = True
return copied_poi
class QueueTargetPOI(POI):
@classmethod
def marshal(cls, dic):
return cls(**dic)
def __init__(self, **dic):
super(QueueTargetPOI, self).__init__(**dic)
self.enter_node = None
self.exit_node = None
hulop_content_json = json.loads(self.properties.hulop_content)
Object.get_object_by_id(hulop_content_json["enter"], self._set_enter_node)
Object.get_object_by_id(hulop_content_json["exit"], self._set_exit_node)
def _set_enter_node(self, node):
self.enter_node = node
def _set_exit_node(self, node):
self.exit_node = node
class Landmark(Facility):
@classmethod
def marshal(cls, dic):
return cls(**dic)
def __init__(self, **dic):
self._id = dic['node']+"_landmark"
super(Landmark, self).__init__(**dic)
| true | true |
f719cfe9dbb5d0f42f324f0f2d5937b2e5f17212 | 1,481 | py | Python | Code Bundle/Chapter02/tests/test_checks.py | ghanigreen/pytest_code | dbdcc322b3469c62ad328043060518edf2b2d83f | [
"MIT"
] | 46 | 2018-06-28T04:40:08.000Z | 2022-02-14T05:36:48.000Z | Code Bundle/Chapter02/tests/test_checks.py | ghanigreen/pytest_code | dbdcc322b3469c62ad328043060518edf2b2d83f | [
"MIT"
] | null | null | null | Code Bundle/Chapter02/tests/test_checks.py | ghanigreen/pytest_code | dbdcc322b3469c62ad328043060518edf2b2d83f | [
"MIT"
] | 22 | 2018-06-10T23:20:29.000Z | 2022-02-24T06:47:18.000Z | import pytest
class InvalidCharacterNameError(Exception):
pass
class InvalidClassNameError(Exception):
pass
class Character:
pass
VALID_CLASSES = ["sorcerer", "warrior"]
def create_character(name: str, class_name: str) -> Character:
"""
Creates a new character and inserts it into the database.
:param name: the character name.
:param class_name: the character class name.
:raise InvalidCharacterNameError:
if the character name is empty.
:raise InvalidClassNameError:
if the class name is invalid.
:return: the newly created Character.
"""
if not name:
raise InvalidCharacterNameError("character name empty")
if class_name not in VALID_CLASSES:
msg = f'invalid class name: "{class_name}"'
raise InvalidCharacterNameError(msg)
...
def test_empty_name():
with pytest.raises(InvalidCharacterNameError):
create_character(name="", class_name="warrior")
def test_invalid_class_name():
with pytest.raises(InvalidClassNameError):
create_character(name="Solaire", class_name="mage")
def test_empty_name():
with pytest.raises(
InvalidCharacterNameError, match="character name empty"
):
create_character(name="", class_name="warrior")
def test_invalid_class_name():
with pytest.raises(
InvalidClassNameError, match='invalid class name: "mage"'
):
create_character(name="Solaire", class_name="mage")
| 22.439394 | 65 | 0.694126 | import pytest
class InvalidCharacterNameError(Exception):
pass
class InvalidClassNameError(Exception):
pass
class Character:
pass
VALID_CLASSES = ["sorcerer", "warrior"]
def create_character(name: str, class_name: str) -> Character:
if not name:
raise InvalidCharacterNameError("character name empty")
if class_name not in VALID_CLASSES:
msg = f'invalid class name: "{class_name}"'
raise InvalidCharacterNameError(msg)
...
def test_empty_name():
with pytest.raises(InvalidCharacterNameError):
create_character(name="", class_name="warrior")
def test_invalid_class_name():
with pytest.raises(InvalidClassNameError):
create_character(name="Solaire", class_name="mage")
def test_empty_name():
with pytest.raises(
InvalidCharacterNameError, match="character name empty"
):
create_character(name="", class_name="warrior")
def test_invalid_class_name():
with pytest.raises(
InvalidClassNameError, match='invalid class name: "mage"'
):
create_character(name="Solaire", class_name="mage")
| true | true |
f719d091d9d47a5add06aa4cc9f22b144941b945 | 1,379 | py | Python | plantara/urls.py | plantara/plantara-backend | 3e3cf1f7aa83a124b7e1b616e44aa1f31333598e | [
"MIT"
] | null | null | null | plantara/urls.py | plantara/plantara-backend | 3e3cf1f7aa83a124b7e1b616e44aa1f31333598e | [
"MIT"
] | null | null | null | plantara/urls.py | plantara/plantara-backend | 3e3cf1f7aa83a124b7e1b616e44aa1f31333598e | [
"MIT"
] | null | null | null | """plantara URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.contrib import admin
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from plantara.contrib.users.views import UserViewSet, ObtainAuthToken
from plantara.contrib.plants.views import PlantViewSet
router = DefaultRouter()
router.register(r"users", UserViewSet, basename="user")
router.register(r"plants", PlantViewSet, basename="plant")
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", include(router.urls)),
path("api/auth/", include("rest_framework.urls")),
path("api/token/", ObtainAuthToken.as_view()),
]
if settings.DEBUG:
import debug_toolbar # NOQA
urlpatterns += [path("__debug__/", include(debug_toolbar.urls))]
| 33.634146 | 77 | 0.730964 | from django.conf import settings
from django.contrib import admin
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from plantara.contrib.users.views import UserViewSet, ObtainAuthToken
from plantara.contrib.plants.views import PlantViewSet
router = DefaultRouter()
router.register(r"users", UserViewSet, basename="user")
router.register(r"plants", PlantViewSet, basename="plant")
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", include(router.urls)),
path("api/auth/", include("rest_framework.urls")),
path("api/token/", ObtainAuthToken.as_view()),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += [path("__debug__/", include(debug_toolbar.urls))]
| true | true |
f719d0cdcf3b09c0fae3b540dda5bf816f23f254 | 5,061 | py | Python | ipypublish/postprocessors/base.py | phelps-sg/ipypublish | c99ba56fbaeef033e3baeb3246143660ac7eb78e | [
"BSD-3-Clause"
] | null | null | null | ipypublish/postprocessors/base.py | phelps-sg/ipypublish | c99ba56fbaeef033e3baeb3246143660ac7eb78e | [
"BSD-3-Clause"
] | null | null | null | ipypublish/postprocessors/base.py | phelps-sg/ipypublish | c99ba56fbaeef033e3baeb3246143660ac7eb78e | [
"BSD-3-Clause"
] | 1 | 2021-02-09T01:12:10.000Z | 2021-02-09T01:12:10.000Z | import logging
from six import string_types
from traitlets import Bool
from traitlets.config.configurable import Configurable
from ipypublish.utils import handle_error, pathlib
try:
from shutil import which as exe_exists
except ImportError:
from distutils.spawn import find_executable as exe_exists # noqa: F401
class IPyPostProcessor(Configurable):
""" an abstract class for post-processors
"""
@property
def allowed_mimetypes(self):
""" override in subclasses
return a list of allowed mime types
if None, then all are allowed
Text based mime-types include: text/plain, text/latex,
text/restructuredtext, text/html, text/x-python, application/json,
text/markdown, text/asciidoc, text/yaml
"""
raise NotImplementedError("allowed_mimetypes")
@property
def requires_path(self):
""" override in subclasses
whether the prostprocessor requires the supplied filepath
to have an existing parent directory
if True and filepath is None, will raise an IOError, otherwise,
will try to make the directory if it doesn't exist
"""
raise NotImplementedError("requires_path")
@property
def logger_name(self):
""" override in subclass
"""
return "post-processor"
@property
def logger(self):
return logging.getLogger(self.logger_name)
skip_mime = Bool(
True,
help="if False, raise a TypeError if the mimetype is not allowed, "
"else return without processing",
).tag(config=True)
def __init__(self, config=None):
super(IPyPostProcessor, self).__init__(config=config)
def __call__(self, stream, mimetype, filepath, resources=None):
"""
See def postprocess() ...
"""
self.postprocess(stream, mimetype, filepath, resources)
def postprocess(self, stream, mimetype, filepath, resources=None):
""" Post-process output.
Parameters
----------
stream: str
the main file contents
mimetype: str
the mimetype of the file
filepath: None or str or pathlib.Path
the path to the output file
the path does not have to exist, but must be absolute
resources: None or dict
a resources dict, output from exporter.from_notebook_node
Returns
-------
stream: str
filepath: None or str or pathlib.Path
"""
if (
self.allowed_mimetypes is not None
and mimetype not in self.allowed_mimetypes
):
if not self.skip_mime:
self.handle_error(
"the mimetype {0} is not in the allowed list: {1}".format(
mimetype, self.allowed_mimetypes
),
TypeError,
)
else:
self.logger.debug("skipping incorrect mime type: {}".format(mimetype))
return stream, filepath, resources
if self.requires_path and filepath is None:
self.handle_error(
"the filepath is None, " "but the post-processor requires a folder",
IOError,
)
if filepath is not None and isinstance(filepath, string_types):
filepath = pathlib.Path(filepath)
if self.requires_path:
if filepath.parent.exists() and not filepath.parent.is_dir():
self.handle_error(
"the filepath's parent is not a folder: {}".format(filepath),
TypeError,
)
if not filepath.parent.exists():
filepath.parent.mkdir(parents=True)
if resources is None:
resources = {}
return self.run_postprocess(stream, mimetype, filepath, resources)
def run_postprocess(self, stream, mimetype, filepath, resources):
""" should not be called directly
override in sub-class
Parameters
----------
stream: str
the main file contents
filepath: None or pathlib.Path
the path to the output file
resources: dict
a resources dict, output from exporter.from_notebook_node
Returns
-------
stream: str
filepath: None or pathlib.Path
resources: dict
"""
raise NotImplementedError("run_postprocess")
def handle_error(self, msg, err_type, raise_msg=None, log_msg=None):
""" handle error by logging it then raising
"""
handle_error(msg, err_type, self.logger, raise_msg=raise_msg, log_msg=log_msg)
def check_exe_exists(self, name, error_msg):
""" test if an executable exists
"""
if not exe_exists(name):
self.handle_error(error_msg, RuntimeError)
return True
if __name__ == "__main__":
print(IPyPostProcessor.allowed_mimetypes)
IPyPostProcessor()("stream", "a")
| 29.424419 | 86 | 0.601857 | import logging
from six import string_types
from traitlets import Bool
from traitlets.config.configurable import Configurable
from ipypublish.utils import handle_error, pathlib
try:
from shutil import which as exe_exists
except ImportError:
from distutils.spawn import find_executable as exe_exists
class IPyPostProcessor(Configurable):
@property
def allowed_mimetypes(self):
raise NotImplementedError("allowed_mimetypes")
@property
def requires_path(self):
raise NotImplementedError("requires_path")
@property
def logger_name(self):
return "post-processor"
@property
def logger(self):
return logging.getLogger(self.logger_name)
skip_mime = Bool(
True,
help="if False, raise a TypeError if the mimetype is not allowed, "
"else return without processing",
).tag(config=True)
def __init__(self, config=None):
super(IPyPostProcessor, self).__init__(config=config)
def __call__(self, stream, mimetype, filepath, resources=None):
self.postprocess(stream, mimetype, filepath, resources)
def postprocess(self, stream, mimetype, filepath, resources=None):
if (
self.allowed_mimetypes is not None
and mimetype not in self.allowed_mimetypes
):
if not self.skip_mime:
self.handle_error(
"the mimetype {0} is not in the allowed list: {1}".format(
mimetype, self.allowed_mimetypes
),
TypeError,
)
else:
self.logger.debug("skipping incorrect mime type: {}".format(mimetype))
return stream, filepath, resources
if self.requires_path and filepath is None:
self.handle_error(
"the filepath is None, " "but the post-processor requires a folder",
IOError,
)
if filepath is not None and isinstance(filepath, string_types):
filepath = pathlib.Path(filepath)
if self.requires_path:
if filepath.parent.exists() and not filepath.parent.is_dir():
self.handle_error(
"the filepath's parent is not a folder: {}".format(filepath),
TypeError,
)
if not filepath.parent.exists():
filepath.parent.mkdir(parents=True)
if resources is None:
resources = {}
return self.run_postprocess(stream, mimetype, filepath, resources)
def run_postprocess(self, stream, mimetype, filepath, resources):
raise NotImplementedError("run_postprocess")
def handle_error(self, msg, err_type, raise_msg=None, log_msg=None):
handle_error(msg, err_type, self.logger, raise_msg=raise_msg, log_msg=log_msg)
def check_exe_exists(self, name, error_msg):
if not exe_exists(name):
self.handle_error(error_msg, RuntimeError)
return True
if __name__ == "__main__":
print(IPyPostProcessor.allowed_mimetypes)
IPyPostProcessor()("stream", "a")
| true | true |
f719d11806bbcb48ec4f51cc84eb95cd4e1c6804 | 2,201 | py | Python | glance/common/crypt.py | komawar/glance | e550cac697dd8c78e837c6884f599ac6ee2137ae | [
"Apache-2.0"
] | 1 | 2018-07-27T15:16:14.000Z | 2018-07-27T15:16:14.000Z | glance/common/crypt.py | komawar/glance | e550cac697dd8c78e837c6884f599ac6ee2137ae | [
"Apache-2.0"
] | null | null | null | glance/common/crypt.py | komawar/glance | e550cac697dd8c78e837c6884f599ac6ee2137ae | [
"Apache-2.0"
] | 1 | 2021-07-18T18:57:04.000Z | 2021-07-18T18:57:04.000Z | #!/usr/bin/env python
# Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Routines for URL-safe encrypting/decrypting
"""
import base64
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Random import random
def urlsafe_encrypt(key, plaintext, blocksize=16):
"""
Encrypts plaintext. Resulting ciphertext will contain URL-safe characters
:param key: AES secret key
:param plaintext: Input text to be encrypted
:param blocksize: Non-zero integer multiple of AES blocksize in bytes (16)
:returns : Resulting ciphertext
"""
def pad(text):
"""
Pads text to be encrypted
"""
pad_length = (blocksize - len(text) % blocksize)
sr = random.StrongRandom()
pad = ''.join(chr(sr.randint(1, 0xFF)) for i in range(pad_length - 1))
# We use chr(0) as a delimiter between text and padding
return text + chr(0) + pad
# random initial 16 bytes for CBC
init_vector = Random.get_random_bytes(16)
cypher = AES.new(key, AES.MODE_CBC, init_vector)
padded = cypher.encrypt(pad(str(plaintext)))
return base64.urlsafe_b64encode(init_vector + padded)
def urlsafe_decrypt(key, ciphertext):
"""
Decrypts URL-safe base64 encoded ciphertext
:param key: AES secret key
:param ciphertext: The encrypted text to decrypt
:returns : Resulting plaintext
"""
# Cast from unicode
ciphertext = base64.urlsafe_b64decode(str(ciphertext))
cypher = AES.new(key, AES.MODE_CBC, ciphertext[:16])
padded = cypher.decrypt(ciphertext[16:])
return padded[:padded.rfind(chr(0))]
| 32.367647 | 78 | 0.695593 |
import base64
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Random import random
def urlsafe_encrypt(key, plaintext, blocksize=16):
def pad(text):
pad_length = (blocksize - len(text) % blocksize)
sr = random.StrongRandom()
pad = ''.join(chr(sr.randint(1, 0xFF)) for i in range(pad_length - 1))
return text + chr(0) + pad
init_vector = Random.get_random_bytes(16)
cypher = AES.new(key, AES.MODE_CBC, init_vector)
padded = cypher.encrypt(pad(str(plaintext)))
return base64.urlsafe_b64encode(init_vector + padded)
def urlsafe_decrypt(key, ciphertext):
ciphertext = base64.urlsafe_b64decode(str(ciphertext))
cypher = AES.new(key, AES.MODE_CBC, ciphertext[:16])
padded = cypher.decrypt(ciphertext[16:])
return padded[:padded.rfind(chr(0))]
| true | true |
f719d17e244fc2d7cacd2371cabf35fc5edcbac2 | 2,609 | py | Python | img-placeholder.py | fisker/img-placeholder | d4b42551b41a546553a47358b9bb616c6492b2da | [
"MIT"
] | 3 | 2017-01-17T05:40:10.000Z | 2022-01-17T02:42:35.000Z | img-placeholder.py | fisker/img-placeholder | d4b42551b41a546553a47358b9bb616c6492b2da | [
"MIT"
] | 1 | 2017-01-15T15:34:58.000Z | 2017-01-16T05:28:34.000Z | img-placeholder.py | fisker/img-placeholder | d4b42551b41a546553a47358b9bb616c6492b2da | [
"MIT"
] | 1 | 2017-01-14T12:00:55.000Z | 2017-01-14T12:00:55.000Z | import sublime
import sublime_plugin
import re
completions = []
def plugin_loaded():
init_settings()
def init_settings():
get_settings()
sublime.load_settings('img-placeholder.sublime-settings').add_on_change('get_settings', get_settings)
def get_settings():
settings = sublime.load_settings('img-placeholder.sublime-settings')
domains = settings.get('domains', [])
protocol = settings.get('protocol', 'http:')
width = str(settings.get('width', 600))
height = str(settings.get('height', 300))
background_color = settings.get('backgroundColor', 'ccc')
text_color = settings.get('textColor', '333')
file_ext = settings.get('format', 'png')
text = settings.get('text', '')
del completions[:]
for domain in domains:
url = protocol + '//' + domain + '/'
completions.append(
(
domain,
url + '${1:' + width + 'x' + height + '}'
)
)
completions.append(
(
domain + ' (full version)',
url + '${1:' + width + 'x' + height + '/' + background_color + '/' + text_color + '.' + file_ext + '?text=' + text + '}'
)
)
def pos(view, pos):
point = view.sel()[0].begin()
return view.substr(sublime.Region(point - pos, point))
def before(view, location):
lineLocation = view.line(location)
return view.substr(sublime.Region(lineLocation.a, location))
def get_before_text(view):
point = view.sel()[0].begin()
lineLocation = view.line(point)
return view.substr(sublime.Region(lineLocation.a, point))
def is_trigger(text, syntax):
text = text.lower()
syntax = syntax.lower()
if syntax.find(u'html'):
search = re.search(r"(?:(?:^|\s))(?:src|poster|srcset)=[\"\']?$", text)
if (search):
return True
for s in (u'html', u'css', u'less', u'sass', u'scss', u'stylus'):
if syntax.find(s):
search = re.search(r"(?:(?:^|\s))url\([\"\']?$", text)
if (search):
return True
for s in (u'markdown', u'multimarkdown'):
if syntax.find(s):
search = re.search(r"(?:(?:^|\s))\!\[.*?\]\(?$", text)
if (search):
return True
return False
class imgHolder(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
syntax = view.settings().get('syntax')
before_text = before(view, locations[0]);
if is_trigger(before_text, syntax):
return (completions, sublime.INHIBIT_EXPLICIT_COMPLETIONS)
return
| 30.694118 | 132 | 0.576849 | import sublime
import sublime_plugin
import re
completions = []
def plugin_loaded():
init_settings()
def init_settings():
get_settings()
sublime.load_settings('img-placeholder.sublime-settings').add_on_change('get_settings', get_settings)
def get_settings():
settings = sublime.load_settings('img-placeholder.sublime-settings')
domains = settings.get('domains', [])
protocol = settings.get('protocol', 'http:')
width = str(settings.get('width', 600))
height = str(settings.get('height', 300))
background_color = settings.get('backgroundColor', 'ccc')
text_color = settings.get('textColor', '333')
file_ext = settings.get('format', 'png')
text = settings.get('text', '')
del completions[:]
for domain in domains:
url = protocol + '//' + domain + '/'
completions.append(
(
domain,
url + '${1:' + width + 'x' + height + '}'
)
)
completions.append(
(
domain + ' (full version)',
url + '${1:' + width + 'x' + height + '/' + background_color + '/' + text_color + '.' + file_ext + '?text=' + text + '}'
)
)
def pos(view, pos):
point = view.sel()[0].begin()
return view.substr(sublime.Region(point - pos, point))
def before(view, location):
lineLocation = view.line(location)
return view.substr(sublime.Region(lineLocation.a, location))
def get_before_text(view):
point = view.sel()[0].begin()
lineLocation = view.line(point)
return view.substr(sublime.Region(lineLocation.a, point))
def is_trigger(text, syntax):
text = text.lower()
syntax = syntax.lower()
if syntax.find(u'html'):
search = re.search(r"(?:(?:^|\s))(?:src|poster|srcset)=[\"\']?$", text)
if (search):
return True
for s in (u'html', u'css', u'less', u'sass', u'scss', u'stylus'):
if syntax.find(s):
search = re.search(r"(?:(?:^|\s))url\([\"\']?$", text)
if (search):
return True
for s in (u'markdown', u'multimarkdown'):
if syntax.find(s):
search = re.search(r"(?:(?:^|\s))\!\[.*?\]\(?$", text)
if (search):
return True
return False
class imgHolder(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
syntax = view.settings().get('syntax')
before_text = before(view, locations[0]);
if is_trigger(before_text, syntax):
return (completions, sublime.INHIBIT_EXPLICIT_COMPLETIONS)
return
| true | true |
f719d3c75df148a6ceda79acf57bc0e57342d5f3 | 4,311 | py | Python | src/test.py | alexey-kaz/python-project | 661fe06e09846cd1c3c6d600973a6e3433096c1d | [
"MIT"
] | null | null | null | src/test.py | alexey-kaz/python-project | 661fe06e09846cd1c3c6d600973a6e3433096c1d | [
"MIT"
] | null | null | null | src/test.py | alexey-kaz/python-project | 661fe06e09846cd1c3c6d600973a6e3433096c1d | [
"MIT"
] | 3 | 2021-04-25T06:37:26.000Z | 2021-06-03T19:19:19.000Z | """Тест."""
import unittest
from recipes import form_answer
from database import delete_table_data
from parsing import NEWS, AFISHA, HOROSCOPE, WEATHER
class TestBot(unittest.TestCase):
"""Тест."""
def test_form_answer(self):
"""Тест."""
rec1 = {"name": "Булочки с изюмом",
"ingrs": ["Мука", "Яйцо куриное", "Изюм"],
"link": "http://recipe"}
ans1 = '<b>Булочки с изюмом</b>\nИнгредиенты:\n 1) Мука\n' + \
'2) Яйцо куриное\n3) Изюм\n\n<a href="http://recipe">Булочки с изюмом</a>'
self.assertEqual(form_answer(rec1), ans1)
rec2 = {"name": "Омлет",
"ingrs": ["Яйцо куриное", "Соль", "Молоко"],
"link": "http://recipe"}
ans2 = '<b>Омлет</b>\nИнгредиенты:\n 1) Яйцо куриное\n2) Соль\n' + \
'3) Молоко\n\n<a href="http://recipe">Омлет</a>'
self.assertEqual(form_answer(rec2), ans2)
with self.assertRaises(KeyError):
form_answer(dict())
# def test_empty_delete_reminders(self):
# self.assertEqual(delete_table_data("reminders"), 0)
def test_parsing_horoscope(self):
"""Тест."""
obj = HOROSCOPE()
self.assertEqual(obj.url, "https://1001goroskop.ru")
def test_parsing_horoscope_1(self):
"""Тест."""
obj = HOROSCOPE()
self.assertEqual(type(obj.get_signs()), type([1, 2]))
def test_parsing_news(self):
"""Тест."""
obj = NEWS()
self.assertEqual(obj.count, None)
def test_parsing_news_1(self):
"""Тест."""
obj = NEWS()
obj.count = 5
obj.make_zero()
self.assertEqual(obj.count, 0)
def test_parsing_news_2(self):
"""Тест."""
obj = NEWS()
self.assertEqual(obj.url, "https://lenta.ru/parts/news")
def test_parsing_news_3(self):
"""Тест."""
obj = NEWS()
self.assertEqual(obj.url_part, "https://lenta.ru")
def test_parsing_news_4(self):
"""Тест."""
obj = NEWS()
self.assertEqual(type(obj.parse()), type([1, 2]))
def test_parsing_weather(self):
"""Тест."""
obj = WEATHER()
self.assertEqual(type(obj.extra_data), type({}))
def test_parsing_weather_1(self):
"""Тест."""
obj = WEATHER()
self.assertEqual(obj.url, "https://www.gismeteo.ru")
def test_parsing_weather_2(self):
"""Тест."""
obj = WEATHER()
self.assertEqual(type(obj.main_data), type({}))
def test_parsing_afisha(self):
"""Тест."""
obj = AFISHA()
self.assertEqual(obj.cinema_count, None)
def test_parsing_afisha_1(self):
"""Тест."""
obj = AFISHA()
obj.cinema_count = 1
obj.make_zero()
self.assertEqual(obj.cinema_count, 0)
def test_parsing_afisha_2(self):
"""Тест."""
obj = AFISHA()
obj.theatre_count = 2
obj.make_zero()
self.assertEqual(obj.theatre_count, 0)
def test_parsing_afisha_3(self):
"""Тест."""
obj = AFISHA()
obj.concert_count = 3
obj.make_zero()
self.assertEqual(obj.concert_count, 0)
def test_parsing_afisha_4(self):
"""Тест."""
obj = AFISHA()
obj.cinema_count = 1
obj.theatre_count = 2
obj.make_zero()
self.assertEqual(obj.cinema_count, 0)
self.assertEqual(obj.theatre_count, 0)
def test_parsing_afisha_5(self):
"""Тест."""
obj = AFISHA()
obj.cinema_count = 1
obj.concert_count = 3
obj.make_zero()
self.assertEqual(obj.cinema_count, 0)
self.assertEqual(obj.concert_count, 0)
def test_parsing_afisha_6(self):
"""Тест."""
obj = AFISHA()
obj.theatre_count = 2
obj.concert_count = 3
obj.make_zero()
self.assertEqual(obj.theatre_count, 0)
self.assertEqual(obj.concert_count, 0)
def test_parsing_afisha_total(self):
"""Тест."""
obj = AFISHA()
obj.cinema_count = 1
obj.theatre_count = 2
obj.concert_count = 3
obj.make_zero()
self.assertEqual(obj.cinema_count, 0)
self.assertEqual(obj.theatre_count, 0)
self.assertEqual(obj.concert_count, 0)
| 29.527397 | 89 | 0.567618 | import unittest
from recipes import form_answer
from database import delete_table_data
from parsing import NEWS, AFISHA, HOROSCOPE, WEATHER
class TestBot(unittest.TestCase):
def test_form_answer(self):
rec1 = {"name": "Булочки с изюмом",
"ingrs": ["Мука", "Яйцо куриное", "Изюм"],
"link": "http://recipe"}
ans1 = '<b>Булочки с изюмом</b>\nИнгредиенты:\n 1) Мука\n' + \
'2) Яйцо куриное\n3) Изюм\n\n<a href="http://recipe">Булочки с изюмом</a>'
self.assertEqual(form_answer(rec1), ans1)
rec2 = {"name": "Омлет",
"ingrs": ["Яйцо куриное", "Соль", "Молоко"],
"link": "http://recipe"}
ans2 = '<b>Омлет</b>\nИнгредиенты:\n 1) Яйцо куриное\n2) Соль\n' + \
'3) Молоко\n\n<a href="http://recipe">Омлет</a>'
self.assertEqual(form_answer(rec2), ans2)
with self.assertRaises(KeyError):
form_answer(dict())
def test_parsing_horoscope(self):
obj = HOROSCOPE()
self.assertEqual(obj.url, "https://1001goroskop.ru")
def test_parsing_horoscope_1(self):
obj = HOROSCOPE()
self.assertEqual(type(obj.get_signs()), type([1, 2]))
def test_parsing_news(self):
obj = NEWS()
self.assertEqual(obj.count, None)
def test_parsing_news_1(self):
obj = NEWS()
obj.count = 5
obj.make_zero()
self.assertEqual(obj.count, 0)
def test_parsing_news_2(self):
obj = NEWS()
self.assertEqual(obj.url, "https://lenta.ru/parts/news")
def test_parsing_news_3(self):
obj = NEWS()
self.assertEqual(obj.url_part, "https://lenta.ru")
def test_parsing_news_4(self):
obj = NEWS()
self.assertEqual(type(obj.parse()), type([1, 2]))
def test_parsing_weather(self):
obj = WEATHER()
self.assertEqual(type(obj.extra_data), type({}))
def test_parsing_weather_1(self):
obj = WEATHER()
self.assertEqual(obj.url, "https://www.gismeteo.ru")
def test_parsing_weather_2(self):
obj = WEATHER()
self.assertEqual(type(obj.main_data), type({}))
def test_parsing_afisha(self):
obj = AFISHA()
self.assertEqual(obj.cinema_count, None)
def test_parsing_afisha_1(self):
obj = AFISHA()
obj.cinema_count = 1
obj.make_zero()
self.assertEqual(obj.cinema_count, 0)
def test_parsing_afisha_2(self):
obj = AFISHA()
obj.theatre_count = 2
obj.make_zero()
self.assertEqual(obj.theatre_count, 0)
def test_parsing_afisha_3(self):
obj = AFISHA()
obj.concert_count = 3
obj.make_zero()
self.assertEqual(obj.concert_count, 0)
def test_parsing_afisha_4(self):
obj = AFISHA()
obj.cinema_count = 1
obj.theatre_count = 2
obj.make_zero()
self.assertEqual(obj.cinema_count, 0)
self.assertEqual(obj.theatre_count, 0)
def test_parsing_afisha_5(self):
obj = AFISHA()
obj.cinema_count = 1
obj.concert_count = 3
obj.make_zero()
self.assertEqual(obj.cinema_count, 0)
self.assertEqual(obj.concert_count, 0)
def test_parsing_afisha_6(self):
obj = AFISHA()
obj.theatre_count = 2
obj.concert_count = 3
obj.make_zero()
self.assertEqual(obj.theatre_count, 0)
self.assertEqual(obj.concert_count, 0)
def test_parsing_afisha_total(self):
obj = AFISHA()
obj.cinema_count = 1
obj.theatre_count = 2
obj.concert_count = 3
obj.make_zero()
self.assertEqual(obj.cinema_count, 0)
self.assertEqual(obj.theatre_count, 0)
self.assertEqual(obj.concert_count, 0)
| true | true |
f719d4ecd4826b2aad60d635215f0987148b894f | 7,097 | py | Python | vendor/bundle/ruby/2.3.0/gems/nokogiri-1.10.10/ext/nokogiri/tmp/x86_64-apple-darwin17/ports/libxml2/2.9.10/libxml2-2.9.10/python/setup.py | emsommers/futureDocs | 344524234d024a532716a8ad4162aad00a455e8b | [
"CC0-1.0"
] | null | null | null | vendor/bundle/ruby/2.3.0/gems/nokogiri-1.10.10/ext/nokogiri/tmp/x86_64-apple-darwin17/ports/libxml2/2.9.10/libxml2-2.9.10/python/setup.py | emsommers/futureDocs | 344524234d024a532716a8ad4162aad00a455e8b | [
"CC0-1.0"
] | null | null | null | vendor/bundle/ruby/2.3.0/gems/nokogiri-1.10.10/ext/nokogiri/tmp/x86_64-apple-darwin17/ports/libxml2/2.9.10/libxml2-2.9.10/python/setup.py | emsommers/futureDocs | 344524234d024a532716a8ad4162aad00a455e8b | [
"CC0-1.0"
] | null | null | null | #!/usr/bin/python -u
#
# Setup script for libxml2 and libxslt if found
#
import sys, os
from distutils.core import setup, Extension
# Below ROOT, we expect to find include, include/libxml2, lib and bin.
# On *nix, it is not needed (but should not harm),
# on Windows, it is set by configure.js.
ROOT = r'/Users/emsommers/Documents/GitHub/futureDocs/vendor/bundle/ruby/2.3.0/gems/nokogiri-1.10.10/ports/x86_64-apple-darwin17/libxml2/2.9.10'
# Thread-enabled libxml2
with_threads = 1
# If this flag is set (windows only),
# a private copy of the dlls are included in the package.
# If this flag is not set, the libxml2 and libxslt
# dlls must be found somewhere in the PATH at runtime.
WITHDLLS = 1 and sys.platform.startswith('win')
def missing(file):
if os.access(file, os.R_OK) == 0:
return 1
return 0
try:
HOME = os.environ['HOME']
except:
HOME="C:"
if WITHDLLS:
# libxml dlls (expected in ROOT/bin)
dlls = [ 'iconv.dll','libxml2.dll','libxslt.dll','libexslt.dll' ]
dlls = [os.path.join(ROOT,'bin',dll) for dll in dlls]
# create __init__.py for the libxmlmods package
if not os.path.exists("libxmlmods"):
os.mkdir("libxmlmods")
open("libxmlmods/__init__.py","w").close()
def altImport(s):
s = s.replace("import libxml2mod","from libxmlmods import libxml2mod")
s = s.replace("import libxsltmod","from libxmlmods import libxsltmod")
return s
if sys.platform.startswith('win'):
libraryPrefix = 'lib'
platformLibs = []
else:
libraryPrefix = ''
platformLibs = ["m","z"]
# those are examined to find
# - libxml2/libxml/tree.h
# - iconv.h
# - libxslt/xsltconfig.h
includes_dir = [
"/usr/include",
"/usr/local/include",
"/opt/include",
os.path.join(ROOT,'include'),
HOME
];
xml_includes=""
for dir in includes_dir:
if not missing(dir + "/libxml2/libxml/tree.h"):
xml_includes=dir + "/libxml2"
break;
if xml_includes == "":
print("failed to find headers for libxml2: update includes_dir")
sys.exit(1)
iconv_includes=""
for dir in includes_dir:
if not missing(dir + "/iconv.h"):
iconv_includes=dir
break;
if iconv_includes == "":
print("failed to find headers for libiconv: update includes_dir")
sys.exit(1)
# those are added in the linker search path for libraries
libdirs = [
os.path.join(ROOT,'lib'),
]
xml_files = ["libxml2-api.xml", "libxml2-python-api.xml",
"libxml.c", "libxml.py", "libxml_wrap.h", "types.c",
"xmlgenerator.py", "README", "TODO", "drv_libxml2.py"]
xslt_files = ["libxslt-api.xml", "libxslt-python-api.xml",
"libxslt.c", "libxsl.py", "libxslt_wrap.h",
"xsltgenerator.py"]
if missing("libxml2-py.c") or missing("libxml2.py"):
try:
try:
import xmlgenerator
except:
import generator
except:
print("failed to find and generate stubs for libxml2, aborting ...")
print(sys.exc_info()[0], sys.exc_info()[1])
sys.exit(1)
head = open("libxml.py", "r")
generated = open("libxml2class.py", "r")
result = open("libxml2.py", "w")
for line in head.readlines():
if WITHDLLS:
result.write(altImport(line))
else:
result.write(line)
for line in generated.readlines():
result.write(line)
head.close()
generated.close()
result.close()
with_xslt=0
if missing("libxslt-py.c") or missing("libxslt.py"):
if missing("xsltgenerator.py") or missing("libxslt-api.xml"):
print("libxslt stub generator not found, libxslt not built")
else:
try:
import xsltgenerator
except:
print("failed to generate stubs for libxslt, aborting ...")
print(sys.exc_info()[0], sys.exc_info()[1])
else:
head = open("libxsl.py", "r")
generated = open("libxsltclass.py", "r")
result = open("libxslt.py", "w")
for line in head.readlines():
if WITHDLLS:
result.write(altImport(line))
else:
result.write(line)
for line in generated.readlines():
result.write(line)
head.close()
generated.close()
result.close()
with_xslt=1
else:
with_xslt=1
if with_xslt == 1:
xslt_includes=""
for dir in includes_dir:
if not missing(dir + "/libxslt/xsltconfig.h"):
xslt_includes=dir + "/libxslt"
break;
if xslt_includes == "":
print("failed to find headers for libxslt: update includes_dir")
with_xslt = 0
descr = "libxml2 package"
modules = [ 'libxml2', 'drv_libxml2' ]
if WITHDLLS:
modules.append('libxmlmods.__init__')
c_files = ['libxml2-py.c', 'libxml.c', 'types.c' ]
includes= [xml_includes, iconv_includes]
libs = [libraryPrefix + "xml2"] + platformLibs
macros = []
if with_threads:
macros.append(('_REENTRANT','1'))
if with_xslt == 1:
descr = "libxml2 and libxslt package"
if not sys.platform.startswith('win'):
#
# We are gonna build 2 identical shared libs with merge initializing
# both libxml2mod and libxsltmod
#
c_files = c_files + ['libxslt-py.c', 'libxslt.c']
xslt_c_files = c_files
macros.append(('MERGED_MODULES', '1'))
else:
#
# On windows the MERGED_MODULE option is not needed
# (and does not work)
#
xslt_c_files = ['libxslt-py.c', 'libxslt.c', 'types.c']
libs.insert(0, libraryPrefix + 'exslt')
libs.insert(0, libraryPrefix + 'xslt')
includes.append(xslt_includes)
modules.append('libxslt')
extens=[Extension('libxml2mod', c_files, include_dirs=includes,
library_dirs=libdirs,
libraries=libs, define_macros=macros)]
if with_xslt == 1:
extens.append(Extension('libxsltmod', xslt_c_files, include_dirs=includes,
library_dirs=libdirs,
libraries=libs, define_macros=macros))
if missing("MANIFEST"):
manifest = open("MANIFEST", "w")
manifest.write("setup.py\n")
for file in xml_files:
manifest.write(file + "\n")
if with_xslt == 1:
for file in xslt_files:
manifest.write(file + "\n")
manifest.close()
if WITHDLLS:
ext_package = "libxmlmods"
if sys.version >= "2.2":
base = "lib/site-packages/"
else:
base = ""
data_files = [(base+"libxmlmods",dlls)]
else:
ext_package = None
data_files = []
setup (name = "libxml2-python",
# On *nix, the version number is created from setup.py.in
# On windows, it is set by configure.js
version = "2.9.10",
description = descr,
author = "Daniel Veillard",
author_email = "veillard@redhat.com",
url = "http://xmlsoft.org/python.html",
licence="MIT Licence",
py_modules=modules,
ext_modules=extens,
ext_package=ext_package,
data_files=data_files,
)
sys.exit(0)
| 29.205761 | 144 | 0.610117 |
import sys, os
from distutils.core import setup, Extension
ROOT = r'/Users/emsommers/Documents/GitHub/futureDocs/vendor/bundle/ruby/2.3.0/gems/nokogiri-1.10.10/ports/x86_64-apple-darwin17/libxml2/2.9.10'
with_threads = 1
WITHDLLS = 1 and sys.platform.startswith('win')
def missing(file):
if os.access(file, os.R_OK) == 0:
return 1
return 0
try:
HOME = os.environ['HOME']
except:
HOME="C:"
if WITHDLLS:
dlls = [ 'iconv.dll','libxml2.dll','libxslt.dll','libexslt.dll' ]
dlls = [os.path.join(ROOT,'bin',dll) for dll in dlls]
if not os.path.exists("libxmlmods"):
os.mkdir("libxmlmods")
open("libxmlmods/__init__.py","w").close()
def altImport(s):
s = s.replace("import libxml2mod","from libxmlmods import libxml2mod")
s = s.replace("import libxsltmod","from libxmlmods import libxsltmod")
return s
if sys.platform.startswith('win'):
libraryPrefix = 'lib'
platformLibs = []
else:
libraryPrefix = ''
platformLibs = ["m","z"]
includes_dir = [
"/usr/include",
"/usr/local/include",
"/opt/include",
os.path.join(ROOT,'include'),
HOME
];
xml_includes=""
for dir in includes_dir:
if not missing(dir + "/libxml2/libxml/tree.h"):
xml_includes=dir + "/libxml2"
break;
if xml_includes == "":
print("failed to find headers for libxml2: update includes_dir")
sys.exit(1)
iconv_includes=""
for dir in includes_dir:
if not missing(dir + "/iconv.h"):
iconv_includes=dir
break;
if iconv_includes == "":
print("failed to find headers for libiconv: update includes_dir")
sys.exit(1)
libdirs = [
os.path.join(ROOT,'lib'),
]
xml_files = ["libxml2-api.xml", "libxml2-python-api.xml",
"libxml.c", "libxml.py", "libxml_wrap.h", "types.c",
"xmlgenerator.py", "README", "TODO", "drv_libxml2.py"]
xslt_files = ["libxslt-api.xml", "libxslt-python-api.xml",
"libxslt.c", "libxsl.py", "libxslt_wrap.h",
"xsltgenerator.py"]
if missing("libxml2-py.c") or missing("libxml2.py"):
try:
try:
import xmlgenerator
except:
import generator
except:
print("failed to find and generate stubs for libxml2, aborting ...")
print(sys.exc_info()[0], sys.exc_info()[1])
sys.exit(1)
head = open("libxml.py", "r")
generated = open("libxml2class.py", "r")
result = open("libxml2.py", "w")
for line in head.readlines():
if WITHDLLS:
result.write(altImport(line))
else:
result.write(line)
for line in generated.readlines():
result.write(line)
head.close()
generated.close()
result.close()
with_xslt=0
if missing("libxslt-py.c") or missing("libxslt.py"):
if missing("xsltgenerator.py") or missing("libxslt-api.xml"):
print("libxslt stub generator not found, libxslt not built")
else:
try:
import xsltgenerator
except:
print("failed to generate stubs for libxslt, aborting ...")
print(sys.exc_info()[0], sys.exc_info()[1])
else:
head = open("libxsl.py", "r")
generated = open("libxsltclass.py", "r")
result = open("libxslt.py", "w")
for line in head.readlines():
if WITHDLLS:
result.write(altImport(line))
else:
result.write(line)
for line in generated.readlines():
result.write(line)
head.close()
generated.close()
result.close()
with_xslt=1
else:
with_xslt=1
if with_xslt == 1:
xslt_includes=""
for dir in includes_dir:
if not missing(dir + "/libxslt/xsltconfig.h"):
xslt_includes=dir + "/libxslt"
break;
if xslt_includes == "":
print("failed to find headers for libxslt: update includes_dir")
with_xslt = 0
descr = "libxml2 package"
modules = [ 'libxml2', 'drv_libxml2' ]
if WITHDLLS:
modules.append('libxmlmods.__init__')
c_files = ['libxml2-py.c', 'libxml.c', 'types.c' ]
includes= [xml_includes, iconv_includes]
libs = [libraryPrefix + "xml2"] + platformLibs
macros = []
if with_threads:
macros.append(('_REENTRANT','1'))
if with_xslt == 1:
descr = "libxml2 and libxslt package"
if not sys.platform.startswith('win'):
c_files = c_files + ['libxslt-py.c', 'libxslt.c']
xslt_c_files = c_files
macros.append(('MERGED_MODULES', '1'))
else:
xslt_c_files = ['libxslt-py.c', 'libxslt.c', 'types.c']
libs.insert(0, libraryPrefix + 'exslt')
libs.insert(0, libraryPrefix + 'xslt')
includes.append(xslt_includes)
modules.append('libxslt')
extens=[Extension('libxml2mod', c_files, include_dirs=includes,
library_dirs=libdirs,
libraries=libs, define_macros=macros)]
if with_xslt == 1:
extens.append(Extension('libxsltmod', xslt_c_files, include_dirs=includes,
library_dirs=libdirs,
libraries=libs, define_macros=macros))
if missing("MANIFEST"):
manifest = open("MANIFEST", "w")
manifest.write("setup.py\n")
for file in xml_files:
manifest.write(file + "\n")
if with_xslt == 1:
for file in xslt_files:
manifest.write(file + "\n")
manifest.close()
if WITHDLLS:
ext_package = "libxmlmods"
if sys.version >= "2.2":
base = "lib/site-packages/"
else:
base = ""
data_files = [(base+"libxmlmods",dlls)]
else:
ext_package = None
data_files = []
setup (name = "libxml2-python",
version = "2.9.10",
description = descr,
author = "Daniel Veillard",
author_email = "veillard@redhat.com",
url = "http://xmlsoft.org/python.html",
licence="MIT Licence",
py_modules=modules,
ext_modules=extens,
ext_package=ext_package,
data_files=data_files,
)
sys.exit(0)
| true | true |
f719d938c36fb80ad1c9ea86ac17254b9fc23390 | 50,482 | py | Python | pyGPs/Core/gp.py | Corentin-LF/pyGPs | b9d36777584cd53756bd4311c3c20ea52e945451 | [
"BSD-2-Clause"
] | null | null | null | pyGPs/Core/gp.py | Corentin-LF/pyGPs | b9d36777584cd53756bd4311c3c20ea52e945451 | [
"BSD-2-Clause"
] | null | null | null | pyGPs/Core/gp.py | Corentin-LF/pyGPs | b9d36777584cd53756bd4311c3c20ea52e945451 | [
"BSD-2-Clause"
] | null | null | null | from __future__ import division
from __future__ import absolute_import
from builtins import str
from builtins import range
from builtins import object
from past.utils import old_div
#================================================================================
# Marion Neumann [marion dot neumann at uni-bonn dot de]
# Daniel Marthaler [dan dot marthaler at gmail dot com]
# Shan Huang [shan dot huang at iais dot fraunhofer dot de]
# Kristian Kersting [kristian dot kersting at cs dot tu-dortmund dot de]
#
# This file is part of pyGPs.
# The software package is released under the BSD 2-Clause (FreeBSD) License.
#
# Copyright (c) by
# Marion Neumann, Daniel Marthaler, Shan Huang & Kristian Kersting, 18/02/2014
#================================================================================
# MEANING OF NOTATION:
#
# inffunc function specifying the inference method
# covfunc prior covariance function (see below)
# meanfunc prior mean function
# likfunc likelihood function
# x n by D matrix of training inputs
# y column vector of length n of training targets
# xs n by D matrix of test inputs
# ys column vector of length nn of true test targets (optional)
# nlZ returned value of the negative log marginal likelihood
# dnlZ column vector of partial derivatives of the negative
# log marginal likelihood w.r.t. each hyperparameter
# ym column vector (of length ns) of predictive output means
# ys2 column vector (of length ns) of predictive output variances
# fm column vector (of length ns) of predictive latent means
# fs2 column vector (of length ns) of predictive latent variances
# lp column vector (of length ns) of log predictive probabilities
# post struct representation of the (approximate) posterior
# post consists of post.alpha, post.L, post.sW
#
# This is a object-oriented python implementation of gpml functionality
# (Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2011-02-18).
# based on the functional-version of python implementation
# (Copyright (c) by Marion Neumann and Daniel Marthaler, 20/05/2013)
#
# Copyright (c) by Marion Neumann and Shan Huang, 30/09/2013
import itertools
import numpy as np
import matplotlib.pyplot as plt
from . import inf, mean, lik, cov, opt
from .tools import unique, jitchol, solve_chol
from copy import deepcopy
import pyGPs
from pyGPs.Core.cov import FITCOfKernel
import logging
SHADEDCOLOR = [0.7539, 0.89453125, 0.62890625, 1.0]
MEANCOLOR = [ 0.2109375, 0.63385, 0.1796875, 1.0]
DATACOLOR = [0.12109375, 0.46875, 1., 1.0]
class GP(object):
'''
Base class for GP model.
'''
def __init__(self):
super(GP, self).__init__()
self.usingDefaultMean = True # was using default mean function now?
self.meanfunc = None # mean function
self.covfunc = None # covariance function
self.likfunc = None # likelihood function
self.inffunc = None # inference function
self.optimizer = None # optimizer object
self.nlZ = None # negative log marginal likelihood
self.dnlZ = None # column vector of partial derivatives of the negative
# log marginal likelihood w.r.t. each hyperparameter
self.posterior = None # struct representation of the (approximate) posterior
self.x = None # n by D matrix of training inputs
self.y = None # column vector of length n of training targets
self.xs = None # n by D matrix of test inputs
self.ys = None # column vector of length nn of true test targets (optional)
self.ym = None # column vector (of length ns) of predictive output means
self.ys2 = None # column vector (of length ns) of predictive output variances
self.fm = None # column vector (of length ns) of predictive latent means
self.fs2 = None # column vector (of length ns) of predictive latent variances
self.lp = None # column vector (of length ns) of log predictive probabilities
self.logger = logging.getLogger(__name__)
def __str__(self):
strvalue = 'To get the properties of the model use:\n'+\
'model.nlZ # negative log marginal likelihood\n'+\
'model.dnlZ.cov # derivatives of cov func of negative log marginal likelihood\n'+\
'model.dnlZ.lik # derivatives of lik func of negative log marginal likelihood\n'+\
'model.dnlZ.mean # derivatives of mean func of negative log marginal likelihood\n'+\
'model.posterior # posterior structure\n'+\
'model.covfunc.hyp # hyperparameters of cov func\n'+\
'model.meanfunc.hyp # hyperparameters of mean func\n'+\
'model.likfunc.hyp # hyperparameters of lik func\n'+\
'model.fm # latent mean\n'+\
'model.fs2 # latent variance\n'+\
'model.ym # predictive mean\n'+\
'model.ys2 # predictive variance\n'+\
'model.lp # log predictive probability'
return strvalue
def __repr__(self):
strvalue = str(type(self))+': '+\
'to get the properties of the model use:\n'+\
'model.nlZ # negative log marginal likelihood\n'+\
'model.dnlZ.cov # derivatives of cov func of negative log marginal likelihood\n'+\
'model.dnlZ.lik # derivatives of lik func of negative log marginal likelihood\n'+\
'model.dnlZ.mean # derivatives of mean func of negative log marginal likelihood\n'+\
'model.posterior # posterior structure\n'+\
'model.covfunc.hyp # hyperparameters of cov func\n'+\
'model.meanfunc.hyp # hyperparameters of mean func\n'+\
'model.likfunc.hyp # hyperparameters of lik func\n'+\
'model.fm # latent mean\n'+\
'model.fs2 # latent variance\n'+\
'model.ym # predictive mean\n'+\
'model.ys2 # predictive variance\n'+\
'model.lp # log predictive probability'
return strvalue
def setData(self, x, y):
'''
Set training inputs and traning labels to model.
:param x: training inputs in shape (n,D)
:param y: training labels in shape (n,1)
Note this method will transform x, y to correct shape
if x, y is given in 1d array.
'''
# check wether the number of inputs and labels match
assert x.shape[0] == y.shape[0], "number of inputs and labels does not match"
# check the shape of inputs
# transform to the correct shape
if x.ndim == 1:
x = np.reshape(x, (x.shape[0],1))
if y.ndim == 1:
y = np.reshape(y, (y.shape[0],1))
self.x = x
self.y = y
if self.usingDefaultMean:
c = np.mean(y)
self.meanfunc = mean.Const(c) # adapt default prior mean wrt. training labels
def plotData_1d(self, axisvals=None):
'''
Toy Method for ploting 1d data of the model.
:param list axisvals: [min_x, max_x, min_y, max_y] setting the plot range
'''
plt.figure()
plt.plot(self.x, self.y, ls='None', marker='+', color=DATACOLOR, ms=12, mew=2)
if axisvals:
plt.axis(axisvals)
plt.grid()
plt.xlabel('input x')
plt.ylabel('target y')
plt.show()
def plotData_2d(self,x1,x2,t1,t2,p1,p2,axisvals=None):
'''
Toy Method for ploting 2d data of the model. \n
For plotting, we superimpose the data points with the posterior equi-probability contour
lines for the probability of class two given complete information about the generating mechanism.
:param x1: inputs for class +1
:param x2: inputs for class -1
:param t1: meshgrid array for the first axis
:param t2: meshgrid array for the second axis
:param p1,p2: contour lines contains p2/(p1+p2)
:param list axisvals: [min_x, max_x, min_y, max_y] setting the plot range
That is to say, the contour is ploted by plt.contour(t1, t2, p2/(p1+p2) )
Note these parameters are (only) used for our hard-coded data for classification demo.
'''
fig = plt.figure()
plt.plot(x1[:,0], x1[:,1], 'b+', markersize = 12)
plt.plot(x2[:,0], x2[:,1], 'r+', markersize = 12)
pc = plt.contour(t1, t2, np.reshape(old_div(p2,(p1+p2)), (t1.shape[0],t1.shape[1]) ))
fig.colorbar(pc)
plt.grid()
if axisvals:
plt.axis(axisvals)
plt.show()
def setPrior(self, mean=None, kernel=None):
'''
Set prior mean and covariance other than the default setting of current model.
:param mean: instance of mean class. (e.g. mean.Linear())
:param kernel: instance of covariance class. (e.g. cov.RBF())
'''
# check the type of inputs
# ensure they are the right class before setting prior
if not mean is None:
assert isinstance(mean, pyGPs.mean.Mean), "mean function is not an instance of pyGPs.mean.Mean"
self.meanfunc = mean
self.usingDefaultMean = False
if not kernel is None:
assert isinstance(kernel, pyGPs.cov.Kernel), "cov function is not an instance of pyGPs.cov.Kernel"
self.covfunc = kernel
if type(kernel) is cov.Pre:
self.usingDefaultMean = False
def setOptimizer(self, method, num_restarts=None, min_threshold=None, meanRange=None, covRange=None, likRange=None):
'''
This method is used to sepecify optimization configuration. By default, gp uses a single run "minimize".
:param method: Optimization methods. Possible values are:\n
"Minimize" -> minimize by Carl Rasmussen (python implementation of "minimize" in GPML)\n
"CG" -> conjugent gradient\n
"BFGS" -> quasi-Newton method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS)\n
"SCG" -> scaled conjugent gradient (faster than CG)\n
:param num_restarts: Set if you want to run mulitiple times of optimization with different initial guess.
It specifys the maximum number of runs/restarts/trials.
:param min_threshold: Set if you want to run mulitiple times of optimization with different initial guess.
It specifys the threshold of objective function value. Stop optimization when this value is reached.
:param meanRange: The range of initial guess for mean hyperparameters.
e.g. meanRange = [(-2,2), (-5,5), (0,1)].
Each tuple specifys the range (low, high) of this hyperparameter,
This is only the range of initial guess, during optimization process, optimal hyperparameters may go out of this range.
(-5,5) for each hyperparameter by default.
:param covRange: The range of initial guess for kernel hyperparameters. Usage see meanRange
:param likRange: The range of initial guess for likelihood hyperparameters. Usage see meanRange
'''
pass
def optimize40(self, x=None, y=None, numIterations=40):
'''
Train optimal hyperparameters based on training data,
adjust new hyperparameters to all mean/cov/lik functions.
:param x: training inputs in shape (n,D)
:param y: training labels in shape (n,1)
'''
# check wether the number of inputs and labels match
if x is not None and y is not None:
assert x.shape[0] == y.shape[0], "number of inputs and labels does not match"
# check the shape of inputs
# transform to the correct shape
if not x is None:
if x.ndim == 1:
x = np.reshape(x, (x.shape[0],1))
self.x = x
if not y is None:
if y.ndim == 1:
y = np.reshape(y, (y.shape[0],1))
self.y = y
if self.usingDefaultMean and self.meanfunc is None:
c = np.mean(y)
self.meanfunc = mean.Const(c) # adapt default prior mean wrt. training labels
# optimize
optimalHyp, optimalNlZ = self.optimizer.findMin(self.x, self.y, numIters = numIterations)
self.nlZ = optimalNlZ
# apply optimal hyp to all mean/cov/lik functions here
self.optimizer._apply_in_objects(optimalHyp)
self.getPosterior()
def optimize(self, x=None, y=None, numIterations=1000):
'''
Train optimal hyperparameters based on training data,
adjust new hyperparameters to all mean/cov/lik functions.
:param x: training inputs in shape (n,D)
:param y: training labels in shape (n,1)
'''
# check wether the number of inputs and labels match
if x is not None and y is not None:
assert x.shape[0] == y.shape[0], "number of inputs and labels does not match"
# check the shape of inputs
# transform to the correct shape
if not x is None:
if x.ndim == 1:
x = np.reshape(x, (x.shape[0],1))
self.x = x
if not y is None:
if y.ndim == 1:
y = np.reshape(y, (y.shape[0],1))
self.y = y
if self.usingDefaultMean and self.meanfunc is None:
c = np.mean(y)
self.meanfunc = mean.Const(c) # adapt default prior mean wrt. training labels
# optimize
optimalHyp, optimalNlZ = self.optimizer.findMin(self.x, self.y, numIters = numIterations)
self.nlZ = optimalNlZ
# apply optimal hyp to all mean/cov/lik functions here
self.optimizer._apply_in_objects(optimalHyp)
self.getPosterior()
def getPosterior(self, x=None, y=None, der=True):
'''
Fit the training data. Update negative log marginal likelihood(nlZ),
partial derivatives of nlZ w.r.t. each hyperparameter(dnlZ),
and struct representation of the (approximate) posterior(post),
which consists of post.alpha, post.L, post.sW.
nlZ, dnlZ, post = getPosterior(x, y, der=True)\n
nlZ, post = getPosterior(x, y, der=False )
:param x: training inputs in shape (n,D)
:param y: training labels in shape (n,1)
:param boolean der: flag for whether to compute derivatives
:return: negative log marginal likelihood (nlZ), derivatives of nlZ (dnlZ), posterior structure(post)
You can print post to see descriptions of posterior.
or see pyGPs.Core.inf for details.
'''
# check wether the number of inputs and labels match
if x is not None and y is not None:
assert x.shape[0] == y.shape[0], "number of inputs and labels does not match"
# check the shape of inputs
# transform to the correct shape
if not x is None:
if x.ndim == 1:
x = np.reshape(x, (x.shape[0],1))
self.x = x
if not y is None:
if y.ndim == 1:
y = np.reshape(y, (y.shape[0],1))
self.y = y
if self.usingDefaultMean and self.meanfunc is None:
c = np.mean(y)
self.meanfunc = mean.Const(c) # adapt default prior mean wrt. training labels
# call inference method
if isinstance(self.likfunc, lik.Erf): #or is instance(self.likfunc, lik.Logistic):
uy = unique(self.y)
ind = ( uy != 1 )
if any( uy[ind] != -1):
raise Exception('You attempt classification using labels different from {+1,-1}')
if not der:
post, nlZ = self.inffunc.evaluate(self.meanfunc, self.covfunc, self.likfunc, self.x, self.y, 2)
self.nlZ = nlZ
self.posterior = deepcopy(post)
return nlZ, post
else:
post, nlZ, dnlZ = self.inffunc.evaluate(self.meanfunc, self.covfunc, self.likfunc, self.x, self.y, 3)
self.nlZ = nlZ
self.dnlZ = deepcopy(dnlZ)
self.posterior = deepcopy(post)
return nlZ, dnlZ, post
def predict(self, xs, ys=None):
'''
Prediction of test points (given by xs) based on training data of the current model.
This method will output the following value:\n
predictive output means(ym),\n
predictive output variances(ys2),\n
predictive latent means(fm),\n
predictive latent variances(fs2),\n
log predictive probabilities(lp).\n
Theses values can also be achieved from model's property. (e.g. model.ym)
:param xs: test input in shape of nn by D
:param ys: test target(optional) in shape of nn by 1 if given
:return: ym, ys2, fm, fs2, lp
'''
# check the shape of inputs
# transform to correct shape if neccessary
if xs.ndim == 1:
xs = np.reshape(xs, (xs.shape[0],1))
self.xs = xs
if not ys is None:
if ys.ndim == 1:
ys = np.reshape(ys, (ys.shape[0],1))
self.ys = ys
meanfunc = self.meanfunc
covfunc = self.covfunc
likfunc = self.likfunc
inffunc = self.inffunc
x = self.x
y = self.y
if self.posterior is None:
self.getPosterior()
alpha = self.posterior.alpha
L = self.posterior.L
sW = self.posterior.sW
nz = list(range(len(alpha[:,0]))) # non-sparse representation
if len(L) == 0: # in case L is not provided, we compute it
K = covfunc.getCovMatrix(x=x[nz,:], mode='train')
#L = np.linalg.cholesky( (np.eye(nz) + np.dot(sW,sW.T)*K).T )
L = jitchol( (np.eye(len(nz)) + np.dot(sW,sW.T)*K).T )
Ltril = np.all( np.tril(L,-1) == 0 ) # is L an upper triangular matrix?
ns = xs.shape[0] # number of data points
nperbatch = 1000 # number of data points per mini batch
nact = 0 # number of already processed test data points
ymu = np.zeros((ns,1))
ys2 = np.zeros((ns,1))
fmu = np.zeros((ns,1))
fs2 = np.zeros((ns,1))
lp = np.zeros((ns,1))
while nact<=ns-1: # process minibatches of test cases to save memory
ids = list(range(nact,min(nact+nperbatch,ns))) # data points to process
kss = covfunc.getCovMatrix(z=xs[ids,:], mode='self_test') # self-variances
if isinstance(covfunc, FITCOfKernel):
Ks = covfunc.getCovMatrix(x=x, z=xs[ids,:], mode='cross') # cross-covariances
Ks = Ks[nz,:]
else:
Ks = covfunc.getCovMatrix(x=x[nz,:], z=xs[ids,:], mode='cross') # cross-covariances
ms = meanfunc.getMean(xs[ids,:])
N = (alpha.shape)[1] # number of alphas (usually 1; more in case of sampling)
Fmu = np.tile(ms,(1,N)) + np.dot(Ks.T,alpha[nz]) # conditional mean fs|f
fmu[ids] = np.reshape(old_div(Fmu.sum(axis=1),N),(len(ids),1)) # predictive means
if Ltril: # L is triangular => use Cholesky parameters (alpha,sW,L)
V = np.linalg.solve(L.T,np.tile(sW,(1,len(ids)))*Ks)
fs2[ids] = kss - np.array([(V*V).sum(axis=0)]).T # predictive variances
else: # L is not triangular => use alternative parametrization
fs2[ids] = kss + np.array([(Ks*np.dot(L,Ks)).sum(axis=0)]).T # predictive variances
fs2[ids] = np.maximum(fs2[ids],0) # remove numerical noise i.e. negative variances
Fs2 = np.tile(fs2[ids],(1,N)) # we have multiple values in case of sampling
if ys is None:
Lp, Ymu, Ys2 = likfunc.evaluate(None,Fmu[:],Fs2[:],None,None,3)
else:
Lp, Ymu, Ys2 = likfunc.evaluate(np.tile(ys[ids],(1,N)), Fmu[:], Fs2[:],None,None,3)
lp[ids] = np.reshape( old_div(np.reshape(Lp,(np.prod(Lp.shape),N)).sum(axis=1),N) , (len(ids),1) ) # log probability; sample averaging
ymu[ids] = np.reshape( old_div(np.reshape(Ymu,(np.prod(Ymu.shape),N)).sum(axis=1),N) ,(len(ids),1) ) # predictive mean ys|y and ...
ys2[ids] = np.reshape( old_div(np.reshape(Ys2,(np.prod(Ys2.shape),N)).sum(axis=1),N) , (len(ids),1) ) # .. variance
nact = ids[-1]+1 # set counter to index of next data point
self.ym = ymu
self.ys2 = ys2
self.lp = lp
self.fm = fmu
self.fs2 = fs2
if ys is None:
return ymu, ys2, fmu, fs2, None
else:
return ymu, ys2, fmu, fs2, lp
def predict_with_posterior(self, post, xs, ys=None):
'''
Prediction of test points (given by xs) based on training data
of the current model with posterior already provided.
(i.e. you already have the posterior and thus don't need the fitting phase.)
This method will output the following value:\n
predictive output means(ym),\n
predictive output variances(ys2),\n
predictive latent means(fm),\n
predictive latent variances(fs2),\n
log predictive probabilities(lp).\n
Theses values can also be achieved from model's property. (e.g. model.ym)
:param post: struct representation of posterior
:param xs: test input
:param ys: test target(optional)
:return: ym, ys2, fm, fs2, lp
'''
# check the shape of inputs
# transform to correct shape if neccessary
if xs.ndim == 1:
xs = np.reshape(xs, (xs.shape[0],1))
self.xs = xs
if not ys is None:
if ys.ndim == 1:
ys = np.reshape(ys, (ys.shape[0],1))
self.ys = ys
meanfunc = self.meanfunc
covfunc = self.covfunc
likfunc = self.likfunc
inffunc = self.inffunc
x = self.x
y = self.y
self.posterior = deepcopy(post)
alpha = post.alpha
L = post.L
sW = post.sW
nz = list(range(len(alpha[:,0]))) # non-sparse representation
if len(L) == 0: # in case L is not provided, we compute it
K = covfunc.getCovMatrix(x=x[nz,:], mode='train')
#L = np.linalg.cholesky( (np.eye(nz) + np.dot(sW,sW.T)*K).T )
L = jitchol( (np.eye(len(nz)) + np.dot(sW,sW.T)*K).T )
Ltril = np.all( np.tril(L,-1) == 0 ) # is L an upper triangular matrix?
ns = xs.shape[0] # number of data points
nperbatch = 1000 # number of data points per mini batch
nact = 0 # number of already processed test data points
ymu = np.zeros((ns,1))
ys2 = np.zeros((ns,1))
fmu = np.zeros((ns,1))
fs2 = np.zeros((ns,1))
lp = np.zeros((ns,1))
while nact<=ns-1: # process minibatches of test cases to save memory
id = list(range(nact,min(nact+nperbatch,ns))) # data points to process
kss = covfunc.getCovMatrix(z=xs[id,:], mode='self_test') # self-variances
Ks = covfunc.getCovMatrix(x=x[nz,:], z=xs[id,:], mode='cross') # cross-covariances
ms = meanfunc.getMean(xs[id,:])
N = (alpha.shape)[1] # number of alphas (usually 1; more in case of sampling)
Fmu = np.tile(ms,(1,N)) + np.dot(Ks.T,alpha[nz]) # conditional mean fs|f
fmu[id] = np.reshape(old_div(Fmu.sum(axis=1),N),(len(id),1)) # predictive means
if Ltril: # L is triangular => use Cholesky parameters (alpha,sW,L)
V = np.linalg.solve(L.T,np.tile(sW,(1,len(id)))*Ks)
fs2[id] = kss - np.array([(V*V).sum(axis=0)]).T # predictive variances
else: # L is not triangular => use alternative parametrization
fs2[id] = kss + np.array([(Ks*np.dot(L,Ks)).sum(axis=0)]).T # predictive variances
fs2[id] = np.maximum(fs2[id],0) # remove numerical noise i.e. negative variances
Fs2 = np.tile(fs2[id],(1,N)) # we have multiple values in case of sampling
if ys is None:
[Lp, Ymu, Ys2] = likfunc.evaluate(None,Fmu[:],Fs2[:],None,None,3)
else:
[Lp, Ymu, Ys2] = likfunc.evaluate(np.tile(ys[id],(1,N)), Fmu[:], Fs2[:],None,None,3)
lp[id] = np.reshape( old_div(np.reshape(Lp,(np.prod(Lp.shape),N)).sum(axis=1),N) , (len(id),1) ) # log probability; sample averaging
ymu[id] = np.reshape( old_div(np.reshape(Ymu,(np.prod(Ymu.shape),N)).sum(axis=1),N) ,(len(id),1) ) # predictive mean ys|y and ...
ys2[id] = np.reshape( old_div(np.reshape(Ys2,(np.prod(Ys2.shape),N)).sum(axis=1),N) , (len(id),1) ) # .. variance
nact = id[-1]+1 # set counter to index of next data point
self.ym = ymu
self.ys2 = ys2
self.lp = lp
self.fm = fmu
self.fs2 = fs2
if ys is None:
return ymu, ys2, fmu, fs2, None
else:
return ymu, ys2, fmu, fs2, lp
class GPR(GP):
'''
Model for Gaussian Process Regression
'''
def __init__(self):
super(GPR, self).__init__()
self.meanfunc = mean.Zero() # default prior mean
self.covfunc = cov.RBF() # default prior covariance
self.likfunc = lik.Gauss() # likihood with default noise variance 0.1
self.inffunc = inf.Exact() # inference method
self.optimizer = opt.Minimize(self) # default optimizer
def setNoise(self,log_sigma):
'''
Set noise other than default noise value
:param log_sigma: logarithm of the noise sigma
'''
self.likfunc = lik.Gauss(log_sigma)
def setOptimizer(self, method, num_restarts=None, min_threshold=None, meanRange=None, covRange=None, likRange=None):
'''
Overriding. Usage see base class pyGPs.gp.GP.setOptimizer
'''
conf = None
if (num_restarts!=None) or (min_threshold!=None):
conf = pyGPs.Optimization.conf.random_init_conf(self.meanfunc,self.covfunc,self.likfunc)
conf.num_restarts = num_restarts
conf.min_threshold = min_threshold
if not meanRange is None:
conf.meanRange = meanRange
if not covRange is None:
conf.covRange = covRange
if not likRange is None:
conf.likRange = likRange
if method == "Minimize":
self.optimizer = opt.Minimize(self,conf)
elif method == "SCG":
self.optimizer = opt.SCG(self,conf)
elif method == "CG":
self.optimizer = opt.CG(self,conf)
elif method == "BFGS":
self.optimizer = opt.BFGS(self,conf)
elif method == "Nelder-Mead":
self.optimizer = opt.Simplex(self, conf)
else:
raise Exception('Optimization method is not set correctly in setOptimizer')
def plot(self,axisvals=None):
'''
Plot 1d GP regression result.
:param list axisvals: [min_x, max_x, min_y, max_y] setting the plot range
'''
xs = self.xs # test point
x = self.x
y = self.y
ym = self.ym # predictive test mean
ys2 = self.ys2 # predictive test variance
plt.figure()
xss = np.reshape(xs,(xs.shape[0],))
ymm = np.reshape(ym,(ym.shape[0],))
ys22 = np.reshape(ys2,(ys2.shape[0],))
plt.plot(x, y, color=DATACOLOR, ls='None', marker='+',ms=12, mew=2)
plt.plot(xs, ym, color=MEANCOLOR, ls='-', lw=3.)
plt.fill_between(xss,ymm + 2.*np.sqrt(ys22), ymm - 2.*np.sqrt(ys22), facecolor=SHADEDCOLOR,linewidths=0.0)
plt.grid()
if not axisvals is None:
plt.axis(axisvals)
plt.xlabel('input x')
plt.ylabel('target y')
plt.show()
def useInference(self, newInf):
'''
Use another inference techinique other than default exact inference.
:param str newInf: 'Laplace' or 'EP'
'''
if newInf == "Laplace":
self.inffunc = inf.Laplace()
elif newInf == "EP":
self.inffunc = inf.EP()
else:
raise Exception('Possible inf values are "Laplace", "EP".')
def useLikelihood(self,newLik):
'''
Use another likelihood function other than default Gaussian likelihood.
:param str newLik: 'Laplace'
'''
if newLik == "Laplace":
self.likfunc = lik.Laplace()
self.inffunc = inf.EP()
else:
raise Exception('Possible lik values are "Laplace".')
class GPC(GP):
'''
Model for Gaussian Process Classification.
'''
def __init__(self):
super(GPC, self).__init__()
self.meanfunc = mean.Zero() # default prior mean
self.covfunc = cov.RBF() # default prior covariance
self.likfunc = lik.Erf() # erf likihood
self.inffunc = inf.EP() # default inference method
self.optimizer = opt.Minimize(self) # default optimizer
def setOptimizer(self, method, num_restarts=None, min_threshold=None, meanRange=None, covRange=None, likRange=None):
'''
Overriding. Usage see base class pyGPs.gp.GP.setOptimizer
'''
conf = None
if (num_restarts!=None) or (min_threshold!=None):
conf = pyGPs.Optimization.conf.random_init_conf(self.meanfunc,self.covfunc,self.likfunc)
conf.num_restarts = num_restarts
conf.min_threshold = min_threshold
if not meanRange is None:
conf.meanRange = meanRange
if not covRange is None:
conf.covRange = covRange
if not likRange is None:
conf.likRange = likRange
if method == "Minimize":
self.optimizer = opt.Minimize(self,conf)
elif method == "SCG":
self.optimizer = opt.SCG(self,conf)
elif method == "CG":
self.optimizer = opt.CG(self,conf)
elif method == "BFGS":
self.optimizer = opt.BFGS(self,conf)
def plot(self,x1,x2,t1,t2,axisvals=None):
'''
Plot 2d GP Classification result.
For plotting, we superimpose the data points with the posterior equi-probability contour
lines for the probability of class two given complete information about the generating mechanism.
:param x1: inputs for class +1
:param x2: inputs for class -1
:param t1: meshgrid array for the first axis
:param t2: meshgrid array for the second axis
:param list axisvals: [min_x, max_x, min_y, max_y] setting the plot range
Note these parameters are (only) used for our hard-coded data for classification demo.
'''
fig = plt.figure()
plt.plot(x1[:,0], x1[:,1], 'b+', markersize = 12)
plt.plot(x2[:,0], x2[:,1], 'r+', markersize = 12)
pc = plt.contour(t1, t2, np.reshape(np.exp(self.lp), (t1.shape[0],t1.shape[1]) ))
fig.colorbar(pc)
plt.grid()
if not axisvals is None:
plt.axis(axisvals)
plt.show()
def useInference(self, newInf):
'''
Use another inference techinique other than default EP inference.
:param str newInf: 'Laplace'
'''
if newInf == "Laplace":
self.inffunc = inf.Laplace()
else:
raise Exception('Possible inf values are "Laplace".')
def useLikelihood(self,newLik):
'''
Use another likelihood function other than default error function.
(Not used in this version)
:param str newLik: 'Logistic'
'''
if newLik == "Logistic":
raise Exception("Logistic likelihood is currently not implemented.")
#self.likfunc = lik.Logistic()
else:
raise Exception('Possible lik values are "Logistic".')
class GPMC(object):
'''
This is a one vs. one classification wrapper for GP Classification
'''
def __init__(self, n_class):
self.meanfunc = mean.Zero() # default prior mean
self.covfunc = cov.RBF() # default prior covariance
self.n_class = n_class # number of different classes
self.x_all = None
self.y_all = None
self.newInf = None # new inference? -> call useInference
self.newLik = None # new likelihood? -> call useLikelihood
self.newPrior = False
def setPrior(self, mean=None, kernel=None):
'''
Set prior mean and covariance other than the default setting of current model.
:param mean: instance of mean class. (e.g. mean.Linear())
:param kernel: instance of covariance class. (e.g. cov.RBF())
'''
# check the type of inputs
# ensure they are the right class before setting prior
if not mean is None:
assert isinstance(mean, pyGPs.mean.Mean), "mean function is not an instance of pyGPs.mean.Mean"
self.meanfunc = mean
self.usingDefaultMean = False
if not kernel is None:
assert isinstance(kernel, pyGPs.cov.Kernel), "cov function is not an instance of pyGPs.cov.Kernel"
self.covfunc = kernel
if type(kernel) is cov.Pre:
self.usingDefaultMean = False
self.newPrior = True
def useInference(self, newInf):
'''
Use another inference techinique other than default EP inference.
:param str newInf: 'Laplace'
'''
if newInf == "Laplace":
self.inffunc = inf.Laplace()
else:
raise Exception('Possible inf values are "Laplace".')
def useLikelihood(self,newLik):
'''
Use another likelihood function other than default error function.
(Not used in this version)
:param str newLik: 'Logistic'
'''
if newLik == "Logistic":
raise Exception("Logistic likelihood is currently not implemented.")
#self.likfunc = lik.Logistic()
else:
raise Exception('Possible lik values are "Logistic".')
def setData(self,x,y):
'''
Set training inputs and traning labels to model.
:param x: training inputs in shape (n,D)
:param y: training labels in shape (n,1)
Note this method will transform x, y to correct shape
if x, y is given in 1d array.
'''
# check wether the number of inputs and labels match
assert x.shape[0] == y.shape[0], "number of inputs and labels does not match"
# check the shape of inputs
# transform to the correct shape
if x.ndim == 1:
x = np.reshape(x, (x.shape[0],1))
if y.ndim == 1:
y = np.reshape(y, (y.shape[0],1))
self.x_all = x
self.y_all = y
def fitAndPredict(self, xs):
'''
Fit the model with given training data and predict for test points (given by xs).
predictive_vote is a matrix where row i is each test point i,
and column j is the probability for being class j
:param xs: test inputs in shape of nn by D
:return: predictive_vote
'''
# check the shape of inputs
if xs.ndim == 1:
xs = np.reshape(xs, (xs.shape[0],1))
predictive_vote = np.zeros((xs.shape[0],self.n_class))
for i in range(self.n_class): # classifier for class i...
for j in range(i+1,self.n_class): # ...and class j
x,y = self.createBinaryClass(i,j)
model = GPC()
if self.newPrior:
model.setPrior(mean=self.meanfunc, kernel=self.covfunc)
if self.newInf:
model.useInference(self.newInf)
if self.newLik:
model.useLikelihood(self.newLik)
model.getPosterior(x,y) # fitting
ym = model.predict(xs)[0]
ym += 1 # now scale into 0 to 2, ym=0 is class j, ym=2 is class i
vote_i = np.zeros((xs.shape[0],self.n_class))
vote_j = np.zeros((xs.shape[0],self.n_class))
vote_i[:,i:i+1] = ym
vote_j[:,j:j+1] = 2-ym
predictive_vote += vote_i
predictive_vote += vote_j
predictive_vote /= predictive_vote.sum(axis=1)[:,np.newaxis]
return predictive_vote
def optimizeAndPredict(self, xs):
'''
Optimize the model with given training data and predict for test points (given by xs).
predictive_vote is a matrix where row i is each test point i,
and column j is the probability for being class j
:param xs: test inputs in shape of nn by D
:return: predictive_vote
'''
# check the shape of inputs
if xs.ndim == 1:
xs = np.reshape(xs, (xs.shape[0],1))
predictive_vote = np.zeros((xs.shape[0],self.n_class))
for i in range(self.n_class): # classifier for class i...
for j in range(i+1,self.n_class): # ...and class j
x,y = self.createBinaryClass(i,j)
model = GPC()
if self.newPrior:
model.setPrior(mean=self.meanfunc, kernel=self.covfunc)
if self.newInf:
model.useInference(self.newInf)
if self.newLik:
model.useLikelihood(self.newLik)
model.optimize(x,y) # training
ym = model.predict(xs)[0]
ym += 1 # now scale into 0 to 2, ym=0 is class j, ym=2 is class i
vote_i = np.zeros((xs.shape[0],self.n_class))
vote_j = np.zeros((xs.shape[0],self.n_class))
vote_i[:,i:i+1] = ym
vote_j[:,j:j+1] = 2-ym
predictive_vote += vote_i
predictive_vote += vote_j
predictive_vote /= predictive_vote.sum(axis=1)[:,np.newaxis]
return predictive_vote
def createBinaryClass(self, i,j):
'''
Create dataset x(data) and y(label) which only contains class i and j.
Relabel class i to +1 and class j to -1
:param int i: the i_th class
:param int j: the j_th class
:return: x(data) and y(label) which only contains class i and j
'''
class_i = []
class_j = []
for index in range(len(self.y_all)): # check all classes
target = self.y_all[index]
if target == i:
class_i.append(index)
elif target == j:
class_j.append(index)
n1 = len(class_i)
n2 = len(class_j)
class_i.extend(class_j)
x = self.x_all[class_i,:]
y = np.concatenate((np.ones((1,n1)),-np.ones((1,n2))),axis=1).T
return x,y
class GP_FITC(GP):
'''
Model for FITC GP base class
'''
def __init__(self):
super(GP_FITC, self).__init__()
self.u = None # inducing points
def setData(self, x, y, value_per_axis=5):
'''
Set training inputs and traning labels to model and derive deault inducing_points..
:param x: training inputs in shape (n,D)
:param y: training labels in shape (n,1)
:param int value_per_axis: number of value in each dimension
when using a uni-distant default inducing points
Note this method will transform x, y to correct shape
if x, y is given in 1d array.
'''
# check wether the number of inputs and labels match
assert x.shape[0] == y.shape[0], "number of inputs and labels does not match"
# check dimension of inputs
# transform to correct shape if neccessary
if x.ndim == 1:
x = np.reshape(x, (x.shape[0],1))
if y.ndim == 1:
y = np.reshape(y, (y.shape[0],1))
self.x = x
self.y = y
if self.usingDefaultMean:
c = np.mean(y)
self.meanfunc = mean.Const(c) # adapt default prior mean wrt. training labels
# get range of x in each dimension
# 5 uniformally selected value for each dimension
gridAxis=[]
for d in range(x.shape[1]):
column = x[:,d]
mini = np.min(column)
maxi = np.max(column)
axis = np.linspace(mini,maxi,value_per_axis)
gridAxis.append(axis)
# default inducing points-> a grid
if self.u is None:
self.u = np.array(list(itertools.product(*gridAxis)))
self.covfunc = self.covfunc.fitc(self.u)
def setPrior(self, mean=None, kernel=None, inducing_points=None):
'''
Set prior mean and covariance other than the default setting of current model,
as well as the inducing points
:param mean: instance of mean class. (e.g. mean.Linear())
:param kernel: instance of covariance class. (e.g. cov.RBF())
:inducing_points: matrix of inducing points in shape of (nu,D)
'''
if not kernel is None:
if not inducing_points is None:
self.covfunc = kernel.fitc(inducing_points)
self.u = inducing_points
else:
if not self.u is None:
self.covfunc = kernel.fitc(self.u)
else:
raise Exception("To use default inducing points, please call setData() first!")
if type(kernel) is cov.Pre:
self.usingDefaultMean = False
if not mean is None:
self.meanfunc = mean
self.usingDefaultMean = False
class GPR_FITC(GP_FITC):
'''
Model for Gaussian Process Regression FITC
'''
def __init__(self):
super(GPR_FITC, self).__init__()
self.meanfunc = mean.Zero() # default prior mean
self.covfunc = cov.RBF() # default prior covariance
self.likfunc = lik.Gauss() # likihood with default noise variance 0.1
self.inffunc = inf.FITC_Exact() # inference method
self.optimizer = opt.Minimize(self) # default optimizer
self.u = None # no default inducing points
def setNoise(self,log_sigma):
'''
Set noise other than default noise value
:param log_sigma: logarithm of the noise sigma
'''
self.likfunc = lik.Gauss(log_sigma)
def setOptimizer(self, method, num_restarts=None, min_threshold=None, meanRange=None, covRange=None, likRange=None):
'''
Overriding. Usage see base class pyGPs.gp.GP.setOptimizer
'''
conf = None
if (num_restarts!=None) or (min_threshold!=None):
conf = pyGPs.Optimization.conf.random_init_conf(self.meanfunc,self.covfunc,self.likfunc)
conf.num_restarts = num_restarts
conf.min_threshold = min_threshold
if not meanRange is None:
conf.meanRange = meanRange
if not covRange is None:
conf.covRange = covRange
if not likRange is None:
conf.likRange = likRange
if method == "Minimize":
self.optimizer = opt.Minimize(self,conf)
elif method == "SCG":
self.optimizer = opt.SCG(self,conf)
elif method == "CG":
self.optimizer = opt.CG(self,conf)
elif method == "BFGS":
self.optimizer = opt.BFGS(self,conf)
def plot(self,axisvals=None):
'''
Plot 1d GP FITC Regression result.
:param list axisvals: [min_x, max_x, min_y, max_y] setting the plot range
'''
plt.figure()
xss = np.reshape(self.xs,(self.xs.shape[0],))
ymm = np.reshape(self.ym,(self.ym.shape[0],))
ys22 = np.reshape(self.ys2,(self.ys2.shape[0],))
plt.plot(self.x, self.y, color=DATACOLOR, ls='None', marker='+',ms=12, mew=2)
plt.plot(self.xs, self.ym, color=MEANCOLOR, ls='-', lw=3.)
plt.fill_between(xss,ymm + 2.*np.sqrt(ys22), ymm - 2.*np.sqrt(ys22), facecolor=SHADEDCOLOR,linewidths=0.0)
plt.grid()
if not axisvals is None:
plt.axis(axisvals)
plt.xlabel('input x')
plt.ylabel('output y')
plt.plot(self.u,np.ones_like(self.u), ls='None', color='k',marker='x',markersize=12,mew=2)
plt.show()
def useInference(self, newInf):
'''
Use another inference techinique other than default exact inference.
:param str newInf: 'Laplace' or 'EP'
'''
if newInf == "Laplace":
self.inffunc = inf.FITC_Laplace()
elif newInf == "EP":
self.inffunc = inf.FITC_EP()
else:
raise Exception('Possible inf values are "Laplace", "EP".')
def useLikelihood(self,newLik):
'''
Use another inference techinique other than default Gaussian likelihood.
:param str newLik: 'Laplace'
'''
if newLik == "Laplace":
self.likfunc = lik.Laplace()
self.inffunc = inf.FITC_EP()
else:
raise Exception('Possible lik values are "Laplace".')
class GPC_FITC(GP_FITC):
'''
Model for Gaussian Process Classification FITC
'''
def __init__(self):
super(GPC_FITC, self).__init__()
self.meanfunc = mean.Zero() # default prior mean
self.covfunc = cov.RBF() # default prior covariance
self.likfunc = lik.Erf() # erf liklihood
self.inffunc = inf.FITC_EP() # default inference method
self.optimizer = opt.Minimize(self) # default optimizer
self.u = None # no default inducing points
def setOptimizer(self, method, num_restarts=None, min_threshold=None, meanRange=None, covRange=None, likRange=None):
'''
Overriding. Usage see base class pyGPs.gp.GP.setOptimizer
'''
conf = None
if (num_restarts!=None) or (min_threshold!=None):
conf = pyGPs.Optimization.conf.random_init_conf(self.meanfunc,self.covfunc,self.likfunc)
conf.num_restarts = num_restarts
conf.min_threshold = min_threshold
if not meanRange is None:
conf.meanRange = meanRange
if not covRange is None:
conf.covRange = covRange
if not likRange is None:
conf.likRange = likRange
if method == "Minimize":
self.optimizer = opt.Minimize(self,conf)
elif method == "SCG":
self.optimizer = opt.SCG(self,conf)
elif method == "CG":
self.optimizer = opt.CG(self,conf)
elif method == "BFGS":
self.optimizer = opt.BFGS(self,conf)
def plot(self,x1,x2,t1,t2,axisvals=None):
'''Plot 2d GP FITC classification.
For plotting, we superimpose the data points with the posterior equi-probability contour
lines for the probability of class two given complete information about the generating mechanism.
:param x1: inputs for class +1
:param x2: inputs for class -1
:param t1: meshgrid array for the first axis
:param t2: meshgrid array for the second axis
:param list axisvals: [min_x, max_x, min_y, max_y] setting the plot range
Note these parameters are (only) used for our hard-coded data for classification demo.
'''
fig = plt.figure()
plt.plot(x1[:,0], x1[:,1], 'b+', markersize = 12)
plt.plot(x2[:,0], x2[:,1], 'r+', markersize = 12)
plt.plot(self.u[:,0],self.u[:,1],'ko', markersize=12)
pc = plt.contour(t1, t2, np.reshape(np.exp(self.lp), (t1.shape[0],t1.shape[1]) ))
fig.colorbar(pc)
plt.grid()
if not axisvals is None:
plt.axis(axisvals)
plt.show()
def useInference(self, newInf):
'''
Use another inference techinique other than default exact inference.
:param str newInf: 'Laplace' or 'EP'
'''
if newInf == "Laplace":
self.inffunc = inf.FITC_Laplace()
else:
raise Exception('Possible inf values are "Laplace".')
def useLikelihood(self,newLik):
'''
Use another inference techinique other than default Erf likelihood.
(Not used in this version)
:param str newLik: 'Logistic'
'''
if newLik == "Logistic":
raise Exception("Logistic likelihood is currently not implemented.")
else:
raise Exception('Possible lik values are "Logistic".')
| 40.450321 | 156 | 0.563389 | from __future__ import division
from __future__ import absolute_import
from builtins import str
from builtins import range
from builtins import object
from past.utils import old_div
import itertools
import numpy as np
import matplotlib.pyplot as plt
from . import inf, mean, lik, cov, opt
from .tools import unique, jitchol, solve_chol
from copy import deepcopy
import pyGPs
from pyGPs.Core.cov import FITCOfKernel
import logging
SHADEDCOLOR = [0.7539, 0.89453125, 0.62890625, 1.0]
MEANCOLOR = [ 0.2109375, 0.63385, 0.1796875, 1.0]
DATACOLOR = [0.12109375, 0.46875, 1., 1.0]
class GP(object):
def __init__(self):
super(GP, self).__init__()
self.usingDefaultMean = True
self.meanfunc = None
self.covfunc = None
self.likfunc = None
self.inffunc = None
self.optimizer = None
self.nlZ = None
self.dnlZ = None
self.posterior = None
self.x = None
self.y = None
self.xs = None
self.ys = None
self.ym = None
self.ys2 = None
self.fm = None
self.fs2 = None
self.lp = None
self.logger = logging.getLogger(__name__)
def __str__(self):
strvalue = 'To get the properties of the model use:\n'+\
'model.nlZ # negative log marginal likelihood\n'+\
'model.dnlZ.cov # derivatives of cov func of negative log marginal likelihood\n'+\
'model.dnlZ.lik # derivatives of lik func of negative log marginal likelihood\n'+\
'model.dnlZ.mean # derivatives of mean func of negative log marginal likelihood\n'+\
'model.posterior # posterior structure\n'+\
'model.covfunc.hyp # hyperparameters of cov func\n'+\
'model.meanfunc.hyp # hyperparameters of mean func\n'+\
'model.likfunc.hyp # hyperparameters of lik func\n'+\
'model.fm # latent mean\n'+\
'model.fs2 # latent variance\n'+\
'model.ym # predictive mean\n'+\
'model.ys2 # predictive variance\n'+\
'model.lp # log predictive probability'
return strvalue
def __repr__(self):
strvalue = str(type(self))+': '+\
'to get the properties of the model use:\n'+\
'model.nlZ # negative log marginal likelihood\n'+\
'model.dnlZ.cov # derivatives of cov func of negative log marginal likelihood\n'+\
'model.dnlZ.lik # derivatives of lik func of negative log marginal likelihood\n'+\
'model.dnlZ.mean # derivatives of mean func of negative log marginal likelihood\n'+\
'model.posterior # posterior structure\n'+\
'model.covfunc.hyp # hyperparameters of cov func\n'+\
'model.meanfunc.hyp # hyperparameters of mean func\n'+\
'model.likfunc.hyp # hyperparameters of lik func\n'+\
'model.fm # latent mean\n'+\
'model.fs2 # latent variance\n'+\
'model.ym # predictive mean\n'+\
'model.ys2 # predictive variance\n'+\
'model.lp # log predictive probability'
return strvalue
def setData(self, x, y):
assert x.shape[0] == y.shape[0], "number of inputs and labels does not match"
if x.ndim == 1:
x = np.reshape(x, (x.shape[0],1))
if y.ndim == 1:
y = np.reshape(y, (y.shape[0],1))
self.x = x
self.y = y
if self.usingDefaultMean:
c = np.mean(y)
self.meanfunc = mean.Const(c)
def plotData_1d(self, axisvals=None):
plt.figure()
plt.plot(self.x, self.y, ls='None', marker='+', color=DATACOLOR, ms=12, mew=2)
if axisvals:
plt.axis(axisvals)
plt.grid()
plt.xlabel('input x')
plt.ylabel('target y')
plt.show()
def plotData_2d(self,x1,x2,t1,t2,p1,p2,axisvals=None):
fig = plt.figure()
plt.plot(x1[:,0], x1[:,1], 'b+', markersize = 12)
plt.plot(x2[:,0], x2[:,1], 'r+', markersize = 12)
pc = plt.contour(t1, t2, np.reshape(old_div(p2,(p1+p2)), (t1.shape[0],t1.shape[1]) ))
fig.colorbar(pc)
plt.grid()
if axisvals:
plt.axis(axisvals)
plt.show()
def setPrior(self, mean=None, kernel=None):
if not mean is None:
assert isinstance(mean, pyGPs.mean.Mean), "mean function is not an instance of pyGPs.mean.Mean"
self.meanfunc = mean
self.usingDefaultMean = False
if not kernel is None:
assert isinstance(kernel, pyGPs.cov.Kernel), "cov function is not an instance of pyGPs.cov.Kernel"
self.covfunc = kernel
if type(kernel) is cov.Pre:
self.usingDefaultMean = False
def setOptimizer(self, method, num_restarts=None, min_threshold=None, meanRange=None, covRange=None, likRange=None):
pass
def optimize40(self, x=None, y=None, numIterations=40):
if x is not None and y is not None:
assert x.shape[0] == y.shape[0], "number of inputs and labels does not match"
if not x is None:
if x.ndim == 1:
x = np.reshape(x, (x.shape[0],1))
self.x = x
if not y is None:
if y.ndim == 1:
y = np.reshape(y, (y.shape[0],1))
self.y = y
if self.usingDefaultMean and self.meanfunc is None:
c = np.mean(y)
self.meanfunc = mean.Const(c)
optimalHyp, optimalNlZ = self.optimizer.findMin(self.x, self.y, numIters = numIterations)
self.nlZ = optimalNlZ
self.optimizer._apply_in_objects(optimalHyp)
self.getPosterior()
def optimize(self, x=None, y=None, numIterations=1000):
if x is not None and y is not None:
assert x.shape[0] == y.shape[0], "number of inputs and labels does not match"
if not x is None:
if x.ndim == 1:
x = np.reshape(x, (x.shape[0],1))
self.x = x
if not y is None:
if y.ndim == 1:
y = np.reshape(y, (y.shape[0],1))
self.y = y
if self.usingDefaultMean and self.meanfunc is None:
c = np.mean(y)
self.meanfunc = mean.Const(c)
optimalHyp, optimalNlZ = self.optimizer.findMin(self.x, self.y, numIters = numIterations)
self.nlZ = optimalNlZ
self.optimizer._apply_in_objects(optimalHyp)
self.getPosterior()
def getPosterior(self, x=None, y=None, der=True):
if x is not None and y is not None:
assert x.shape[0] == y.shape[0], "number of inputs and labels does not match"
if not x is None:
if x.ndim == 1:
x = np.reshape(x, (x.shape[0],1))
self.x = x
if not y is None:
if y.ndim == 1:
y = np.reshape(y, (y.shape[0],1))
self.y = y
if self.usingDefaultMean and self.meanfunc is None:
c = np.mean(y)
self.meanfunc = mean.Const(c)
if isinstance(self.likfunc, lik.Erf):
uy = unique(self.y)
ind = ( uy != 1 )
if any( uy[ind] != -1):
raise Exception('You attempt classification using labels different from {+1,-1}')
if not der:
post, nlZ = self.inffunc.evaluate(self.meanfunc, self.covfunc, self.likfunc, self.x, self.y, 2)
self.nlZ = nlZ
self.posterior = deepcopy(post)
return nlZ, post
else:
post, nlZ, dnlZ = self.inffunc.evaluate(self.meanfunc, self.covfunc, self.likfunc, self.x, self.y, 3)
self.nlZ = nlZ
self.dnlZ = deepcopy(dnlZ)
self.posterior = deepcopy(post)
return nlZ, dnlZ, post
def predict(self, xs, ys=None):
if xs.ndim == 1:
xs = np.reshape(xs, (xs.shape[0],1))
self.xs = xs
if not ys is None:
if ys.ndim == 1:
ys = np.reshape(ys, (ys.shape[0],1))
self.ys = ys
meanfunc = self.meanfunc
covfunc = self.covfunc
likfunc = self.likfunc
inffunc = self.inffunc
x = self.x
y = self.y
if self.posterior is None:
self.getPosterior()
alpha = self.posterior.alpha
L = self.posterior.L
sW = self.posterior.sW
nz = list(range(len(alpha[:,0])))
if len(L) == 0:
K = covfunc.getCovMatrix(x=x[nz,:], mode='train')
L = jitchol( (np.eye(len(nz)) + np.dot(sW,sW.T)*K).T )
Ltril = np.all( np.tril(L,-1) == 0 )
ns = xs.shape[0]
nperbatch = 1000
nact = 0
ymu = np.zeros((ns,1))
ys2 = np.zeros((ns,1))
fmu = np.zeros((ns,1))
fs2 = np.zeros((ns,1))
lp = np.zeros((ns,1))
while nact<=ns-1:
ids = list(range(nact,min(nact+nperbatch,ns)))
kss = covfunc.getCovMatrix(z=xs[ids,:], mode='self_test')
if isinstance(covfunc, FITCOfKernel):
Ks = covfunc.getCovMatrix(x=x, z=xs[ids,:], mode='cross')
Ks = Ks[nz,:]
else:
Ks = covfunc.getCovMatrix(x=x[nz,:], z=xs[ids,:], mode='cross')
ms = meanfunc.getMean(xs[ids,:])
N = (alpha.shape)[1]
Fmu = np.tile(ms,(1,N)) + np.dot(Ks.T,alpha[nz])
fmu[ids] = np.reshape(old_div(Fmu.sum(axis=1),N),(len(ids),1))
if Ltril:
V = np.linalg.solve(L.T,np.tile(sW,(1,len(ids)))*Ks)
fs2[ids] = kss - np.array([(V*V).sum(axis=0)]).T
else:
fs2[ids] = kss + np.array([(Ks*np.dot(L,Ks)).sum(axis=0)]).T
fs2[ids] = np.maximum(fs2[ids],0)
Fs2 = np.tile(fs2[ids],(1,N))
if ys is None:
Lp, Ymu, Ys2 = likfunc.evaluate(None,Fmu[:],Fs2[:],None,None,3)
else:
Lp, Ymu, Ys2 = likfunc.evaluate(np.tile(ys[ids],(1,N)), Fmu[:], Fs2[:],None,None,3)
lp[ids] = np.reshape( old_div(np.reshape(Lp,(np.prod(Lp.shape),N)).sum(axis=1),N) , (len(ids),1) )
ymu[ids] = np.reshape( old_div(np.reshape(Ymu,(np.prod(Ymu.shape),N)).sum(axis=1),N) ,(len(ids),1) )
ys2[ids] = np.reshape( old_div(np.reshape(Ys2,(np.prod(Ys2.shape),N)).sum(axis=1),N) , (len(ids),1) )
nact = ids[-1]+1
self.ym = ymu
self.ys2 = ys2
self.lp = lp
self.fm = fmu
self.fs2 = fs2
if ys is None:
return ymu, ys2, fmu, fs2, None
else:
return ymu, ys2, fmu, fs2, lp
def predict_with_posterior(self, post, xs, ys=None):
if xs.ndim == 1:
xs = np.reshape(xs, (xs.shape[0],1))
self.xs = xs
if not ys is None:
if ys.ndim == 1:
ys = np.reshape(ys, (ys.shape[0],1))
self.ys = ys
meanfunc = self.meanfunc
covfunc = self.covfunc
likfunc = self.likfunc
inffunc = self.inffunc
x = self.x
y = self.y
self.posterior = deepcopy(post)
alpha = post.alpha
L = post.L
sW = post.sW
nz = list(range(len(alpha[:,0])))
if len(L) == 0:
K = covfunc.getCovMatrix(x=x[nz,:], mode='train')
L = jitchol( (np.eye(len(nz)) + np.dot(sW,sW.T)*K).T )
Ltril = np.all( np.tril(L,-1) == 0 )
ns = xs.shape[0]
nperbatch = 1000
nact = 0
ymu = np.zeros((ns,1))
ys2 = np.zeros((ns,1))
fmu = np.zeros((ns,1))
fs2 = np.zeros((ns,1))
lp = np.zeros((ns,1))
while nact<=ns-1:
id = list(range(nact,min(nact+nperbatch,ns)))
kss = covfunc.getCovMatrix(z=xs[id,:], mode='self_test')
Ks = covfunc.getCovMatrix(x=x[nz,:], z=xs[id,:], mode='cross')
ms = meanfunc.getMean(xs[id,:])
N = (alpha.shape)[1]
Fmu = np.tile(ms,(1,N)) + np.dot(Ks.T,alpha[nz])
fmu[id] = np.reshape(old_div(Fmu.sum(axis=1),N),(len(id),1))
if Ltril:
V = np.linalg.solve(L.T,np.tile(sW,(1,len(id)))*Ks)
fs2[id] = kss - np.array([(V*V).sum(axis=0)]).T
else:
fs2[id] = kss + np.array([(Ks*np.dot(L,Ks)).sum(axis=0)]).T
fs2[id] = np.maximum(fs2[id],0)
Fs2 = np.tile(fs2[id],(1,N))
if ys is None:
[Lp, Ymu, Ys2] = likfunc.evaluate(None,Fmu[:],Fs2[:],None,None,3)
else:
[Lp, Ymu, Ys2] = likfunc.evaluate(np.tile(ys[id],(1,N)), Fmu[:], Fs2[:],None,None,3)
lp[id] = np.reshape( old_div(np.reshape(Lp,(np.prod(Lp.shape),N)).sum(axis=1),N) , (len(id),1) )
ymu[id] = np.reshape( old_div(np.reshape(Ymu,(np.prod(Ymu.shape),N)).sum(axis=1),N) ,(len(id),1) )
ys2[id] = np.reshape( old_div(np.reshape(Ys2,(np.prod(Ys2.shape),N)).sum(axis=1),N) , (len(id),1) )
nact = id[-1]+1
self.ym = ymu
self.ys2 = ys2
self.lp = lp
self.fm = fmu
self.fs2 = fs2
if ys is None:
return ymu, ys2, fmu, fs2, None
else:
return ymu, ys2, fmu, fs2, lp
class GPR(GP):
def __init__(self):
super(GPR, self).__init__()
self.meanfunc = mean.Zero()
self.covfunc = cov.RBF()
self.likfunc = lik.Gauss()
self.inffunc = inf.Exact()
self.optimizer = opt.Minimize(self)
def setNoise(self,log_sigma):
self.likfunc = lik.Gauss(log_sigma)
def setOptimizer(self, method, num_restarts=None, min_threshold=None, meanRange=None, covRange=None, likRange=None):
conf = None
if (num_restarts!=None) or (min_threshold!=None):
conf = pyGPs.Optimization.conf.random_init_conf(self.meanfunc,self.covfunc,self.likfunc)
conf.num_restarts = num_restarts
conf.min_threshold = min_threshold
if not meanRange is None:
conf.meanRange = meanRange
if not covRange is None:
conf.covRange = covRange
if not likRange is None:
conf.likRange = likRange
if method == "Minimize":
self.optimizer = opt.Minimize(self,conf)
elif method == "SCG":
self.optimizer = opt.SCG(self,conf)
elif method == "CG":
self.optimizer = opt.CG(self,conf)
elif method == "BFGS":
self.optimizer = opt.BFGS(self,conf)
elif method == "Nelder-Mead":
self.optimizer = opt.Simplex(self, conf)
else:
raise Exception('Optimization method is not set correctly in setOptimizer')
def plot(self,axisvals=None):
xs = self.xs
x = self.x
y = self.y
ym = self.ym
ys2 = self.ys2
plt.figure()
xss = np.reshape(xs,(xs.shape[0],))
ymm = np.reshape(ym,(ym.shape[0],))
ys22 = np.reshape(ys2,(ys2.shape[0],))
plt.plot(x, y, color=DATACOLOR, ls='None', marker='+',ms=12, mew=2)
plt.plot(xs, ym, color=MEANCOLOR, ls='-', lw=3.)
plt.fill_between(xss,ymm + 2.*np.sqrt(ys22), ymm - 2.*np.sqrt(ys22), facecolor=SHADEDCOLOR,linewidths=0.0)
plt.grid()
if not axisvals is None:
plt.axis(axisvals)
plt.xlabel('input x')
plt.ylabel('target y')
plt.show()
def useInference(self, newInf):
if newInf == "Laplace":
self.inffunc = inf.Laplace()
elif newInf == "EP":
self.inffunc = inf.EP()
else:
raise Exception('Possible inf values are "Laplace", "EP".')
def useLikelihood(self,newLik):
if newLik == "Laplace":
self.likfunc = lik.Laplace()
self.inffunc = inf.EP()
else:
raise Exception('Possible lik values are "Laplace".')
class GPC(GP):
def __init__(self):
super(GPC, self).__init__()
self.meanfunc = mean.Zero()
self.covfunc = cov.RBF()
self.likfunc = lik.Erf()
self.inffunc = inf.EP()
self.optimizer = opt.Minimize(self)
def setOptimizer(self, method, num_restarts=None, min_threshold=None, meanRange=None, covRange=None, likRange=None):
conf = None
if (num_restarts!=None) or (min_threshold!=None):
conf = pyGPs.Optimization.conf.random_init_conf(self.meanfunc,self.covfunc,self.likfunc)
conf.num_restarts = num_restarts
conf.min_threshold = min_threshold
if not meanRange is None:
conf.meanRange = meanRange
if not covRange is None:
conf.covRange = covRange
if not likRange is None:
conf.likRange = likRange
if method == "Minimize":
self.optimizer = opt.Minimize(self,conf)
elif method == "SCG":
self.optimizer = opt.SCG(self,conf)
elif method == "CG":
self.optimizer = opt.CG(self,conf)
elif method == "BFGS":
self.optimizer = opt.BFGS(self,conf)
def plot(self,x1,x2,t1,t2,axisvals=None):
fig = plt.figure()
plt.plot(x1[:,0], x1[:,1], 'b+', markersize = 12)
plt.plot(x2[:,0], x2[:,1], 'r+', markersize = 12)
pc = plt.contour(t1, t2, np.reshape(np.exp(self.lp), (t1.shape[0],t1.shape[1]) ))
fig.colorbar(pc)
plt.grid()
if not axisvals is None:
plt.axis(axisvals)
plt.show()
def useInference(self, newInf):
if newInf == "Laplace":
self.inffunc = inf.Laplace()
else:
raise Exception('Possible inf values are "Laplace".')
def useLikelihood(self,newLik):
if newLik == "Logistic":
raise Exception("Logistic likelihood is currently not implemented.")
else:
raise Exception('Possible lik values are "Logistic".')
class GPMC(object):
def __init__(self, n_class):
self.meanfunc = mean.Zero()
self.covfunc = cov.RBF()
self.n_class = n_class
self.x_all = None
self.y_all = None
self.newInf = None
self.newLik = None
self.newPrior = False
def setPrior(self, mean=None, kernel=None):
if not mean is None:
assert isinstance(mean, pyGPs.mean.Mean), "mean function is not an instance of pyGPs.mean.Mean"
self.meanfunc = mean
self.usingDefaultMean = False
if not kernel is None:
assert isinstance(kernel, pyGPs.cov.Kernel), "cov function is not an instance of pyGPs.cov.Kernel"
self.covfunc = kernel
if type(kernel) is cov.Pre:
self.usingDefaultMean = False
self.newPrior = True
def useInference(self, newInf):
if newInf == "Laplace":
self.inffunc = inf.Laplace()
else:
raise Exception('Possible inf values are "Laplace".')
def useLikelihood(self,newLik):
if newLik == "Logistic":
raise Exception("Logistic likelihood is currently not implemented.")
else:
raise Exception('Possible lik values are "Logistic".')
def setData(self,x,y):
assert x.shape[0] == y.shape[0], "number of inputs and labels does not match"
if x.ndim == 1:
x = np.reshape(x, (x.shape[0],1))
if y.ndim == 1:
y = np.reshape(y, (y.shape[0],1))
self.x_all = x
self.y_all = y
def fitAndPredict(self, xs):
if xs.ndim == 1:
xs = np.reshape(xs, (xs.shape[0],1))
predictive_vote = np.zeros((xs.shape[0],self.n_class))
for i in range(self.n_class):
for j in range(i+1,self.n_class):
x,y = self.createBinaryClass(i,j)
model = GPC()
if self.newPrior:
model.setPrior(mean=self.meanfunc, kernel=self.covfunc)
if self.newInf:
model.useInference(self.newInf)
if self.newLik:
model.useLikelihood(self.newLik)
model.getPosterior(x,y)
ym = model.predict(xs)[0]
ym += 1
vote_i = np.zeros((xs.shape[0],self.n_class))
vote_j = np.zeros((xs.shape[0],self.n_class))
vote_i[:,i:i+1] = ym
vote_j[:,j:j+1] = 2-ym
predictive_vote += vote_i
predictive_vote += vote_j
predictive_vote /= predictive_vote.sum(axis=1)[:,np.newaxis]
return predictive_vote
def optimizeAndPredict(self, xs):
if xs.ndim == 1:
xs = np.reshape(xs, (xs.shape[0],1))
predictive_vote = np.zeros((xs.shape[0],self.n_class))
for i in range(self.n_class):
for j in range(i+1,self.n_class):
x,y = self.createBinaryClass(i,j)
model = GPC()
if self.newPrior:
model.setPrior(mean=self.meanfunc, kernel=self.covfunc)
if self.newInf:
model.useInference(self.newInf)
if self.newLik:
model.useLikelihood(self.newLik)
model.optimize(x,y)
ym = model.predict(xs)[0]
ym += 1
vote_i = np.zeros((xs.shape[0],self.n_class))
vote_j = np.zeros((xs.shape[0],self.n_class))
vote_i[:,i:i+1] = ym
vote_j[:,j:j+1] = 2-ym
predictive_vote += vote_i
predictive_vote += vote_j
predictive_vote /= predictive_vote.sum(axis=1)[:,np.newaxis]
return predictive_vote
def createBinaryClass(self, i,j):
class_i = []
class_j = []
for index in range(len(self.y_all)):
target = self.y_all[index]
if target == i:
class_i.append(index)
elif target == j:
class_j.append(index)
n1 = len(class_i)
n2 = len(class_j)
class_i.extend(class_j)
x = self.x_all[class_i,:]
y = np.concatenate((np.ones((1,n1)),-np.ones((1,n2))),axis=1).T
return x,y
class GP_FITC(GP):
def __init__(self):
super(GP_FITC, self).__init__()
self.u = None
def setData(self, x, y, value_per_axis=5):
assert x.shape[0] == y.shape[0], "number of inputs and labels does not match"
if x.ndim == 1:
x = np.reshape(x, (x.shape[0],1))
if y.ndim == 1:
y = np.reshape(y, (y.shape[0],1))
self.x = x
self.y = y
if self.usingDefaultMean:
c = np.mean(y)
self.meanfunc = mean.Const(c)
gridAxis=[]
for d in range(x.shape[1]):
column = x[:,d]
mini = np.min(column)
maxi = np.max(column)
axis = np.linspace(mini,maxi,value_per_axis)
gridAxis.append(axis)
if self.u is None:
self.u = np.array(list(itertools.product(*gridAxis)))
self.covfunc = self.covfunc.fitc(self.u)
def setPrior(self, mean=None, kernel=None, inducing_points=None):
if not kernel is None:
if not inducing_points is None:
self.covfunc = kernel.fitc(inducing_points)
self.u = inducing_points
else:
if not self.u is None:
self.covfunc = kernel.fitc(self.u)
else:
raise Exception("To use default inducing points, please call setData() first!")
if type(kernel) is cov.Pre:
self.usingDefaultMean = False
if not mean is None:
self.meanfunc = mean
self.usingDefaultMean = False
class GPR_FITC(GP_FITC):
def __init__(self):
super(GPR_FITC, self).__init__()
self.meanfunc = mean.Zero()
self.covfunc = cov.RBF()
self.likfunc = lik.Gauss()
self.inffunc = inf.FITC_Exact()
self.optimizer = opt.Minimize(self)
self.u = None
def setNoise(self,log_sigma):
self.likfunc = lik.Gauss(log_sigma)
def setOptimizer(self, method, num_restarts=None, min_threshold=None, meanRange=None, covRange=None, likRange=None):
conf = None
if (num_restarts!=None) or (min_threshold!=None):
conf = pyGPs.Optimization.conf.random_init_conf(self.meanfunc,self.covfunc,self.likfunc)
conf.num_restarts = num_restarts
conf.min_threshold = min_threshold
if not meanRange is None:
conf.meanRange = meanRange
if not covRange is None:
conf.covRange = covRange
if not likRange is None:
conf.likRange = likRange
if method == "Minimize":
self.optimizer = opt.Minimize(self,conf)
elif method == "SCG":
self.optimizer = opt.SCG(self,conf)
elif method == "CG":
self.optimizer = opt.CG(self,conf)
elif method == "BFGS":
self.optimizer = opt.BFGS(self,conf)
def plot(self,axisvals=None):
plt.figure()
xss = np.reshape(self.xs,(self.xs.shape[0],))
ymm = np.reshape(self.ym,(self.ym.shape[0],))
ys22 = np.reshape(self.ys2,(self.ys2.shape[0],))
plt.plot(self.x, self.y, color=DATACOLOR, ls='None', marker='+',ms=12, mew=2)
plt.plot(self.xs, self.ym, color=MEANCOLOR, ls='-', lw=3.)
plt.fill_between(xss,ymm + 2.*np.sqrt(ys22), ymm - 2.*np.sqrt(ys22), facecolor=SHADEDCOLOR,linewidths=0.0)
plt.grid()
if not axisvals is None:
plt.axis(axisvals)
plt.xlabel('input x')
plt.ylabel('output y')
plt.plot(self.u,np.ones_like(self.u), ls='None', color='k',marker='x',markersize=12,mew=2)
plt.show()
def useInference(self, newInf):
if newInf == "Laplace":
self.inffunc = inf.FITC_Laplace()
elif newInf == "EP":
self.inffunc = inf.FITC_EP()
else:
raise Exception('Possible inf values are "Laplace", "EP".')
def useLikelihood(self,newLik):
if newLik == "Laplace":
self.likfunc = lik.Laplace()
self.inffunc = inf.FITC_EP()
else:
raise Exception('Possible lik values are "Laplace".')
class GPC_FITC(GP_FITC):
def __init__(self):
super(GPC_FITC, self).__init__()
self.meanfunc = mean.Zero()
self.covfunc = cov.RBF()
self.likfunc = lik.Erf()
self.inffunc = inf.FITC_EP()
self.optimizer = opt.Minimize(self)
self.u = None
def setOptimizer(self, method, num_restarts=None, min_threshold=None, meanRange=None, covRange=None, likRange=None):
conf = None
if (num_restarts!=None) or (min_threshold!=None):
conf = pyGPs.Optimization.conf.random_init_conf(self.meanfunc,self.covfunc,self.likfunc)
conf.num_restarts = num_restarts
conf.min_threshold = min_threshold
if not meanRange is None:
conf.meanRange = meanRange
if not covRange is None:
conf.covRange = covRange
if not likRange is None:
conf.likRange = likRange
if method == "Minimize":
self.optimizer = opt.Minimize(self,conf)
elif method == "SCG":
self.optimizer = opt.SCG(self,conf)
elif method == "CG":
self.optimizer = opt.CG(self,conf)
elif method == "BFGS":
self.optimizer = opt.BFGS(self,conf)
def plot(self,x1,x2,t1,t2,axisvals=None):
fig = plt.figure()
plt.plot(x1[:,0], x1[:,1], 'b+', markersize = 12)
plt.plot(x2[:,0], x2[:,1], 'r+', markersize = 12)
plt.plot(self.u[:,0],self.u[:,1],'ko', markersize=12)
pc = plt.contour(t1, t2, np.reshape(np.exp(self.lp), (t1.shape[0],t1.shape[1]) ))
fig.colorbar(pc)
plt.grid()
if not axisvals is None:
plt.axis(axisvals)
plt.show()
def useInference(self, newInf):
if newInf == "Laplace":
self.inffunc = inf.FITC_Laplace()
else:
raise Exception('Possible inf values are "Laplace".')
def useLikelihood(self,newLik):
if newLik == "Logistic":
raise Exception("Logistic likelihood is currently not implemented.")
else:
raise Exception('Possible lik values are "Logistic".')
| true | true |
f719d9b90696ca91133528a980477a87a5e8550f | 3,619 | py | Python | tfx/components/example_gen/custom_executors/parquet_executor.py | NikeNano/tfx | 8f7756f223e3bd3bd5abe37fa287010509cdae75 | [
"Apache-2.0"
] | null | null | null | tfx/components/example_gen/custom_executors/parquet_executor.py | NikeNano/tfx | 8f7756f223e3bd3bd5abe37fa287010509cdae75 | [
"Apache-2.0"
] | null | null | null | tfx/components/example_gen/custom_executors/parquet_executor.py | NikeNano/tfx | 8f7756f223e3bd3bd5abe37fa287010509cdae75 | [
"Apache-2.0"
] | null | null | null | # Lint as: python2, python3
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Parquet based TFX example gen executor."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from typing import Any, Dict, Text
from absl import logging
import apache_beam as beam
import tensorflow as tf
from tfx.components.example_gen import utils
from tfx.components.example_gen.base_example_gen_executor import BaseExampleGenExecutor
from tfx.types import standard_component_specs
@beam.ptransform_fn
@beam.typehints.with_input_types(beam.Pipeline)
@beam.typehints.with_output_types(tf.train.Example)
def _ParquetToExample( # pylint: disable=invalid-name
pipeline: beam.Pipeline, exec_properties: Dict[Text, Any],
split_pattern: Text) -> beam.pvalue.PCollection:
"""Read Parquet files and transform to TF examples.
Note that each input split will be transformed by this function separately.
Args:
pipeline: beam pipeline.
exec_properties: A dict of execution properties.
- input_base: input dir that contains Parquet data.
split_pattern: Split.pattern in Input config, glob relative file pattern
that maps to input files with root directory given by input_base.
Returns:
PCollection of TF examples.
"""
input_base_uri = exec_properties[standard_component_specs.INPUT_BASE_KEY]
parquet_pattern = os.path.join(input_base_uri, split_pattern)
logging.info('Processing input parquet data %s to TFExample.',
parquet_pattern)
return (pipeline
# TODO(jyzhao): support per column read by input_config.
| 'ReadFromParquet' >> beam.io.ReadFromParquet(parquet_pattern)
| 'ToTFExample' >> beam.Map(utils.dict_to_example))
class Executor(BaseExampleGenExecutor):
"""TFX example gen executor for processing parquet format.
Data type conversion:
integer types will be converted to tf.train.Feature with tf.train.Int64List.
float types will be converted to tf.train.Feature with tf.train.FloatList.
string types will be converted to tf.train.Feature with tf.train.BytesList
and utf-8 encoding.
Note that,
Single value will be converted to a list of that single value.
Missing value will be converted to empty tf.train.Feature().
Parquet data might lose precision, e.g., int96.
For details, check the dict_to_example function in example_gen.utils.
Example usage:
from tfx.components.base import executor_spec
from tfx.components.example_gen.component import
FileBasedExampleGen
from tfx.components.example_gen.custom_executors import
parquet_executor
from tfx.utils.dsl_utils import external_input
example_gen = FileBasedExampleGen(
input=external_input(parquet_dir_path),
custom_executor_spec=executor_spec.ExecutorClassSpec(
parquet_executor.Executor))
"""
def GetInputSourceToExamplePTransform(self) -> beam.PTransform:
"""Returns PTransform for parquet to TF examples."""
return _ParquetToExample
| 36.928571 | 87 | 0.762089 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from typing import Any, Dict, Text
from absl import logging
import apache_beam as beam
import tensorflow as tf
from tfx.components.example_gen import utils
from tfx.components.example_gen.base_example_gen_executor import BaseExampleGenExecutor
from tfx.types import standard_component_specs
@beam.ptransform_fn
@beam.typehints.with_input_types(beam.Pipeline)
@beam.typehints.with_output_types(tf.train.Example)
def _ParquetToExample(
pipeline: beam.Pipeline, exec_properties: Dict[Text, Any],
split_pattern: Text) -> beam.pvalue.PCollection:
input_base_uri = exec_properties[standard_component_specs.INPUT_BASE_KEY]
parquet_pattern = os.path.join(input_base_uri, split_pattern)
logging.info('Processing input parquet data %s to TFExample.',
parquet_pattern)
return (pipeline
| 'ReadFromParquet' >> beam.io.ReadFromParquet(parquet_pattern)
| 'ToTFExample' >> beam.Map(utils.dict_to_example))
class Executor(BaseExampleGenExecutor):
def GetInputSourceToExamplePTransform(self) -> beam.PTransform:
return _ParquetToExample
| true | true |
f719dc710e799dfa2967b8713a4d68b60594d1ec | 8,170 | py | Python | Tests/compat/sbs_builtin.py | dsonbill/IronPython3-NETCore | 8c76bdbec1754233f04b41ecd28e9bae2c862fd0 | [
"Apache-2.0"
] | 2 | 2019-09-21T22:22:30.000Z | 2020-05-09T12:45:51.000Z | Tests/compat/sbs_builtin.py | dsonbill/IronPython3-NETCore | 8c76bdbec1754233f04b41ecd28e9bae2c862fd0 | [
"Apache-2.0"
] | null | null | null | Tests/compat/sbs_builtin.py | dsonbill/IronPython3-NETCore | 8c76bdbec1754233f04b41ecd28e9bae2c862fd0 | [
"Apache-2.0"
] | null | null | null | #####################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of this distribution. If
# you cannot locate the Apache License, Version 2.0, please send an email to
# ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
# by the terms of the Apache License, Version 2.0.
#
# You must not remove this notice, or any other, from this software.
#
#
#####################################################################################
from common import *
import testdata
import sys
def complex_case_repr(*args):
ret = "complex with "
for x in args:
ret += "'%s (%s)'" % (str(x), type(x))
return ret
class test_builtin(object):
''' test built-in type, etc '''
def test_slice(self):
''' currently mainly test
del list[slice]
'''
test_str = testdata.long_string
str_len = len(test_str)
choices = ['', 0]
numbers = [1, 2, 3, str_len/2-1, str_len/2, str_len/2+1, str_len-3, str_len-2, str_len-1, str_len, str_len+1, str_len+2, str_len+3, str_len*2]
numbers = numbers[::3] # Temporary approach to speed things up...
choices.extend(numbers)
choices.extend([-1 * x for x in numbers])
for x in choices:
for y in choices:
for z in choices:
if z == 0: continue
line = "l = list(test_str); del l[%s:%s:%s]" % (str(x), str(y), str(z))
exec(line)
printwith("case", "del l[%s:%s:%s]" % (str(x), str(y), str(z)))
printwith("same", eval("l"), eval("len(l)"))
def test_xrange(self):
''' test xrange with corner cases'''
import sys
maxint = sys.maxsize
numbers = [1, 2, maxint/2, maxint-1, maxint, maxint+1, maxint+2]
choices = [0]
choices.extend(numbers)
choices.extend([-1 * x for x in numbers])
for x in choices:
for y in choices:
for z in choices:
line = "xrange(%s, %s, %s)" % (str(x), str(y), str(z))
printwith("case", line)
try:
xr = eval(line)
xl = len(xr)
cnt = 0
first = last = first2 = last2 = "n/a"
# testing XRangeIterator
if xl < 10:
for x in xr:
if cnt == 0: first = x
if cnt == xl -1 : last = x
cnt += 1
# testing this[index]
if xl == 0: first2 = xr[0]
if xl > 1 : first2, last2 = xr[0], xr[xl - 1]
printwith("same", xr, xl, first, last, first2, last2)
except:
printwith("same", sys.exc_info()[0])
def test_complex_ctor_str(self):
l = [ "-1", "0", "1", "+1", "+1.1", "-1.01", "-.101", ".234", "-1.3e3", "1.09e-3", "33.2e+10"] #, " ", ""] #http://ironpython.codeplex.com/workitem/28385
for s in l:
try:
printwith("case", complex_case_repr(s))
c = complex(s)
printwithtype(c)
except:
printwith("same", sys.exc_info()[0], sys.exc_info()[1])
s += "j"
try:
printwith("case", complex_case_repr(s))
c = complex(s)
printwithtype(c)
except:
printwith("same", sys.exc_info()[0], sys.exc_info()[1])
for s1 in l:
for s2 in l:
try:
if s2.startswith("+") or s2.startswith("-"):
s = "%s%sJ" % (s1, s2)
else:
s = "%s+%sj" % (s1, s2)
printwith("case", complex_case_repr(s))
c = complex(s)
printwithtype(c)
except:
printwith("same", sys.exc_info()[0], sys.exc_info()[1])
def test_complex_ctor(self):
# None is not included due to defaultvalue issue
ln = [-1, 1, 1.5, 1.5e+5, 1+2j, -1-9.3j ]
ls = ["1", "1L", "-1.5", "1.5e+5", "-34-2j"]
la = []
la.extend(ln)
la.extend(ls)
for s in la:
try:
printwith("case", complex_case_repr(s))
c = complex(s)
printwithtype(c)
except:
printwith("same", sys.exc_info()[0], sys.exc_info()[1])
for s in la:
try:
printwith("case", "real only", complex_case_repr(s))
c = complex(real=s)
printwithtype(c)
except:
printwith("same", sys.exc_info()[0], sys.exc_info()[1])
for s in la:
try:
printwith("case", "imag only", complex_case_repr(s))
c = complex(imag=s)
printwithtype(c)
except:
printwith("same", sys.exc_info()[0], sys.exc_info()[1])
for s1 in la:
for s2 in ln:
try:
printwith("case", complex_case_repr(s1, s2))
c = complex(s1, s2)
printwithtype(c)
except:
printwith("same", sys.exc_info()[0], sys.exc_info()[1])
def test_bigint(self):
s = '1234567890'
for x in range(10): s += str(x) * x
s = s * 10
l = [7, 1001, 5.89, True]
for start in range(1, 50, 7):
startx = start
for length in [1, 20, 50, 60, 100]:
startx += 1
l.append(int(s[startx:startx + length]))
for x in l:
for y in l:
print(x, y)
printwith('case', '%s, %s' % (x, y))
printwith('same', x+y)
printwith('same', x-y)
printwith('same', x*y)
if y:
printwith('same', x/y)
t = divmod(x, y)
printwithtype(t[0])
printwithtype(t[1])
l.remove(5.89)
l.remove(True) #
for a in range(1, 100, 7):
for x in l:
for y in l:
if x and y:
printwith('case', a, x, y)
printwith('same', pow(a, x, y))
def test_file_mode(self):
disabled_modes = ['Ut+', 'rUt+', 'Urt+']
disabled_modes += ['Ut', 'U+t', 'rUt', 'rU+t', 'Urt', 'Ur+t'] #http://ironpython.codeplex.com/workitem/28386
arw = ['', 'a', 'r', 'w', 'U', 'rU', 'Ur', 'wU', 'Uw', 'Ua', 'aU']
bt = ['', 'b', 't']
plus = ['', '+']
modes = []
for x in arw:
for y in bt:
for z in plus:
modes.append(x + y + z)
for y in plus:
for z in bt:
modes.append(x + y + z)
modes = [x for x in modes if x not in disabled_modes]
filename = 'tempfile.txt'
for m in modes:
printwith('case', m)
try:
f = file(filename, m)
s = str(f)
atPos = s.find('at')
printwith('same', s[:atPos])
f.close()
except:
printwith("same", 'throw')
runtests(test_builtin) | 35.991189 | 161 | 0.408813 | true | true | |
f719dc95d1f1ad1b119e769f41c66e49e76fe5d2 | 695 | py | Python | abastece/migrations/0006_auto_20210531_1145.py | lembon/atizar | 579ef6212e9b2582beb86c5e14339b0615ec16ee | [
"Apache-2.0"
] | null | null | null | abastece/migrations/0006_auto_20210531_1145.py | lembon/atizar | 579ef6212e9b2582beb86c5e14339b0615ec16ee | [
"Apache-2.0"
] | null | null | null | abastece/migrations/0006_auto_20210531_1145.py | lembon/atizar | 579ef6212e9b2582beb86c5e14339b0615ec16ee | [
"Apache-2.0"
] | null | null | null | # Generated by Django 3.1.2 on 2021-05-31 14:45
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('abastece', '0005_auto_20210528_1946'),
]
operations = [
migrations.AlterField(
model_name='pedido',
name='timestamp',
field=models.DateTimeField(default=datetime.datetime(2021, 5, 31, 11, 45, 20, 503212), editable=False,
verbose_name='fecha y hora'),
),
migrations.AlterField(
model_name='producto',
name='titulo',
field=models.CharField(max_length=200),
),
]
| 26.730769 | 114 | 0.574101 |
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('abastece', '0005_auto_20210528_1946'),
]
operations = [
migrations.AlterField(
model_name='pedido',
name='timestamp',
field=models.DateTimeField(default=datetime.datetime(2021, 5, 31, 11, 45, 20, 503212), editable=False,
verbose_name='fecha y hora'),
),
migrations.AlterField(
model_name='producto',
name='titulo',
field=models.CharField(max_length=200),
),
]
| true | true |
f719dd4e36211e0181b4b0387c2d5462aad335b3 | 1,305 | py | Python | lib/surface/meta/apis/collections/describe.py | bopopescu/Google-Cloud-SDK-1 | c4683bacb2f6192d8a816932e438a0493085469b | [
"Apache-2.0"
] | null | null | null | lib/surface/meta/apis/collections/describe.py | bopopescu/Google-Cloud-SDK-1 | c4683bacb2f6192d8a816932e438a0493085469b | [
"Apache-2.0"
] | null | null | null | lib/surface/meta/apis/collections/describe.py | bopopescu/Google-Cloud-SDK-1 | c4683bacb2f6192d8a816932e438a0493085469b | [
"Apache-2.0"
] | 1 | 2020-07-24T20:13:29.000Z | 2020-07-24T20:13:29.000Z | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A command that describes a resource collection for a given API."""
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.meta.apis import flags
from googlecloudsdk.command_lib.util.apis import registry
class Describe(base.DescribeCommand):
"""Describe the details of a collection for an API."""
@staticmethod
def Args(parser):
flags.API_VERSION_FLAG.AddToParser(parser)
parser.add_argument(
'collection',
completer=flags.CollectionCompleter,
help='The name of the collection to get the details of.')
def Run(self, args):
return registry.GetAPICollection(args.collection,
api_version=args.api_version)
| 36.25 | 74 | 0.738697 |
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.meta.apis import flags
from googlecloudsdk.command_lib.util.apis import registry
class Describe(base.DescribeCommand):
@staticmethod
def Args(parser):
flags.API_VERSION_FLAG.AddToParser(parser)
parser.add_argument(
'collection',
completer=flags.CollectionCompleter,
help='The name of the collection to get the details of.')
def Run(self, args):
return registry.GetAPICollection(args.collection,
api_version=args.api_version)
| true | true |
f719df2ec061fcd0ec591c84a3ef60c4759b669f | 3,398 | py | Python | tests/data_generation/animate_berlin_y_stretch.py | Algomorph/NeuralTracking | 6312be8e18828344c65e25a423c239efcd3428dd | [
"Apache-2.0"
] | 3 | 2021-04-18T04:23:08.000Z | 2022-02-01T08:37:51.000Z | tests/data_generation/animate_berlin_y_stretch.py | Algomorph/NeuralTracking | 6312be8e18828344c65e25a423c239efcd3428dd | [
"Apache-2.0"
] | 24 | 2021-05-28T21:59:11.000Z | 2022-02-03T16:09:41.000Z | tests/data_generation/animate_berlin_y_stretch.py | Algomorph/NeuralTracking | 6312be8e18828344c65e25a423c239efcd3428dd | [
"Apache-2.0"
] | 5 | 2021-03-10T02:56:16.000Z | 2021-12-14T06:04:50.000Z | import sys
import os
import shutil
import cv2
import open3d as o3d
import open3d.core as o3c
import numpy as np
from rendering.pytorch3d_renderer import PyTorch3DRenderer
from data import StandaloneFrameDataset
import data.presets as presets
import tsdf.default_voxel_grid
import data.camera
from settings import process_arguments, PathParameters, DeformNetParameters
PROGRAM_EXIT_SUCCESS = 0
def main():
process_arguments()
frame_dataset: StandaloneFrameDataset = presets.StandaloneFramePreset.BERLIN_0.value
device = o3c.Device("cuda:0")
volume: o3d.t = tsdf.default_voxel_grid.make_default_tsdf_voxel_grid(device)
depth_image = frame_dataset.load_depth_image_open3d(device)
color_image = frame_dataset.load_color_image_open3d(device)
intrinsics_open3d_cpu, _ = data.camera.load_open3d_intrinsics_from_text_4x4_matrix_and_image(frame_dataset.get_intrinsics_path(),
frame_dataset.get_depth_image_path())
intrinsics_open3d_cuda = o3d.core.Tensor(intrinsics_open3d_cpu.intrinsic_matrix, o3d.core.Dtype.Float32, device)
extrinsics_open3d_cuda = o3d.core.Tensor.eye(4, o3d.core.Dtype.Float32, device)
volume.integrate(depth_image, color_image, intrinsics_open3d_cuda, extrinsics_open3d_cuda, DeformNetParameters.depth_scale.value, 3.0)
original_mesh: o3d.geometry.TriangleMesh = volume.extract_surface_mesh(-1, 0).to_legacy_triangle_mesh()
renderer = PyTorch3DRenderer((depth_image.rows, depth_image.columns), device, intrinsics_open3d_cuda)
frame_count = 6
scale_factor_increment = 0.1
scale_center = np.array([0.0855289, -0.03289237, 2.79831315], dtype=np.float32)
def scale_mesh_y(mesh: o3d.geometry.TriangleMesh, factor: float) -> o3d.geometry.TriangleMesh:
vertices = np.array(mesh.vertices)
stretched_vertices = vertices - scale_center
stretched_vertices[:, 1] *= factor
stretched_vertices += scale_center
_scaled_mesh = o3d.geometry.TriangleMesh(o3d.cuda.pybind.utility.Vector3dVector(stretched_vertices), mesh.triangles)
_scaled_mesh.vertex_colors = mesh.vertex_colors
return _scaled_mesh
# prepare folders
root_output_directory = os.path.join(PathParameters.output_directory.value, "berlin_y_stretch_sequence")
depth_output_directory = os.path.join(root_output_directory, "depth")
if not os.path.exists(depth_output_directory):
os.makedirs(depth_output_directory)
color_output_directory = os.path.join(root_output_directory, "color")
if not os.path.exists(color_output_directory):
os.makedirs(color_output_directory)
# record animation rendering output
for i_frame in range(0, frame_count):
scaled_mesh = scale_mesh_y(original_mesh, 1.0 + scale_factor_increment * i_frame)
depth, color = renderer.render_mesh_legacy(scaled_mesh, depth_scale=1000.0)
color_path = os.path.join(color_output_directory, f"{i_frame:06d}.jpg")
depth_path = os.path.join(depth_output_directory, f"{i_frame:06d}.png")
cv2.imwrite(color_path, color)
cv2.imwrite(depth_path, depth.astype(np.uint16))
shutil.copy(frame_dataset.get_intrinsics_path(), os.path.join(root_output_directory, "intrinsics.txt"))
return PROGRAM_EXIT_SUCCESS
if __name__ == "__main__":
sys.exit(main())
| 43.564103 | 138 | 0.751619 | import sys
import os
import shutil
import cv2
import open3d as o3d
import open3d.core as o3c
import numpy as np
from rendering.pytorch3d_renderer import PyTorch3DRenderer
from data import StandaloneFrameDataset
import data.presets as presets
import tsdf.default_voxel_grid
import data.camera
from settings import process_arguments, PathParameters, DeformNetParameters
PROGRAM_EXIT_SUCCESS = 0
def main():
process_arguments()
frame_dataset: StandaloneFrameDataset = presets.StandaloneFramePreset.BERLIN_0.value
device = o3c.Device("cuda:0")
volume: o3d.t = tsdf.default_voxel_grid.make_default_tsdf_voxel_grid(device)
depth_image = frame_dataset.load_depth_image_open3d(device)
color_image = frame_dataset.load_color_image_open3d(device)
intrinsics_open3d_cpu, _ = data.camera.load_open3d_intrinsics_from_text_4x4_matrix_and_image(frame_dataset.get_intrinsics_path(),
frame_dataset.get_depth_image_path())
intrinsics_open3d_cuda = o3d.core.Tensor(intrinsics_open3d_cpu.intrinsic_matrix, o3d.core.Dtype.Float32, device)
extrinsics_open3d_cuda = o3d.core.Tensor.eye(4, o3d.core.Dtype.Float32, device)
volume.integrate(depth_image, color_image, intrinsics_open3d_cuda, extrinsics_open3d_cuda, DeformNetParameters.depth_scale.value, 3.0)
original_mesh: o3d.geometry.TriangleMesh = volume.extract_surface_mesh(-1, 0).to_legacy_triangle_mesh()
renderer = PyTorch3DRenderer((depth_image.rows, depth_image.columns), device, intrinsics_open3d_cuda)
frame_count = 6
scale_factor_increment = 0.1
scale_center = np.array([0.0855289, -0.03289237, 2.79831315], dtype=np.float32)
def scale_mesh_y(mesh: o3d.geometry.TriangleMesh, factor: float) -> o3d.geometry.TriangleMesh:
vertices = np.array(mesh.vertices)
stretched_vertices = vertices - scale_center
stretched_vertices[:, 1] *= factor
stretched_vertices += scale_center
_scaled_mesh = o3d.geometry.TriangleMesh(o3d.cuda.pybind.utility.Vector3dVector(stretched_vertices), mesh.triangles)
_scaled_mesh.vertex_colors = mesh.vertex_colors
return _scaled_mesh
root_output_directory = os.path.join(PathParameters.output_directory.value, "berlin_y_stretch_sequence")
depth_output_directory = os.path.join(root_output_directory, "depth")
if not os.path.exists(depth_output_directory):
os.makedirs(depth_output_directory)
color_output_directory = os.path.join(root_output_directory, "color")
if not os.path.exists(color_output_directory):
os.makedirs(color_output_directory)
for i_frame in range(0, frame_count):
scaled_mesh = scale_mesh_y(original_mesh, 1.0 + scale_factor_increment * i_frame)
depth, color = renderer.render_mesh_legacy(scaled_mesh, depth_scale=1000.0)
color_path = os.path.join(color_output_directory, f"{i_frame:06d}.jpg")
depth_path = os.path.join(depth_output_directory, f"{i_frame:06d}.png")
cv2.imwrite(color_path, color)
cv2.imwrite(depth_path, depth.astype(np.uint16))
shutil.copy(frame_dataset.get_intrinsics_path(), os.path.join(root_output_directory, "intrinsics.txt"))
return PROGRAM_EXIT_SUCCESS
if __name__ == "__main__":
sys.exit(main())
| true | true |
f719dfc68869c7b36d4086ce6861e839d17b9e4c | 338 | py | Python | src/utils.py | delbio/maze | cbc58ebb2c54f300f6413b770b57b0cab0750672 | [
"MIT"
] | null | null | null | src/utils.py | delbio/maze | cbc58ebb2c54f300f6413b770b57b0cab0750672 | [
"MIT"
] | null | null | null | src/utils.py | delbio/maze | cbc58ebb2c54f300f6413b770b57b0cab0750672 | [
"MIT"
] | null | null | null |
def rotate_counterclockwise(array_2d):
list_of_tuples = zip(*array_2d[::])
return [list(elem) for elem in list_of_tuples]
def rotate_clockwise(array_2d):
"""
Code copied by: https://stackoverflow.com/a/48444999/3753724
"""
list_of_tuples = zip(*array_2d[::-1])
return [list(elem) for elem in list_of_tuples]
| 28.166667 | 64 | 0.695266 |
def rotate_counterclockwise(array_2d):
list_of_tuples = zip(*array_2d[::])
return [list(elem) for elem in list_of_tuples]
def rotate_clockwise(array_2d):
list_of_tuples = zip(*array_2d[::-1])
return [list(elem) for elem in list_of_tuples]
| true | true |
f719e02577fb8babdf4f9190cb1e562309acb229 | 5,806 | py | Python | sdk/python/pulumi_alicloud/fc/get_triggers.py | pulumi/pulumi-alicloud | 9c34d84b4588a7c885c6bec1f03b5016e5a41683 | [
"ECL-2.0",
"Apache-2.0"
] | 42 | 2019-03-18T06:34:37.000Z | 2022-03-24T07:08:57.000Z | sdk/python/pulumi_alicloud/fc/get_triggers.py | pulumi/pulumi-alicloud | 9c34d84b4588a7c885c6bec1f03b5016e5a41683 | [
"ECL-2.0",
"Apache-2.0"
] | 152 | 2019-04-15T21:03:44.000Z | 2022-03-29T18:00:57.000Z | sdk/python/pulumi_alicloud/fc/get_triggers.py | pulumi/pulumi-alicloud | 9c34d84b4588a7c885c6bec1f03b5016e5a41683 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2020-08-26T17:30:07.000Z | 2021-07-05T01:37:45.000Z | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
__all__ = [
'GetTriggersResult',
'AwaitableGetTriggersResult',
'get_triggers',
]
@pulumi.output_type
class GetTriggersResult:
"""
A collection of values returned by getTriggers.
"""
def __init__(__self__, function_name=None, id=None, ids=None, name_regex=None, names=None, output_file=None, service_name=None, triggers=None):
if function_name and not isinstance(function_name, str):
raise TypeError("Expected argument 'function_name' to be a str")
pulumi.set(__self__, "function_name", function_name)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if ids and not isinstance(ids, list):
raise TypeError("Expected argument 'ids' to be a list")
pulumi.set(__self__, "ids", ids)
if name_regex and not isinstance(name_regex, str):
raise TypeError("Expected argument 'name_regex' to be a str")
pulumi.set(__self__, "name_regex", name_regex)
if names and not isinstance(names, list):
raise TypeError("Expected argument 'names' to be a list")
pulumi.set(__self__, "names", names)
if output_file and not isinstance(output_file, str):
raise TypeError("Expected argument 'output_file' to be a str")
pulumi.set(__self__, "output_file", output_file)
if service_name and not isinstance(service_name, str):
raise TypeError("Expected argument 'service_name' to be a str")
pulumi.set(__self__, "service_name", service_name)
if triggers and not isinstance(triggers, list):
raise TypeError("Expected argument 'triggers' to be a list")
pulumi.set(__self__, "triggers", triggers)
@property
@pulumi.getter(name="functionName")
def function_name(self) -> str:
return pulumi.get(self, "function_name")
@property
@pulumi.getter
def id(self) -> str:
"""
The provider-assigned unique ID for this managed resource.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def ids(self) -> Sequence[str]:
"""
A list of FC triggers ids.
"""
return pulumi.get(self, "ids")
@property
@pulumi.getter(name="nameRegex")
def name_regex(self) -> Optional[str]:
return pulumi.get(self, "name_regex")
@property
@pulumi.getter
def names(self) -> Sequence[str]:
"""
A list of FC triggers names.
"""
return pulumi.get(self, "names")
@property
@pulumi.getter(name="outputFile")
def output_file(self) -> Optional[str]:
return pulumi.get(self, "output_file")
@property
@pulumi.getter(name="serviceName")
def service_name(self) -> str:
return pulumi.get(self, "service_name")
@property
@pulumi.getter
def triggers(self) -> Sequence['outputs.GetTriggersTriggerResult']:
"""
A list of FC triggers. Each element contains the following attributes:
"""
return pulumi.get(self, "triggers")
class AwaitableGetTriggersResult(GetTriggersResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetTriggersResult(
function_name=self.function_name,
id=self.id,
ids=self.ids,
name_regex=self.name_regex,
names=self.names,
output_file=self.output_file,
service_name=self.service_name,
triggers=self.triggers)
def get_triggers(function_name: Optional[str] = None,
ids: Optional[Sequence[str]] = None,
name_regex: Optional[str] = None,
output_file: Optional[str] = None,
service_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTriggersResult:
"""
This data source provides the Function Compute triggers of the current Alibaba Cloud user.
## Example Usage
```python
import pulumi
import pulumi_alicloud as alicloud
fc_triggers_ds = alicloud.fc.get_triggers(function_name="sample_function",
name_regex="sample_fc_trigger",
service_name="sample_service")
pulumi.export("firstFcTriggerName", fc_triggers_ds.triggers[0].name)
```
:param str function_name: FC function name.
:param Sequence[str] ids: - A list of FC triggers ids.
:param str name_regex: A regex string to filter results by FC trigger name.
:param str service_name: FC service name.
"""
__args__ = dict()
__args__['functionName'] = function_name
__args__['ids'] = ids
__args__['nameRegex'] = name_regex
__args__['outputFile'] = output_file
__args__['serviceName'] = service_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('alicloud:fc/getTriggers:getTriggers', __args__, opts=opts, typ=GetTriggersResult).value
return AwaitableGetTriggersResult(
function_name=__ret__.function_name,
id=__ret__.id,
ids=__ret__.ids,
name_regex=__ret__.name_regex,
names=__ret__.names,
output_file=__ret__.output_file,
service_name=__ret__.service_name,
triggers=__ret__.triggers)
| 34.975904 | 147 | 0.650189 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
__all__ = [
'GetTriggersResult',
'AwaitableGetTriggersResult',
'get_triggers',
]
@pulumi.output_type
class GetTriggersResult:
def __init__(__self__, function_name=None, id=None, ids=None, name_regex=None, names=None, output_file=None, service_name=None, triggers=None):
if function_name and not isinstance(function_name, str):
raise TypeError("Expected argument 'function_name' to be a str")
pulumi.set(__self__, "function_name", function_name)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if ids and not isinstance(ids, list):
raise TypeError("Expected argument 'ids' to be a list")
pulumi.set(__self__, "ids", ids)
if name_regex and not isinstance(name_regex, str):
raise TypeError("Expected argument 'name_regex' to be a str")
pulumi.set(__self__, "name_regex", name_regex)
if names and not isinstance(names, list):
raise TypeError("Expected argument 'names' to be a list")
pulumi.set(__self__, "names", names)
if output_file and not isinstance(output_file, str):
raise TypeError("Expected argument 'output_file' to be a str")
pulumi.set(__self__, "output_file", output_file)
if service_name and not isinstance(service_name, str):
raise TypeError("Expected argument 'service_name' to be a str")
pulumi.set(__self__, "service_name", service_name)
if triggers and not isinstance(triggers, list):
raise TypeError("Expected argument 'triggers' to be a list")
pulumi.set(__self__, "triggers", triggers)
@property
@pulumi.getter(name="functionName")
def function_name(self) -> str:
return pulumi.get(self, "function_name")
@property
@pulumi.getter
def id(self) -> str:
return pulumi.get(self, "id")
@property
@pulumi.getter
def ids(self) -> Sequence[str]:
return pulumi.get(self, "ids")
@property
@pulumi.getter(name="nameRegex")
def name_regex(self) -> Optional[str]:
return pulumi.get(self, "name_regex")
@property
@pulumi.getter
def names(self) -> Sequence[str]:
return pulumi.get(self, "names")
@property
@pulumi.getter(name="outputFile")
def output_file(self) -> Optional[str]:
return pulumi.get(self, "output_file")
@property
@pulumi.getter(name="serviceName")
def service_name(self) -> str:
return pulumi.get(self, "service_name")
@property
@pulumi.getter
def triggers(self) -> Sequence['outputs.GetTriggersTriggerResult']:
return pulumi.get(self, "triggers")
class AwaitableGetTriggersResult(GetTriggersResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetTriggersResult(
function_name=self.function_name,
id=self.id,
ids=self.ids,
name_regex=self.name_regex,
names=self.names,
output_file=self.output_file,
service_name=self.service_name,
triggers=self.triggers)
def get_triggers(function_name: Optional[str] = None,
ids: Optional[Sequence[str]] = None,
name_regex: Optional[str] = None,
output_file: Optional[str] = None,
service_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTriggersResult:
__args__ = dict()
__args__['functionName'] = function_name
__args__['ids'] = ids
__args__['nameRegex'] = name_regex
__args__['outputFile'] = output_file
__args__['serviceName'] = service_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('alicloud:fc/getTriggers:getTriggers', __args__, opts=opts, typ=GetTriggersResult).value
return AwaitableGetTriggersResult(
function_name=__ret__.function_name,
id=__ret__.id,
ids=__ret__.ids,
name_regex=__ret__.name_regex,
names=__ret__.names,
output_file=__ret__.output_file,
service_name=__ret__.service_name,
triggers=__ret__.triggers)
| true | true |
f719e0a27fcf5d467cb187747490a3e0cc93edc0 | 2,159 | py | Python | py-games/first_game/part1.py | martanunesdea/cpp-shop-management | ed9371e8b5d6c5b3bdc31385158c747ea538046d | [
"MIT"
] | null | null | null | py-games/first_game/part1.py | martanunesdea/cpp-shop-management | ed9371e8b5d6c5b3bdc31385158c747ea538046d | [
"MIT"
] | null | null | null | py-games/first_game/part1.py | martanunesdea/cpp-shop-management | ed9371e8b5d6c5b3bdc31385158c747ea538046d | [
"MIT"
] | 1 | 2021-01-18T21:14:31.000Z | 2021-01-18T21:14:31.000Z | import pygame, sys
from pygame.locals import *
import random
#### GAME SETUP ######
pygame.init()
FPS = 60
FramePerSec = pygame.time.Clock()
# Defining game constants
RED = (255, 0, 0)
WHITE = (255, 255, 255)
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
GAME_NAME = "Dodge The Enemy"
SCORE = 0
# Creating the main surface
DISPLAYSURF = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
DISPLAYSURF.fill(WHITE)
pygame.display.set_caption(GAME_NAME)
# Create class interfaces
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("images/alien.png")
self.surf = pygame.Surface((100, 100))
self.rect = self.surf.get_rect(center = (random.randint(40, (SCREEN_WIDTH-40)),0))
def move(self):
self.rect.move_ip(0,5)
if (self.rect.bottom > 600):
self.rect.top = 0
self.rect.center = (random.randint(40, (SCREEN_WIDTH-40)), 0)
def draw(self, surface):
surface.blit(self.image, self.rect)
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__() # initilizing Sprite
self.image = pygame.image.load("images/rocket.png")
self.surf = pygame.Surface((100, 100))
self.rect = self.surf.get_rect(center = (250, 500))
def update(self):
pressed_keys = pygame.key.get_pressed()
if self.rect.left > 0:
if pressed_keys[K_LEFT]:
self.rect.move_ip(-5, 0)
if self.rect.right < SCREEN_WIDTH:
if pressed_keys[K_RIGHT]:
self.rect.move_ip(5, 0)
def draw(self, surface):
surface.blit(self.image, self.rect)
### GAME STARTUP #######
P1 = Player()
E1 = Enemy()
while True:
list_events = pygame.event.get()
for event in list_events:
if event.type == QUIT:
pygame.quit()
sys.exit()
# get physical updates
P1.update()
E1.move()
# update graphics
DISPLAYSURF.fill(WHITE)
P1.draw(DISPLAYSURF)
E1.draw(DISPLAYSURF)
pygame.display.update()
FramePerSec.tick(FPS) | 26.654321 | 95 | 0.610468 | import pygame, sys
from pygame.locals import *
import random
WHITE = (255, 255, 255)
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
GAME_NAME = "Dodge The Enemy"
SCORE = 0
DISPLAYSURF = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
DISPLAYSURF.fill(WHITE)
pygame.display.set_caption(GAME_NAME)
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("images/alien.png")
self.surf = pygame.Surface((100, 100))
self.rect = self.surf.get_rect(center = (random.randint(40, (SCREEN_WIDTH-40)),0))
def move(self):
self.rect.move_ip(0,5)
if (self.rect.bottom > 600):
self.rect.top = 0
self.rect.center = (random.randint(40, (SCREEN_WIDTH-40)), 0)
def draw(self, surface):
surface.blit(self.image, self.rect)
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("images/rocket.png")
self.surf = pygame.Surface((100, 100))
self.rect = self.surf.get_rect(center = (250, 500))
def update(self):
pressed_keys = pygame.key.get_pressed()
if self.rect.left > 0:
if pressed_keys[K_LEFT]:
self.rect.move_ip(-5, 0)
if self.rect.right < SCREEN_WIDTH:
if pressed_keys[K_RIGHT]:
self.rect.move_ip(5, 0)
def draw(self, surface):
surface.blit(self.image, self.rect)
ent.get()
for event in list_events:
if event.type == QUIT:
pygame.quit()
sys.exit()
P1.update()
E1.move()
DISPLAYSURF.fill(WHITE)
P1.draw(DISPLAYSURF)
E1.draw(DISPLAYSURF)
pygame.display.update()
FramePerSec.tick(FPS) | true | true |
f719e0a51e64125bb5ced9ad77431d75f5d0af9c | 2,550 | py | Python | new_model/test_big.py | aliabid2243/deepgaze | 8c602db89a1d1d8a644b44a381ddb8a693375e08 | [
"MIT"
] | 2 | 2019-02-24T15:03:19.000Z | 2019-07-29T09:06:33.000Z | new_model/test_big.py | aliabid2243/deepgaze | 8c602db89a1d1d8a644b44a381ddb8a693375e08 | [
"MIT"
] | null | null | null | new_model/test_big.py | aliabid2243/deepgaze | 8c602db89a1d1d8a644b44a381ddb8a693375e08 | [
"MIT"
] | null | null | null | import os
from load_data import load_batch, load_data_names, load_batch_from_names, load_batch_from_names_random
from my_model import get_eye_tracker_model
import numpy as np
from keras.models import load_model
from keras.optimizers import SGD, adam
def generator(data, batch_size, img_cols, img_rows, img_ch):
while True:
for it in list(range(0, data[0].shape[0], batch_size)):
x, y = load_batch([l[it:it + batch_size] for l in data], img_cols, img_rows, img_ch)
yield x, y
def test_big(args):
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = args.dev
names_path = r"C:\Users\Aliab\PycharmProjects\data\test"
print("Names to test: {}".format(names_path))
dataset_path = r"D:\GazeCapture"
print("Dataset: {}".format(names_path))
weights_path = "weight_vgg.hdf5"
print("Weights: {}".format(weights_path))
# image parameter
img_cols = 128
img_rows = 128
img_ch = 3
# test parameter
batch_size = 64
chunk_size = 500
# model
model = get_eye_tracker_model(img_cols, img_rows, img_ch)
# model summary
model.summary()
# weights
print("Loading weights...")
model = load_model(weights_path)
model.load_weights(weights_path)
# data
test_names = load_data_names(names_path)
# limit amount of testing data
# test_names = test_names[:1000]
# results
err_x = []
err_y = []
print("Loading testing data...")
for it in list(range(0, len(test_names), chunk_size)):
x, y = load_batch_from_names_random(test_names[it:it + chunk_size], dataset_path, batch_size, img_cols, img_rows, img_ch)
# x, y = load_batch_from_names(test_names[it:it + chunk_size], dataset_path, img_ch, img_cols, img_rows)
predictions = model.predict(x=x, batch_size=batch_size, verbose=1)
# print and analyze predictions
for i, prediction in enumerate(predictions):
print("PR: {} {}".format(prediction[0], prediction[1]))
print("GT: {} {} \n".format(y[i][0], y[i][1]))
err_x.append(abs(prediction[0] - y[i][0]))
err_y.append(abs(prediction[1] - y[i][1]))
# mean absolute error
mae_x = np.mean(err_x)
mae_y = np.mean(err_y)
# standard deviation
std_x = np.std(err_x)
std_y = np.std(err_y)
# final results
print("MAE: {} {} ( samples)".format(mae_x, mae_y))
print("STD: {} {} ( samples)".format(std_x, std_y))
if __name__ == '__main__':
test_big()
| 28.651685 | 130 | 0.65098 | import os
from load_data import load_batch, load_data_names, load_batch_from_names, load_batch_from_names_random
from my_model import get_eye_tracker_model
import numpy as np
from keras.models import load_model
from keras.optimizers import SGD, adam
def generator(data, batch_size, img_cols, img_rows, img_ch):
while True:
for it in list(range(0, data[0].shape[0], batch_size)):
x, y = load_batch([l[it:it + batch_size] for l in data], img_cols, img_rows, img_ch)
yield x, y
def test_big(args):
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = args.dev
names_path = r"C:\Users\Aliab\PycharmProjects\data\test"
print("Names to test: {}".format(names_path))
dataset_path = r"D:\GazeCapture"
print("Dataset: {}".format(names_path))
weights_path = "weight_vgg.hdf5"
print("Weights: {}".format(weights_path))
img_cols = 128
img_rows = 128
img_ch = 3
batch_size = 64
chunk_size = 500
model = get_eye_tracker_model(img_cols, img_rows, img_ch)
model.summary()
print("Loading weights...")
model = load_model(weights_path)
model.load_weights(weights_path)
test_names = load_data_names(names_path)
err_x = []
err_y = []
print("Loading testing data...")
for it in list(range(0, len(test_names), chunk_size)):
x, y = load_batch_from_names_random(test_names[it:it + chunk_size], dataset_path, batch_size, img_cols, img_rows, img_ch)
predictions = model.predict(x=x, batch_size=batch_size, verbose=1)
for i, prediction in enumerate(predictions):
print("PR: {} {}".format(prediction[0], prediction[1]))
print("GT: {} {} \n".format(y[i][0], y[i][1]))
err_x.append(abs(prediction[0] - y[i][0]))
err_y.append(abs(prediction[1] - y[i][1]))
mae_x = np.mean(err_x)
mae_y = np.mean(err_y)
std_x = np.std(err_x)
std_y = np.std(err_y)
print("MAE: {} {} ( samples)".format(mae_x, mae_y))
print("STD: {} {} ( samples)".format(std_x, std_y))
if __name__ == '__main__':
test_big()
| true | true |
f719e0c57fd4991be0a999dbdc1c3d13878ecbff | 9,695 | py | Python | src/collectors/diskspace/diskspace.py | smartattack/Diamond | 0559cb212559a852fce9a3cdb8643c1d129f41d4 | [
"MIT"
] | null | null | null | src/collectors/diskspace/diskspace.py | smartattack/Diamond | 0559cb212559a852fce9a3cdb8643c1d129f41d4 | [
"MIT"
] | 1 | 2022-02-22T08:46:21.000Z | 2022-02-22T12:56:05.000Z | src/collectors/diskspace/diskspace.py | hostedgraphite/Diamond | e70fe7d358897ef9082c8778fba288215788b3d5 | [
"MIT"
] | null | null | null | # coding=utf-8
"""
Uses /proc/mounts and os.statvfs() to get disk space usage
#### Dependencies
* /proc/mounts
#### Examples
# no exclude filters at all
exclude_filters =,
# exclude everything that begins /boot or /mnt
exclude_filters = ^/boot, ^/mnt
# exclude everything that includes the letter 'm'
exclude_filters = m,
"""
import diamond.collector
import diamond.convertor
import os
import re
try:
import psutil
except ImportError:
psutil = None
class DiskSpaceCollector(diamond.collector.Collector):
def get_default_config_help(self):
config_help = super(DiskSpaceCollector, self).get_default_config_help()
config_help.update({
'filesystems': "filesystems to examine",
'exclude_filters':
"A list of regex patterns. Any filesystem" +
" matching any of these patterns will be excluded from disk" +
" space metrics collection",
})
return config_help
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(DiskSpaceCollector, self).get_default_config()
config.update({
'path': 'diskspace',
# filesystems to examine
'filesystems': 'ext2, ext3, ext4, xfs, glusterfs, nfs, nfs4, ' +
' ntfs, hfs, fat32, fat16, btrfs',
# exclude_filters
# A list of regex patterns
# A filesystem matching any of these patterns will be excluded
# from disk space metrics collection.
#
# Examples:
# exclude_filters =,
# no exclude filters at all
# exclude_filters = ^/boot, ^/mnt
# exclude everything that begins /boot or /mnt
# exclude_filters = m,
# exclude everything that includes the letter "m"
'exclude_filters': ['^/export/home'],
# Default numeric output
'byte_unit': ['byte']
})
return config
def process_config(self):
super(DiskSpaceCollector, self).process_config()
# Precompile things
self.exclude_filters = self.config['exclude_filters']
if isinstance(self.exclude_filters, basestring):
self.exclude_filters = [self.exclude_filters]
if not self.exclude_filters:
self.exclude_reg = re.compile('!.*')
else:
self.exclude_reg = re.compile('|'.join(self.exclude_filters))
self.filesystems = []
if isinstance(self.config['filesystems'], basestring):
for filesystem in self.config['filesystems'].split(','):
self.filesystems.append(filesystem.strip())
elif isinstance(self.config['filesystems'], list):
self.filesystems = self.config['filesystems']
def get_disk_labels(self):
"""
Creates a mapping of device nodes to filesystem labels
"""
path = '/dev/disk/by-label/'
labels = {}
if not os.path.isdir(path):
return labels
for label in os.listdir(path):
label = label.replace('\\x2f', '/')
device = os.path.realpath(path + '/' + label)
labels[device] = label
return labels
def get_file_systems(self):
"""
Creates a map of mounted filesystems on the machine.
iostat(1): Each sector has size of 512 bytes.
Returns:
st_dev -> FileSystem(device, mount_point)
"""
result = {}
if os.access('/proc/mounts', os.R_OK):
file = open('/proc/mounts')
for line in file:
try:
mount = line.split()
device = mount[0]
mount_point = mount[1]
fs_type = mount[2]
except (IndexError, ValueError):
continue
# Skip the filesystem if it is not in the list of valid
# filesystems
if fs_type not in self.filesystems:
self.log.debug("Ignoring %s since it is of type %s " +
" which is not in the list of filesystems.",
mount_point, fs_type)
continue
# Process the filters
if self.exclude_reg.search(mount_point):
self.log.debug("Ignoring %s since it is in the " +
"exclude_filter list.", mount_point)
continue
if ((('/' in device or ':' in device or device == 'tmpfs') and
mount_point.startswith('/'))):
try:
stat = os.stat(mount_point)
except OSError:
self.log.debug("Path %s is not mounted - skipping.",
mount_point)
continue
if stat.st_dev in result:
continue
result[stat.st_dev] = {
'device': os.path.realpath(device),
'mount_point': mount_point,
'fs_type': fs_type
}
file.close()
else:
if not psutil:
self.log.error('Unable to import psutil')
return None
partitions = psutil.disk_partitions(False)
for partition in partitions:
result[len(result)] = {
'device': os.path.realpath(partition.device),
'mount_point': partition.mountpoint,
'fs_type': partition.fstype
}
pass
return result
def collect(self):
labels = self.get_disk_labels()
results = self.get_file_systems()
if not results:
self.log.error('No diskspace metrics retrieved')
return None
for info in results.itervalues():
if info['device'] in labels:
name = labels[info['device']]
else:
name = info['mount_point'].replace('/', '_')
name = name.replace('.', '_').replace('\\', '')
if name == '_':
name = 'root'
if name == '_tmp':
name = 'tmp'
if hasattr(os, 'statvfs'): # POSIX
try:
data = os.statvfs(info['mount_point'])
except OSError as e:
self.log.exception(e)
continue
# Changed from data.f_bsize as f_frsize seems to be a more
# accurate representation of block size on multiple POSIX
# operating systems.
block_size = data.f_frsize
blocks_total = data.f_blocks
blocks_free = data.f_bfree
blocks_avail = data.f_bavail
inodes_total = data.f_files
inodes_free = data.f_ffree
inodes_avail = data.f_favail
elif os.name == 'nt': # Windows
# fixme: used still not exact compared to disk_usage.py
# from psutil
raw_data = psutil.disk_usage(info['mount_point'])
block_size = 1 # fixme: ?
blocks_total = raw_data.total
blocks_free = raw_data.free
else:
raise NotImplementedError("platform not supported")
for unit in self.config['byte_unit']:
metric_name = '%s.%s_percentfree' % (name, unit)
try:
metric_value = float(blocks_free) / float(
blocks_free + (blocks_total - blocks_free)) * 100
except ZeroDivisionError:
metric_value = 0
self.publish_gauge(metric_name, metric_value, 2)
metric_name = '%s.%s_used' % (name, unit)
metric_value = float(block_size) * float(
blocks_total - blocks_free)
metric_value = diamond.convertor.binary.convert(
value=metric_value, oldUnit='byte', newUnit=unit)
self.publish_gauge(metric_name, metric_value, 2)
metric_name = '%s.%s_free' % (name, unit)
metric_value = float(block_size) * float(blocks_free)
metric_value = diamond.convertor.binary.convert(
value=metric_value, oldUnit='byte', newUnit=unit)
self.publish_gauge(metric_name, metric_value, 2)
if os.name != 'nt':
metric_name = '%s.%s_avail' % (name, unit)
metric_value = float(block_size) * float(blocks_avail)
metric_value = diamond.convertor.binary.convert(
value=metric_value, oldUnit='byte', newUnit=unit)
self.publish_gauge(metric_name, metric_value, 2)
if os.name != 'nt':
if float(inodes_total) > 0:
self.publish_gauge(
'%s.inodes_percentfree' % name,
float(inodes_free) / float(inodes_total) * 100)
self.publish_gauge('%s.inodes_used' % name,
inodes_total - inodes_free)
self.publish_gauge('%s.inodes_free' % name, inodes_free)
self.publish_gauge('%s.inodes_avail' % name, inodes_avail)
| 35.774908 | 79 | 0.513357 |
import diamond.collector
import diamond.convertor
import os
import re
try:
import psutil
except ImportError:
psutil = None
class DiskSpaceCollector(diamond.collector.Collector):
def get_default_config_help(self):
config_help = super(DiskSpaceCollector, self).get_default_config_help()
config_help.update({
'filesystems': "filesystems to examine",
'exclude_filters':
"A list of regex patterns. Any filesystem" +
" matching any of these patterns will be excluded from disk" +
" space metrics collection",
})
return config_help
def get_default_config(self):
config = super(DiskSpaceCollector, self).get_default_config()
config.update({
'path': 'diskspace',
'filesystems': 'ext2, ext3, ext4, xfs, glusterfs, nfs, nfs4, ' +
' ntfs, hfs, fat32, fat16, btrfs',
'exclude_filters': ['^/export/home'],
'byte_unit': ['byte']
})
return config
def process_config(self):
super(DiskSpaceCollector, self).process_config()
self.exclude_filters = self.config['exclude_filters']
if isinstance(self.exclude_filters, basestring):
self.exclude_filters = [self.exclude_filters]
if not self.exclude_filters:
self.exclude_reg = re.compile('!.*')
else:
self.exclude_reg = re.compile('|'.join(self.exclude_filters))
self.filesystems = []
if isinstance(self.config['filesystems'], basestring):
for filesystem in self.config['filesystems'].split(','):
self.filesystems.append(filesystem.strip())
elif isinstance(self.config['filesystems'], list):
self.filesystems = self.config['filesystems']
def get_disk_labels(self):
path = '/dev/disk/by-label/'
labels = {}
if not os.path.isdir(path):
return labels
for label in os.listdir(path):
label = label.replace('\\x2f', '/')
device = os.path.realpath(path + '/' + label)
labels[device] = label
return labels
def get_file_systems(self):
result = {}
if os.access('/proc/mounts', os.R_OK):
file = open('/proc/mounts')
for line in file:
try:
mount = line.split()
device = mount[0]
mount_point = mount[1]
fs_type = mount[2]
except (IndexError, ValueError):
continue
if fs_type not in self.filesystems:
self.log.debug("Ignoring %s since it is of type %s " +
" which is not in the list of filesystems.",
mount_point, fs_type)
continue
if self.exclude_reg.search(mount_point):
self.log.debug("Ignoring %s since it is in the " +
"exclude_filter list.", mount_point)
continue
if ((('/' in device or ':' in device or device == 'tmpfs') and
mount_point.startswith('/'))):
try:
stat = os.stat(mount_point)
except OSError:
self.log.debug("Path %s is not mounted - skipping.",
mount_point)
continue
if stat.st_dev in result:
continue
result[stat.st_dev] = {
'device': os.path.realpath(device),
'mount_point': mount_point,
'fs_type': fs_type
}
file.close()
else:
if not psutil:
self.log.error('Unable to import psutil')
return None
partitions = psutil.disk_partitions(False)
for partition in partitions:
result[len(result)] = {
'device': os.path.realpath(partition.device),
'mount_point': partition.mountpoint,
'fs_type': partition.fstype
}
pass
return result
def collect(self):
labels = self.get_disk_labels()
results = self.get_file_systems()
if not results:
self.log.error('No diskspace metrics retrieved')
return None
for info in results.itervalues():
if info['device'] in labels:
name = labels[info['device']]
else:
name = info['mount_point'].replace('/', '_')
name = name.replace('.', '_').replace('\\', '')
if name == '_':
name = 'root'
if name == '_tmp':
name = 'tmp'
if hasattr(os, 'statvfs'):
try:
data = os.statvfs(info['mount_point'])
except OSError as e:
self.log.exception(e)
continue
block_size = data.f_frsize
blocks_total = data.f_blocks
blocks_free = data.f_bfree
blocks_avail = data.f_bavail
inodes_total = data.f_files
inodes_free = data.f_ffree
inodes_avail = data.f_favail
elif os.name == 'nt':
raw_data = psutil.disk_usage(info['mount_point'])
block_size = 1
blocks_total = raw_data.total
blocks_free = raw_data.free
else:
raise NotImplementedError("platform not supported")
for unit in self.config['byte_unit']:
metric_name = '%s.%s_percentfree' % (name, unit)
try:
metric_value = float(blocks_free) / float(
blocks_free + (blocks_total - blocks_free)) * 100
except ZeroDivisionError:
metric_value = 0
self.publish_gauge(metric_name, metric_value, 2)
metric_name = '%s.%s_used' % (name, unit)
metric_value = float(block_size) * float(
blocks_total - blocks_free)
metric_value = diamond.convertor.binary.convert(
value=metric_value, oldUnit='byte', newUnit=unit)
self.publish_gauge(metric_name, metric_value, 2)
metric_name = '%s.%s_free' % (name, unit)
metric_value = float(block_size) * float(blocks_free)
metric_value = diamond.convertor.binary.convert(
value=metric_value, oldUnit='byte', newUnit=unit)
self.publish_gauge(metric_name, metric_value, 2)
if os.name != 'nt':
metric_name = '%s.%s_avail' % (name, unit)
metric_value = float(block_size) * float(blocks_avail)
metric_value = diamond.convertor.binary.convert(
value=metric_value, oldUnit='byte', newUnit=unit)
self.publish_gauge(metric_name, metric_value, 2)
if os.name != 'nt':
if float(inodes_total) > 0:
self.publish_gauge(
'%s.inodes_percentfree' % name,
float(inodes_free) / float(inodes_total) * 100)
self.publish_gauge('%s.inodes_used' % name,
inodes_total - inodes_free)
self.publish_gauge('%s.inodes_free' % name, inodes_free)
self.publish_gauge('%s.inodes_avail' % name, inodes_avail)
| true | true |
f719e23150154f51fed830c34ef140c0f8e124fa | 1,831 | py | Python | backend/app/api/api_v1/endpoints/users.py | BartlomiejRasztabiga/Rentally | ba70199d329895a5295ceddd0ecc4c61928890dd | [
"MIT"
] | 2 | 2021-01-11T23:24:29.000Z | 2021-01-12T09:55:58.000Z | backend/app/api/api_v1/endpoints/users.py | BartlomiejRasztabiga/Rentally | ba70199d329895a5295ceddd0ecc4c61928890dd | [
"MIT"
] | null | null | null | backend/app/api/api_v1/endpoints/users.py | BartlomiejRasztabiga/Rentally | ba70199d329895a5295ceddd0ecc4c61928890dd | [
"MIT"
] | null | null | null | from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app import models, schemas, services
from app.api import deps
router = APIRouter()
@router.get("/", response_model=List[schemas.User])
def read_users(
db: Session = Depends(deps.get_db),
current_user: models.User = Depends(deps.get_current_active_admin),
) -> Any:
"""
Retrieve users.
"""
users = services.user.get_all(db)
return users
@router.post("/", response_model=schemas.User)
def create_user(
*,
db: Session = Depends(deps.get_db),
user_in: schemas.UserCreateDto,
current_user: models.User = Depends(deps.get_current_active_admin),
) -> Any:
"""
Create new user.
"""
user = services.user.get_by_email(db, email=user_in.email)
if user:
raise HTTPException(
status_code=400,
detail="The user with this username already exists in the system.",
)
user = services.user.create(db, obj_in=user_in)
return user
@router.get("/me", response_model=schemas.User)
def read_user_me(
db: Session = Depends(deps.get_db),
current_user: models.User = Depends(deps.get_current_user),
) -> Any:
"""
Get current user.
"""
return current_user
@router.get("/{user_id}", response_model=schemas.User)
def read_user_by_id(
user_id: int,
current_user: models.User = Depends(deps.get_current_user),
db: Session = Depends(deps.get_db),
) -> Any:
"""
Get a specific user by id.
"""
user = services.user.get(db, _id=user_id)
if user == current_user:
return user
if not services.user.is_admin(current_user):
raise HTTPException(
status_code=400, detail="The user doesn't have enough privileges"
)
return user
| 25.082192 | 79 | 0.666303 | from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app import models, schemas, services
from app.api import deps
router = APIRouter()
@router.get("/", response_model=List[schemas.User])
def read_users(
db: Session = Depends(deps.get_db),
current_user: models.User = Depends(deps.get_current_active_admin),
) -> Any:
users = services.user.get_all(db)
return users
@router.post("/", response_model=schemas.User)
def create_user(
*,
db: Session = Depends(deps.get_db),
user_in: schemas.UserCreateDto,
current_user: models.User = Depends(deps.get_current_active_admin),
) -> Any:
user = services.user.get_by_email(db, email=user_in.email)
if user:
raise HTTPException(
status_code=400,
detail="The user with this username already exists in the system.",
)
user = services.user.create(db, obj_in=user_in)
return user
@router.get("/me", response_model=schemas.User)
def read_user_me(
db: Session = Depends(deps.get_db),
current_user: models.User = Depends(deps.get_current_user),
) -> Any:
return current_user
@router.get("/{user_id}", response_model=schemas.User)
def read_user_by_id(
user_id: int,
current_user: models.User = Depends(deps.get_current_user),
db: Session = Depends(deps.get_db),
) -> Any:
user = services.user.get(db, _id=user_id)
if user == current_user:
return user
if not services.user.is_admin(current_user):
raise HTTPException(
status_code=400, detail="The user doesn't have enough privileges"
)
return user
| true | true |
f719e2f9ea943ab752ebf80ab241bf9d6a0bde56 | 273 | py | Python | urls.py | ActuallyZach/in_app_purchase_receipt_verifier | f342809bcc2a16a34de3cccf965f0821a5bd552b | [
"Apache-2.0"
] | 1 | 2021-12-10T09:59:17.000Z | 2021-12-10T09:59:17.000Z | urls.py | ActuallyZach/in_app_purchase_receipt_verifier | f342809bcc2a16a34de3cccf965f0821a5bd552b | [
"Apache-2.0"
] | null | null | null | urls.py | ActuallyZach/in_app_purchase_receipt_verifier | f342809bcc2a16a34de3cccf965f0821a5bd552b | [
"Apache-2.0"
] | null | null | null | from django.conf.urls import include, url
from django.http import HttpResponse
from app import views
urlpatterns = [
url(r'^verify', views.verify_receipt),
url('verify/scum', views.verify_receipt_scum),
url('verify/jellycuts', views.verify_receipt_jelly),
]
| 22.75 | 56 | 0.747253 | from django.conf.urls import include, url
from django.http import HttpResponse
from app import views
urlpatterns = [
url(r'^verify', views.verify_receipt),
url('verify/scum', views.verify_receipt_scum),
url('verify/jellycuts', views.verify_receipt_jelly),
]
| true | true |
f719e312e4286ce9cdd25018ce166a3a13eee31c | 6,014 | py | Python | nikola/plugins/compile/rest/post_list.py | pellenilsson/nikola | 67a944a40b35584525a1bb363b3abd85582704cb | [
"MIT"
] | 1 | 2015-11-06T01:07:29.000Z | 2015-11-06T01:07:29.000Z | nikola/plugins/compile/rest/post_list.py | pellenilsson/nikola | 67a944a40b35584525a1bb363b3abd85582704cb | [
"MIT"
] | null | null | null | nikola/plugins/compile/rest/post_list.py | pellenilsson/nikola | 67a944a40b35584525a1bb363b3abd85582704cb | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright © 2013-2014 Udo Spallek, Roberto Alsina and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice
# shall be included in all copies or substantial portions of
# the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from __future__ import unicode_literals
import uuid
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from nikola import utils
from nikola.plugin_categories import RestExtension
# WARNING: the directive name is post-list
# (with a DASH instead of an UNDERSCORE)
class Plugin(RestExtension):
name = "rest_post_list"
def set_site(self, site):
self.site = site
directives.register_directive('post-list', PostList)
PostList.site = site
return super(Plugin, self).set_site(site)
class PostList(Directive):
"""
Post List
=========
:Directive Arguments: None.
:Directive Options: lang, start, stop, reverse, tags, template, id
:Directive Content: None.
Provides a reStructuredText directive to create a list of posts.
The posts appearing in the list can be filtered by options.
*List slicing* is provided with the *start*, *stop* and *reverse* options.
The following not required options are recognized:
``start`` : integer
The index of the first post to show.
A negative value like ``-3`` will show the *last* three posts in the
post-list.
Defaults to None.
``stop`` : integer
The index of the last post to show.
A value negative value like ``-1`` will show every post, but not the
*last* in the post-list.
Defaults to None.
``reverse`` : flag
Reverse the order of the post-list.
Defaults is to not reverse the order of posts.
``tags`` : string [, string...]
Filter posts to show only posts having at least one of the ``tags``.
Defaults to None.
``slugs`` : string [, string...]
Filter posts to show only posts having at least one of the ``slugs``.
Defaults to None.
``all`` : flag
Shows all posts and pages in the post list.
Defaults to show only posts with set *use_in_feeds*.
``lang`` : string
The language of post *titles* and *links*.
Defaults to default language.
``template`` : string
The name of an alternative template to render the post-list.
Defaults to ``post_list_directive.tmpl``
``id`` : string
A manual id for the post list.
Defaults to a random name composed by 'post_list_' + uuid.uuid4().hex.
"""
option_spec = {
'start': int,
'stop': int,
'reverse': directives.flag,
'tags': directives.unchanged,
'slugs': directives.unchanged,
'all': directives.flag,
'lang': directives.unchanged,
'template': directives.path,
'id': directives.unchanged,
}
def run(self):
start = self.options.get('start')
stop = self.options.get('stop')
reverse = self.options.get('reverse', False)
tags = self.options.get('tags')
tags = [t.strip().lower() for t in tags.split(',')] if tags else []
slugs = self.options.get('slugs')
slugs = [s.strip() for s in slugs.split(',')] if slugs else []
show_all = self.options.get('all', False)
lang = self.options.get('lang', utils.LocaleBorg().current_lang)
template = self.options.get('template', 'post_list_directive.tmpl')
if self.site.invariant: # for testing purposes
post_list_id = self.options.get('id', 'post_list_' + 'fixedvaluethatisnotauuid')
else:
post_list_id = self.options.get('id', 'post_list_' + uuid.uuid4().hex)
filtered_timeline = []
posts = []
step = -1 if reverse is None else None
if show_all is None:
timeline = [p for p in self.site.timeline]
else:
timeline = [p for p in self.site.timeline if p.use_in_feeds]
for post in timeline:
if tags:
cont = True
tags_lower = [t.lower() for t in post.tags]
for tag in tags:
if tag in tags_lower:
cont = False
if cont:
continue
filtered_timeline.append(post)
for post in filtered_timeline[start:stop:step]:
if slugs:
cont = True
for slug in slugs:
if slug == post.meta('slug'):
cont = False
if cont:
continue
posts += [post]
if not posts:
return []
template_data = {
'lang': lang,
'posts': posts,
'date_format': self.site.GLOBAL_CONTEXT.get('date_format'),
'post_list_id': post_list_id,
}
output = self.site.template_system.render_template(
template, None, template_data)
return [nodes.raw('', output, format='html')]
| 33.977401 | 92 | 0.617559 |
from __future__ import unicode_literals
import uuid
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from nikola import utils
from nikola.plugin_categories import RestExtension
class Plugin(RestExtension):
name = "rest_post_list"
def set_site(self, site):
self.site = site
directives.register_directive('post-list', PostList)
PostList.site = site
return super(Plugin, self).set_site(site)
class PostList(Directive):
option_spec = {
'start': int,
'stop': int,
'reverse': directives.flag,
'tags': directives.unchanged,
'slugs': directives.unchanged,
'all': directives.flag,
'lang': directives.unchanged,
'template': directives.path,
'id': directives.unchanged,
}
def run(self):
start = self.options.get('start')
stop = self.options.get('stop')
reverse = self.options.get('reverse', False)
tags = self.options.get('tags')
tags = [t.strip().lower() for t in tags.split(',')] if tags else []
slugs = self.options.get('slugs')
slugs = [s.strip() for s in slugs.split(',')] if slugs else []
show_all = self.options.get('all', False)
lang = self.options.get('lang', utils.LocaleBorg().current_lang)
template = self.options.get('template', 'post_list_directive.tmpl')
if self.site.invariant:
post_list_id = self.options.get('id', 'post_list_' + 'fixedvaluethatisnotauuid')
else:
post_list_id = self.options.get('id', 'post_list_' + uuid.uuid4().hex)
filtered_timeline = []
posts = []
step = -1 if reverse is None else None
if show_all is None:
timeline = [p for p in self.site.timeline]
else:
timeline = [p for p in self.site.timeline if p.use_in_feeds]
for post in timeline:
if tags:
cont = True
tags_lower = [t.lower() for t in post.tags]
for tag in tags:
if tag in tags_lower:
cont = False
if cont:
continue
filtered_timeline.append(post)
for post in filtered_timeline[start:stop:step]:
if slugs:
cont = True
for slug in slugs:
if slug == post.meta('slug'):
cont = False
if cont:
continue
posts += [post]
if not posts:
return []
template_data = {
'lang': lang,
'posts': posts,
'date_format': self.site.GLOBAL_CONTEXT.get('date_format'),
'post_list_id': post_list_id,
}
output = self.site.template_system.render_template(
template, None, template_data)
return [nodes.raw('', output, format='html')]
| true | true |
f719e34865d33ff09f68d04ec4e19add1ab00e5b | 5,344 | py | Python | analysis.py | edpolanco/air_cargo | 20ddf6c72dafed85b87486ca46a9c09656f31d90 | [
"MIT"
] | null | null | null | analysis.py | edpolanco/air_cargo | 20ddf6c72dafed85b87486ca46a9c09656f31d90 | [
"MIT"
] | null | null | null | analysis.py | edpolanco/air_cargo | 20ddf6c72dafed85b87486ca46a9c09656f31d90 | [
"MIT"
] | null | null | null | """Module for summarizing cargo planning testing results.
Ed Polanco
ed.polanco@outlook.com
"""
import pandas as pd
from collections import OrderedDict
import datetime
import time
from aimacode.search import Problem, Node
from timeit import default_timer as timer
from run_search import PrintableProblem, PROBLEMS
from aimacode.search import (breadth_first_search, astar_search,
breadth_first_tree_search, depth_first_graph_search, uniform_cost_search,
greedy_best_first_graph_search, depth_limited_search,
recursive_best_first_search)
#Names of the various search algorithms
SEARCHES_SHORT_NAME = [["Breadth First", breadth_first_search, ""], #1
['Breadth First Tree', breadth_first_tree_search, ""], #2
['Depth First Graph', depth_first_graph_search, ""], #3
['Depth Limited', depth_limited_search, ""], #4
['Uniform Cost', uniform_cost_search, ""], #5
['Recursive Best First w/ h1', recursive_best_first_search, 'h_1'], #6
['Greedy Best First Graph w/ h1', greedy_best_first_graph_search, 'h_1'], #7
['Astar w/ h1', astar_search, 'h_1'], #8
['Astar w/ ignore pre-cond.', astar_search, 'h_ignore_preconditions'], #9
['Astar w/ level-sum', astar_search, 'h_pg_levelsum'], #10
]
def show_path(node:Node):
"""
Print solution set to screen
Paremeter
----------
node: Node
Search tree object that has 'solution()' method
"""
if node is None:
print("The selected planner did not find a solution for this problem. " +
"Make sure you have completed the AirCargoProblem implementation " +
"and pass all unit tests first.")
else:
msg = "Search function {} plan length: {} ".format(node[0],len(node[1].solution()) )
print(msg)
for action in node[1].solution():
print("{}{}".format(action.name, action.args))
def run_search_table(problem: Problem, search_function, parameter=None):
"""Perform a test to find a solution to one of cargo problems.
Paremeters:
----------
problem: Problem
Cargo planning problem
search_function: str
Search algorithm function name
parameter: parameter value if any [None]
Parameter value for the search algorithms that require it.
Returns:
----------
Returns tuple of 5 values:
1 = Node expansions count
2 = number of times we tested for goal state
3 = Number of new nodes
4 = Number of steps
5 = Search tree Node object
"""
start = timer()
ip = PrintableProblem(problem)
if parameter is not None:
node = search_function(ip, parameter)
else:
node = search_function(ip)
end = timer()
return (ip.succs, ip.goal_tests, ip.states, end - start, node )
def search_data(problem_id: int, s_choices: list):
""" Perform test to solve cargo planning problem with
the given search algorithms.
Paremeters:
----------
problem_id: int
Cargo planning problem id
s_choices: list
List of the search algorithm to try.
Returns:
----------
Returns tuple of two items:
1 = DataFrame that summarizes test result
2 = A list of tuples, where the first item in the
tuple is the search algorithm name and the second
is its corresponding search Node object.
"""
#lets get a list of problems and search algorithms
problem_name,problem = PROBLEMS[problem_id - 1][0],PROBLEMS[problem_id- 1][1]
searches = [SEARCHES_SHORT_NAME[i-1] for i in map(int, s_choices)]
# helper variables to create DataFrame
steps = []
fun_name = []
expansions = []
goal_test =[]
new_nodes = []
elapsed_time = []
nodes = []
for sname, s, h in searches:
start_time = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %I:%M:%S%p')
print("\nSolving {} using {} start time {}...".format(problem_name, sname, start_time))
_p = problem()
_h = None if not h else getattr(_p, h)
#perform test get result
result = run_search_table(_p, s, _h)
#update helper list variables
fun_name.append(sname)
expansions.append(result[0])
goal_test.append(result[1])
new_nodes.append(result[2])
elapsed_time.append(result[3])
steps.append(len(result[4].solution()) )
nodes.append([sname,result[4]])
#create dictionary for DataFrame input
table_dict = OrderedDict()
table_dict["Function Name"] = fun_name
table_dict["Solution Steps"] = steps
table_dict["Expansions"] = expansions
table_dict["Goal Tests"] = goal_test
table_dict["New_Nodes"] = new_nodes
table_dict["Elapsed Seconds"] = elapsed_time
dataframe = pd.DataFrame(table_dict)
dataframe.index +=1
return dataframe, nodes | 36.60274 | 98 | 0.595434 | import pandas as pd
from collections import OrderedDict
import datetime
import time
from aimacode.search import Problem, Node
from timeit import default_timer as timer
from run_search import PrintableProblem, PROBLEMS
from aimacode.search import (breadth_first_search, astar_search,
breadth_first_tree_search, depth_first_graph_search, uniform_cost_search,
greedy_best_first_graph_search, depth_limited_search,
recursive_best_first_search)
SEARCHES_SHORT_NAME = [["Breadth First", breadth_first_search, ""],
['Breadth First Tree', breadth_first_tree_search, ""],
['Depth First Graph', depth_first_graph_search, ""],
['Depth Limited', depth_limited_search, ""],
['Uniform Cost', uniform_cost_search, ""],
['Recursive Best First w/ h1', recursive_best_first_search, 'h_1'],
['Greedy Best First Graph w/ h1', greedy_best_first_graph_search, 'h_1'],
['Astar w/ h1', astar_search, 'h_1'],
['Astar w/ ignore pre-cond.', astar_search, 'h_ignore_preconditions'],
['Astar w/ level-sum', astar_search, 'h_pg_levelsum'],
]
def show_path(node:Node):
if node is None:
print("The selected planner did not find a solution for this problem. " +
"Make sure you have completed the AirCargoProblem implementation " +
"and pass all unit tests first.")
else:
msg = "Search function {} plan length: {} ".format(node[0],len(node[1].solution()) )
print(msg)
for action in node[1].solution():
print("{}{}".format(action.name, action.args))
def run_search_table(problem: Problem, search_function, parameter=None):
start = timer()
ip = PrintableProblem(problem)
if parameter is not None:
node = search_function(ip, parameter)
else:
node = search_function(ip)
end = timer()
return (ip.succs, ip.goal_tests, ip.states, end - start, node )
def search_data(problem_id: int, s_choices: list):
problem_name,problem = PROBLEMS[problem_id - 1][0],PROBLEMS[problem_id- 1][1]
searches = [SEARCHES_SHORT_NAME[i-1] for i in map(int, s_choices)]
steps = []
fun_name = []
expansions = []
goal_test =[]
new_nodes = []
elapsed_time = []
nodes = []
for sname, s, h in searches:
start_time = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %I:%M:%S%p')
print("\nSolving {} using {} start time {}...".format(problem_name, sname, start_time))
_p = problem()
_h = None if not h else getattr(_p, h)
result = run_search_table(_p, s, _h)
fun_name.append(sname)
expansions.append(result[0])
goal_test.append(result[1])
new_nodes.append(result[2])
elapsed_time.append(result[3])
steps.append(len(result[4].solution()) )
nodes.append([sname,result[4]])
table_dict = OrderedDict()
table_dict["Function Name"] = fun_name
table_dict["Solution Steps"] = steps
table_dict["Expansions"] = expansions
table_dict["Goal Tests"] = goal_test
table_dict["New_Nodes"] = new_nodes
table_dict["Elapsed Seconds"] = elapsed_time
dataframe = pd.DataFrame(table_dict)
dataframe.index +=1
return dataframe, nodes | true | true |
f719e4fc1c2f57473dc26131829f497ab8dd2ff2 | 854 | py | Python | autogl/module/nas/estimator/one_shot.py | THUMNLab/AutoGL | 9dfcabcda41620a7d12d6322f0e52e68dd7dcec4 | [
"Apache-2.0"
] | 824 | 2020-11-30T14:38:07.000Z | 2022-03-19T10:14:04.000Z | autogl/module/nas/estimator/one_shot.py | MitchellTesla/AutoGL | 7b551961e90f5042d9b91d92c083f3f09dd9dbdd | [
"Apache-2.0"
] | 38 | 2020-12-21T12:32:57.000Z | 2022-01-31T02:32:05.000Z | autogl/module/nas/estimator/one_shot.py | MitchellTesla/AutoGL | 7b551961e90f5042d9b91d92c083f3f09dd9dbdd | [
"Apache-2.0"
] | 85 | 2020-12-21T05:16:09.000Z | 2022-03-28T08:44:22.000Z | import torch.nn as nn
import torch.nn.functional as F
from . import register_nas_estimator
from ..space import BaseSpace
from .base import BaseEstimator
@register_nas_estimator("oneshot")
class OneShotEstimator(BaseEstimator):
"""
One shot estimator.
Use model directly to get estimations.
"""
def infer(self, model: BaseSpace, dataset, mask="train"):
device = next(model.parameters()).device
dset = dataset[0].to(device)
pred = model(dset)[getattr(dset, f"{mask}_mask")]
y = dset.y[getattr(dset, f"{mask}_mask")]
loss = getattr(F, self.loss_f)(pred, y)
# acc=sum(pred.max(1)[1]==y).item()/y.size(0)
probs = F.softmax(pred, dim=1).detach().cpu().numpy()
y = y.cpu()
metrics = [eva.evaluate(probs, y) for eva in self.evaluation]
return metrics, loss
| 30.5 | 69 | 0.640515 | import torch.nn as nn
import torch.nn.functional as F
from . import register_nas_estimator
from ..space import BaseSpace
from .base import BaseEstimator
@register_nas_estimator("oneshot")
class OneShotEstimator(BaseEstimator):
def infer(self, model: BaseSpace, dataset, mask="train"):
device = next(model.parameters()).device
dset = dataset[0].to(device)
pred = model(dset)[getattr(dset, f"{mask}_mask")]
y = dset.y[getattr(dset, f"{mask}_mask")]
loss = getattr(F, self.loss_f)(pred, y)
probs = F.softmax(pred, dim=1).detach().cpu().numpy()
y = y.cpu()
metrics = [eva.evaluate(probs, y) for eva in self.evaluation]
return metrics, loss
| true | true |
f719e58172c6f8335918d776edd53b5bed9dae39 | 13,398 | py | Python | vissl/optimizers/optimizer_helper.py | tjdbsrud/vissl | 1cf1ee0c82c8a0d65544b82a6fc2f28c7d5eb175 | [
"MIT"
] | 3 | 2021-07-08T15:06:49.000Z | 2021-08-13T18:55:02.000Z | vissl/optimizers/optimizer_helper.py | pzharrington/vissl | b647c256447af7ea66655811849be1f642377db8 | [
"MIT"
] | 2 | 2021-07-25T15:46:07.000Z | 2021-08-11T10:08:53.000Z | vissl/optimizers/optimizer_helper.py | pzharrington/vissl | b647c256447af7ea66655811849be1f642377db8 | [
"MIT"
] | 2 | 2021-07-08T15:15:55.000Z | 2021-08-25T14:16:01.000Z | # Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from typing import Any, List
import torch.nn as nn
from vissl.utils.misc import is_apex_available
_CONV_TYPES = (nn.Conv1d, nn.Conv2d, nn.Conv3d)
_NORM_TYPES = (
nn.BatchNorm1d,
nn.BatchNorm2d,
nn.BatchNorm3d,
nn.SyncBatchNorm, # pytorch SyncBN
nn.LayerNorm,
)
if is_apex_available():
import apex
_NORM_TYPES += (apex.parallel.SyncBatchNorm,)
def _get_bn_optimizer_params(
module, regularized_params, unregularized_params, optimizer_config
):
"""
Given the (Sync)BatchNorm module in the model, we separate the module params
into regularized or non-regularized (weight_decay=0).
"""
# this is called by get_optimizer_params for BN specific layer only
if module.weight is not None:
if optimizer_config["regularize_bn"]:
regularized_params.append(module.weight)
else:
unregularized_params.append(module.weight)
if module.bias is not None:
if optimizer_config["regularize_bn"] and optimizer_config["regularize_bias"]:
regularized_params.append(module.bias)
else:
unregularized_params.append(module.bias)
return regularized_params, unregularized_params
def _filter_trainable(param_list: List[Any]) -> List[Any]:
"""
Keep on the trainable parameters of the model and return the list of
trainable params.
"""
# Keep only the trainable params
return list(filter(lambda x: x.requires_grad, param_list))
def _assign_regularized_params(
regularized_param_list=None,
unregularized_param_list=None,
parameters_to_unregularize=None,
):
"""
Takes a list parameters_to_unregularize (a list of parameters to ensure are
not regularized) and compares it to regularized_param_list, a list of
regularized parameters. Any parameters in parameters_to_unregularize that
are present in regularized_param_list are removed from
regularized_param_list. Will also check against an optional
unregularized_param_list (pre-existing list of parameters not to regularize)
and remove any items from parameters_to_unregularize that are in
unregularized_param_list. Used for when we have parameters that we don't
want to regularize (e.g. the class token and position embeddings for the
vision transformer). See config.OPTIMIZER.non_regularized_params. Needs
to be called separately for head, trunk, and remaining params.
"""
indices_to_remove_from_regularized = []
indices_to_remove_from_new_unregularized = []
# Iterate through new parameters to unregularize
for unreg_param_ind, new_unreg_param in enumerate(parameters_to_unregularize):
# Iterate through list of regularized parameters
for reg_param_ind, reg_param in enumerate(regularized_param_list):
# Note any matchess
if reg_param is new_unreg_param:
indices_to_remove_from_regularized.append(reg_param_ind)
if unregularized_param_list:
# Iterate through pre-existing list of unregularized parameters
for unreg_param in unregularized_param_list:
# Note any matches
if unreg_param is new_unreg_param:
indices_to_remove_from_new_unregularized.append(unreg_param_ind)
indices_to_remove_from_regularized.sort(reverse=True)
# Iterate through indices to remove from list regularized params and
# remove them
for i in indices_to_remove_from_regularized:
del regularized_param_list[i]
if unregularized_param_list:
indices_to_remove_from_new_unregularized.sort(reverse=True)
# Iterate through indices to remove from new list of unregularized
# parameters
for i in indices_to_remove_from_new_unregularized:
del parameters_to_unregularize[i]
return parameters_to_unregularize, regularized_param_list, unregularized_param_list
def get_optimizer_param_groups(
model, model_config, optimizer_config, optimizer_schedulers
):
"""
Go through all the layers, sort out which parameters should be regularized,
unregularized and optimization settings for the head/trunk. We filter
the trainable params only and add them to the param_groups.
Returns:
param_groups (List[Dict]): [
{
"params": trunk_regularized_params, "lr": lr_value,
"weight_decay": wd_value,
},
{
"params": trunk_unregularized_params, "lr": lr_value,
"weight_decay": 0.0,
},
{
"params": head_regularized_params, "lr": head_lr_value,
"weight_decay": head_weight_decay,
},
{
"params": head_unregularized_params, "lr": head_lr_value,
"weight_decay": 0.0,
},
{
"params": remaining_regularized_params, "lr": lr_value
}
]
"""
if "weight_decay" in optimizer_schedulers:
weight_decay_main_config = optimizer_schedulers["weight_decay"]
else:
weight_decay_main_config = optimizer_config.weight_decay
if "weight_decay_head" in optimizer_schedulers:
weight_decay_head_main_config = optimizer_schedulers["weight_decay_head"]
else:
weight_decay_head_main_config = (
optimizer_config.head_optimizer_params.weight_decay
)
if optimizer_config.construct_single_param_group_only:
# If single param_group is asked, we just use the parameters
# returned from model.parameters(). This is useful in FSDP
# param flattening mode.
return [
{
"params": list(model.parameters()),
"lr": optimizer_schedulers["lr"],
"weight_decay": weight_decay_main_config,
}
]
# if the different LR, weight decay value for head is not specified, we use the
# same LR/wd as trunk.
if not optimizer_config.head_optimizer_params.use_different_lr:
assert "lr_head" in optimizer_schedulers
# we create 4 params groups: trunk regularized, trunk unregularized, head
# regularized and head unregularized. Unregularized can contain BN layers.
trunk_regularized_params, trunk_unregularized_params = [], []
head_regularized_params, head_unregularized_params = [], []
# for anything else
regularized_params = []
unregularized_params = []
for name, module in model.named_modules():
# head, Linear/Conv layer
if "head" in name and (
isinstance(module, nn.Linear) or isinstance(module, _CONV_TYPES)
):
# weight normalized linear layers, used in swav_prototypes_head for example,
# have "weight_g" and "weight_v" parameters in place of "weight"
if hasattr(module, "weight_g"):
head_regularized_params.append(module.weight_g)
head_regularized_params.append(module.weight_v)
else:
head_regularized_params.append(module.weight)
if module.bias is not None:
if optimizer_config["regularize_bias"]:
head_regularized_params.append(module.bias)
else:
head_unregularized_params.append(module.bias)
# head, BN/LN layer
elif "head" in name and isinstance(module, _NORM_TYPES):
(
head_regularized_params,
head_unregularized_params,
) = _get_bn_optimizer_params(
module,
head_regularized_params,
head_unregularized_params,
optimizer_config,
)
# trunk, Linear/Conv
elif isinstance(module, nn.Linear) or isinstance(module, _CONV_TYPES):
if hasattr(module, "weight_g"): # weight_norm linear layers
trunk_regularized_params.append(module.weight_g)
trunk_regularized_params.append(module.weight_v)
else:
trunk_regularized_params.append(module.weight)
if module.bias is not None:
if optimizer_config["regularize_bias"]:
trunk_regularized_params.append(module.bias)
else:
trunk_unregularized_params.append(module.bias)
# trunk, BN/LN layer
elif isinstance(module, _NORM_TYPES):
(
trunk_regularized_params,
trunk_unregularized_params,
) = _get_bn_optimizer_params(
module,
trunk_regularized_params,
trunk_unregularized_params,
optimizer_config,
)
elif len(list(module.children())) >= 0:
# for any other layers not bn_types, conv_types or nn.Linear, if
# the layers are the leaf nodes and have parameters, we regularize
# them. Similarly, if non-leaf nodes but have parameters, regularize
# them (set recurse=False)
for params in module.parameters(recurse=False):
regularized_params.append(params)
# Collect user-specified non-regularized params and remove them for the
# lists of regularized params, and check they're not already on the lists
# of unregularized params
if optimizer_config.non_regularized_parameters:
non_reg_param_names = optimizer_config.non_regularized_parameters
for name, param in model.named_parameters():
hits = [p for p in non_reg_param_names if p in name]
if any(hits):
unregularized_params.append(param)
# Call for trunk params
(
non_reg_params,
trunk_regularized_params,
trunk_unregularized_params,
) = _assign_regularized_params(
parameters_to_unregularize=unregularized_params,
regularized_param_list=trunk_regularized_params,
unregularized_param_list=trunk_unregularized_params,
)
# Call for head params
(
non_reg_params,
head_regularized_params,
head_unregularized_params,
) = _assign_regularized_params(
parameters_to_unregularize=unregularized_params,
regularized_param_list=head_regularized_params,
unregularized_param_list=head_unregularized_params,
)
# Call for remaining params
non_reg_params, regularized_params, _ = _assign_regularized_params(
parameters_to_unregularize=unregularized_params,
regularized_param_list=regularized_params,
)
# for non-trainable params, set the requires_grad to False
non_trainable_params = []
for name, param in model.named_parameters():
if name in model_config.NON_TRAINABLE_PARAMS:
param.requires_grad = False
non_trainable_params.append(param)
trainable_params = _filter_trainable(model.parameters())
trunk_regularized_params = _filter_trainable(trunk_regularized_params)
trunk_unregularized_params = _filter_trainable(trunk_unregularized_params)
head_regularized_params = _filter_trainable(head_regularized_params)
head_unregularized_params = _filter_trainable(head_unregularized_params)
regularized_params = _filter_trainable(regularized_params)
logging.info(
f"\nTrainable params: {len(trainable_params)}, \n"
f"Non-Trainable params: {len(non_trainable_params)}, \n"
f"Trunk Regularized Parameters: {len(trunk_regularized_params)}, \n"
f"Trunk Unregularized Parameters {len(trunk_unregularized_params)}, \n"
f"Head Regularized Parameters: {len(head_regularized_params)}, \n"
f"Head Unregularized Parameters: {len(head_unregularized_params)} \n"
f"Remaining Regularized Parameters: {len(regularized_params)} \n"
f"Remaining Unregularized Parameters: {len(unregularized_params)}"
)
param_groups = [
{
"params": trunk_regularized_params,
"lr": optimizer_schedulers["lr"],
"weight_decay": weight_decay_main_config,
},
{
"params": trunk_unregularized_params,
"lr": optimizer_schedulers["lr"],
"weight_decay": 0.0,
},
{
"params": head_regularized_params,
"lr": optimizer_schedulers["lr_head"],
"weight_decay": weight_decay_head_main_config,
},
{
"params": head_unregularized_params,
"lr": optimizer_schedulers["lr_head"],
"weight_decay": 0.0,
},
]
if len(regularized_params) > 0:
param_groups.append(
{
"params": regularized_params,
"lr": optimizer_schedulers["lr"],
"weight_decay": weight_decay_main_config,
}
)
if len(unregularized_params) > 0:
param_groups.append(
{
"params": unregularized_params,
"lr": optimizer_schedulers["lr"],
"weight_decay": 0.0,
}
)
return param_groups
| 40.847561 | 88 | 0.657785 |
import logging
from typing import Any, List
import torch.nn as nn
from vissl.utils.misc import is_apex_available
_CONV_TYPES = (nn.Conv1d, nn.Conv2d, nn.Conv3d)
_NORM_TYPES = (
nn.BatchNorm1d,
nn.BatchNorm2d,
nn.BatchNorm3d,
nn.SyncBatchNorm,
nn.LayerNorm,
)
if is_apex_available():
import apex
_NORM_TYPES += (apex.parallel.SyncBatchNorm,)
def _get_bn_optimizer_params(
module, regularized_params, unregularized_params, optimizer_config
):
if module.weight is not None:
if optimizer_config["regularize_bn"]:
regularized_params.append(module.weight)
else:
unregularized_params.append(module.weight)
if module.bias is not None:
if optimizer_config["regularize_bn"] and optimizer_config["regularize_bias"]:
regularized_params.append(module.bias)
else:
unregularized_params.append(module.bias)
return regularized_params, unregularized_params
def _filter_trainable(param_list: List[Any]) -> List[Any]:
return list(filter(lambda x: x.requires_grad, param_list))
def _assign_regularized_params(
regularized_param_list=None,
unregularized_param_list=None,
parameters_to_unregularize=None,
):
indices_to_remove_from_regularized = []
indices_to_remove_from_new_unregularized = []
for unreg_param_ind, new_unreg_param in enumerate(parameters_to_unregularize):
for reg_param_ind, reg_param in enumerate(regularized_param_list):
if reg_param is new_unreg_param:
indices_to_remove_from_regularized.append(reg_param_ind)
if unregularized_param_list:
for unreg_param in unregularized_param_list:
if unreg_param is new_unreg_param:
indices_to_remove_from_new_unregularized.append(unreg_param_ind)
indices_to_remove_from_regularized.sort(reverse=True)
for i in indices_to_remove_from_regularized:
del regularized_param_list[i]
if unregularized_param_list:
indices_to_remove_from_new_unregularized.sort(reverse=True)
for i in indices_to_remove_from_new_unregularized:
del parameters_to_unregularize[i]
return parameters_to_unregularize, regularized_param_list, unregularized_param_list
def get_optimizer_param_groups(
model, model_config, optimizer_config, optimizer_schedulers
):
if "weight_decay" in optimizer_schedulers:
weight_decay_main_config = optimizer_schedulers["weight_decay"]
else:
weight_decay_main_config = optimizer_config.weight_decay
if "weight_decay_head" in optimizer_schedulers:
weight_decay_head_main_config = optimizer_schedulers["weight_decay_head"]
else:
weight_decay_head_main_config = (
optimizer_config.head_optimizer_params.weight_decay
)
if optimizer_config.construct_single_param_group_only:
return [
{
"params": list(model.parameters()),
"lr": optimizer_schedulers["lr"],
"weight_decay": weight_decay_main_config,
}
]
if not optimizer_config.head_optimizer_params.use_different_lr:
assert "lr_head" in optimizer_schedulers
trunk_regularized_params, trunk_unregularized_params = [], []
head_regularized_params, head_unregularized_params = [], []
regularized_params = []
unregularized_params = []
for name, module in model.named_modules():
if "head" in name and (
isinstance(module, nn.Linear) or isinstance(module, _CONV_TYPES)
):
if hasattr(module, "weight_g"):
head_regularized_params.append(module.weight_g)
head_regularized_params.append(module.weight_v)
else:
head_regularized_params.append(module.weight)
if module.bias is not None:
if optimizer_config["regularize_bias"]:
head_regularized_params.append(module.bias)
else:
head_unregularized_params.append(module.bias)
elif "head" in name and isinstance(module, _NORM_TYPES):
(
head_regularized_params,
head_unregularized_params,
) = _get_bn_optimizer_params(
module,
head_regularized_params,
head_unregularized_params,
optimizer_config,
)
elif isinstance(module, nn.Linear) or isinstance(module, _CONV_TYPES):
if hasattr(module, "weight_g"):
trunk_regularized_params.append(module.weight_g)
trunk_regularized_params.append(module.weight_v)
else:
trunk_regularized_params.append(module.weight)
if module.bias is not None:
if optimizer_config["regularize_bias"]:
trunk_regularized_params.append(module.bias)
else:
trunk_unregularized_params.append(module.bias)
elif isinstance(module, _NORM_TYPES):
(
trunk_regularized_params,
trunk_unregularized_params,
) = _get_bn_optimizer_params(
module,
trunk_regularized_params,
trunk_unregularized_params,
optimizer_config,
)
elif len(list(module.children())) >= 0:
for params in module.parameters(recurse=False):
regularized_params.append(params)
# of unregularized params
if optimizer_config.non_regularized_parameters:
non_reg_param_names = optimizer_config.non_regularized_parameters
for name, param in model.named_parameters():
hits = [p for p in non_reg_param_names if p in name]
if any(hits):
unregularized_params.append(param)
# Call for trunk params
(
non_reg_params,
trunk_regularized_params,
trunk_unregularized_params,
) = _assign_regularized_params(
parameters_to_unregularize=unregularized_params,
regularized_param_list=trunk_regularized_params,
unregularized_param_list=trunk_unregularized_params,
)
# Call for head params
(
non_reg_params,
head_regularized_params,
head_unregularized_params,
) = _assign_regularized_params(
parameters_to_unregularize=unregularized_params,
regularized_param_list=head_regularized_params,
unregularized_param_list=head_unregularized_params,
)
# Call for remaining params
non_reg_params, regularized_params, _ = _assign_regularized_params(
parameters_to_unregularize=unregularized_params,
regularized_param_list=regularized_params,
)
# for non-trainable params, set the requires_grad to False
non_trainable_params = []
for name, param in model.named_parameters():
if name in model_config.NON_TRAINABLE_PARAMS:
param.requires_grad = False
non_trainable_params.append(param)
trainable_params = _filter_trainable(model.parameters())
trunk_regularized_params = _filter_trainable(trunk_regularized_params)
trunk_unregularized_params = _filter_trainable(trunk_unregularized_params)
head_regularized_params = _filter_trainable(head_regularized_params)
head_unregularized_params = _filter_trainable(head_unregularized_params)
regularized_params = _filter_trainable(regularized_params)
logging.info(
f"\nTrainable params: {len(trainable_params)}, \n"
f"Non-Trainable params: {len(non_trainable_params)}, \n"
f"Trunk Regularized Parameters: {len(trunk_regularized_params)}, \n"
f"Trunk Unregularized Parameters {len(trunk_unregularized_params)}, \n"
f"Head Regularized Parameters: {len(head_regularized_params)}, \n"
f"Head Unregularized Parameters: {len(head_unregularized_params)} \n"
f"Remaining Regularized Parameters: {len(regularized_params)} \n"
f"Remaining Unregularized Parameters: {len(unregularized_params)}"
)
param_groups = [
{
"params": trunk_regularized_params,
"lr": optimizer_schedulers["lr"],
"weight_decay": weight_decay_main_config,
},
{
"params": trunk_unregularized_params,
"lr": optimizer_schedulers["lr"],
"weight_decay": 0.0,
},
{
"params": head_regularized_params,
"lr": optimizer_schedulers["lr_head"],
"weight_decay": weight_decay_head_main_config,
},
{
"params": head_unregularized_params,
"lr": optimizer_schedulers["lr_head"],
"weight_decay": 0.0,
},
]
if len(regularized_params) > 0:
param_groups.append(
{
"params": regularized_params,
"lr": optimizer_schedulers["lr"],
"weight_decay": weight_decay_main_config,
}
)
if len(unregularized_params) > 0:
param_groups.append(
{
"params": unregularized_params,
"lr": optimizer_schedulers["lr"],
"weight_decay": 0.0,
}
)
return param_groups
| true | true |
f719e5ce46b0b141781817964a94f8d39288893c | 6,959 | py | Python | src/ggrc_workflows/migrations/versions/20150707143127_44047daa31a9_add_non_adjusted_next_cycle_start_date.py | trevordonnelly/ggrc-core | 499cf0d3cce70737b080991b12c203ec22015cea | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2018-03-30T11:28:48.000Z | 2018-03-30T11:28:48.000Z | src/ggrc_workflows/migrations/versions/20150707143127_44047daa31a9_add_non_adjusted_next_cycle_start_date.py | trevordonnelly/ggrc-core | 499cf0d3cce70737b080991b12c203ec22015cea | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/ggrc_workflows/migrations/versions/20150707143127_44047daa31a9_add_non_adjusted_next_cycle_start_date.py | trevordonnelly/ggrc-core | 499cf0d3cce70737b080991b12c203ec22015cea | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Add non-adjusted next cycle start date
Revision ID: 44047daa31a9
Revises: 1431e7094e26
Create Date: 2015-07-07 14:31:27.780564
"""
# Workaround legacy code which blocks Workflow new attribute addition
# flake8: noqa
# pylint: skip-file
# revision identifiers, used by Alembic.
revision = '44047daa31a9'
down_revision = '4840f4760f4b'
from alembic import op
import sqlalchemy as sa
# from sqlalchemy.dialects import mysql
# from datetime import date
# from ggrc.app import app
# from ggrc import settings, db
# import ggrc_workflows.models as models
# from ggrc_workflows import adjust_next_cycle_start_date
# from ggrc_workflows.services.workflow_cycle_calculator import \
# get_cycle_calculator
def upgrade():
op.add_column('workflows',
sa.Column('non_adjusted_next_cycle_start_date',
sa.Date(), nullable=True))
# Workaround legacy code which blocks Workflow new attribute addition
return
# If somebody deleted all the tasks we must clear the next cycle start
# date
workflows = db.session.query(models.Workflow) \
.filter(
models.Workflow.next_cycle_start_date != None,
models.Workflow.recurrences == True,
models.Workflow.status == 'Active',
models.Workflow.next_cycle_start_date < date.today()
).all()
for workflow in workflows:
tasks_start_days = [task.relative_start_day
for tg in workflow.task_groups
for task in tg.task_group_tasks]
tasks_end_days = [task.relative_end_day
for tg in workflow.task_groups
for task in tg.task_group_tasks]
if ((not all(tasks_start_days) and not all(tasks_end_days)) or
(not tasks_start_days and not tasks_end_days)):
app.logger.warning(
"Removing NCSD from expired WF {} because no tasks are "
"set up. Current NCSD: {}".format(
workflow.id,
workflow.next_cycle_start_date
))
workflow.next_cycle_start_date = None
db.session.add(workflow)
workflows = db.session.query(models.Workflow) \
.filter(
models.Workflow.next_cycle_start_date != None,
models.Workflow.non_adjusted_next_cycle_start_date == None,
models.Workflow.recurrences == True,
models.Workflow.status == 'Active',
models.Workflow.next_cycle_start_date >= date.today()
).all()
for workflow in workflows:
tasks_start_days = [task.relative_start_day
for tg in workflow.task_groups
for task in tg.task_group_tasks]
tasks_end_days = [task.relative_end_day
for tg in workflow.task_groups
for task in tg.task_group_tasks]
# We must skip tasks that don't have start days and end days defined
if ((not all(tasks_start_days) and not all(tasks_end_days)) or
(not tasks_start_days and not tasks_end_days)):
append_msg = ""
if workflow.next_cycle_start_date:
workflow.next_cycle_start_date = None
append_msg += (" Removing existing next cycle start date "
"because none are configured.")
db.session.add(workflow)
app.logger.warning(
"Skipping active WF {0} because no tasks "
"are set up.{1}".format(
workflow.id,
append_msg
))
continue
pre_compute_ncsd = workflow.next_cycle_start_date
last_cycle_start_date = None
if workflow.cycles:
last_cycle_start_date = max([c.start_date for c in workflow.cycles])
if last_cycle_start_date:
base_date = last_cycle_start_date
else:
base_date = base_date.today()
base_date = max(base_date, workflow.next_cycle_start_date)
calculator = get_cycle_calculator(workflow, base_date=base_date)
if workflow.frequency in {"weekly", "monthly"}:
nancsd_day = min(
v['relative_start'] for v in calculator.reified_tasks.values())
nancsd_month = None
else:
nancsd_month, nancsd_day = min(
v['relative_start'] for v in calculator.reified_tasks.values())
nancsd_date = calculator.relative_day_to_date(
relative_day=nancsd_day,
relative_month=nancsd_month,
base_date=base_date)
if last_cycle_start_date:
while calculator.adjust_date(nancsd_date) <= last_cycle_start_date:
base_date = base_date + calculator.time_delta
nancsd_date = calculator.relative_day_to_date(
relative_day=nancsd_day,
relative_month=nancsd_month,
base_date=base_date
)
else:
base_date = base_date - calculator.time_delta
while calculator.adjust_date(nancsd_date) <= pre_compute_ncsd:
base_date = base_date + calculator.time_delta
nancsd_date = calculator.relative_day_to_date(
relative_day=nancsd_day,
relative_month=nancsd_month,
base_date=base_date
)
workflow.non_adjusted_next_cycle_start_date = nancsd_date
workflow.next_cycle_start_date = calculator.adjust_date(nancsd_date)
post_compute_ncsd = workflow.next_cycle_start_date
start_dates = ["{}/{}".format(
task.relative_start_month,
task.relative_start_day) for tg in workflow.task_groups
for task in tg.task_group_tasks]
end_dates = ["{}/{}".format(
task.relative_end_month,
task.relative_end_day) for tg in workflow.task_groups
for task in tg.task_group_tasks]
if pre_compute_ncsd != post_compute_ncsd:
app.logger.warning(
"Adjusted NCSD for workflow {}. "
"Freq: {}, PRE: {}, Last cycle: {}, POST: {}, NON: {},"
"tasks start: {}, tasks end: {},".format(
workflow.id,
workflow.frequency[:2],
pre_compute_ncsd,
last_cycle_start_date,
post_compute_ncsd,
workflow.non_adjusted_next_cycle_start_date,
start_dates,
end_dates))
db.session.add(workflow)
# Save
db.session.commit()
def downgrade():
op.drop_column('workflows', 'non_adjusted_next_cycle_start_date')
| 38.027322 | 80 | 0.601523 |
revision = '44047daa31a9'
down_revision = '4840f4760f4b'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('workflows',
sa.Column('non_adjusted_next_cycle_start_date',
sa.Date(), nullable=True))
return
workflows = db.session.query(models.Workflow) \
.filter(
models.Workflow.next_cycle_start_date != None,
models.Workflow.recurrences == True,
models.Workflow.status == 'Active',
models.Workflow.next_cycle_start_date < date.today()
).all()
for workflow in workflows:
tasks_start_days = [task.relative_start_day
for tg in workflow.task_groups
for task in tg.task_group_tasks]
tasks_end_days = [task.relative_end_day
for tg in workflow.task_groups
for task in tg.task_group_tasks]
if ((not all(tasks_start_days) and not all(tasks_end_days)) or
(not tasks_start_days and not tasks_end_days)):
app.logger.warning(
"Removing NCSD from expired WF {} because no tasks are "
"set up. Current NCSD: {}".format(
workflow.id,
workflow.next_cycle_start_date
))
workflow.next_cycle_start_date = None
db.session.add(workflow)
workflows = db.session.query(models.Workflow) \
.filter(
models.Workflow.next_cycle_start_date != None,
models.Workflow.non_adjusted_next_cycle_start_date == None,
models.Workflow.recurrences == True,
models.Workflow.status == 'Active',
models.Workflow.next_cycle_start_date >= date.today()
).all()
for workflow in workflows:
tasks_start_days = [task.relative_start_day
for tg in workflow.task_groups
for task in tg.task_group_tasks]
tasks_end_days = [task.relative_end_day
for tg in workflow.task_groups
for task in tg.task_group_tasks]
if ((not all(tasks_start_days) and not all(tasks_end_days)) or
(not tasks_start_days and not tasks_end_days)):
append_msg = ""
if workflow.next_cycle_start_date:
workflow.next_cycle_start_date = None
append_msg += (" Removing existing next cycle start date "
"because none are configured.")
db.session.add(workflow)
app.logger.warning(
"Skipping active WF {0} because no tasks "
"are set up.{1}".format(
workflow.id,
append_msg
))
continue
pre_compute_ncsd = workflow.next_cycle_start_date
last_cycle_start_date = None
if workflow.cycles:
last_cycle_start_date = max([c.start_date for c in workflow.cycles])
if last_cycle_start_date:
base_date = last_cycle_start_date
else:
base_date = base_date.today()
base_date = max(base_date, workflow.next_cycle_start_date)
calculator = get_cycle_calculator(workflow, base_date=base_date)
if workflow.frequency in {"weekly", "monthly"}:
nancsd_day = min(
v['relative_start'] for v in calculator.reified_tasks.values())
nancsd_month = None
else:
nancsd_month, nancsd_day = min(
v['relative_start'] for v in calculator.reified_tasks.values())
nancsd_date = calculator.relative_day_to_date(
relative_day=nancsd_day,
relative_month=nancsd_month,
base_date=base_date)
if last_cycle_start_date:
while calculator.adjust_date(nancsd_date) <= last_cycle_start_date:
base_date = base_date + calculator.time_delta
nancsd_date = calculator.relative_day_to_date(
relative_day=nancsd_day,
relative_month=nancsd_month,
base_date=base_date
)
else:
base_date = base_date - calculator.time_delta
while calculator.adjust_date(nancsd_date) <= pre_compute_ncsd:
base_date = base_date + calculator.time_delta
nancsd_date = calculator.relative_day_to_date(
relative_day=nancsd_day,
relative_month=nancsd_month,
base_date=base_date
)
workflow.non_adjusted_next_cycle_start_date = nancsd_date
workflow.next_cycle_start_date = calculator.adjust_date(nancsd_date)
post_compute_ncsd = workflow.next_cycle_start_date
start_dates = ["{}/{}".format(
task.relative_start_month,
task.relative_start_day) for tg in workflow.task_groups
for task in tg.task_group_tasks]
end_dates = ["{}/{}".format(
task.relative_end_month,
task.relative_end_day) for tg in workflow.task_groups
for task in tg.task_group_tasks]
if pre_compute_ncsd != post_compute_ncsd:
app.logger.warning(
"Adjusted NCSD for workflow {}. "
"Freq: {}, PRE: {}, Last cycle: {}, POST: {}, NON: {},"
"tasks start: {}, tasks end: {},".format(
workflow.id,
workflow.frequency[:2],
pre_compute_ncsd,
last_cycle_start_date,
post_compute_ncsd,
workflow.non_adjusted_next_cycle_start_date,
start_dates,
end_dates))
db.session.add(workflow)
# Save
db.session.commit()
def downgrade():
op.drop_column('workflows', 'non_adjusted_next_cycle_start_date')
| true | true |
f719e6b707f00ff2d2978971d22b48f62a159092 | 4,228 | py | Python | vise/analyzer/dielectric_function.py | kumagai-group/vise | 8adfe61ad8f31767ec562f02f271e2495f357cd4 | [
"MIT"
] | 16 | 2020-07-14T13:14:05.000Z | 2022-03-04T13:39:30.000Z | vise/analyzer/dielectric_function.py | kumagai-group/vise | 8adfe61ad8f31767ec562f02f271e2495f357cd4 | [
"MIT"
] | 10 | 2021-03-15T20:47:45.000Z | 2021-08-19T00:47:12.000Z | vise/analyzer/dielectric_function.py | kumagai-group/vise | 8adfe61ad8f31767ec562f02f271e2495f357cd4 | [
"MIT"
] | 6 | 2020-03-03T00:42:39.000Z | 2022-02-22T02:34:47.000Z | # -*- coding: utf-8 -*-
# Copyright (c) 2020. Distributed under the terms of the MIT License.
from dataclasses import dataclass
from math import sqrt, pi
from typing import List
import numpy as np
from monty.json import MSONable
from tqdm import tqdm
from vise.util.mix_in import ToJsonFileMixIn
from scipy.constants import physical_constants as pc
eV_to_inv_cm = pc["electron volt-inverse meter relationship"][0] / 100
def diele_func_to_coeff(freq, real, imag):
return (2 * sqrt(2) * pi * sqrt(sqrt(real ** 2 + imag ** 2) - real)
* freq * eV_to_inv_cm)
@dataclass
class DieleFuncData(MSONable, ToJsonFileMixIn):
energies: List[float] # in eV
diele_func_real: List[List[float]] # [xx, yy, zz, xy, yz, xz]
diele_func_imag: List[List[float]] # [xx, yy, zz, xy, yz, xz]
band_gap: float # in eV
@property
def ave_absorption_coeff(self):
reals = [sum(self.diele_func_real[i][:3]) / 3
for i in range(len(self.energies))]
imags = [sum(self.diele_func_imag[i][:3]) / 3
for i in range(len(self.energies))]
return [diele_func_to_coeff(freq, real, imag)
for freq, real, imag in zip(self.energies, reals, imags)]
def target_coeff_min_e(self, target_coeff: float = 10**4):
for e, coeff in zip(self.energies, self.ave_absorption_coeff):
if coeff > target_coeff:
return e
return None
def make_shifted_diele_func(diele_func_data: DieleFuncData,
original_band_gap: float,
shift: float) -> DieleFuncData:
imag = imag_shift(diele_func_data.diele_func_imag,
diele_func_data.energies,
original_band_gap + shift, shift)
real = kramers_kronig_trans(imag, diele_func_data.energies)
return DieleFuncData(diele_func_data.energies,
real.tolist(),
imag.tolist(),
original_band_gap + shift)
def imag_shift(diele_func_imag: List[List[float]],
energies: List[float],
band_gap: float,
shift: float) -> np.ndarray:
energies = np.array(energies)
assert shift > 0
result = []
for energy_grid in energies:
old_e = energy_grid - shift
right_idx = np.argwhere(energies > old_e)[0][0]
left_e, right_e = energies[right_idx - 1], energies[right_idx]
# linear interpolation
left_ratio = (right_e - old_e) / (right_e - left_e)
inner_result = []
for imag_idx in range(6):
if energy_grid < band_gap:
inner_result.append(0.0)
else:
old_diele = \
diele_func_imag[right_idx - 1][imag_idx] * left_ratio + \
diele_func_imag[right_idx][imag_idx] * (1 - left_ratio)
inner_result.append(
old_diele * (energy_grid - shift) / energy_grid)
result.append(inner_result)
return np.array(result)
def kramers_kronig_trans(diele_func_imag: np.array,
energies: List[float],
ita: float = 0.01) -> np.ndarray:
mesh = energies[1] - energies[0]
result = []
ee2ss = [[e ** 2 - energy_grid ** 2 for e in energies]
for energy_grid in energies]
for imag_idx in tqdm(range(6)):
imags = diele_func_imag[:, imag_idx]
if imag_idx == 0 or \
(imag_idx > 0
and np.allclose(
imags, diele_func_imag[:, imag_idx - 1]) is False):
if np.count_nonzero(imags) == 0:
inner_result = [0.0] * len(energies)
else:
inner_result = []
for ee2s in ee2ss:
integrals = [e * imag * ee2 / (ee2 ** 2 + ita ** 2)
for e, ee2, imag in zip(energies, ee2s, imags)]
integral = sum(integrals) * mesh * 2 / pi
if imag_idx < 3:
integral += 1
inner_result.append(integral)
result.append(inner_result)
return np.array(result).T | 37.087719 | 80 | 0.565989 |
from dataclasses import dataclass
from math import sqrt, pi
from typing import List
import numpy as np
from monty.json import MSONable
from tqdm import tqdm
from vise.util.mix_in import ToJsonFileMixIn
from scipy.constants import physical_constants as pc
eV_to_inv_cm = pc["electron volt-inverse meter relationship"][0] / 100
def diele_func_to_coeff(freq, real, imag):
return (2 * sqrt(2) * pi * sqrt(sqrt(real ** 2 + imag ** 2) - real)
* freq * eV_to_inv_cm)
@dataclass
class DieleFuncData(MSONable, ToJsonFileMixIn):
energies: List[float]
diele_func_real: List[List[float]]
diele_func_imag: List[List[float]]
band_gap: float
@property
def ave_absorption_coeff(self):
reals = [sum(self.diele_func_real[i][:3]) / 3
for i in range(len(self.energies))]
imags = [sum(self.diele_func_imag[i][:3]) / 3
for i in range(len(self.energies))]
return [diele_func_to_coeff(freq, real, imag)
for freq, real, imag in zip(self.energies, reals, imags)]
def target_coeff_min_e(self, target_coeff: float = 10**4):
for e, coeff in zip(self.energies, self.ave_absorption_coeff):
if coeff > target_coeff:
return e
return None
def make_shifted_diele_func(diele_func_data: DieleFuncData,
original_band_gap: float,
shift: float) -> DieleFuncData:
imag = imag_shift(diele_func_data.diele_func_imag,
diele_func_data.energies,
original_band_gap + shift, shift)
real = kramers_kronig_trans(imag, diele_func_data.energies)
return DieleFuncData(diele_func_data.energies,
real.tolist(),
imag.tolist(),
original_band_gap + shift)
def imag_shift(diele_func_imag: List[List[float]],
energies: List[float],
band_gap: float,
shift: float) -> np.ndarray:
energies = np.array(energies)
assert shift > 0
result = []
for energy_grid in energies:
old_e = energy_grid - shift
right_idx = np.argwhere(energies > old_e)[0][0]
left_e, right_e = energies[right_idx - 1], energies[right_idx]
left_ratio = (right_e - old_e) / (right_e - left_e)
inner_result = []
for imag_idx in range(6):
if energy_grid < band_gap:
inner_result.append(0.0)
else:
old_diele = \
diele_func_imag[right_idx - 1][imag_idx] * left_ratio + \
diele_func_imag[right_idx][imag_idx] * (1 - left_ratio)
inner_result.append(
old_diele * (energy_grid - shift) / energy_grid)
result.append(inner_result)
return np.array(result)
def kramers_kronig_trans(diele_func_imag: np.array,
energies: List[float],
ita: float = 0.01) -> np.ndarray:
mesh = energies[1] - energies[0]
result = []
ee2ss = [[e ** 2 - energy_grid ** 2 for e in energies]
for energy_grid in energies]
for imag_idx in tqdm(range(6)):
imags = diele_func_imag[:, imag_idx]
if imag_idx == 0 or \
(imag_idx > 0
and np.allclose(
imags, diele_func_imag[:, imag_idx - 1]) is False):
if np.count_nonzero(imags) == 0:
inner_result = [0.0] * len(energies)
else:
inner_result = []
for ee2s in ee2ss:
integrals = [e * imag * ee2 / (ee2 ** 2 + ita ** 2)
for e, ee2, imag in zip(energies, ee2s, imags)]
integral = sum(integrals) * mesh * 2 / pi
if imag_idx < 3:
integral += 1
inner_result.append(integral)
result.append(inner_result)
return np.array(result).T | true | true |
f719e7006ad29396ce30e456e8d231c230206adc | 2,488 | py | Python | main.py | Kiny-Kiny/WordlistCreator | 3492f8176959beca23fa22877f2923c74ca6bf89 | [
"BSD-3-Clause"
] | 2 | 2021-10-31T15:38:55.000Z | 2021-12-12T06:20:20.000Z | main.py | Kiny-Kiny/WordlistCreator | 3492f8176959beca23fa22877f2923c74ca6bf89 | [
"BSD-3-Clause"
] | null | null | null | main.py | Kiny-Kiny/WordlistCreator | 3492f8176959beca23fa22877f2923c74ca6bf89 | [
"BSD-3-Clause"
] | null | null | null | # Recomendação : Use apenas se seu computador/celular for bom.
# Autor : Kiny
# Pix : (61) 9603-5417
# Github : https://github.com/Kiny-Kiny
# WhatsApp : http://wa.me/552179180533
# Telegram : @K_iny
# Instagram : @parziovanni
# Twitter : @KinyBruno
############################################
'''Módulos'''
from itertools import product;
from sys import argv,stdout;
from time import sleep;
from os import system;
############################################
'''Cores'''
global R,B,C,G
R='\033[1;31m';
B='\033[1;34m';
C='\033[1;37m';
G='\033[1;32m';
############################################
'''Funções'''
def slow(msg):
for i in msg: stdout.write(i);sleep(0.007);stdout.flush();
def clear(): system('cls||clear');
############################################
'''Banner'''
logo=B+''' __ __ __ __ __ __ __
/\ \/ / /\ \ /\ "-.\ \ /\ \_\ \
\ \ _"-. \ \ \ \ \ \-. \ \ \____ \
\ \_\ \_\ \ \_\ \ \_\\"\_\ \/\_____\
\/_/\/_/ \/_/ \/_/ \/_/ \/_____/ \n'''+C
############################################
'''Parte de criação da Wordlist'''
def wordlist(i):
msg='';res = product('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_1234567890', repeat=i);
for g in res:
senha=''
for i in g: senha+=i
msg+=f'{senha}\n'
return msg
def main(min,max):
lis=[]
slow(
f'[{G}!{C}] Criando a WordList...\n'
)
for i in range(int(min),int(max)): lis.append(str(wordlist(i)));
msg='';
for i in lis: msg+=i
file=open('KingCrimson.txt','w+');
file.write(msg);
file.close();
clear();
slow(
f'{logo}\n[{G}Wordlist Criada!{C}] A wordlist foi criada e salva no arquivo KingCrimson.txt\n'
);
############################################
if int(len(argv)) < 3:
slow(
str(logo) + f'\n{G}- {C}Modo de Uso{G} : {C}python3 '+ str(argv[0]) + G+' {'+C+'Quantidade mínima'+G+'} {' +C+'Quantidade Máxima'+G+'}\n'+C
);exit();
try: int(argv[1]);int(argv[2]);
except: slow(
f'{logo}\n[{R}Error{C}] Use apenas números inteiros! (ex: 7)\n'
);exit();
if __name__=='__main__':
clear()
if int(argv[1]) == int(argv[2]):
slow(
f'{logo}\n[{R}Error{C}] A quantidade mínima não pode ser igual a quantidade máxima.\n'
);
elif int(argv[1]) > int(argv[2]):
slow(
f'{logo}\n[{R}Error{C}] A quantidade mínima não pode ser maior que a quantidade máxima.\n'
);
else:
try:
main(int(argv[1]),int(argv[2]));
except:
clear();
slow(
f'{logo}[{R}Error{C}] Erro Desconhecido.\n'
);
| 27.043478 | 140 | 0.513264 | true | true | |
f719e947d81719e7404f7f12a8aca3b32f7370bb | 66 | py | Python | core/__init__.py | berendkleinhaneveld/Registrationshop | 0d6f3ee5324865cdcb419369139f37c39dfe9a1c | [
"MIT"
] | 25 | 2015-11-08T16:36:54.000Z | 2022-01-20T16:03:28.000Z | core/__init__.py | berendkleinhaneveld/Registrationshop | 0d6f3ee5324865cdcb419369139f37c39dfe9a1c | [
"MIT"
] | 2 | 2016-12-01T23:13:08.000Z | 2017-07-25T02:40:49.000Z | core/__init__.py | berendkleinhaneveld/Registrationshop | 0d6f3ee5324865cdcb419369139f37c39dfe9a1c | [
"MIT"
] | 10 | 2016-07-05T14:39:16.000Z | 2022-01-01T02:05:55.000Z | from AppVars import AppVars
from AppResources import AppResources
| 22 | 37 | 0.878788 | from AppVars import AppVars
from AppResources import AppResources
| true | true |
f719e96b6824efbbe4833272ec5ec4b37e319c12 | 2,894 | py | Python | test/functional/interface_bitcoin_cli.py | ComputerCraftr/pivx-gui | 79c13d9dcaf48dfb11400f0bc5733aaa7c83cee9 | [
"MIT"
] | null | null | null | test/functional/interface_bitcoin_cli.py | ComputerCraftr/pivx-gui | 79c13d9dcaf48dfb11400f0bc5733aaa7c83cee9 | [
"MIT"
] | null | null | null | test/functional/interface_bitcoin_cli.py | ComputerCraftr/pivx-gui | 79c13d9dcaf48dfb11400f0bc5733aaa7c83cee9 | [
"MIT"
] | 1 | 2021-01-23T04:15:52.000Z | 2021-01-23T04:15:52.000Z | #!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test ysw-cli"""
from test_framework.test_framework import YieldSakingWalletTestFramework
from test_framework.util import assert_equal, assert_raises_process_error, get_auth_cookie
import time
class TestBitcoinCli(YieldSakingWalletTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
"""Main test logic"""
self.log.info("Sleeping 30 seconds...")
time.sleep(30)
self.log.info("Compare responses from gewalletinfo RPC and `ysw-cli getwalletinfo`")
cli_response = self.nodes[0].cli.getwalletinfo()
rpc_response = self.nodes[0].getwalletinfo()
assert_equal(cli_response, rpc_response)
self.log.info("Compare responses from getblockchaininfo RPC and `ysw-cli getblockchaininfo`")
cli_response = self.nodes[0].cli.getblockchaininfo()
rpc_response = self.nodes[0].getblockchaininfo()
assert_equal(cli_response, rpc_response)
user, password = get_auth_cookie(self.nodes[0].datadir)
self.log.info("Compare responses from `ysw-cli -getinfo` and the RPCs data is retrieved from.")
cli_get_info = self.nodes[0].cli('getinfo').send_cli()
wallet_info = self.nodes[0].getwalletinfo()
network_info = self.nodes[0].getnetworkinfo()
blockchain_info = self.nodes[0].getblockchaininfo()
assert_equal(cli_get_info['version'], network_info['version'])
assert_equal(cli_get_info['protocolversion'], network_info['protocolversion'])
assert_equal(cli_get_info['walletversion'], wallet_info['walletversion'])
assert_equal(cli_get_info['balance'], wallet_info['balance'])
assert_equal(cli_get_info['blocks'], blockchain_info['blocks'])
assert_equal(cli_get_info['timeoffset'], network_info['timeoffset'])
assert_equal(cli_get_info['connections'], network_info['connections'])
assert_equal(cli_get_info['proxy'], network_info['networks'][0]['proxy'])
assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty'])
assert_equal(cli_get_info['testnet'], blockchain_info['chain'] == "test")
assert_equal(cli_get_info['balance'], wallet_info['balance'])
assert_equal(cli_get_info['keypoololdest'], wallet_info['keypoololdest'])
assert_equal(cli_get_info['keypoolsize'], wallet_info['keypoolsize'])
assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee'])
assert_equal(cli_get_info['relayfee'], network_info['relayfee'])
# unlocked_until is not tested because the wallet is not encrypted
if __name__ == '__main__':
TestBitcoinCli().main()
| 49.050847 | 103 | 0.715619 |
from test_framework.test_framework import YieldSakingWalletTestFramework
from test_framework.util import assert_equal, assert_raises_process_error, get_auth_cookie
import time
class TestBitcoinCli(YieldSakingWalletTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
self.log.info("Sleeping 30 seconds...")
time.sleep(30)
self.log.info("Compare responses from gewalletinfo RPC and `ysw-cli getwalletinfo`")
cli_response = self.nodes[0].cli.getwalletinfo()
rpc_response = self.nodes[0].getwalletinfo()
assert_equal(cli_response, rpc_response)
self.log.info("Compare responses from getblockchaininfo RPC and `ysw-cli getblockchaininfo`")
cli_response = self.nodes[0].cli.getblockchaininfo()
rpc_response = self.nodes[0].getblockchaininfo()
assert_equal(cli_response, rpc_response)
user, password = get_auth_cookie(self.nodes[0].datadir)
self.log.info("Compare responses from `ysw-cli -getinfo` and the RPCs data is retrieved from.")
cli_get_info = self.nodes[0].cli('getinfo').send_cli()
wallet_info = self.nodes[0].getwalletinfo()
network_info = self.nodes[0].getnetworkinfo()
blockchain_info = self.nodes[0].getblockchaininfo()
assert_equal(cli_get_info['version'], network_info['version'])
assert_equal(cli_get_info['protocolversion'], network_info['protocolversion'])
assert_equal(cli_get_info['walletversion'], wallet_info['walletversion'])
assert_equal(cli_get_info['balance'], wallet_info['balance'])
assert_equal(cli_get_info['blocks'], blockchain_info['blocks'])
assert_equal(cli_get_info['timeoffset'], network_info['timeoffset'])
assert_equal(cli_get_info['connections'], network_info['connections'])
assert_equal(cli_get_info['proxy'], network_info['networks'][0]['proxy'])
assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty'])
assert_equal(cli_get_info['testnet'], blockchain_info['chain'] == "test")
assert_equal(cli_get_info['balance'], wallet_info['balance'])
assert_equal(cli_get_info['keypoololdest'], wallet_info['keypoololdest'])
assert_equal(cli_get_info['keypoolsize'], wallet_info['keypoolsize'])
assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee'])
assert_equal(cli_get_info['relayfee'], network_info['relayfee'])
if __name__ == '__main__':
TestBitcoinCli().main()
| true | true |
f719ea3d7dd63575d0159399e9ac03475a0baa21 | 924 | py | Python | aldryn_google_chrome_frame/models.py | aldryn/aldryn-google-chrome-frame | a0deda5d7b4b60b1ca88b7c3b09685e86b598e2a | [
"BSD-3-Clause"
] | null | null | null | aldryn_google_chrome_frame/models.py | aldryn/aldryn-google-chrome-frame | a0deda5d7b4b60b1ca88b7c3b09685e86b598e2a | [
"BSD-3-Clause"
] | null | null | null | aldryn_google_chrome_frame/models.py | aldryn/aldryn-google-chrome-frame | a0deda5d7b4b60b1ca88b7c3b09685e86b598e2a | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
from cmscloud.template_api import registry
from django.conf import settings
def get_meta_version(max_version):
max_version = int(max_version)
assert 6 <= max_version <= 9
if max_version == 9:
return '1'
else:
return 'IE%d' % (max_version, )
META_TAG = '<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=%(meta_version)s">'
registry.add_to_head(META_TAG % {'meta_version': get_meta_version(settings.GOOGLE_CHROME_FRAME_MAX_VERSION)})
PROMPT_SCRIPT = """<!--[if lte IE %(max_version)s ]>
<script src="//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.2/CFInstall.min.js"></script>
<script>window.attachEvent("onload",function(){CFInstall.check({mode:"overlay"})})</script>
<![endif]-->"""
if getattr(settings, 'GOOGLE_CHROME_FRAME_PROMPT', False):
registry.add_to_tail(PROMPT_SCRIPT % {'max_version': settings.GOOGLE_CHROME_FRAME_MAX_VERSION})
| 36.96 | 109 | 0.712121 |
from cmscloud.template_api import registry
from django.conf import settings
def get_meta_version(max_version):
max_version = int(max_version)
assert 6 <= max_version <= 9
if max_version == 9:
return '1'
else:
return 'IE%d' % (max_version, )
META_TAG = '<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=%(meta_version)s">'
registry.add_to_head(META_TAG % {'meta_version': get_meta_version(settings.GOOGLE_CHROME_FRAME_MAX_VERSION)})
PROMPT_SCRIPT = """<!--[if lte IE %(max_version)s ]>
<script src="//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.2/CFInstall.min.js"></script>
<script>window.attachEvent("onload",function(){CFInstall.check({mode:"overlay"})})</script>
<![endif]-->"""
if getattr(settings, 'GOOGLE_CHROME_FRAME_PROMPT', False):
registry.add_to_tail(PROMPT_SCRIPT % {'max_version': settings.GOOGLE_CHROME_FRAME_MAX_VERSION})
| true | true |
f719ea5c0a903eafeb8163fd0cad4442d6c73370 | 520 | py | Python | torchtools/callbacks/__init__.py | Time1ess/torchtools | 1c48591188827f8a7403162728f86229203354c5 | [
"BSD-3-Clause"
] | 16 | 2017-08-15T14:01:13.000Z | 2020-12-21T11:23:31.000Z | torchtools/callbacks/__init__.py | Time1ess/torchtools | 1c48591188827f8a7403162728f86229203354c5 | [
"BSD-3-Clause"
] | null | null | null | torchtools/callbacks/__init__.py | Time1ess/torchtools | 1c48591188827f8a7403162728f86229203354c5 | [
"BSD-3-Clause"
] | 2 | 2017-12-28T14:09:09.000Z | 2020-07-14T14:29:30.000Z | # coding: UTF-8
from .callback import Hook, Callback
from .checkpoint import ModelCheckPoint
from .csvlogger import CSVLogger
from .early_stopping import EarlyStopping
from .lr_scheduler import (
LambdaLR, StepLR, MultiStepLR, ExponentialLR, ReduceLROnPlateau)
from .tensorboard_logger import TensorBoardLogger
__all__ = [
'Hook', 'Callback',
'ModelCheckPoint',
'CSVLogger',
'EarlyStopping',
'LambdaLR', 'StepLR', 'MultiStepLR', 'ExponentialLR', 'ReduceLROnPlateau',
'TensorBoardLogger',
]
| 27.368421 | 78 | 0.75 |
from .callback import Hook, Callback
from .checkpoint import ModelCheckPoint
from .csvlogger import CSVLogger
from .early_stopping import EarlyStopping
from .lr_scheduler import (
LambdaLR, StepLR, MultiStepLR, ExponentialLR, ReduceLROnPlateau)
from .tensorboard_logger import TensorBoardLogger
__all__ = [
'Hook', 'Callback',
'ModelCheckPoint',
'CSVLogger',
'EarlyStopping',
'LambdaLR', 'StepLR', 'MultiStepLR', 'ExponentialLR', 'ReduceLROnPlateau',
'TensorBoardLogger',
]
| true | true |
f719ea9ceaf6800cbd249182d3c34733fdae35f0 | 3,716 | py | Python | test.py | AlbertoSousaSantana/devopslav_full02 | 679bdca0f2fb886febeba37696f49143105894b6 | [
"MIT"
] | null | null | null | test.py | AlbertoSousaSantana/devopslav_full02 | 679bdca0f2fb886febeba37696f49143105894b6 | [
"MIT"
] | null | null | null | test.py | AlbertoSousaSantana/devopslav_full02 | 679bdca0f2fb886febeba37696f49143105894b6 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from app import app
import unittest
class Test(unittest.TestCase):
def setUp(self):
# cria uma instância do unittest, precisa do nome "setUp"
self.app = app.test_client()
# envia uma requisicao GET para a URL
self.result = self.app.get('/')
def test_requisicao(self):
# compara o status da requisicao (precisa ser igual a 200)
self.assertEqual(self.result.status_code, 200)
def test_conteudo(self):
# verifica o retorno do conteudo da pagina
self.assertEqual(self.result.data.decode('utf-8'), "mensagem personalizada Alberto3")
if __name__ == "__main__":
print ('INICIANDO OS TESTES')
print('----------------------------------------------------------------------')
unittest.main(verbosity=2) | 148.64 | 222 | 0.130786 |
from app import app
import unittest
class Test(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
self.result = self.app.get('/')
def test_requisicao(self):
self.assertEqual(self.result.status_code, 200)
def test_conteudo(self):
self.assertEqual(self.result.data.decode('utf-8'), "mensagem personalizada Alberto3")
if __name__ == "__main__":
print ('INICIANDO OS TESTES')
print('----------------------------------------------------------------------')
unittest.main(verbosity=2) | true | true |
f719eb4a68e5fddea525ab05f9a6de0a28ad334a | 10,408 | py | Python | retinanet/losses_vehicle.py | RobinCondat/pytorch-retinanet | 14a2085cd3785a667454898dc65f5324b1b9c6b8 | [
"Apache-2.0"
] | null | null | null | retinanet/losses_vehicle.py | RobinCondat/pytorch-retinanet | 14a2085cd3785a667454898dc65f5324b1b9c6b8 | [
"Apache-2.0"
] | null | null | null | retinanet/losses_vehicle.py | RobinCondat/pytorch-retinanet | 14a2085cd3785a667454898dc65f5324b1b9c6b8 | [
"Apache-2.0"
] | null | null | null | import numpy as np
import torch
import torch.nn as nn
from retinanet.config_experiment_2 import INDEXES_MIX, VEHICLE_INDEXES
def calc_iou(a, b):
area = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])
iw = torch.min(torch.unsqueeze(a[:, 2], dim=1), b[:, 2]) - torch.max(torch.unsqueeze(a[:, 0], 1), b[:, 0])
ih = torch.min(torch.unsqueeze(a[:, 3], dim=1), b[:, 3]) - torch.max(torch.unsqueeze(a[:, 1], 1), b[:, 1])
iw = torch.clamp(iw, min=0)
ih = torch.clamp(ih, min=0)
ua = torch.unsqueeze((a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1]), dim=1) + area - iw * ih
ua = torch.clamp(ua, min=1e-8)
intersection = iw * ih
IoU = intersection / ua
return IoU
def cal_ioa(a, b):
# Intersection over Area (for ignore regions)
area = torch.unsqueeze((a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1]),dim=1)
area = torch.clamp(area, min=1e-8)
iw = torch.min(torch.unsqueeze(a[:, 2], dim=1), b[:, 2]) - torch.max(torch.unsqueeze(a[:, 0], 1), b[:, 0])
ih = torch.min(torch.unsqueeze(a[:, 3], dim=1), b[:, 3]) - torch.max(torch.unsqueeze(a[:, 1], 1), b[:, 1])
iw = torch.clamp(iw, min=0)
ih = torch.clamp(ih, min=0)
intersection = iw * ih
IoA = intersection / area
return IoA
class FocalLoss(nn.Module):
#def __init__(self):
def forward(self, classifications, regressions, anchors, annotations, dataset, ignore_index=None, merge_index=None):
classes_from_other_datasets = [i for i in range(classifications.shape[-1]+1) if i not in INDEXES_MIX[dataset]]
alpha = 0.25
gamma = 2.0
batch_size = classifications.shape[0]
classification_losses = []
regression_losses = []
anchor = anchors[0, :, :]
num_anchors = anchor.shape[0]
anchor_widths = anchor[:, 2] - anchor[:, 0]
anchor_heights = anchor[:, 3] - anchor[:, 1]
anchor_ctr_x = anchor[:, 0] + 0.5 * anchor_widths
anchor_ctr_y = anchor[:, 1] + 0.5 * anchor_heights
if merge_index is not None:
classifications = torch.cat((classifications,torch.zeros((classifications.shape[0],classifications.shape[1],1)).cuda()),2)
print(classifications.shape)
for j in range(batch_size):
classification = classifications[j, :, :]
regression = regressions[j, :, :]
bbox_annotation = annotations[j, :, :]
bbox_annotation = bbox_annotation[bbox_annotation[:, 4] != -1]
# Merge vehicle detections in vehicle class
if merge_index is not None:
if merge_index not in classes_from_other_datasets:
#print(torch.max(classification[:,VEHICLE_INDEXES], dim=1)[0].shape)
classification[:,merge_index] = torch.max(classification[:,VEHICLE_INDEXES], dim=1)[0]
# Ignore class from other datasets
classification[:,classes_from_other_datasets]=0
classification = torch.clamp(classification, 1e-4, 1.0 - 1e-4)
if bbox_annotation.shape[0] == 0:
if torch.cuda.is_available():
alpha_factor = torch.ones(classification.shape).cuda() * alpha
alpha_factor = 1. - alpha_factor
focal_weight = classification
focal_weight = alpha_factor * torch.pow(focal_weight, gamma)
bce = -(torch.log(1.0 - classification))
cls_loss = focal_weight * bce
classification_losses.append(cls_loss.sum())
regression_losses.append(torch.tensor(0).float().cuda())
else:
alpha_factor = torch.ones(classification.shape) * alpha
alpha_factor = 1. - alpha_factor
focal_weight = classification
focal_weight = alpha_factor * torch.pow(focal_weight, gamma)
bce = -(torch.log(1.0 - classification))
cls_loss = focal_weight * bce
classification_losses.append(cls_loss.sum())
regression_losses.append(torch.tensor(0).float())
continue
# Filter ignore class (via ignore_index)
if ignore_index is not None:
# On sépare ici les annotations en 2 objets :
# - bbox_annotation (pour tous les objets à détecter)
# - ignore_annotation (pour toutes les régions à ignorer)
ignore_annotation = bbox_annotation[bbox_annotation[:,4] == ignore_index]
bbox_annotation = bbox_annotation[bbox_annotation[:,4] != ignore_index]
if bbox_annotation.shape[0] != 0:
IoU = calc_iou(anchors[0, :, :], bbox_annotation[:, :4]) # num_anchors x num_annotations_to_detect
IoU_max, IoU_argmax = torch.max(IoU, dim=1) # num_anchors x 1
else:
IoU_max = None
IoU_argmax = None
if ignore_index is not None:
# On calcule ici l'intersection over area :
# tous les anchors ayant une IoA avec une région à ignorer supérieure à 0.5 seront ignorées pour la suite
if ignore_annotation.shape[0] !=0:
IoA = cal_ioa(anchors[0, :, :], ignore_annotation[:, :4]) # num_anchors x num_annotations_to_ignore
IoA_max, IoA_argmax = torch.max(IoA, dim=1) # num_anchors x 1
else:
IoA_max = None
IoA_argmax = None
# compute the loss for classification
targets = torch.ones(classification.shape) * -1
if torch.cuda.is_available():
targets = targets.cuda()
if IoU_max is not None:
targets[torch.lt(IoU_max, 0.4), :] = 0
else:
targets = targets*0
if ignore_index is not None:
if IoA_max is not None:
ignore_indices = torch.ge(IoA_max, 0.5)
else:
ignore_indices = (torch.ones((num_anchors)) * 0).type(torch.ByteTensor)
if IoU_max is not None:
positive_indices = torch.ge(IoU_max, 0.5)
num_positive_anchors = positive_indices.sum()
else:
positive_indices = (torch.ones((num_anchors)) * 0).type(torch.ByteTensor)
num_positive_anchors = torch.tensor(0)
if ignore_index is not None:
if ignore_indices is not None:
targets[ignore_indices, :] = -1
if IoU_argmax is not None:
assigned_annotations = bbox_annotation[IoU_argmax, :]
targets[positive_indices, :] = 0
targets[positive_indices, assigned_annotations[positive_indices, 4].long()] = 1
if torch.cuda.is_available():
alpha_factor = torch.ones(targets.shape).cuda() * alpha
else:
alpha_factor = torch.ones(targets.shape) * alpha
alpha_factor = torch.where(torch.eq(targets, 1.), alpha_factor, 1. - alpha_factor)
focal_weight = torch.where(torch.eq(targets, 1.), 1. - classification, classification)
focal_weight = alpha_factor * torch.pow(focal_weight, gamma)
bce = -(targets * torch.log(classification) + (1.0 - targets) * torch.log(1.0 - classification))
cls_loss = focal_weight * bce
if torch.cuda.is_available():
cls_loss = torch.where(torch.ne(targets, -1.0), cls_loss, torch.zeros(cls_loss.shape).cuda())
else:
cls_loss = torch.where(torch.ne(targets, -1.0), cls_loss, torch.zeros(cls_loss.shape))
classification_losses.append(cls_loss.sum()/torch.clamp(num_positive_anchors.float(), min=1.0))
# compute the loss for regression
if num_positive_anchors > 0:
assigned_annotations = assigned_annotations[positive_indices, :]
anchor_widths_pi = anchor_widths[positive_indices]
anchor_heights_pi = anchor_heights[positive_indices]
anchor_ctr_x_pi = anchor_ctr_x[positive_indices]
anchor_ctr_y_pi = anchor_ctr_y[positive_indices]
gt_widths = assigned_annotations[:, 2] - assigned_annotations[:, 0]
gt_heights = assigned_annotations[:, 3] - assigned_annotations[:, 1]
gt_ctr_x = assigned_annotations[:, 0] + 0.5 * gt_widths
gt_ctr_y = assigned_annotations[:, 1] + 0.5 * gt_heights
# clip widths to 1
gt_widths = torch.clamp(gt_widths, min=1)
gt_heights = torch.clamp(gt_heights, min=1)
targets_dx = (gt_ctr_x - anchor_ctr_x_pi) / anchor_widths_pi
targets_dy = (gt_ctr_y - anchor_ctr_y_pi) / anchor_heights_pi
targets_dw = torch.log(gt_widths / anchor_widths_pi)
targets_dh = torch.log(gt_heights / anchor_heights_pi)
targets = torch.stack((targets_dx, targets_dy, targets_dw, targets_dh))
targets = targets.t()
if torch.cuda.is_available():
targets = targets/torch.Tensor([[0.1, 0.1, 0.2, 0.2]]).cuda()
else:
targets = targets/torch.Tensor([[0.1, 0.1, 0.2, 0.2]])
negative_indices = 1 + (~positive_indices)
regression_diff = torch.abs(targets - regression[positive_indices, :])
regression_loss = torch.where(
torch.le(regression_diff, 1.0 / 9.0),
0.5 * 9.0 * torch.pow(regression_diff, 2),
regression_diff - 0.5 / 9.0
)
regression_losses.append(regression_loss.mean())
else:
if torch.cuda.is_available():
regression_losses.append(torch.tensor(0).float().cuda())
else:
regression_losses.append(torch.tensor(0).float())
return torch.stack(classification_losses).mean(dim=0, keepdim=True), torch.stack(regression_losses).mean(dim=0, keepdim=True)
| 42.831276 | 133 | 0.560146 | import numpy as np
import torch
import torch.nn as nn
from retinanet.config_experiment_2 import INDEXES_MIX, VEHICLE_INDEXES
def calc_iou(a, b):
area = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])
iw = torch.min(torch.unsqueeze(a[:, 2], dim=1), b[:, 2]) - torch.max(torch.unsqueeze(a[:, 0], 1), b[:, 0])
ih = torch.min(torch.unsqueeze(a[:, 3], dim=1), b[:, 3]) - torch.max(torch.unsqueeze(a[:, 1], 1), b[:, 1])
iw = torch.clamp(iw, min=0)
ih = torch.clamp(ih, min=0)
ua = torch.unsqueeze((a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1]), dim=1) + area - iw * ih
ua = torch.clamp(ua, min=1e-8)
intersection = iw * ih
IoU = intersection / ua
return IoU
def cal_ioa(a, b):
area = torch.unsqueeze((a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1]),dim=1)
area = torch.clamp(area, min=1e-8)
iw = torch.min(torch.unsqueeze(a[:, 2], dim=1), b[:, 2]) - torch.max(torch.unsqueeze(a[:, 0], 1), b[:, 0])
ih = torch.min(torch.unsqueeze(a[:, 3], dim=1), b[:, 3]) - torch.max(torch.unsqueeze(a[:, 1], 1), b[:, 1])
iw = torch.clamp(iw, min=0)
ih = torch.clamp(ih, min=0)
intersection = iw * ih
IoA = intersection / area
return IoA
class FocalLoss(nn.Module):
def forward(self, classifications, regressions, anchors, annotations, dataset, ignore_index=None, merge_index=None):
classes_from_other_datasets = [i for i in range(classifications.shape[-1]+1) if i not in INDEXES_MIX[dataset]]
alpha = 0.25
gamma = 2.0
batch_size = classifications.shape[0]
classification_losses = []
regression_losses = []
anchor = anchors[0, :, :]
num_anchors = anchor.shape[0]
anchor_widths = anchor[:, 2] - anchor[:, 0]
anchor_heights = anchor[:, 3] - anchor[:, 1]
anchor_ctr_x = anchor[:, 0] + 0.5 * anchor_widths
anchor_ctr_y = anchor[:, 1] + 0.5 * anchor_heights
if merge_index is not None:
classifications = torch.cat((classifications,torch.zeros((classifications.shape[0],classifications.shape[1],1)).cuda()),2)
print(classifications.shape)
for j in range(batch_size):
classification = classifications[j, :, :]
regression = regressions[j, :, :]
bbox_annotation = annotations[j, :, :]
bbox_annotation = bbox_annotation[bbox_annotation[:, 4] != -1]
if merge_index is not None:
if merge_index not in classes_from_other_datasets:
classification[:,merge_index] = torch.max(classification[:,VEHICLE_INDEXES], dim=1)[0]
classification[:,classes_from_other_datasets]=0
classification = torch.clamp(classification, 1e-4, 1.0 - 1e-4)
if bbox_annotation.shape[0] == 0:
if torch.cuda.is_available():
alpha_factor = torch.ones(classification.shape).cuda() * alpha
alpha_factor = 1. - alpha_factor
focal_weight = classification
focal_weight = alpha_factor * torch.pow(focal_weight, gamma)
bce = -(torch.log(1.0 - classification))
cls_loss = focal_weight * bce
classification_losses.append(cls_loss.sum())
regression_losses.append(torch.tensor(0).float().cuda())
else:
alpha_factor = torch.ones(classification.shape) * alpha
alpha_factor = 1. - alpha_factor
focal_weight = classification
focal_weight = alpha_factor * torch.pow(focal_weight, gamma)
bce = -(torch.log(1.0 - classification))
cls_loss = focal_weight * bce
classification_losses.append(cls_loss.sum())
regression_losses.append(torch.tensor(0).float())
continue
if ignore_index is not None:
ignore_annotation = bbox_annotation[bbox_annotation[:,4] == ignore_index]
bbox_annotation = bbox_annotation[bbox_annotation[:,4] != ignore_index]
if bbox_annotation.shape[0] != 0:
IoU = calc_iou(anchors[0, :, :], bbox_annotation[:, :4])
IoU_max, IoU_argmax = torch.max(IoU, dim=1)
else:
IoU_max = None
IoU_argmax = None
if ignore_index is not None:
# tous les anchors ayant une IoA avec une région à ignorer supérieure à 0.5 seront ignorées pour la suite
if ignore_annotation.shape[0] !=0:
IoA = cal_ioa(anchors[0, :, :], ignore_annotation[:, :4]) # num_anchors x num_annotations_to_ignore
IoA_max, IoA_argmax = torch.max(IoA, dim=1) # num_anchors x 1
else:
IoA_max = None
IoA_argmax = None
# compute the loss for classification
targets = torch.ones(classification.shape) * -1
if torch.cuda.is_available():
targets = targets.cuda()
if IoU_max is not None:
targets[torch.lt(IoU_max, 0.4), :] = 0
else:
targets = targets*0
if ignore_index is not None:
if IoA_max is not None:
ignore_indices = torch.ge(IoA_max, 0.5)
else:
ignore_indices = (torch.ones((num_anchors)) * 0).type(torch.ByteTensor)
if IoU_max is not None:
positive_indices = torch.ge(IoU_max, 0.5)
num_positive_anchors = positive_indices.sum()
else:
positive_indices = (torch.ones((num_anchors)) * 0).type(torch.ByteTensor)
num_positive_anchors = torch.tensor(0)
if ignore_index is not None:
if ignore_indices is not None:
targets[ignore_indices, :] = -1
if IoU_argmax is not None:
assigned_annotations = bbox_annotation[IoU_argmax, :]
targets[positive_indices, :] = 0
targets[positive_indices, assigned_annotations[positive_indices, 4].long()] = 1
if torch.cuda.is_available():
alpha_factor = torch.ones(targets.shape).cuda() * alpha
else:
alpha_factor = torch.ones(targets.shape) * alpha
alpha_factor = torch.where(torch.eq(targets, 1.), alpha_factor, 1. - alpha_factor)
focal_weight = torch.where(torch.eq(targets, 1.), 1. - classification, classification)
focal_weight = alpha_factor * torch.pow(focal_weight, gamma)
bce = -(targets * torch.log(classification) + (1.0 - targets) * torch.log(1.0 - classification))
cls_loss = focal_weight * bce
if torch.cuda.is_available():
cls_loss = torch.where(torch.ne(targets, -1.0), cls_loss, torch.zeros(cls_loss.shape).cuda())
else:
cls_loss = torch.where(torch.ne(targets, -1.0), cls_loss, torch.zeros(cls_loss.shape))
classification_losses.append(cls_loss.sum()/torch.clamp(num_positive_anchors.float(), min=1.0))
# compute the loss for regression
if num_positive_anchors > 0:
assigned_annotations = assigned_annotations[positive_indices, :]
anchor_widths_pi = anchor_widths[positive_indices]
anchor_heights_pi = anchor_heights[positive_indices]
anchor_ctr_x_pi = anchor_ctr_x[positive_indices]
anchor_ctr_y_pi = anchor_ctr_y[positive_indices]
gt_widths = assigned_annotations[:, 2] - assigned_annotations[:, 0]
gt_heights = assigned_annotations[:, 3] - assigned_annotations[:, 1]
gt_ctr_x = assigned_annotations[:, 0] + 0.5 * gt_widths
gt_ctr_y = assigned_annotations[:, 1] + 0.5 * gt_heights
# clip widths to 1
gt_widths = torch.clamp(gt_widths, min=1)
gt_heights = torch.clamp(gt_heights, min=1)
targets_dx = (gt_ctr_x - anchor_ctr_x_pi) / anchor_widths_pi
targets_dy = (gt_ctr_y - anchor_ctr_y_pi) / anchor_heights_pi
targets_dw = torch.log(gt_widths / anchor_widths_pi)
targets_dh = torch.log(gt_heights / anchor_heights_pi)
targets = torch.stack((targets_dx, targets_dy, targets_dw, targets_dh))
targets = targets.t()
if torch.cuda.is_available():
targets = targets/torch.Tensor([[0.1, 0.1, 0.2, 0.2]]).cuda()
else:
targets = targets/torch.Tensor([[0.1, 0.1, 0.2, 0.2]])
negative_indices = 1 + (~positive_indices)
regression_diff = torch.abs(targets - regression[positive_indices, :])
regression_loss = torch.where(
torch.le(regression_diff, 1.0 / 9.0),
0.5 * 9.0 * torch.pow(regression_diff, 2),
regression_diff - 0.5 / 9.0
)
regression_losses.append(regression_loss.mean())
else:
if torch.cuda.is_available():
regression_losses.append(torch.tensor(0).float().cuda())
else:
regression_losses.append(torch.tensor(0).float())
return torch.stack(classification_losses).mean(dim=0, keepdim=True), torch.stack(regression_losses).mean(dim=0, keepdim=True)
| true | true |
f719ee1200d97dbce407161a29de73e610926f93 | 1,780 | py | Python | kubernetes_asyncio/test/test_storage_v1alpha1_api.py | aK0nshin/kubernetes_asyncio | aef9edcc1f8671a5b1bba9f4684bde890176b19c | [
"Apache-2.0"
] | null | null | null | kubernetes_asyncio/test/test_storage_v1alpha1_api.py | aK0nshin/kubernetes_asyncio | aef9edcc1f8671a5b1bba9f4684bde890176b19c | [
"Apache-2.0"
] | null | null | null | kubernetes_asyncio/test/test_storage_v1alpha1_api.py | aK0nshin/kubernetes_asyncio | aef9edcc1f8671a5b1bba9f4684bde890176b19c | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: v1.14.7
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import kubernetes_asyncio.client
from kubernetes_asyncio.client.api.storage_v1alpha1_api import StorageV1alpha1Api # noqa: E501
from kubernetes_asyncio.client.rest import ApiException
class TestStorageV1alpha1Api(unittest.TestCase):
"""StorageV1alpha1Api unit test stubs"""
def setUp(self):
self.api = kubernetes_asyncio.client.api.storage_v1alpha1_api.StorageV1alpha1Api() # noqa: E501
def tearDown(self):
pass
def test_create_volume_attachment(self):
"""Test case for create_volume_attachment
"""
pass
def test_delete_collection_volume_attachment(self):
"""Test case for delete_collection_volume_attachment
"""
pass
def test_delete_volume_attachment(self):
"""Test case for delete_volume_attachment
"""
pass
def test_get_api_resources(self):
"""Test case for get_api_resources
"""
pass
def test_list_volume_attachment(self):
"""Test case for list_volume_attachment
"""
pass
def test_patch_volume_attachment(self):
"""Test case for patch_volume_attachment
"""
pass
def test_read_volume_attachment(self):
"""Test case for read_volume_attachment
"""
pass
def test_replace_volume_attachment(self):
"""Test case for replace_volume_attachment
"""
pass
if __name__ == '__main__':
unittest.main()
| 21.707317 | 124 | 0.676404 |
from __future__ import absolute_import
import unittest
import kubernetes_asyncio.client
from kubernetes_asyncio.client.api.storage_v1alpha1_api import StorageV1alpha1Api
from kubernetes_asyncio.client.rest import ApiException
class TestStorageV1alpha1Api(unittest.TestCase):
def setUp(self):
self.api = kubernetes_asyncio.client.api.storage_v1alpha1_api.StorageV1alpha1Api()
def tearDown(self):
pass
def test_create_volume_attachment(self):
pass
def test_delete_collection_volume_attachment(self):
pass
def test_delete_volume_attachment(self):
pass
def test_get_api_resources(self):
pass
def test_list_volume_attachment(self):
pass
def test_patch_volume_attachment(self):
pass
def test_read_volume_attachment(self):
pass
def test_replace_volume_attachment(self):
pass
if __name__ == '__main__':
unittest.main()
| true | true |
f719ee2700b12c9c0e630bfb643af003a5b4013a | 7,162 | py | Python | clicktocall/app.py | Python-725/clicktocall-flask | 83268b7c90e487a70fc5ef0dcdbb3343d1dc783d | [
"MIT"
] | null | null | null | clicktocall/app.py | Python-725/clicktocall-flask | 83268b7c90e487a70fc5ef0dcdbb3343d1dc783d | [
"MIT"
] | null | null | null | clicktocall/app.py | Python-725/clicktocall-flask | 83268b7c90e487a70fc5ef0dcdbb3343d1dc783d | [
"MIT"
] | null | null | null | from flask import Flask
from flask import jsonify
from flask import render_template
from flask import request
import os, base64, uuid
from twilio.twiml.voice_response import VoiceResponse, Gather, Dial
from twilio.rest import Client
# Declare and configure application
app = Flask(__name__, static_url_path='/static')
app.config.from_pyfile('local_settings.py')
# Route for Click to Call demo page.
@app.route('/')
def index():
return render_template('index.html',
configuration_error=None)
sessionID_to_callsid = {}
sessionID_to_confsid = {}
sessionID_to_destNo = {}
# +918698583414
# +919404041811
# +918767805516
# Generate random session id for conference
def get_session_id(source_number, destination_number):
return 'Conf' + destination_number + '-' + uuid.uuid4().hex
def get_client():
try:
twilio_client = Client(app.config['TWILIO_ACCOUNT_SID'],
app.config['TWILIO_AUTH_TOKEN'])
return twilio_client
except Exception as e:
msg = f"Missing configuration variable: {e}"
return jsonify({'error': msg}), 400
# Voice Request URL
@app.route('/join_conference', methods=['GET', 'POST'])
@app.route('/call_number', methods=['GET', 'POST'])
def join_conference():
# Get phone numbers from request
source_number = request.form.get('source_number', None)
dest_number = request.form.get('dest_number', None)
print(f"Call Request received! source_number:{source_number}, dest_number:{dest_number}")
if not source_number or not dest_number:
msg = "Missing phone number value. Expected params source_number and dest_number"
return jsonify({'error': msg}), 400
try:
twilio_client = get_client()
session_id = get_session_id(source_number, dest_number)
call = twilio_client.calls.create(record=True,
from_=app.config['TWILIO_NUMBER'],
to=source_number,
url='https://3.137.150.83:8001/voip/api_voip/voip_callback/' + str(session_id),
status_callback_event=['completed'],
status_callback='https://3.137.150.83:8001/voip/api_voip/complete_call/' + str(session_id)
)
sessionID_to_callsid[session_id] = call.sid
sessionID_to_destNo[session_id] = dest_number
print("Initiated a Source number Call, session_id:", session_id)
except Exception as e:
message = e.msg if hasattr(e, 'msg') else str(e)
return jsonify({'error': message}), 400
return jsonify({'message': 'Success!'})
@app.route('/voip_callback/<string:session_id>', methods=['GET', 'POST'])
def voip_callback(session_id):
print("## Conference request received, session id:{} Making a conference call", session_id)
"""Processes results from the <Gather> prompt in /voice"""
resp = VoiceResponse()
# If Twilio's request to our app included already gathered digits, process them
if 'Digits' in request.values:
# Get which digit the caller chose
choice = request.values['Digits']
# Say a different message depending on the caller's choice
if choice == '1':
resp.say('Adding destination number to the conference!')
resp.redirect('https://3.137.150.83:8001/voip/api_voip/add-user/' + session_id)
print(str(resp))
return jsonify(resp)
elif choice == '2':
resp.say('Thank you for calling, have a nice day!')
# End the call with <Hangup>
resp.hangup()
print(str(resp))
return jsonify(resp)
else:
# If the caller didn't choose 1 or 2, apologize and ask them again
resp.say("Sorry, I don't understand that choice.")
else:
# Get user input
gather = Gather(num_digits=1, action='/voip_callback/' + session_id)
gather.say('Please Press 1 to connect to destination. Press 2 to end the call.')
resp.append(gather)
# If the user didn't choose 1 or 2 (or anything), repeat the message
resp.redirect('https://3.137.150.83:8001/voip/api_voip/voip_callback/' + session_id)
print(str(resp))
return jsonify(resp)
@app.route('/add-user/<string:session_id>', methods=['POST'])
def add_user_to_conf(session_id):
print("# Add user request received, session id:{}", session_id)
destination_number = sessionID_to_destNo.get(session_id)
print("Attemtping to add phone number to call: " + destination_number)
client = get_client()
resp = VoiceResponse()
dial = Dial()
dial.conference(destination_number)
resp.append(dial)
participant = client.conferences(destination_number).participants.create(
from_=app.config['TWILIO_NUMBER'],
to=destination_number,
conference_status_callback='https://3.137.150.83:8001/voip/api_voip/leave/' + session_id,
conference_status_callback_event="leave")
print(participant)
return str(resp)
@app.route('/leave/<string:session_id>', methods=['GET', 'POST'])
def leave(session_id):
event = request.values['SequenceNumber']
conference_sid = request.values['ConferenceSid']
sessionID_to_confsid[session_id] = conference_sid
print("Leave call request:", conference_sid, event, session_id)
if request.values['StatusCallbackEvent'] == 'participant-leave':
print("A Participant Left Call")
client = get_client()
# ends conference call if only 1 participant left
participants = client.conferences(conference_sid).participants
if len(participants.list()) == 1:
client.conferences(conference_sid).update(status='completed')
print("Call ended")
# ends conference call if original caller leaves before callee picks up
elif len(participants.list()) == 0 and event == '2':
client.calls(sessionID_to_callsid.get(session_id)).update(status='completed')
print("Call ended")
resp = VoiceResponse()
return str(resp)
# this is an endpoint to end the conference call if the callee rejects the call
@app.route('/complete_call/<string:call_session_id>', methods=['GET', 'POST'])
def complete_call(call_session_id):
print("## Ending conference call, callee rejected call")
client = get_client()
global sessionID_to_confsid
participants = client.conferences(sessionID_to_confsid.get(call_session_id)).participants
# only does so if 1 participant left in the conference call (i.e. the caller)
if len(participants.list()) == 1:
client.conferences(sessionID_to_confsid.get(call_session_id)).update(status='completed')
print("Call ended")
data = {
"status_code": 200,
}
resp = jsonify(data)
return resp
# Route for Landing Page after deploy.
@app.route('/landing.html')
def landing():
print("Get Request received!")
return render_template('landing.html',
configuration_error=None)
| 36.728205 | 132 | 0.655962 | from flask import Flask
from flask import jsonify
from flask import render_template
from flask import request
import os, base64, uuid
from twilio.twiml.voice_response import VoiceResponse, Gather, Dial
from twilio.rest import Client
app = Flask(__name__, static_url_path='/static')
app.config.from_pyfile('local_settings.py')
@app.route('/')
def index():
return render_template('index.html',
configuration_error=None)
sessionID_to_callsid = {}
sessionID_to_confsid = {}
sessionID_to_destNo = {}
def get_session_id(source_number, destination_number):
return 'Conf' + destination_number + '-' + uuid.uuid4().hex
def get_client():
try:
twilio_client = Client(app.config['TWILIO_ACCOUNT_SID'],
app.config['TWILIO_AUTH_TOKEN'])
return twilio_client
except Exception as e:
msg = f"Missing configuration variable: {e}"
return jsonify({'error': msg}), 400
@app.route('/join_conference', methods=['GET', 'POST'])
@app.route('/call_number', methods=['GET', 'POST'])
def join_conference():
source_number = request.form.get('source_number', None)
dest_number = request.form.get('dest_number', None)
print(f"Call Request received! source_number:{source_number}, dest_number:{dest_number}")
if not source_number or not dest_number:
msg = "Missing phone number value. Expected params source_number and dest_number"
return jsonify({'error': msg}), 400
try:
twilio_client = get_client()
session_id = get_session_id(source_number, dest_number)
call = twilio_client.calls.create(record=True,
from_=app.config['TWILIO_NUMBER'],
to=source_number,
url='https://3.137.150.83:8001/voip/api_voip/voip_callback/' + str(session_id),
status_callback_event=['completed'],
status_callback='https://3.137.150.83:8001/voip/api_voip/complete_call/' + str(session_id)
)
sessionID_to_callsid[session_id] = call.sid
sessionID_to_destNo[session_id] = dest_number
print("Initiated a Source number Call, session_id:", session_id)
except Exception as e:
message = e.msg if hasattr(e, 'msg') else str(e)
return jsonify({'error': message}), 400
return jsonify({'message': 'Success!'})
@app.route('/voip_callback/<string:session_id>', methods=['GET', 'POST'])
def voip_callback(session_id):
print("## Conference request received, session id:{} Making a conference call", session_id)
resp = VoiceResponse()
if 'Digits' in request.values:
# Get which digit the caller chose
choice = request.values['Digits']
# Say a different message depending on the caller's choice
if choice == '1':
resp.say('Adding destination number to the conference!')
resp.redirect('https://3.137.150.83:8001/voip/api_voip/add-user/' + session_id)
print(str(resp))
return jsonify(resp)
elif choice == '2':
resp.say('Thank you for calling, have a nice day!')
resp.hangup()
print(str(resp))
return jsonify(resp)
else:
resp.say("Sorry, I don't understand that choice.")
else:
gather = Gather(num_digits=1, action='/voip_callback/' + session_id)
gather.say('Please Press 1 to connect to destination. Press 2 to end the call.')
resp.append(gather)
resp.redirect('https://3.137.150.83:8001/voip/api_voip/voip_callback/' + session_id)
print(str(resp))
return jsonify(resp)
@app.route('/add-user/<string:session_id>', methods=['POST'])
def add_user_to_conf(session_id):
print("# Add user request received, session id:{}", session_id)
destination_number = sessionID_to_destNo.get(session_id)
print("Attemtping to add phone number to call: " + destination_number)
client = get_client()
resp = VoiceResponse()
dial = Dial()
dial.conference(destination_number)
resp.append(dial)
participant = client.conferences(destination_number).participants.create(
from_=app.config['TWILIO_NUMBER'],
to=destination_number,
conference_status_callback='https://3.137.150.83:8001/voip/api_voip/leave/' + session_id,
conference_status_callback_event="leave")
print(participant)
return str(resp)
@app.route('/leave/<string:session_id>', methods=['GET', 'POST'])
def leave(session_id):
event = request.values['SequenceNumber']
conference_sid = request.values['ConferenceSid']
sessionID_to_confsid[session_id] = conference_sid
print("Leave call request:", conference_sid, event, session_id)
if request.values['StatusCallbackEvent'] == 'participant-leave':
print("A Participant Left Call")
client = get_client()
# ends conference call if only 1 participant left
participants = client.conferences(conference_sid).participants
if len(participants.list()) == 1:
client.conferences(conference_sid).update(status='completed')
print("Call ended")
# ends conference call if original caller leaves before callee picks up
elif len(participants.list()) == 0 and event == '2':
client.calls(sessionID_to_callsid.get(session_id)).update(status='completed')
print("Call ended")
resp = VoiceResponse()
return str(resp)
# this is an endpoint to end the conference call if the callee rejects the call
@app.route('/complete_call/<string:call_session_id>', methods=['GET', 'POST'])
def complete_call(call_session_id):
print("## Ending conference call, callee rejected call")
client = get_client()
global sessionID_to_confsid
participants = client.conferences(sessionID_to_confsid.get(call_session_id)).participants
# only does so if 1 participant left in the conference call (i.e. the caller)
if len(participants.list()) == 1:
client.conferences(sessionID_to_confsid.get(call_session_id)).update(status='completed')
print("Call ended")
data = {
"status_code": 200,
}
resp = jsonify(data)
return resp
# Route for Landing Page after deploy.
@app.route('/landing.html')
def landing():
print("Get Request received!")
return render_template('landing.html',
configuration_error=None)
| true | true |
f719ee8eea12cfc3dea84e56aaeb16666fde914e | 133 | py | Python | twl/c2.py | xiaolinzi-xl/python_imooc | 07bde890e3ab0ddef4467b0c77ef33614339a657 | [
"Apache-2.0"
] | null | null | null | twl/c2.py | xiaolinzi-xl/python_imooc | 07bde890e3ab0ddef4467b0c77ef33614339a657 | [
"Apache-2.0"
] | null | null | null | twl/c2.py | xiaolinzi-xl/python_imooc | 07bde890e3ab0ddef4467b0c77ef33614339a657 | [
"Apache-2.0"
] | null | null | null |
list_x = [1,2,3,4,5,6,7,8]
def square(x):
return x*x
# for x in list_x:
# square(x)
r = map(square,list_x)
print(list(r)) | 12.090909 | 26 | 0.578947 |
list_x = [1,2,3,4,5,6,7,8]
def square(x):
return x*x
r = map(square,list_x)
print(list(r)) | true | true |
f719eeaa3c3602f09dba2e13bf498a6011b27cbe | 787 | py | Python | pyspark-utils/wordcounts.py | domvwt/uol-ds-tools | 62348b3e04a2f27ceaa19776fb3024eaaf21d593 | [
"MIT"
] | 4 | 2020-11-27T06:08:05.000Z | 2021-04-29T15:57:12.000Z | pyspark-utils/wordcounts.py | domvwt/uol-ds-tools | 62348b3e04a2f27ceaa19776fb3024eaaf21d593 | [
"MIT"
] | null | null | null | pyspark-utils/wordcounts.py | domvwt/uol-ds-tools | 62348b3e04a2f27ceaa19776fb3024eaaf21d593 | [
"MIT"
] | 2 | 2020-12-16T11:01:48.000Z | 2020-12-28T14:02:24.000Z | #! /opt/spark/bin/pyspark
import re
from pathlib import Path
INPUT_TXT = "~/uol-ds-tools/pyspark-utils/frankenstein.txt"
myfile = Path(INPUT_TXT).expanduser().absolute()
rdd_txt = sc.textFile(f"file:///{myfile}")
# Simple word counts splitting on whitespace
counts = (
rdd_txt.flatMap(lambda line: line.split())
.map(lambda word: (word, 1))
.reduceByKey(lambda a, b: a + b)
.map(lambda a: (a[1], a[0]))
)
res1 = counts.collect()[:20]
for i in res1:
print(i)
print()
# Word counts splitting on non word elements
word_counts = (
rdd_txt.flatMap(lambda line: re.split(r"\W+", line))
.map(lambda word: (word, 1))
.reduceByKey(lambda a, b: a + b)
.map(lambda a: (a[1], a[0]))
)
res2 = word_counts.collect()[:20]
for i in res2:
print(i)
print()
| 21.27027 | 59 | 0.64676 |
import re
from pathlib import Path
INPUT_TXT = "~/uol-ds-tools/pyspark-utils/frankenstein.txt"
myfile = Path(INPUT_TXT).expanduser().absolute()
rdd_txt = sc.textFile(f"file:///{myfile}")
counts = (
rdd_txt.flatMap(lambda line: line.split())
.map(lambda word: (word, 1))
.reduceByKey(lambda a, b: a + b)
.map(lambda a: (a[1], a[0]))
)
res1 = counts.collect()[:20]
for i in res1:
print(i)
print()
word_counts = (
rdd_txt.flatMap(lambda line: re.split(r"\W+", line))
.map(lambda word: (word, 1))
.reduceByKey(lambda a, b: a + b)
.map(lambda a: (a[1], a[0]))
)
res2 = word_counts.collect()[:20]
for i in res2:
print(i)
print()
| true | true |
f719eeae51beeb20ebbfea489acc9d5269a4d2a2 | 397 | py | Python | simpleblog/asgi.py | itsmusa/simpleblog | fceef520684a8249e119c337898b945689515957 | [
"MIT"
] | null | null | null | simpleblog/asgi.py | itsmusa/simpleblog | fceef520684a8249e119c337898b945689515957 | [
"MIT"
] | null | null | null | simpleblog/asgi.py | itsmusa/simpleblog | fceef520684a8249e119c337898b945689515957 | [
"MIT"
] | null | null | null | """
ASGI config for simpleblog project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'simpleblog.settings')
application = get_asgi_application()
| 23.352941 | 78 | 0.788413 |
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'simpleblog.settings')
application = get_asgi_application()
| true | true |
f719ef2757a2269c2a99feca23fcebc07b42be06 | 2,215 | py | Python | src/myip.py | Fuhrmann/keypirinha-myip | 5a68e1061d6c597dfc21ab8cd86319c4d32efb07 | [
"MIT"
] | 13 | 2018-03-29T23:40:04.000Z | 2021-06-28T19:18:42.000Z | src/myip.py | Fuhrmann/keypirinha-myip | 5a68e1061d6c597dfc21ab8cd86319c4d32efb07 | [
"MIT"
] | null | null | null | src/myip.py | Fuhrmann/keypirinha-myip | 5a68e1061d6c597dfc21ab8cd86319c4d32efb07 | [
"MIT"
] | null | null | null | # Keypirinha launcher (keypirinha.com)
import socket
import keypirinha as kp
import keypirinha_net as kpnet
import keypirinha_util as kpu
class MyIP(kp.Plugin):
"""
Get your public and local IP directly from Keypirinha.
"""
ITEM_CAT = kp.ItemCategory.USER_BASE + 1
KEYWORD = 'ip'
def __init__(self):
super().__init__()
self._urlopener = kpnet.build_urllib_opener()
def on_suggest(self, user_input, items_chain):
if user_input.lower() == self.KEYWORD:
public_ip = self._get_public_ip()
local_ip = self._get_local_ip()
self.set_catalog(
[
self.create_item(
category=kp.ItemCategory.KEYWORD,
label='Your public IP',
short_desc=public_ip,
target='public_ip',
args_hint=kp.ItemArgsHint.FORBIDDEN,
hit_hint=kp.ItemHitHint.NOARGS
),
self.create_item(
category=kp.ItemCategory.KEYWORD,
label='Your local IP',
short_desc=local_ip,
target='local_ip',
args_hint=kp.ItemArgsHint.FORBIDDEN,
hit_hint=kp.ItemHitHint.NOARGS
)
]
)
def on_execute(self, item, action):
kpu.set_clipboard(item.short_desc())
def on_events(self, flags):
if flags & kp.Events.NETOPTIONS:
self._urlopener = kpnet.build_urllib_opener()
def _get_public_ip(self):
try:
with self._urlopener.open('http://icanhazip.com') as res:
return res.read().decode('utf-8')
except Exception as ex:
self.err(ex)
return 'Could not establish your public ip'
def _get_local_ip(self):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
except Exception as ex:
self.err(ex)
return 'Could not establish your local ip'
| 31.197183 | 69 | 0.531377 |
import socket
import keypirinha as kp
import keypirinha_net as kpnet
import keypirinha_util as kpu
class MyIP(kp.Plugin):
ITEM_CAT = kp.ItemCategory.USER_BASE + 1
KEYWORD = 'ip'
def __init__(self):
super().__init__()
self._urlopener = kpnet.build_urllib_opener()
def on_suggest(self, user_input, items_chain):
if user_input.lower() == self.KEYWORD:
public_ip = self._get_public_ip()
local_ip = self._get_local_ip()
self.set_catalog(
[
self.create_item(
category=kp.ItemCategory.KEYWORD,
label='Your public IP',
short_desc=public_ip,
target='public_ip',
args_hint=kp.ItemArgsHint.FORBIDDEN,
hit_hint=kp.ItemHitHint.NOARGS
),
self.create_item(
category=kp.ItemCategory.KEYWORD,
label='Your local IP',
short_desc=local_ip,
target='local_ip',
args_hint=kp.ItemArgsHint.FORBIDDEN,
hit_hint=kp.ItemHitHint.NOARGS
)
]
)
def on_execute(self, item, action):
kpu.set_clipboard(item.short_desc())
def on_events(self, flags):
if flags & kp.Events.NETOPTIONS:
self._urlopener = kpnet.build_urllib_opener()
def _get_public_ip(self):
try:
with self._urlopener.open('http://icanhazip.com') as res:
return res.read().decode('utf-8')
except Exception as ex:
self.err(ex)
return 'Could not establish your public ip'
def _get_local_ip(self):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
except Exception as ex:
self.err(ex)
return 'Could not establish your local ip'
| true | true |
f719ef5038ede533d676debe6b7851092917855f | 6,254 | py | Python | src/main.py | PeterouZh/PyTorch-StudioGAN | faef6048d25dadee4fa31b2955f16f7d1ca8e1e2 | [
"MIT"
] | null | null | null | src/main.py | PeterouZh/PyTorch-StudioGAN | faef6048d25dadee4fa31b2955f16f7d1ca8e1e2 | [
"MIT"
] | null | null | null | src/main.py | PeterouZh/PyTorch-StudioGAN | faef6048d25dadee4fa31b2955f16f7d1ca8e1e2 | [
"MIT"
] | null | null | null | # PyTorch StudioGAN: https://github.com/POSTECH-CVLab/PyTorch-StudioGAN
# The MIT License (MIT)
# See license file or visit https://github.com/POSTECH-CVLab/PyTorch-StudioGAN for details
# src/main.py
import json
import os
import sys
import random
import warnings
from argparse import ArgumentParser
from utils.misc import *
from utils.make_hdf5 import make_hdf5
from utils.log import make_run_name
from loader import prepare_train_eval
import torch
from torch.backends import cudnn
import torch.multiprocessing as mp
RUN_NAME_FORMAT = (
"{framework}-"
"{phase}-"
"{timestamp}"
)
def main():
parser = ArgumentParser(add_help=False)
parser.add_argument('-c', '--config_path', type=str, default='./src/configs/CIFAR10/ContraGAN.json')
parser.add_argument('--checkpoint_folder', type=str, default=None)
parser.add_argument('-current', '--load_current', action='store_true', help='whether you load the current or best checkpoint')
parser.add_argument('--log_output_path', type=str, default=None)
parser.add_argument('-DDP', '--distributed_data_parallel', action='store_true')
parser.add_argument('-n', '--nodes', default=1, type=int, metavar='N')
parser.add_argument('-nr', '--nr', default=0, type=int, help='ranking within the nodes')
parser.add_argument('--seed', type=int, default=-1, help='seed for generating random numbers')
parser.add_argument('--num_workers', type=int, default=8, help='')
parser.add_argument('-sync_bn', '--synchronized_bn', action='store_true', help='whether turn on synchronized batchnorm')
parser.add_argument('-mpc', '--mixed_precision', action='store_true', help='whether turn on mixed precision training')
parser.add_argument('-LARS', '--LARS_optimizer', action='store_true', help='whether turn on LARS optimizer')
parser.add_argument('-rm_API', '--disable_debugging_API', action='store_true', help='whether disable pytorch autograd debugging mode')
parser.add_argument('--reduce_train_dataset', type=float, default=1.0, help='control the number of train dataset')
parser.add_argument('--truncated_factor', type=float, default=-1.0, help='factor for truncation trick')
parser.add_argument('-stat_otf', '--bn_stat_OnTheFly', action='store_true', help='when evaluating, use the statistics of a batch')
parser.add_argument('-std_stat', '--standing_statistics', action='store_true')
parser.add_argument('--standing_step', type=int, default=-1, help='# of steps for accumulation batchnorm')
parser.add_argument('--freeze_layers', type=int, default=-1, help='# of layers for freezing discriminator')
parser.add_argument('-l', '--load_all_data_in_memory', action='store_true')
parser.add_argument('-t', '--train', action='store_true')
parser.add_argument('-e', '--eval', action='store_true')
parser.add_argument('-s', '--save_images', action='store_true')
parser.add_argument('-iv', '--image_visualization', action='store_true', help='select whether conduct image visualization')
parser.add_argument('-knn', '--k_nearest_neighbor', action='store_true', help='select whether conduct k-nearest neighbor analysis')
parser.add_argument('-itp', '--interpolation', action='store_true', help='whether conduct interpolation analysis')
parser.add_argument('-fa', '--frequency_analysis', action='store_true', help='whether conduct frequency analysis')
parser.add_argument('-tsne', '--tsne_analysis', action='store_true', help='whether conduct tsne analysis')
parser.add_argument('--nrow', type=int, default=10, help='number of rows to plot image canvas')
parser.add_argument('--ncol', type=int, default=8, help='number of cols to plot image canvas')
parser.add_argument('--print_every', type=int, default=100, help='control log interval')
parser.add_argument('--save_every', type=int, default=2000, help='control evaluation and save interval')
parser.add_argument('--eval_type', type=str, default='test', help='[train/valid/test]')
from template_lib.v2.config_cfgnode import update_parser_defaults_from_yaml, global_cfg
update_parser_defaults_from_yaml(parser=parser)
args = parser.parse_args()
if not args.train and \
not args.eval and \
not args.save_images and \
not args.image_visualization and \
not args.k_nearest_neighbor and \
not args.interpolation and \
not args.frequency_analysis and \
not args.tsne_analysis:
parser.print_help(sys.stderr)
sys.exit(1)
if args.config_path is not None:
with open(args.config_path) as f:
model_configs = json.load(f)
train_configs = vars(args)
else:
raise NotImplementedError
hdf5_path_train = make_hdf5(model_configs['data_processing'], train_configs, mode="train") \
if train_configs['load_all_data_in_memory'] else None
if train_configs['seed'] == -1:
train_configs['seed'] = random.randint(1,4096)
cudnn.benchmark, cudnn.deterministic = True, False
else:
cudnn.benchmark, cudnn.deterministic = False, True
fix_all_seed(train_configs['seed'])
gpus_per_node, rank = torch.cuda.device_count(), torch.cuda.current_device()
world_size = gpus_per_node*train_configs['nodes']
if world_size == 1:
warnings.warn('You have chosen a specific GPU. This will completely disable data parallelism.')
run_name = make_run_name(RUN_NAME_FORMAT, framework=train_configs['config_path'].split('/')[-1][:-5], phase='train')
if train_configs['disable_debugging_API']: torch.autograd.set_detect_anomaly(False)
check_flags(train_configs, model_configs, world_size)
if train_configs['distributed_data_parallel'] and world_size > 1:
print("Train the models through DistributedDataParallel (DDP) mode.")
mp.spawn(prepare_train_eval, nprocs=gpus_per_node, args=(gpus_per_node, world_size, run_name,
train_configs, model_configs, hdf5_path_train))
else:
prepare_train_eval(rank, gpus_per_node, world_size, run_name, train_configs, model_configs, hdf5_path_train=hdf5_path_train)
if __name__ == '__main__':
main()
| 50.435484 | 138 | 0.714103 |
import json
import os
import sys
import random
import warnings
from argparse import ArgumentParser
from utils.misc import *
from utils.make_hdf5 import make_hdf5
from utils.log import make_run_name
from loader import prepare_train_eval
import torch
from torch.backends import cudnn
import torch.multiprocessing as mp
RUN_NAME_FORMAT = (
"{framework}-"
"{phase}-"
"{timestamp}"
)
def main():
parser = ArgumentParser(add_help=False)
parser.add_argument('-c', '--config_path', type=str, default='./src/configs/CIFAR10/ContraGAN.json')
parser.add_argument('--checkpoint_folder', type=str, default=None)
parser.add_argument('-current', '--load_current', action='store_true', help='whether you load the current or best checkpoint')
parser.add_argument('--log_output_path', type=str, default=None)
parser.add_argument('-DDP', '--distributed_data_parallel', action='store_true')
parser.add_argument('-n', '--nodes', default=1, type=int, metavar='N')
parser.add_argument('-nr', '--nr', default=0, type=int, help='ranking within the nodes')
parser.add_argument('--seed', type=int, default=-1, help='seed for generating random numbers')
parser.add_argument('--num_workers', type=int, default=8, help='')
parser.add_argument('-sync_bn', '--synchronized_bn', action='store_true', help='whether turn on synchronized batchnorm')
parser.add_argument('-mpc', '--mixed_precision', action='store_true', help='whether turn on mixed precision training')
parser.add_argument('-LARS', '--LARS_optimizer', action='store_true', help='whether turn on LARS optimizer')
parser.add_argument('-rm_API', '--disable_debugging_API', action='store_true', help='whether disable pytorch autograd debugging mode')
parser.add_argument('--reduce_train_dataset', type=float, default=1.0, help='control the number of train dataset')
parser.add_argument('--truncated_factor', type=float, default=-1.0, help='factor for truncation trick')
parser.add_argument('-stat_otf', '--bn_stat_OnTheFly', action='store_true', help='when evaluating, use the statistics of a batch')
parser.add_argument('-std_stat', '--standing_statistics', action='store_true')
parser.add_argument('--standing_step', type=int, default=-1, help='# of steps for accumulation batchnorm')
parser.add_argument('--freeze_layers', type=int, default=-1, help='# of layers for freezing discriminator')
parser.add_argument('-l', '--load_all_data_in_memory', action='store_true')
parser.add_argument('-t', '--train', action='store_true')
parser.add_argument('-e', '--eval', action='store_true')
parser.add_argument('-s', '--save_images', action='store_true')
parser.add_argument('-iv', '--image_visualization', action='store_true', help='select whether conduct image visualization')
parser.add_argument('-knn', '--k_nearest_neighbor', action='store_true', help='select whether conduct k-nearest neighbor analysis')
parser.add_argument('-itp', '--interpolation', action='store_true', help='whether conduct interpolation analysis')
parser.add_argument('-fa', '--frequency_analysis', action='store_true', help='whether conduct frequency analysis')
parser.add_argument('-tsne', '--tsne_analysis', action='store_true', help='whether conduct tsne analysis')
parser.add_argument('--nrow', type=int, default=10, help='number of rows to plot image canvas')
parser.add_argument('--ncol', type=int, default=8, help='number of cols to plot image canvas')
parser.add_argument('--print_every', type=int, default=100, help='control log interval')
parser.add_argument('--save_every', type=int, default=2000, help='control evaluation and save interval')
parser.add_argument('--eval_type', type=str, default='test', help='[train/valid/test]')
from template_lib.v2.config_cfgnode import update_parser_defaults_from_yaml, global_cfg
update_parser_defaults_from_yaml(parser=parser)
args = parser.parse_args()
if not args.train and \
not args.eval and \
not args.save_images and \
not args.image_visualization and \
not args.k_nearest_neighbor and \
not args.interpolation and \
not args.frequency_analysis and \
not args.tsne_analysis:
parser.print_help(sys.stderr)
sys.exit(1)
if args.config_path is not None:
with open(args.config_path) as f:
model_configs = json.load(f)
train_configs = vars(args)
else:
raise NotImplementedError
hdf5_path_train = make_hdf5(model_configs['data_processing'], train_configs, mode="train") \
if train_configs['load_all_data_in_memory'] else None
if train_configs['seed'] == -1:
train_configs['seed'] = random.randint(1,4096)
cudnn.benchmark, cudnn.deterministic = True, False
else:
cudnn.benchmark, cudnn.deterministic = False, True
fix_all_seed(train_configs['seed'])
gpus_per_node, rank = torch.cuda.device_count(), torch.cuda.current_device()
world_size = gpus_per_node*train_configs['nodes']
if world_size == 1:
warnings.warn('You have chosen a specific GPU. This will completely disable data parallelism.')
run_name = make_run_name(RUN_NAME_FORMAT, framework=train_configs['config_path'].split('/')[-1][:-5], phase='train')
if train_configs['disable_debugging_API']: torch.autograd.set_detect_anomaly(False)
check_flags(train_configs, model_configs, world_size)
if train_configs['distributed_data_parallel'] and world_size > 1:
print("Train the models through DistributedDataParallel (DDP) mode.")
mp.spawn(prepare_train_eval, nprocs=gpus_per_node, args=(gpus_per_node, world_size, run_name,
train_configs, model_configs, hdf5_path_train))
else:
prepare_train_eval(rank, gpus_per_node, world_size, run_name, train_configs, model_configs, hdf5_path_train=hdf5_path_train)
if __name__ == '__main__':
main()
| true | true |
f719f008f608295f63a3a4f7b4b174f389cd19b8 | 6,048 | py | Python | test/Scanner/source_scanner-dict.py | KastB/scons | b6f9defefba687bc1050605ebcf3d816af3c2808 | [
"MIT"
] | null | null | null | test/Scanner/source_scanner-dict.py | KastB/scons | b6f9defefba687bc1050605ebcf3d816af3c2808 | [
"MIT"
] | null | null | null | test/Scanner/source_scanner-dict.py | KastB/scons | b6f9defefba687bc1050605ebcf3d816af3c2808 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Verify that a source_scanner that uses a dictionary to select more
specific scanners for source file suffixes works correctly, even
when it's handed a file suffix that it doesn't know how to scan
(i.e., for which it doesn't have a specific scanner in its dictionary).
"""
import TestSCons
_python_ = TestSCons._python_
test = TestSCons.TestSCons()
test.write('build.py', r"""
import sys
with open(sys.argv[1], 'w') as ofp:
for infile in sys.argv[2:]:
with open(infile, 'r') as ifp:
include_prefix = 'include%s ' % infile[-1]
def process(infp, outfp, include_prefix=include_prefix):
for line in infp.readlines():
if line[:len(include_prefix)] == include_prefix:
file = line[len(include_prefix):-1]
with open(file, 'r') as f:
process(f, outfp)
else:
outfp.write(line)
process(ifp, ofp)
sys.exit(0)
""")
# Execute a subsidiary SConscript just to make sure we can
# get at the Scanner keyword from there.
test.write('SConstruct', """
SConscript('SConscript')
""")
test.write('SConscript', """
import re
include1_re = re.compile(r'^include1\s+(\S+)$', re.M)
include2_re = re.compile(r'^include2\s+(\S+)$', re.M)
include3_re = re.compile(r'^include3\s+(\S+)$', re.M)
def k1_scan(node, env, scanpaths, arg=None):
contents = node.get_text_contents()
includes = include1_re.findall(contents)
return includes
def k2_scan(node, env, scanpaths, arg=None):
contents = node.get_text_contents()
includes = include2_re.findall(contents)
return includes
def k3_scan(node, env, scanpaths, arg=None):
contents = node.get_text_contents()
includes = include3_re.findall(contents)
return includes
kscanner = Scanner({'.k1' : Scanner(k1_scan), '.k2': Scanner(k2_scan)})
b = Builder(action=r'%(_python_)s build.py $TARGET $SOURCES',
source_scanner=kscanner)
env = Environment(BUILDERS={'Build':b})
kscanner.add_scanner('.k3', Scanner(k3_scan))
env.Build('aaa', 'aaa.k1')
env.Build('bbb', 'bbb.k2')
env.Build('ccc', 'ccc.k3')
env.Build('ddd', ['ddd.k4', 'aaa.k1', 'bbb.k2', 'ccc.k3'])
""" % locals())
test.write('aaa.k1',
"""aaa.k1 1
line 2
include1 xxx
include2 yyy
include3 zzz
line 6
""")
test.write('bbb.k2',
"""bbb.k2 1
line 2
include1 xxx
include2 yyy
include3 zzz
line 6
""")
test.write('ccc.k3',
"""ccc.k3 1
line 2
include1 xxx
include2 yyy
include3 zzz
line 6
""")
test.write('ddd.k4',
"""ddd.k4 1
line 2
line 3
""")
test.write('xxx', "xxx 1\n")
test.write('yyy', "yyy 1\n")
test.write('zzz', "zzz 1\n")
expect = test.wrap_stdout("""\
%(_python_)s build.py aaa aaa.k1
%(_python_)s build.py bbb bbb.k2
%(_python_)s build.py ccc ccc.k3
%(_python_)s build.py ddd ddd.k4 aaa.k1 bbb.k2 ccc.k3
""" % locals())
test.run(stdout=expect)
expect_aaa = 'aaa.k1 1\nline 2\nxxx 1\ninclude2 yyy\ninclude3 zzz\nline 6\n'
expect_bbb = 'bbb.k2 1\nline 2\ninclude1 xxx\nyyy 1\ninclude3 zzz\nline 6\n'
expect_ccc = 'ccc.k3 1\nline 2\ninclude1 xxx\ninclude2 yyy\nzzz 1\nline 6\n'
expect_ddd = 'ddd.k4 1\nline 2\nline 3\n' + expect_aaa + expect_bbb + expect_ccc
test.must_match('aaa', expect_aaa, mode='r')
test.must_match('bbb', expect_bbb, mode='r')
test.must_match('ccc', expect_ccc, mode='r')
test.must_match('ddd', expect_ddd, mode='r')
test.up_to_date(arguments = '.')
test.write('zzz', "zzz 2\n")
expect = test.wrap_stdout("""\
%(_python_)s build.py ccc ccc.k3
%(_python_)s build.py ddd ddd.k4 aaa.k1 bbb.k2 ccc.k3
""" % locals())
test.run(stdout=expect)
expect_ccc = 'ccc.k3 1\nline 2\ninclude1 xxx\ninclude2 yyy\nzzz 2\nline 6\n'
expect_ddd = 'ddd.k4 1\nline 2\nline 3\n' + expect_aaa + expect_bbb + expect_ccc
test.must_match('bbb', expect_bbb, mode='r')
test.must_match('ddd', expect_ddd, mode='r')
test.write('yyy', "yyy 2\n")
expect = test.wrap_stdout("""\
%(_python_)s build.py bbb bbb.k2
%(_python_)s build.py ddd ddd.k4 aaa.k1 bbb.k2 ccc.k3
""" % locals())
test.run(stdout=expect)
expect_bbb = 'bbb.k2 1\nline 2\ninclude1 xxx\nyyy 2\ninclude3 zzz\nline 6\n'
expect_ddd = 'ddd.k4 1\nline 2\nline 3\n' + expect_aaa + expect_bbb + expect_ccc
test.must_match('bbb', expect_bbb, mode='r')
test.must_match('ddd', expect_ddd, mode='r')
test.write('xxx', "xxx 2\n")
expect = test.wrap_stdout("""\
%(_python_)s build.py aaa aaa.k1
%(_python_)s build.py ddd ddd.k4 aaa.k1 bbb.k2 ccc.k3
""" % locals())
test.run(stdout=expect)
expect_aaa = 'aaa.k1 1\nline 2\nxxx 2\ninclude2 yyy\ninclude3 zzz\nline 6\n'
expect_ddd = 'ddd.k4 1\nline 2\nline 3\n' + expect_aaa + expect_bbb + expect_ccc
test.must_match('aaa', expect_aaa, mode='r')
test.must_match('ddd', expect_ddd, mode='r')
test.pass_test()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| 26.88 | 80 | 0.687335 |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import TestSCons
_python_ = TestSCons._python_
test = TestSCons.TestSCons()
test.write('build.py', r"""
import sys
with open(sys.argv[1], 'w') as ofp:
for infile in sys.argv[2:]:
with open(infile, 'r') as ifp:
include_prefix = 'include%s ' % infile[-1]
def process(infp, outfp, include_prefix=include_prefix):
for line in infp.readlines():
if line[:len(include_prefix)] == include_prefix:
file = line[len(include_prefix):-1]
with open(file, 'r') as f:
process(f, outfp)
else:
outfp.write(line)
process(ifp, ofp)
sys.exit(0)
""")
test.write('SConstruct', """
SConscript('SConscript')
""")
test.write('SConscript', """
import re
include1_re = re.compile(r'^include1\s+(\S+)$', re.M)
include2_re = re.compile(r'^include2\s+(\S+)$', re.M)
include3_re = re.compile(r'^include3\s+(\S+)$', re.M)
def k1_scan(node, env, scanpaths, arg=None):
contents = node.get_text_contents()
includes = include1_re.findall(contents)
return includes
def k2_scan(node, env, scanpaths, arg=None):
contents = node.get_text_contents()
includes = include2_re.findall(contents)
return includes
def k3_scan(node, env, scanpaths, arg=None):
contents = node.get_text_contents()
includes = include3_re.findall(contents)
return includes
kscanner = Scanner({'.k1' : Scanner(k1_scan), '.k2': Scanner(k2_scan)})
b = Builder(action=r'%(_python_)s build.py $TARGET $SOURCES',
source_scanner=kscanner)
env = Environment(BUILDERS={'Build':b})
kscanner.add_scanner('.k3', Scanner(k3_scan))
env.Build('aaa', 'aaa.k1')
env.Build('bbb', 'bbb.k2')
env.Build('ccc', 'ccc.k3')
env.Build('ddd', ['ddd.k4', 'aaa.k1', 'bbb.k2', 'ccc.k3'])
""" % locals())
test.write('aaa.k1',
"""aaa.k1 1
line 2
include1 xxx
include2 yyy
include3 zzz
line 6
""")
test.write('bbb.k2',
"""bbb.k2 1
line 2
include1 xxx
include2 yyy
include3 zzz
line 6
""")
test.write('ccc.k3',
"""ccc.k3 1
line 2
include1 xxx
include2 yyy
include3 zzz
line 6
""")
test.write('ddd.k4',
"""ddd.k4 1
line 2
line 3
""")
test.write('xxx', "xxx 1\n")
test.write('yyy', "yyy 1\n")
test.write('zzz', "zzz 1\n")
expect = test.wrap_stdout("""\
%(_python_)s build.py aaa aaa.k1
%(_python_)s build.py bbb bbb.k2
%(_python_)s build.py ccc ccc.k3
%(_python_)s build.py ddd ddd.k4 aaa.k1 bbb.k2 ccc.k3
""" % locals())
test.run(stdout=expect)
expect_aaa = 'aaa.k1 1\nline 2\nxxx 1\ninclude2 yyy\ninclude3 zzz\nline 6\n'
expect_bbb = 'bbb.k2 1\nline 2\ninclude1 xxx\nyyy 1\ninclude3 zzz\nline 6\n'
expect_ccc = 'ccc.k3 1\nline 2\ninclude1 xxx\ninclude2 yyy\nzzz 1\nline 6\n'
expect_ddd = 'ddd.k4 1\nline 2\nline 3\n' + expect_aaa + expect_bbb + expect_ccc
test.must_match('aaa', expect_aaa, mode='r')
test.must_match('bbb', expect_bbb, mode='r')
test.must_match('ccc', expect_ccc, mode='r')
test.must_match('ddd', expect_ddd, mode='r')
test.up_to_date(arguments = '.')
test.write('zzz', "zzz 2\n")
expect = test.wrap_stdout("""\
%(_python_)s build.py ccc ccc.k3
%(_python_)s build.py ddd ddd.k4 aaa.k1 bbb.k2 ccc.k3
""" % locals())
test.run(stdout=expect)
expect_ccc = 'ccc.k3 1\nline 2\ninclude1 xxx\ninclude2 yyy\nzzz 2\nline 6\n'
expect_ddd = 'ddd.k4 1\nline 2\nline 3\n' + expect_aaa + expect_bbb + expect_ccc
test.must_match('bbb', expect_bbb, mode='r')
test.must_match('ddd', expect_ddd, mode='r')
test.write('yyy', "yyy 2\n")
expect = test.wrap_stdout("""\
%(_python_)s build.py bbb bbb.k2
%(_python_)s build.py ddd ddd.k4 aaa.k1 bbb.k2 ccc.k3
""" % locals())
test.run(stdout=expect)
expect_bbb = 'bbb.k2 1\nline 2\ninclude1 xxx\nyyy 2\ninclude3 zzz\nline 6\n'
expect_ddd = 'ddd.k4 1\nline 2\nline 3\n' + expect_aaa + expect_bbb + expect_ccc
test.must_match('bbb', expect_bbb, mode='r')
test.must_match('ddd', expect_ddd, mode='r')
test.write('xxx', "xxx 2\n")
expect = test.wrap_stdout("""\
%(_python_)s build.py aaa aaa.k1
%(_python_)s build.py ddd ddd.k4 aaa.k1 bbb.k2 ccc.k3
""" % locals())
test.run(stdout=expect)
expect_aaa = 'aaa.k1 1\nline 2\nxxx 2\ninclude2 yyy\ninclude3 zzz\nline 6\n'
expect_ddd = 'ddd.k4 1\nline 2\nline 3\n' + expect_aaa + expect_bbb + expect_ccc
test.must_match('aaa', expect_aaa, mode='r')
test.must_match('ddd', expect_ddd, mode='r')
test.pass_test()
| true | true |
f719f0382623361ba7540988b5ee46b2739e8570 | 1,237 | py | Python | HW3/Add-command/cloudmesh_numpy/cloudmesh_numpy/plugins/cm_shell_numpy.py | futuresystems/465-git4hiroaki | bfd9068e0d074d7b6132844dc0f92780bf63bcb9 | [
"Apache-2.0"
] | null | null | null | HW3/Add-command/cloudmesh_numpy/cloudmesh_numpy/plugins/cm_shell_numpy.py | futuresystems/465-git4hiroaki | bfd9068e0d074d7b6132844dc0f92780bf63bcb9 | [
"Apache-2.0"
] | null | null | null | HW3/Add-command/cloudmesh_numpy/cloudmesh_numpy/plugins/cm_shell_numpy.py | futuresystems/465-git4hiroaki | bfd9068e0d074d7b6132844dc0f92780bf63bcb9 | [
"Apache-2.0"
] | null | null | null | from __future__ import print_function
import os
from cmd3.console import Console
from cmd3.shell import command
from cloudmesh_numpy.command_numpy import command_numpy
class cm_shell_numpy:
def activate_cm_shell_numpy(self):
self.register_command_topic('mycommands', 'numpy')
@command
def do_numpy(self, args, arguments):
"""
::
Usage:
numpy NAME
tests via ping if the host ith the give NAME is reachable
Arguments:
NAME Name of the machine to test
Options:
-v verbose mode
"""
# pprint(arguments)
if arguments["NAME"] is None:
Console.error("Please specify a host name")
else:
host = arguments["NAME"]
Console.info("trying to reach {0}".format(host))
status = command_numpy.status(host)
if status:
Console.info("machine " + host + " has been found. ok.")
else:
Console.error("machine " + host + " not reachable. error.")
pass
if __name__ == '__main__':
command = cm_shell_numpy()
command.do_numpy("iu.edu")
command.do_numpy("iu.edu-wrong")
| 24.254902 | 75 | 0.579628 | from __future__ import print_function
import os
from cmd3.console import Console
from cmd3.shell import command
from cloudmesh_numpy.command_numpy import command_numpy
class cm_shell_numpy:
def activate_cm_shell_numpy(self):
self.register_command_topic('mycommands', 'numpy')
@command
def do_numpy(self, args, arguments):
if arguments["NAME"] is None:
Console.error("Please specify a host name")
else:
host = arguments["NAME"]
Console.info("trying to reach {0}".format(host))
status = command_numpy.status(host)
if status:
Console.info("machine " + host + " has been found. ok.")
else:
Console.error("machine " + host + " not reachable. error.")
pass
if __name__ == '__main__':
command = cm_shell_numpy()
command.do_numpy("iu.edu")
command.do_numpy("iu.edu-wrong")
| true | true |
f719f0690f45a487b47db964c4e0e9f736b885dc | 20,953 | py | Python | anyex/bitbank.py | ttwishing/anyex | cfd1f2f04ab992b790add4843aafff91e5773cbf | [
"MIT"
] | null | null | null | anyex/bitbank.py | ttwishing/anyex | cfd1f2f04ab992b790add4843aafff91e5773cbf | [
"MIT"
] | null | null | null | anyex/bitbank.py | ttwishing/anyex | cfd1f2f04ab992b790add4843aafff91e5773cbf | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/anyex/anyex/blob/master/CONTRIBUTING.md#how-to-contribute-code
from anyex.base.exchange import Exchange
from anyex.base.errors import ExchangeError
from anyex.base.errors import AuthenticationError
from anyex.base.errors import PermissionDenied
from anyex.base.errors import InsufficientFunds
from anyex.base.errors import InvalidOrder
from anyex.base.errors import OrderNotFound
from anyex.base.errors import InvalidNonce
class bitbank (Exchange):
def describe(self):
return self.deep_extend(super(bitbank, self).describe(), {
'id': 'bitbank',
'name': 'bitbank',
'countries': 'JP',
'version': 'v1',
'has': {
'fetchOHLCV': True,
'fetchOpenOrders': True,
'fetchMyTrades': True,
'fetchDepositAddress': True,
'withdraw': True,
},
'timeframes': {
'1m': '1min',
'5m': '5min',
'15m': '15min',
'30m': '30min',
'1h': '1hour',
'4h': '4hour',
'8h': '8hour',
'12h': '12hour',
'1d': '1day',
'1w': '1week',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/37808081-b87f2d9c-2e59-11e8-894d-c1900b7584fe.jpg',
'api': {
'public': 'https://public.bitbank.cc',
'private': 'https://api.bitbank.cc',
},
'www': 'https://bitbank.cc/',
'doc': 'https://docs.bitbank.cc/',
'fees': 'https://bitbank.cc/docs/fees/',
},
'api': {
'public': {
'get': [
'{pair}/ticker',
'{pair}/depth',
'{pair}/transactions',
'{pair}/transactions/{YYYYMMDD}',
'{pair}/candlestick/{candle-type}/{YYYYMMDD}',
],
},
'private': {
'get': [
'user/assets',
'user/spot/order',
'user/spot/active_orders',
'user/spot/trade_history',
'user/withdrawal_account',
],
'post': [
'user/spot/order',
'user/spot/cancel_order',
'user/spot/cancel_orders',
'user/spot/orders_info',
'user/request_withdrawal',
],
},
},
'markets': {
'BCH/BTC': {'id': 'bcc_btc', 'symbol': 'BCH/BTC', 'base': 'BCH', 'quote': 'BTC', 'baseId': 'bcc', 'quoteId': 'btc'},
'BCH/JPY': {'id': 'bcc_jpy', 'symbol': 'BCH/JPY', 'base': 'BCH', 'quote': 'JPY', 'baseId': 'bcc', 'quoteId': 'jpy'},
'MONA/BTC': {'id': 'mona_btc', 'symbol': 'MONA/BTC', 'base': 'MONA', 'quote': 'BTC', 'baseId': 'mona', 'quoteId': 'btc'},
'MONA/JPY': {'id': 'mona_jpy', 'symbol': 'MONA/JPY', 'base': 'MONA', 'quote': 'JPY', 'baseId': 'mona', 'quoteId': 'jpy'},
'ETH/BTC': {'id': 'eth_btc', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC', 'baseId': 'eth', 'quoteId': 'btc'},
'LTC/BTC': {'id': 'ltc_btc', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC', 'baseId': 'ltc', 'quoteId': 'btc'},
'XRP/JPY': {'id': 'xrp_jpy', 'symbol': 'XRP/JPY', 'base': 'XRP', 'quote': 'JPY', 'baseId': 'xrp', 'quoteId': 'jpy'},
'BTC/JPY': {'id': 'btc_jpy', 'symbol': 'BTC/JPY', 'base': 'BTC', 'quote': 'JPY', 'baseId': 'btc', 'quoteId': 'jpy'},
},
'fees': {
'trading': {
# only temporarily
'maker': 0.0,
'taker': 0.0,
},
'funding': {
'withdraw': {
# 'JPY': amount => amount > 756 if 30000 else 540,
'BTC': 0.001,
'LTC': 0.001,
'XRP': 0.15,
'ETH': 0.0005,
'MONA': 0.001,
'BCC': 0.001,
},
},
},
'precision': {
'price': 8,
'amount': 8,
},
'exceptions': {
'20001': AuthenticationError,
'20002': AuthenticationError,
'20003': AuthenticationError,
'20005': AuthenticationError,
'20004': InvalidNonce,
'40020': InvalidOrder,
'40021': InvalidOrder,
'40025': ExchangeError,
'40013': OrderNotFound,
'40014': OrderNotFound,
'50008': PermissionDenied,
'50009': OrderNotFound,
'50010': OrderNotFound,
'60001': InsufficientFunds,
},
})
def parse_ticker(self, ticker, market=None):
symbol = market['symbol']
timestamp = ticker['timestamp']
last = float(ticker['last'])
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'bidVolume': None,
'ask': float(ticker['sell']),
'askVolume': None,
'vwap': None,
'open': None,
'close': last,
'last': last,
'previousClose': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['vol']),
'quoteVolume': None,
'info': ticker,
}
def fetch_ticker(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetPairTicker(self.extend({
'pair': market['id'],
}, params))
return self.parse_ticker(response['data'], market)
def fetch_order_book(self, symbol, limit=None, params={}):
self.load_markets()
response = self.publicGetPairDepth(self.extend({
'pair': self.market_id(symbol),
}, params))
orderbook = response['data']
return self.parse_order_book(orderbook, orderbook['timestamp'])
def parse_trade(self, trade, market=None):
timestamp = trade['executed_at']
price = float(trade['price'])
amount = float(trade['amount'])
symbol = market['symbol']
cost = self.cost_to_precision(symbol, price * amount)
id = self.safe_string(trade, 'transaction_id')
if not id:
id = self.safe_string(trade, 'trade_id')
fee = None
if 'fee_amount_quote' in trade:
fee = {
'currency': market['quote'],
'cost': self.safe_float(trade, 'fee_amount_quote'),
}
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'id': id,
'order': self.safe_string(trade, 'order_id'),
'type': self.safe_string(trade, 'type'),
'side': trade['side'],
'price': price,
'amount': amount,
'cost': cost,
'fee': fee,
'info': trade,
}
def fetch_trades(self, symbol, since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
trades = self.publicGetPairTransactions(self.extend({
'pair': market['id'],
}, params))
return self.parse_trades(trades['data']['transactions'], market, since, limit)
def parse_ohlcv(self, ohlcv, market=None, timeframe='5m', since=None, limit=None):
return [
ohlcv[5],
float(ohlcv[0]),
float(ohlcv[1]),
float(ohlcv[2]),
float(ohlcv[3]),
float(ohlcv[4]),
]
def fetch_ohlcv(self, symbol, timeframe='5m', since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
date = self.milliseconds()
date = self.ymd(date)
date = date.split('-')
response = self.publicGetPairCandlestickCandleTypeYYYYMMDD(self.extend({
'pair': market['id'],
'candle-type': self.timeframes[timeframe],
'YYYYMMDD': ''.join(date),
}, params))
ohlcv = response['data']['candlestick'][0]['ohlcv']
return self.parse_ohlcvs(ohlcv, market, timeframe, since, limit)
def fetch_balance(self, params={}):
self.load_markets()
response = self.privateGetUserAssets(params)
result = {'info': response}
balances = response['data']['assets']
for i in range(0, len(balances)):
balance = balances[i]
id = balance['asset']
code = id
if id in self.currencies_by_id:
code = self.currencies_by_id[id]['code']
account = {
'free': float(balance['free_amount']),
'used': float(balance['locked_amount']),
'total': float(balance['onhand_amount']),
}
result[code] = account
return self.parse_balance(result)
def parse_order(self, order, market=None):
marketId = self.safe_string(order, 'pair')
symbol = None
if marketId and not market and(marketId in list(self.marketsById.keys())):
market = self.marketsById[marketId]
if market:
symbol = market['symbol']
timestamp = self.safe_integer(order, 'ordered_at') * 1000
price = float(order['price'])
amount = self.safe_float(order, 'start_amount')
filled = self.safe_float(order, 'executed_amount')
remaining = self.safe_float(order, 'remaining_amount')
cost = filled * self.safe_float(order, 'average_price')
status = self.safe_string(order, 'status')
# UNFILLED
# PARTIALLY_FILLED
# FULLY_FILLED
# CANCELED_UNFILLED
# CANCELED_PARTIALLY_FILLED
if status == 'FULLY_FILLED':
status = 'closed'
elif status == 'CANCELED_UNFILLED' or status == 'CANCELED_PARTIALLY_FILLED':
status = 'canceled'
else:
status = 'open'
return {
'id': self.safe_string(order, 'order_id'),
'datetime': self.iso8601(timestamp),
'timestamp': timestamp,
'lastTradeTimestamp': None,
'status': status,
'symbol': symbol,
'type': order['type'],
'side': order['side'],
'price': price,
'cost': cost,
'amount': amount,
'filled': filled,
'remaining': remaining,
'trades': None,
'fee': None,
'info': order,
}
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
market = self.market(symbol)
if price is None:
raise InvalidOrder(self.id + ' createOrder requires a price argument for both market and limit orders')
request = {
'pair': market['id'],
'amount': self.amount_to_string(symbol, amount),
'price': self.price_to_precision(symbol, price),
'side': side,
'type': type,
}
response = self.privatePostUserSpotOrder(self.extend(request, params))
id = response['data']['order_id']
order = self.parse_order(response['data'], market)
self.orders[id] = order
return order
def cancel_order(self, id, symbol=None, params={}):
self.load_markets()
market = self.market(symbol)
response = self.privatePostUserSpotCancelOrder(self.extend({
'order_id': id,
'pair': market['id'],
}, params))
return response['data']
def fetch_order(self, id, symbol=None, params={}):
self.load_markets()
market = self.market(symbol)
response = self.privateGetUserSpotOrder(self.extend({
'order_id': id,
'pair': market['id'],
}, params))
return self.parse_order(response['data'])
def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
request = {
'pair': market['id'],
}
if limit:
request['count'] = limit
if since:
request['since'] = int(since / 1000)
orders = self.privateGetUserSpotActiveOrders(self.extend(request, params))
return self.parse_orders(orders['data']['orders'], market, since, limit)
def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
market = None
if symbol is not None:
self.load_markets()
market = self.market(symbol)
request = {}
if market is not None:
request['pair'] = market['id']
if limit is not None:
request['count'] = limit
if since is not None:
request['since'] = int(since / 1000)
trades = self.privateGetUserSpotTradeHistory(self.extend(request, params))
return self.parse_trades(trades['data']['trades'], market, since, limit)
def fetch_deposit_address(self, code, params={}):
self.load_markets()
currency = self.currency(code)
response = self.privateGetUserWithdrawalAccount(self.extend({
'asset': currency['id'],
}, params))
# Not sure about self if there could be more accounts...
accounts = response['data']['accounts']
address = self.safe_string(accounts[0], 'address')
status = 'ok' if address else 'none'
return {
'currency': currency,
'address': address,
'tag': None,
'status': status,
'info': response,
}
def withdraw(self, code, amount, address, tag=None, params={}):
if not('uuid' in list(params.keys())):
raise ExchangeError(self.id + ' uuid is required for withdrawal')
self.load_markets()
currency = self.currency(code)
response = self.privatePostUserRequestWithdrawal(self.extend({
'asset': currency['id'],
'amount': amount,
}, params))
return {
'info': response,
'id': response['data']['txid'],
}
def nonce(self):
return self.milliseconds()
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
query = self.omit(params, self.extract_params(path))
url = self.urls['api'][api] + '/'
if api == 'public':
url += self.implode_params(path, params)
if query:
url += '?' + self.urlencode(query)
else:
self.check_required_credentials()
nonce = str(self.nonce())
auth = nonce
url += self.version + '/' + self.implode_params(path, params)
if method == 'POST':
body = self.json(query)
auth += body
else:
auth += '/' + self.version + '/' + path
if query:
query = self.urlencode(query)
url += '?' + query
auth += '?' + query
headers = {
'Content-Type': 'application/json',
'ACCESS-KEY': self.apiKey,
'ACCESS-NONCE': nonce,
'ACCESS-SIGNATURE': self.hmac(self.encode(auth), self.encode(self.secret)),
}
return {'url': url, 'method': method, 'body': body, 'headers': headers}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
response = self.fetch2(path, api, method, params, headers, body)
success = self.safe_integer(response, 'success')
data = self.safe_value(response, 'data')
if not success or not data:
errorMessages = {
'10000': 'URL does not exist',
'10001': 'A system error occurred. Please contact support',
'10002': 'Invalid JSON format. Please check the contents of transmission',
'10003': 'A system error occurred. Please contact support',
'10005': 'A timeout error occurred. Please wait for a while and try again',
'20001': 'API authentication failed',
'20002': 'Illegal API key',
'20003': 'API key does not exist',
'20004': 'API Nonce does not exist',
'20005': 'API signature does not exist',
'20011': 'Two-step verification failed',
'20014': 'SMS authentication failed',
'30001': 'Please specify the order quantity',
'30006': 'Please specify the order ID',
'30007': 'Please specify the order ID array',
'30009': 'Please specify the stock',
'30012': 'Please specify the order price',
'30013': 'Trade Please specify either',
'30015': 'Please specify the order type',
'30016': 'Please specify asset name',
'30019': 'Please specify uuid',
'30039': 'Please specify the amount to be withdrawn',
'40001': 'The order quantity is invalid',
'40006': 'Count value is invalid',
'40007': 'End time is invalid',
'40008': 'end_id Value is invalid',
'40009': 'The from_id value is invalid',
'40013': 'The order ID is invalid',
'40014': 'The order ID array is invalid',
'40015': 'Too many specified orders',
'40017': 'Incorrect issue name',
'40020': 'The order price is invalid',
'40021': 'The trading classification is invalid',
'40022': 'Start date is invalid',
'40024': 'The order type is invalid',
'40025': 'Incorrect asset name',
'40028': 'uuid is invalid',
'40048': 'The amount of withdrawal is illegal',
'50003': 'Currently, self account is in a state where you can not perform the operation you specified. Please contact support',
'50004': 'Currently, self account is temporarily registered. Please try again after registering your account',
'50005': 'Currently, self account is locked. Please contact support',
'50006': 'Currently, self account is locked. Please contact support',
'50008': 'User identification has not been completed',
'50009': 'Your order does not exist',
'50010': 'Can not cancel specified order',
'50011': 'API not found',
'60001': 'The number of possessions is insufficient',
'60002': 'It exceeds the quantity upper limit of the tender buying order',
'60003': 'The specified quantity exceeds the limit',
'60004': 'The specified quantity is below the threshold',
'60005': 'The specified price is above the limit',
'60006': 'The specified price is below the lower limit',
'70001': 'A system error occurred. Please contact support',
'70002': 'A system error occurred. Please contact support',
'70003': 'A system error occurred. Please contact support',
'70004': 'We are unable to accept orders as the transaction is currently suspended',
'70005': 'Order can not be accepted because purchase order is currently suspended',
'70006': 'We can not accept orders because we are currently unsubscribed ',
}
errorClasses = self.exceptions
code = self.safe_string(data, 'code')
message = self.safe_string(errorMessages, code, 'Error')
ErrorClass = self.safe_value(errorClasses, code)
if ErrorClass is not None:
raise ErrorClass(message)
else:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
| 41.906 | 143 | 0.509617 |
nge import Exchange
from anyex.base.errors import ExchangeError
from anyex.base.errors import AuthenticationError
from anyex.base.errors import PermissionDenied
from anyex.base.errors import InsufficientFunds
from anyex.base.errors import InvalidOrder
from anyex.base.errors import OrderNotFound
from anyex.base.errors import InvalidNonce
class bitbank (Exchange):
def describe(self):
return self.deep_extend(super(bitbank, self).describe(), {
'id': 'bitbank',
'name': 'bitbank',
'countries': 'JP',
'version': 'v1',
'has': {
'fetchOHLCV': True,
'fetchOpenOrders': True,
'fetchMyTrades': True,
'fetchDepositAddress': True,
'withdraw': True,
},
'timeframes': {
'1m': '1min',
'5m': '5min',
'15m': '15min',
'30m': '30min',
'1h': '1hour',
'4h': '4hour',
'8h': '8hour',
'12h': '12hour',
'1d': '1day',
'1w': '1week',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/37808081-b87f2d9c-2e59-11e8-894d-c1900b7584fe.jpg',
'api': {
'public': 'https://public.bitbank.cc',
'private': 'https://api.bitbank.cc',
},
'www': 'https://bitbank.cc/',
'doc': 'https://docs.bitbank.cc/',
'fees': 'https://bitbank.cc/docs/fees/',
},
'api': {
'public': {
'get': [
'{pair}/ticker',
'{pair}/depth',
'{pair}/transactions',
'{pair}/transactions/{YYYYMMDD}',
'{pair}/candlestick/{candle-type}/{YYYYMMDD}',
],
},
'private': {
'get': [
'user/assets',
'user/spot/order',
'user/spot/active_orders',
'user/spot/trade_history',
'user/withdrawal_account',
],
'post': [
'user/spot/order',
'user/spot/cancel_order',
'user/spot/cancel_orders',
'user/spot/orders_info',
'user/request_withdrawal',
],
},
},
'markets': {
'BCH/BTC': {'id': 'bcc_btc', 'symbol': 'BCH/BTC', 'base': 'BCH', 'quote': 'BTC', 'baseId': 'bcc', 'quoteId': 'btc'},
'BCH/JPY': {'id': 'bcc_jpy', 'symbol': 'BCH/JPY', 'base': 'BCH', 'quote': 'JPY', 'baseId': 'bcc', 'quoteId': 'jpy'},
'MONA/BTC': {'id': 'mona_btc', 'symbol': 'MONA/BTC', 'base': 'MONA', 'quote': 'BTC', 'baseId': 'mona', 'quoteId': 'btc'},
'MONA/JPY': {'id': 'mona_jpy', 'symbol': 'MONA/JPY', 'base': 'MONA', 'quote': 'JPY', 'baseId': 'mona', 'quoteId': 'jpy'},
'ETH/BTC': {'id': 'eth_btc', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC', 'baseId': 'eth', 'quoteId': 'btc'},
'LTC/BTC': {'id': 'ltc_btc', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC', 'baseId': 'ltc', 'quoteId': 'btc'},
'XRP/JPY': {'id': 'xrp_jpy', 'symbol': 'XRP/JPY', 'base': 'XRP', 'quote': 'JPY', 'baseId': 'xrp', 'quoteId': 'jpy'},
'BTC/JPY': {'id': 'btc_jpy', 'symbol': 'BTC/JPY', 'base': 'BTC', 'quote': 'JPY', 'baseId': 'btc', 'quoteId': 'jpy'},
},
'fees': {
'trading': {
'maker': 0.0,
'taker': 0.0,
},
'funding': {
'withdraw': {
'BTC': 0.001,
'LTC': 0.001,
'XRP': 0.15,
'ETH': 0.0005,
'MONA': 0.001,
'BCC': 0.001,
},
},
},
'precision': {
'price': 8,
'amount': 8,
},
'exceptions': {
'20001': AuthenticationError,
'20002': AuthenticationError,
'20003': AuthenticationError,
'20005': AuthenticationError,
'20004': InvalidNonce,
'40020': InvalidOrder,
'40021': InvalidOrder,
'40025': ExchangeError,
'40013': OrderNotFound,
'40014': OrderNotFound,
'50008': PermissionDenied,
'50009': OrderNotFound,
'50010': OrderNotFound,
'60001': InsufficientFunds,
},
})
def parse_ticker(self, ticker, market=None):
symbol = market['symbol']
timestamp = ticker['timestamp']
last = float(ticker['last'])
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'bidVolume': None,
'ask': float(ticker['sell']),
'askVolume': None,
'vwap': None,
'open': None,
'close': last,
'last': last,
'previousClose': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['vol']),
'quoteVolume': None,
'info': ticker,
}
def fetch_ticker(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetPairTicker(self.extend({
'pair': market['id'],
}, params))
return self.parse_ticker(response['data'], market)
def fetch_order_book(self, symbol, limit=None, params={}):
self.load_markets()
response = self.publicGetPairDepth(self.extend({
'pair': self.market_id(symbol),
}, params))
orderbook = response['data']
return self.parse_order_book(orderbook, orderbook['timestamp'])
def parse_trade(self, trade, market=None):
timestamp = trade['executed_at']
price = float(trade['price'])
amount = float(trade['amount'])
symbol = market['symbol']
cost = self.cost_to_precision(symbol, price * amount)
id = self.safe_string(trade, 'transaction_id')
if not id:
id = self.safe_string(trade, 'trade_id')
fee = None
if 'fee_amount_quote' in trade:
fee = {
'currency': market['quote'],
'cost': self.safe_float(trade, 'fee_amount_quote'),
}
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'id': id,
'order': self.safe_string(trade, 'order_id'),
'type': self.safe_string(trade, 'type'),
'side': trade['side'],
'price': price,
'amount': amount,
'cost': cost,
'fee': fee,
'info': trade,
}
def fetch_trades(self, symbol, since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
trades = self.publicGetPairTransactions(self.extend({
'pair': market['id'],
}, params))
return self.parse_trades(trades['data']['transactions'], market, since, limit)
def parse_ohlcv(self, ohlcv, market=None, timeframe='5m', since=None, limit=None):
return [
ohlcv[5],
float(ohlcv[0]),
float(ohlcv[1]),
float(ohlcv[2]),
float(ohlcv[3]),
float(ohlcv[4]),
]
def fetch_ohlcv(self, symbol, timeframe='5m', since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
date = self.milliseconds()
date = self.ymd(date)
date = date.split('-')
response = self.publicGetPairCandlestickCandleTypeYYYYMMDD(self.extend({
'pair': market['id'],
'candle-type': self.timeframes[timeframe],
'YYYYMMDD': ''.join(date),
}, params))
ohlcv = response['data']['candlestick'][0]['ohlcv']
return self.parse_ohlcvs(ohlcv, market, timeframe, since, limit)
def fetch_balance(self, params={}):
self.load_markets()
response = self.privateGetUserAssets(params)
result = {'info': response}
balances = response['data']['assets']
for i in range(0, len(balances)):
balance = balances[i]
id = balance['asset']
code = id
if id in self.currencies_by_id:
code = self.currencies_by_id[id]['code']
account = {
'free': float(balance['free_amount']),
'used': float(balance['locked_amount']),
'total': float(balance['onhand_amount']),
}
result[code] = account
return self.parse_balance(result)
def parse_order(self, order, market=None):
marketId = self.safe_string(order, 'pair')
symbol = None
if marketId and not market and(marketId in list(self.marketsById.keys())):
market = self.marketsById[marketId]
if market:
symbol = market['symbol']
timestamp = self.safe_integer(order, 'ordered_at') * 1000
price = float(order['price'])
amount = self.safe_float(order, 'start_amount')
filled = self.safe_float(order, 'executed_amount')
remaining = self.safe_float(order, 'remaining_amount')
cost = filled * self.safe_float(order, 'average_price')
status = self.safe_string(order, 'status')
if status == 'FULLY_FILLED':
status = 'closed'
elif status == 'CANCELED_UNFILLED' or status == 'CANCELED_PARTIALLY_FILLED':
status = 'canceled'
else:
status = 'open'
return {
'id': self.safe_string(order, 'order_id'),
'datetime': self.iso8601(timestamp),
'timestamp': timestamp,
'lastTradeTimestamp': None,
'status': status,
'symbol': symbol,
'type': order['type'],
'side': order['side'],
'price': price,
'cost': cost,
'amount': amount,
'filled': filled,
'remaining': remaining,
'trades': None,
'fee': None,
'info': order,
}
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
market = self.market(symbol)
if price is None:
raise InvalidOrder(self.id + ' createOrder requires a price argument for both market and limit orders')
request = {
'pair': market['id'],
'amount': self.amount_to_string(symbol, amount),
'price': self.price_to_precision(symbol, price),
'side': side,
'type': type,
}
response = self.privatePostUserSpotOrder(self.extend(request, params))
id = response['data']['order_id']
order = self.parse_order(response['data'], market)
self.orders[id] = order
return order
def cancel_order(self, id, symbol=None, params={}):
self.load_markets()
market = self.market(symbol)
response = self.privatePostUserSpotCancelOrder(self.extend({
'order_id': id,
'pair': market['id'],
}, params))
return response['data']
def fetch_order(self, id, symbol=None, params={}):
self.load_markets()
market = self.market(symbol)
response = self.privateGetUserSpotOrder(self.extend({
'order_id': id,
'pair': market['id'],
}, params))
return self.parse_order(response['data'])
def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
request = {
'pair': market['id'],
}
if limit:
request['count'] = limit
if since:
request['since'] = int(since / 1000)
orders = self.privateGetUserSpotActiveOrders(self.extend(request, params))
return self.parse_orders(orders['data']['orders'], market, since, limit)
def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
market = None
if symbol is not None:
self.load_markets()
market = self.market(symbol)
request = {}
if market is not None:
request['pair'] = market['id']
if limit is not None:
request['count'] = limit
if since is not None:
request['since'] = int(since / 1000)
trades = self.privateGetUserSpotTradeHistory(self.extend(request, params))
return self.parse_trades(trades['data']['trades'], market, since, limit)
def fetch_deposit_address(self, code, params={}):
self.load_markets()
currency = self.currency(code)
response = self.privateGetUserWithdrawalAccount(self.extend({
'asset': currency['id'],
}, params))
accounts = response['data']['accounts']
address = self.safe_string(accounts[0], 'address')
status = 'ok' if address else 'none'
return {
'currency': currency,
'address': address,
'tag': None,
'status': status,
'info': response,
}
def withdraw(self, code, amount, address, tag=None, params={}):
if not('uuid' in list(params.keys())):
raise ExchangeError(self.id + ' uuid is required for withdrawal')
self.load_markets()
currency = self.currency(code)
response = self.privatePostUserRequestWithdrawal(self.extend({
'asset': currency['id'],
'amount': amount,
}, params))
return {
'info': response,
'id': response['data']['txid'],
}
def nonce(self):
return self.milliseconds()
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
query = self.omit(params, self.extract_params(path))
url = self.urls['api'][api] + '/'
if api == 'public':
url += self.implode_params(path, params)
if query:
url += '?' + self.urlencode(query)
else:
self.check_required_credentials()
nonce = str(self.nonce())
auth = nonce
url += self.version + '/' + self.implode_params(path, params)
if method == 'POST':
body = self.json(query)
auth += body
else:
auth += '/' + self.version + '/' + path
if query:
query = self.urlencode(query)
url += '?' + query
auth += '?' + query
headers = {
'Content-Type': 'application/json',
'ACCESS-KEY': self.apiKey,
'ACCESS-NONCE': nonce,
'ACCESS-SIGNATURE': self.hmac(self.encode(auth), self.encode(self.secret)),
}
return {'url': url, 'method': method, 'body': body, 'headers': headers}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
response = self.fetch2(path, api, method, params, headers, body)
success = self.safe_integer(response, 'success')
data = self.safe_value(response, 'data')
if not success or not data:
errorMessages = {
'10000': 'URL does not exist',
'10001': 'A system error occurred. Please contact support',
'10002': 'Invalid JSON format. Please check the contents of transmission',
'10003': 'A system error occurred. Please contact support',
'10005': 'A timeout error occurred. Please wait for a while and try again',
'20001': 'API authentication failed',
'20002': 'Illegal API key',
'20003': 'API key does not exist',
'20004': 'API Nonce does not exist',
'20005': 'API signature does not exist',
'20011': 'Two-step verification failed',
'20014': 'SMS authentication failed',
'30001': 'Please specify the order quantity',
'30006': 'Please specify the order ID',
'30007': 'Please specify the order ID array',
'30009': 'Please specify the stock',
'30012': 'Please specify the order price',
'30013': 'Trade Please specify either',
'30015': 'Please specify the order type',
'30016': 'Please specify asset name',
'30019': 'Please specify uuid',
'30039': 'Please specify the amount to be withdrawn',
'40001': 'The order quantity is invalid',
'40006': 'Count value is invalid',
'40007': 'End time is invalid',
'40008': 'end_id Value is invalid',
'40009': 'The from_id value is invalid',
'40013': 'The order ID is invalid',
'40014': 'The order ID array is invalid',
'40015': 'Too many specified orders',
'40017': 'Incorrect issue name',
'40020': 'The order price is invalid',
'40021': 'The trading classification is invalid',
'40022': 'Start date is invalid',
'40024': 'The order type is invalid',
'40025': 'Incorrect asset name',
'40028': 'uuid is invalid',
'40048': 'The amount of withdrawal is illegal',
'50003': 'Currently, self account is in a state where you can not perform the operation you specified. Please contact support',
'50004': 'Currently, self account is temporarily registered. Please try again after registering your account',
'50005': 'Currently, self account is locked. Please contact support',
'50006': 'Currently, self account is locked. Please contact support',
'50008': 'User identification has not been completed',
'50009': 'Your order does not exist',
'50010': 'Can not cancel specified order',
'50011': 'API not found',
'60001': 'The number of possessions is insufficient',
'60002': 'It exceeds the quantity upper limit of the tender buying order',
'60003': 'The specified quantity exceeds the limit',
'60004': 'The specified quantity is below the threshold',
'60005': 'The specified price is above the limit',
'60006': 'The specified price is below the lower limit',
'70001': 'A system error occurred. Please contact support',
'70002': 'A system error occurred. Please contact support',
'70003': 'A system error occurred. Please contact support',
'70004': 'We are unable to accept orders as the transaction is currently suspended',
'70005': 'Order can not be accepted because purchase order is currently suspended',
'70006': 'We can not accept orders because we are currently unsubscribed ',
}
errorClasses = self.exceptions
code = self.safe_string(data, 'code')
message = self.safe_string(errorMessages, code, 'Error')
ErrorClass = self.safe_value(errorClasses, code)
if ErrorClass is not None:
raise ErrorClass(message)
else:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
| true | true |
f719f0bd0810de624991f194db2d5e2731bca1d7 | 2,976 | py | Python | etcd/setup.py | dvanderveer/integrations-core | 41dd9950296455457c9b7342584153678503d5aa | [
"BSD-3-Clause"
] | null | null | null | etcd/setup.py | dvanderveer/integrations-core | 41dd9950296455457c9b7342584153678503d5aa | [
"BSD-3-Clause"
] | null | null | null | etcd/setup.py | dvanderveer/integrations-core | 41dd9950296455457c9b7342584153678503d5aa | [
"BSD-3-Clause"
] | null | null | null | # Always prefer setuptools over distutils
from setuptools import setup
# To use a consistent encoding
from codecs import open
from os import path
import re
here = path.abspath(path.dirname(__file__))
# get the long description from the readme file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
runtime_reqs = ['datadog_checks_base']
with open(path.join(here, 'requirements.txt'), encoding='utf-8') as f:
for line in f.readlines():
line = line.strip()
if not line or line.startswith('--hash') or line[0] == '#':
continue
req = line.rpartition('#')
if not len(req[1]):
if '--hash=' in req[2]:
tokens = req[2].split()
if len(tokens) > 1:
runtime_reqs.append(tokens[0])
elif ';' in req[2]:
runtime_reqs.append(req[2])
else:
runtime_reqs.append(req[0])
def read(*parts):
with open(path.join(here, *parts), 'r') as fp:
return fp.read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
# https://packaging.python.org/guides/single-sourcing-package-version/
version = find_version("datadog_checks", "etcd", "__init__.py")
setup(
name='datadog-etcd',
version=version,
description='The Etcd check',
long_description=long_description,
keywords='datadog agent etcd check',
# The project's main homepage.
url='https://github.com/DataDog/integrations-core',
# Author details
author='Datadog',
author_email='packages@datadoghq.com',
# License
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Topic :: System :: Monitoring',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
# The package we're going to ship
packages=['datadog_checks.etcd'],
# Run-time dependencies
install_requires=list(set(runtime_reqs)),
# Development dependencies, run with:
# $ pip install -e .[dev]
extras_require={
'dev': [
'check-manifest',
'datadog_agent_tk>=5.15',
],
},
# Testing setup and dependencies
tests_require=[
'nose',
'coverage',
'datadog_agent_tk>=5.15',
],
test_suite='nose.collector',
# Extra files to ship with the wheel package
package_data={b'datadog_checks.etcd': ['conf.yaml.example']},
include_package_data=True,
)
| 29.176471 | 70 | 0.612231 |
from setuptools import setup
from codecs import open
from os import path
import re
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
runtime_reqs = ['datadog_checks_base']
with open(path.join(here, 'requirements.txt'), encoding='utf-8') as f:
for line in f.readlines():
line = line.strip()
if not line or line.startswith('--hash') or line[0] == '#':
continue
req = line.rpartition('#')
if not len(req[1]):
if '--hash=' in req[2]:
tokens = req[2].split()
if len(tokens) > 1:
runtime_reqs.append(tokens[0])
elif ';' in req[2]:
runtime_reqs.append(req[2])
else:
runtime_reqs.append(req[0])
def read(*parts):
with open(path.join(here, *parts), 'r') as fp:
return fp.read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
# https://packaging.python.org/guides/single-sourcing-package-version/
version = find_version("datadog_checks", "etcd", "__init__.py")
setup(
name='datadog-etcd',
version=version,
description='The Etcd check',
long_description=long_description,
keywords='datadog agent etcd check',
# The project's main homepage.
url='https://github.com/DataDog/integrations-core',
# Author details
author='Datadog',
author_email='packages@datadoghq.com',
# License
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Topic :: System :: Monitoring',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
# The package we're going to ship
packages=['datadog_checks.etcd'],
# Run-time dependencies
install_requires=list(set(runtime_reqs)),
# Development dependencies, run with:
# $ pip install -e .[dev]
extras_require={
'dev': [
'check-manifest',
'datadog_agent_tk>=5.15',
],
},
# Testing setup and dependencies
tests_require=[
'nose',
'coverage',
'datadog_agent_tk>=5.15',
],
test_suite='nose.collector',
# Extra files to ship with the wheel package
package_data={b'datadog_checks.etcd': ['conf.yaml.example']},
include_package_data=True,
)
| true | true |
f719f29ce078fb015c146ba0d7a5bb429d7c7c23 | 69 | py | Python | src/masonite/api/middleware/__init__.py | cercos/masonite | f7f220efa7fae833683e9f07ce13c3795a87d3b8 | [
"MIT"
] | 1,816 | 2018-02-14T01:59:51.000Z | 2022-03-31T17:09:20.000Z | src/masonite/api/middleware/__init__.py | cercos/masonite | f7f220efa7fae833683e9f07ce13c3795a87d3b8 | [
"MIT"
] | 340 | 2018-02-11T00:27:26.000Z | 2022-03-21T12:00:24.000Z | src/masonite/api/middleware/__init__.py | cercos/masonite | f7f220efa7fae833683e9f07ce13c3795a87d3b8 | [
"MIT"
] | 144 | 2018-03-18T00:08:16.000Z | 2022-02-26T01:51:58.000Z | from .JWTAuthenticationMiddleware import JWTAuthenticationMiddleware
| 34.5 | 68 | 0.927536 | from .JWTAuthenticationMiddleware import JWTAuthenticationMiddleware
| true | true |
f719f32c0de53ae35c0223c63678dbad415c2f11 | 22 | py | Python | __init__.py | andy-96/GFPGAN | 0ed1214760170cc27fdfd60da1f64a0699a28cf4 | [
"BSD-3-Clause"
] | null | null | null | __init__.py | andy-96/GFPGAN | 0ed1214760170cc27fdfd60da1f64a0699a28cf4 | [
"BSD-3-Clause"
] | null | null | null | __init__.py | andy-96/GFPGAN | 0ed1214760170cc27fdfd60da1f64a0699a28cf4 | [
"BSD-3-Clause"
] | null | null | null | from .gfpgan import *
| 11 | 21 | 0.727273 | from .gfpgan import *
| true | true |
f719f37af819374470555e086638c20bfd0d0001 | 1,250 | py | Python | leasing/viewsets/contact_additional_views.py | hkotkanen/mvj | a22d40869ef1b13924da428f3026d248acef81a7 | [
"MIT"
] | null | null | null | leasing/viewsets/contact_additional_views.py | hkotkanen/mvj | a22d40869ef1b13924da428f3026d248acef81a7 | [
"MIT"
] | null | null | null | leasing/viewsets/contact_additional_views.py | hkotkanen/mvj | a22d40869ef1b13924da428f3026d248acef81a7 | [
"MIT"
] | null | null | null | import re
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from rest_framework.views import APIView
from leasing.models import Contact
from leasing.permissions import PerMethodPermission
class ContactExistsView(APIView):
permission_classes = (PerMethodPermission,)
perms_map = {
'GET': ['leasing.view_contact'],
}
def get_view_name(self):
return _("Check if contact already exist")
def get_view_description(self, html=False):
return _("Check if contact already exist by business id or national identification number")
def get(self, request, format=None):
identifier = request.query_params.get('identifier', None)
if not identifier:
raise APIException(_('Query parameter "identifier" is mandatory'))
if re.match(r'FI\d{8}', identifier, re.IGNORECASE):
identifier = "{}-{}".format(identifier[2:9], identifier[-1])
return Response({
"exists": Contact.objects.filter(
Q(business_id__iexact=identifier) | Q(national_identification_number__iexact=identifier)).exists(),
})
| 33.783784 | 115 | 0.7056 | import re
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from rest_framework.views import APIView
from leasing.models import Contact
from leasing.permissions import PerMethodPermission
class ContactExistsView(APIView):
permission_classes = (PerMethodPermission,)
perms_map = {
'GET': ['leasing.view_contact'],
}
def get_view_name(self):
return _("Check if contact already exist")
def get_view_description(self, html=False):
return _("Check if contact already exist by business id or national identification number")
def get(self, request, format=None):
identifier = request.query_params.get('identifier', None)
if not identifier:
raise APIException(_('Query parameter "identifier" is mandatory'))
if re.match(r'FI\d{8}', identifier, re.IGNORECASE):
identifier = "{}-{}".format(identifier[2:9], identifier[-1])
return Response({
"exists": Contact.objects.filter(
Q(business_id__iexact=identifier) | Q(national_identification_number__iexact=identifier)).exists(),
})
| true | true |
f719f62e2d8ed7d50dbaff87b0c28e125875ad70 | 21,056 | py | Python | tensorflow/lite/python/convert.py | anigasan/tensorflow | 5b780b4983007661ca479bf4d7ed9a260d8ce43f | [
"Apache-2.0"
] | 1 | 2019-11-18T10:54:10.000Z | 2019-11-18T10:54:10.000Z | tensorflow/lite/python/convert.py | anigasan/tensorflow | 5b780b4983007661ca479bf4d7ed9a260d8ce43f | [
"Apache-2.0"
] | 1 | 2018-04-02T23:42:30.000Z | 2018-05-03T23:12:23.000Z | tensorflow/lite/python/convert.py | anigasan/tensorflow | 5b780b4983007661ca479bf4d7ed9a260d8ce43f | [
"Apache-2.0"
] | null | null | null | # Lint as: python2, python3
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Converts a frozen graph into a TFLite FlatBuffer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import enum # pylint: disable=g-bad-import-order
import os as _os
import platform as _platform
import subprocess as _subprocess
import tempfile as _tempfile
import six
from six.moves import map
from tensorflow.lite.python import lite_constants
from tensorflow.lite.python import util
from tensorflow.lite.python import wrap_toco
from tensorflow.lite.toco import model_flags_pb2 as _model_flags_pb2
from tensorflow.lite.toco import toco_flags_pb2 as _toco_flags_pb2
from tensorflow.lite.toco import types_pb2 as _types_pb2
from tensorflow.python.platform import resource_loader as _resource_loader
from tensorflow.python.util import deprecation
from tensorflow.python.util.tf_export import tf_export as _tf_export
# Find the toco_from_protos binary using the resource loader if using from
# bazel, otherwise we are in a pip where console_scripts already has
# the toco_from_protos tool.
if lite_constants.EXPERIMENTAL_USE_TOCO_API_DIRECTLY:
_toco_from_proto_bin = ""
else:
_toco_from_proto_bin = _resource_loader.get_path_to_datafile(
"../toco/python/toco_from_protos")
if _toco_from_proto_bin and not _os.path.exists(_toco_from_proto_bin):
_toco_from_proto_bin = "toco_from_protos"
def _try_convert_to_unicode(output):
if output is None:
return u""
if isinstance(output, bytes):
try:
return six.ensure_text(output)
except UnicodeDecodeError:
pass
return output
@_tf_export("lite.OpsSet")
class OpsSet(enum.Enum):
"""Enum class defining the sets of ops available to generate TFLite models.
WARNING: Experimental interface, subject to change.
"""
# Convert model using TensorFlow Lite builtin ops.
TFLITE_BUILTINS = "TFLITE_BUILTINS"
# Convert model using TensorFlow ops. Not all TensorFlow ops are available.
# WARNING: Experimental interface, subject to change.
SELECT_TF_OPS = "SELECT_TF_OPS"
# Convert model using only TensorFlow Lite quantized int8 operations.
# Specifying this will throw an error for operations that do not yet have
# quantized implementations.
TFLITE_BUILTINS_INT8 = "TFLITE_BUILTINS_INT8"
def __str__(self):
return self.value
@staticmethod
def get_options():
"""Returns a list of OpsSet options as a list of strings."""
return [str(option) for option in list(OpsSet)]
class ConverterError(Exception):
"""Raised when an error occurs during model conversion."""
pass
def toco_convert_protos(model_flags_str,
toco_flags_str,
input_data_str,
debug_info_str=None,
enable_mlir_converter=False):
"""Convert `input_data_str` according to model and toco parameters.
Unless you know what you are doing consider using
the more friendly `tf.compat.v1.lite.toco_convert`.
Args:
model_flags_str: Serialized proto describing model properties, see
`toco/model_flags.proto`.
toco_flags_str: Serialized proto describing conversion properties, see
`toco/toco_flags.proto`.
input_data_str: Input data in serialized form (e.g. a graphdef is common)
debug_info_str: Serialized `GraphDebugInfo` proto describing logging
information. (default None)
enable_mlir_converter: Enables MLIR-based conversion instead of the default
TOCO conversion. (default False)
Returns:
Converted model in serialized form (e.g. a TFLITE model is common).
Raises:
ConverterError: When conversion fails in TFLiteConverter, usually due to
ops not being supported.
RuntimeError: When conversion fails, an exception is raised with the error
message embedded.
"""
# TODO(aselle): When toco does not use fatal errors for failure, we can
# switch this on.
if not _toco_from_proto_bin:
try:
model_str = wrap_toco.wrapped_toco_convert(model_flags_str,
toco_flags_str, input_data_str,
debug_info_str,
enable_mlir_converter)
return model_str
except Exception as e:
raise ConverterError(str(e))
# Windows and TemporaryFile are not that useful together,
# since you cannot have two readers/writers. So we have to
# make the temporaries and close and delete them explicitly.
toco_filename, model_filename, input_filename, output_filename = (
None, None, None, None)
try:
# Build all input files
with _tempfile.NamedTemporaryFile(delete=False) as fp_toco, \
_tempfile.NamedTemporaryFile(delete=False) as fp_model, \
_tempfile.NamedTemporaryFile(delete=False) as fp_input, \
_tempfile.NamedTemporaryFile(delete=False) as fp_debug:
toco_filename = fp_toco.name
input_filename = fp_input.name
model_filename = fp_model.name
debug_filename = fp_debug.name
fp_model.write(model_flags_str)
fp_toco.write(toco_flags_str)
fp_input.write(six.ensure_binary(input_data_str))
debug_info_str = debug_info_str if debug_info_str else ""
# if debug_info_str contains a "string value", then the call to
# fp_debug.write(debug_info_str) will fail with the following error
#
# TypeError: a bytes-like object is required, not 'str'
#
# Some of the subtests within the "convert_test" unit-test fail
# with the error shown above. So watch out for that scenario and
# convert debug_info_str to bytes where needed
if not isinstance(debug_info_str, bytes):
fp_debug.write(debug_info_str.encode("utf-8"))
else:
fp_debug.write(debug_info_str)
# Reserve an output file
with _tempfile.NamedTemporaryFile(delete=False) as fp:
output_filename = fp.name
# Run
cmd = [
_toco_from_proto_bin,
model_filename,
toco_filename,
input_filename,
output_filename,
"--debug_proto_file={}".format(debug_filename),
]
if enable_mlir_converter:
cmd.append("--enable_mlir_converter")
cmdline = " ".join(cmd)
is_windows = _platform.system() == "Windows"
proc = _subprocess.Popen(
cmdline,
shell=True,
stdout=_subprocess.PIPE,
stderr=_subprocess.STDOUT,
close_fds=not is_windows)
stdout, stderr = proc.communicate()
exitcode = proc.returncode
if exitcode == 0:
with open(output_filename, "rb") as fp:
return fp.read()
else:
stdout = _try_convert_to_unicode(stdout)
stderr = _try_convert_to_unicode(stderr)
raise ConverterError("See console for info.\n%s\n%s\n" % (stdout, stderr))
finally:
# Must manually cleanup files.
for filename in [
toco_filename, input_filename, model_filename, output_filename]:
try:
_os.unlink(filename)
except (OSError, TypeError):
pass
def build_toco_convert_protos(input_tensors,
output_tensors,
inference_type=lite_constants.FLOAT,
inference_input_type=None,
input_format=lite_constants.TENSORFLOW_GRAPHDEF,
input_shapes=None,
output_format=lite_constants.TFLITE,
quantized_input_stats=None,
default_ranges_stats=None,
drop_control_dependency=True,
reorder_across_fake_quant=False,
allow_custom_ops=False,
custom_opdefs=None,
change_concat_input_ranges=False,
post_training_quantize=False,
quantize_to_float16=False,
dump_graphviz_dir=None,
dump_graphviz_video=False,
target_ops=None,
allow_nonexistent_arrays=False,
debug_info=None,
conversion_summary_dir=None):
"""Builds protocol buffers describing a conversion of a model using TOCO.
Typically this is to convert from TensorFlow GraphDef to TFLite, in which
case the default `input_format` and `output_format` are sufficient.
Args:
input_tensors: List of input tensors. Type and shape are computed using
`foo.shape` and `foo.dtype`.
output_tensors: List of output tensors (only .name is used from this).
inference_type: Target data type of real-number arrays in the output file.
Must be `{tf.float32, tf.uint8}`. (default tf.float32)
Must be `{tf.float32, tf.uint8}`. (default `inference_type`)
inference_input_type: Target data type of real-number input arrays. Allows
for a different type for input arrays in the case of quantization.
input_format: Type of data to read Currently must be
`{TENSORFLOW_GRAPHDEF}`. (default TENSORFLOW_GRAPHDEF)
input_shapes: Input array shape. It needs to be a list of the same length
as `input_tensors`, or None. (default None)
output_format: Output file format. Currently must be `{TFLITE,
GRAPHVIZ_DOT}`. (default TFLITE)
quantized_input_stats: List of tuples of floats representing the mean and
standard deviation. Each tuple maps to the corresponding input tensor.
Only need if `inference_input_type` is `QUANTIZED_UINT8`.
real_input_value = (quantized_input_value - mean_value) / std_dev_value.
(default None)
default_ranges_stats: Tuple of integers representing (min, max) range values
for all arrays without a specified range. Intended for experimenting with
quantization via "dummy quantization". (default None)
drop_control_dependency: Boolean indicating whether to drop control
dependencies silently. This is due to TFLite not supporting control
dependencies. (default True)
reorder_across_fake_quant: Boolean indicating whether to reorder FakeQuant
nodes in unexpected locations. Used when the location of the FakeQuant
nodes is preventing graph transformations necessary to convert the graph.
Results in a graph that differs from the quantized training graph,
potentially causing differing arithmetic behavior. (default False)
allow_custom_ops: Boolean indicating whether to allow custom operations.
When false any unknown operation is an error. When true, custom ops are
created for any op that is unknown. The developer will need to provide
these to the TensorFlow Lite runtime with a custom resolver.
(default False)
custom_opdefs: List of strings representing custom ops OpDefs that are
included in the GraphDef. Required when using custom operations with the
MLIR-based converter. (default None)
change_concat_input_ranges: Boolean to change behavior of min/max ranges for
inputs and outputs of the concat operator for quantized models. Changes
the ranges of concat operator overlap when true. (default False)
post_training_quantize: Boolean indicating whether to quantize the weights
of the converted float model. Model size will be reduced and there will be
latency improvements (at the cost of accuracy).
(default False)
quantize_to_float16: Boolean indicating whether to convert float buffers
to float16. (default False)
dump_graphviz_dir: Full filepath of folder to dump the graphs at various
stages of processing GraphViz .dot files. Preferred over
--output_format=GRAPHVIZ_DOT in order to keep the requirements of the
output file. (default None)
dump_graphviz_video: Boolean indicating whether to dump the graph after
every graph transformation. (default False)
target_ops: Experimental flag, subject to change. Set of OpsSet
options indicating which converter to use.
(default set([OpsSet.TFLITE_BUILTINS]))
allow_nonexistent_arrays: Allow specifying array names that don't exist
or are unused in the final graph. (default False)
debug_info: `GraphDebugInfo` proto containing the stack traces for the
original nodes referred by the converted graph.
conversion_summary_dir: A string, the path to the generated conversion logs.
Returns:
model_flags, toco_flags, debug_info: three protocol buffers describing the
conversion process and debug information.
Raises:
ValueError:
If the input tensor type is unknown
Missing mean_values or std_dev_values
RuntimeError: If TOCO fails to convert (in which case the runtime error's
error text will contain the TOCO error log)
"""
toco = _toco_flags_pb2.TocoFlags()
toco.input_format = input_format
toco.output_format = output_format
toco.inference_type = util.convert_dtype_to_tflite_type(inference_type)
if inference_input_type:
toco.inference_input_type = util.convert_dtype_to_tflite_type(
inference_input_type)
else:
toco.inference_input_type = toco.inference_type
toco.drop_control_dependency = drop_control_dependency
toco.reorder_across_fake_quant = reorder_across_fake_quant
toco.allow_custom_ops = allow_custom_ops
if custom_opdefs:
toco.custom_opdefs.extend(custom_opdefs)
toco.post_training_quantize = post_training_quantize
toco.quantize_to_float16 = quantize_to_float16
if default_ranges_stats:
toco.default_ranges_min = default_ranges_stats[0]
toco.default_ranges_max = default_ranges_stats[1]
if dump_graphviz_dir:
toco.dump_graphviz_dir = dump_graphviz_dir
toco.dump_graphviz_include_video = dump_graphviz_video
if conversion_summary_dir:
toco.conversion_summary_dir = conversion_summary_dir
if target_ops:
if set(target_ops) == set([OpsSet.TFLITE_BUILTINS, OpsSet.SELECT_TF_OPS]):
toco.enable_select_tf_ops = True
elif set(target_ops) == set([OpsSet.SELECT_TF_OPS]):
toco.enable_select_tf_ops = True
toco.force_select_tf_ops = True
model = _model_flags_pb2.ModelFlags()
model.change_concat_input_ranges = change_concat_input_ranges
for idx, input_tensor in enumerate(input_tensors):
input_array = model.input_arrays.add()
input_array.name = util.get_tensor_name(input_tensor)
input_array.data_type = util.convert_dtype_to_tflite_type(
input_tensor.dtype)
if toco.inference_input_type in \
[_types_pb2.QUANTIZED_UINT8, _types_pb2.INT8]:
if not quantized_input_stats:
raise ValueError("std_dev and mean must be defined when "
"inference_input_type is QUANTIZED_UINT8.")
input_array.mean_value, input_array.std_value = quantized_input_stats[idx]
if input_shapes is None:
shape = input_tensor.shape
else:
shape = input_shapes[idx]
input_array.shape.dims.extend(list(map(int, shape)))
for output_tensor in output_tensors:
model.output_arrays.append(util.get_tensor_name(output_tensor))
model.allow_nonexistent_arrays = allow_nonexistent_arrays
return model, toco, debug_info
def toco_convert_graph_def(input_data, input_arrays_with_shape, output_arrays,
enable_mlir_converter, *args, **kwargs):
""""Convert a model using TOCO.
This function is used to convert GraphDefs that cannot be loaded into
TensorFlow to TFLite. Conversion can be customized by providing arguments
that are forwarded to `build_toco_convert_protos` (see documentation for
details).
Args:
input_data: Input data (i.e. often `sess.graph_def`),
input_arrays_with_shape: Tuple of strings representing input tensor names
and list of integers representing input shapes
(e.g., [("foo" : [1, 16, 16, 3])]). Use only when graph cannot be loaded
into TensorFlow and when `input_tensors` is None. (default None)
output_arrays: List of output tensors to freeze graph with. Use only when
graph cannot be loaded into TensorFlow and when `output_tensors` is None.
(default None)
enable_mlir_converter: Enables MLIR-based conversion instead of TOCO
conversion.
*args: See `build_toco_convert_protos`,
**kwargs: See `build_toco_convert_protos`.
Returns:
The converted data. For example if TFLite was the destination, then
this will be a tflite flatbuffer in a bytes array.
Raises:
Defined in `build_toco_convert_protos`.
"""
model_flags, toco_flags, _ = build_toco_convert_protos(
input_tensors=[], output_tensors=[], *args, **kwargs)
for idx, (name, shape) in enumerate(input_arrays_with_shape):
input_array = model_flags.input_arrays.add()
if toco_flags.inference_input_type == _types_pb2.QUANTIZED_UINT8:
if (("quantized_input_stats" not in kwargs) or
(not kwargs["quantized_input_stats"])):
raise ValueError("std_dev and mean must be defined when "
"inference_input_type is QUANTIZED_UINT8.")
input_array.mean_value, input_array.std_value = kwargs[
"quantized_input_stats"][idx]
input_array.name = name
input_array.shape.dims.extend(list(map(int, shape)))
for name in output_arrays:
model_flags.output_arrays.append(name)
data = toco_convert_protos(
model_flags.SerializeToString(),
toco_flags.SerializeToString(),
input_data.SerializeToString(),
enable_mlir_converter=enable_mlir_converter)
return data
def toco_convert_impl(input_data, input_tensors, output_tensors,
enable_mlir_converter, *args, **kwargs):
""""Convert a model using TOCO.
Typically this function is used to convert from TensorFlow GraphDef to TFLite.
Conversion can be customized by providing arguments that are forwarded to
`build_toco_convert_protos` (see documentation for details).
Args:
input_data: Input data (i.e. often `sess.graph_def`),
input_tensors: List of input tensors. Type and shape are computed using
`foo.shape` and `foo.dtype`.
output_tensors: List of output tensors (only .name is used from this).
enable_mlir_converter: Enables MLIR-based conversion instead of TOCO
conversion.
*args: See `build_toco_convert_protos`,
**kwargs: See `build_toco_convert_protos`.
Returns:
The converted data. For example if TFLite was the destination, then
this will be a tflite flatbuffer in a bytes array.
Raises:
Defined in `build_toco_convert_protos`.
"""
model_flags, toco_flags, debug_info = build_toco_convert_protos(
input_tensors, output_tensors, *args, **kwargs)
debug_info_str = debug_info.SerializeToString() if debug_info else None
data = toco_convert_protos(
model_flags.SerializeToString(),
toco_flags.SerializeToString(),
input_data.SerializeToString(),
debug_info_str=debug_info_str,
enable_mlir_converter=enable_mlir_converter)
return data
@_tf_export(v1=["lite.toco_convert"])
@deprecation.deprecated(None, "Use `lite.TFLiteConverter` instead.")
def toco_convert(input_data, input_tensors, output_tensors, *args, **kwargs):
"""Convert a model using TOCO.
Typically this function is used to convert from TensorFlow GraphDef to TFLite.
Conversion can be customized by providing arguments that are forwarded to
`build_toco_convert_protos` (see documentation for details). This function has
been deprecated. Please use `lite.TFLiteConverter` instead.
Args:
input_data: Input data (i.e. often `sess.graph_def`),
input_tensors: List of input tensors. Type and shape are computed using
`foo.shape` and `foo.dtype`.
output_tensors: List of output tensors (only .name is used from this).
*args: See `build_toco_convert_protos`,
**kwargs: See `build_toco_convert_protos`.
Returns:
The converted data. For example if TFLite was the destination, then
this will be a tflite flatbuffer in a bytes array.
Raises:
Defined in `build_toco_convert_protos`.
"""
enable_mlir_converter = kwargs.get("enable_mlir_converter", False)
return toco_convert_impl(input_data, input_tensors, output_tensors,
enable_mlir_converter, *args, **kwargs)
| 42.537374 | 80 | 0.714381 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import enum
import os as _os
import platform as _platform
import subprocess as _subprocess
import tempfile as _tempfile
import six
from six.moves import map
from tensorflow.lite.python import lite_constants
from tensorflow.lite.python import util
from tensorflow.lite.python import wrap_toco
from tensorflow.lite.toco import model_flags_pb2 as _model_flags_pb2
from tensorflow.lite.toco import toco_flags_pb2 as _toco_flags_pb2
from tensorflow.lite.toco import types_pb2 as _types_pb2
from tensorflow.python.platform import resource_loader as _resource_loader
from tensorflow.python.util import deprecation
from tensorflow.python.util.tf_export import tf_export as _tf_export
if lite_constants.EXPERIMENTAL_USE_TOCO_API_DIRECTLY:
_toco_from_proto_bin = ""
else:
_toco_from_proto_bin = _resource_loader.get_path_to_datafile(
"../toco/python/toco_from_protos")
if _toco_from_proto_bin and not _os.path.exists(_toco_from_proto_bin):
_toco_from_proto_bin = "toco_from_protos"
def _try_convert_to_unicode(output):
if output is None:
return u""
if isinstance(output, bytes):
try:
return six.ensure_text(output)
except UnicodeDecodeError:
pass
return output
@_tf_export("lite.OpsSet")
class OpsSet(enum.Enum):
TFLITE_BUILTINS = "TFLITE_BUILTINS"
SELECT_TF_OPS = "SELECT_TF_OPS"
TFLITE_BUILTINS_INT8 = "TFLITE_BUILTINS_INT8"
def __str__(self):
return self.value
@staticmethod
def get_options():
return [str(option) for option in list(OpsSet)]
class ConverterError(Exception):
pass
def toco_convert_protos(model_flags_str,
toco_flags_str,
input_data_str,
debug_info_str=None,
enable_mlir_converter=False):
if not _toco_from_proto_bin:
try:
model_str = wrap_toco.wrapped_toco_convert(model_flags_str,
toco_flags_str, input_data_str,
debug_info_str,
enable_mlir_converter)
return model_str
except Exception as e:
raise ConverterError(str(e))
toco_filename, model_filename, input_filename, output_filename = (
None, None, None, None)
try:
with _tempfile.NamedTemporaryFile(delete=False) as fp_toco, \
_tempfile.NamedTemporaryFile(delete=False) as fp_model, \
_tempfile.NamedTemporaryFile(delete=False) as fp_input, \
_tempfile.NamedTemporaryFile(delete=False) as fp_debug:
toco_filename = fp_toco.name
input_filename = fp_input.name
model_filename = fp_model.name
debug_filename = fp_debug.name
fp_model.write(model_flags_str)
fp_toco.write(toco_flags_str)
fp_input.write(six.ensure_binary(input_data_str))
debug_info_str = debug_info_str if debug_info_str else ""
if not isinstance(debug_info_str, bytes):
fp_debug.write(debug_info_str.encode("utf-8"))
else:
fp_debug.write(debug_info_str)
with _tempfile.NamedTemporaryFile(delete=False) as fp:
output_filename = fp.name
cmd = [
_toco_from_proto_bin,
model_filename,
toco_filename,
input_filename,
output_filename,
"--debug_proto_file={}".format(debug_filename),
]
if enable_mlir_converter:
cmd.append("--enable_mlir_converter")
cmdline = " ".join(cmd)
is_windows = _platform.system() == "Windows"
proc = _subprocess.Popen(
cmdline,
shell=True,
stdout=_subprocess.PIPE,
stderr=_subprocess.STDOUT,
close_fds=not is_windows)
stdout, stderr = proc.communicate()
exitcode = proc.returncode
if exitcode == 0:
with open(output_filename, "rb") as fp:
return fp.read()
else:
stdout = _try_convert_to_unicode(stdout)
stderr = _try_convert_to_unicode(stderr)
raise ConverterError("See console for info.\n%s\n%s\n" % (stdout, stderr))
finally:
for filename in [
toco_filename, input_filename, model_filename, output_filename]:
try:
_os.unlink(filename)
except (OSError, TypeError):
pass
def build_toco_convert_protos(input_tensors,
output_tensors,
inference_type=lite_constants.FLOAT,
inference_input_type=None,
input_format=lite_constants.TENSORFLOW_GRAPHDEF,
input_shapes=None,
output_format=lite_constants.TFLITE,
quantized_input_stats=None,
default_ranges_stats=None,
drop_control_dependency=True,
reorder_across_fake_quant=False,
allow_custom_ops=False,
custom_opdefs=None,
change_concat_input_ranges=False,
post_training_quantize=False,
quantize_to_float16=False,
dump_graphviz_dir=None,
dump_graphviz_video=False,
target_ops=None,
allow_nonexistent_arrays=False,
debug_info=None,
conversion_summary_dir=None):
toco = _toco_flags_pb2.TocoFlags()
toco.input_format = input_format
toco.output_format = output_format
toco.inference_type = util.convert_dtype_to_tflite_type(inference_type)
if inference_input_type:
toco.inference_input_type = util.convert_dtype_to_tflite_type(
inference_input_type)
else:
toco.inference_input_type = toco.inference_type
toco.drop_control_dependency = drop_control_dependency
toco.reorder_across_fake_quant = reorder_across_fake_quant
toco.allow_custom_ops = allow_custom_ops
if custom_opdefs:
toco.custom_opdefs.extend(custom_opdefs)
toco.post_training_quantize = post_training_quantize
toco.quantize_to_float16 = quantize_to_float16
if default_ranges_stats:
toco.default_ranges_min = default_ranges_stats[0]
toco.default_ranges_max = default_ranges_stats[1]
if dump_graphviz_dir:
toco.dump_graphviz_dir = dump_graphviz_dir
toco.dump_graphviz_include_video = dump_graphviz_video
if conversion_summary_dir:
toco.conversion_summary_dir = conversion_summary_dir
if target_ops:
if set(target_ops) == set([OpsSet.TFLITE_BUILTINS, OpsSet.SELECT_TF_OPS]):
toco.enable_select_tf_ops = True
elif set(target_ops) == set([OpsSet.SELECT_TF_OPS]):
toco.enable_select_tf_ops = True
toco.force_select_tf_ops = True
model = _model_flags_pb2.ModelFlags()
model.change_concat_input_ranges = change_concat_input_ranges
for idx, input_tensor in enumerate(input_tensors):
input_array = model.input_arrays.add()
input_array.name = util.get_tensor_name(input_tensor)
input_array.data_type = util.convert_dtype_to_tflite_type(
input_tensor.dtype)
if toco.inference_input_type in \
[_types_pb2.QUANTIZED_UINT8, _types_pb2.INT8]:
if not quantized_input_stats:
raise ValueError("std_dev and mean must be defined when "
"inference_input_type is QUANTIZED_UINT8.")
input_array.mean_value, input_array.std_value = quantized_input_stats[idx]
if input_shapes is None:
shape = input_tensor.shape
else:
shape = input_shapes[idx]
input_array.shape.dims.extend(list(map(int, shape)))
for output_tensor in output_tensors:
model.output_arrays.append(util.get_tensor_name(output_tensor))
model.allow_nonexistent_arrays = allow_nonexistent_arrays
return model, toco, debug_info
def toco_convert_graph_def(input_data, input_arrays_with_shape, output_arrays,
enable_mlir_converter, *args, **kwargs):
model_flags, toco_flags, _ = build_toco_convert_protos(
input_tensors=[], output_tensors=[], *args, **kwargs)
for idx, (name, shape) in enumerate(input_arrays_with_shape):
input_array = model_flags.input_arrays.add()
if toco_flags.inference_input_type == _types_pb2.QUANTIZED_UINT8:
if (("quantized_input_stats" not in kwargs) or
(not kwargs["quantized_input_stats"])):
raise ValueError("std_dev and mean must be defined when "
"inference_input_type is QUANTIZED_UINT8.")
input_array.mean_value, input_array.std_value = kwargs[
"quantized_input_stats"][idx]
input_array.name = name
input_array.shape.dims.extend(list(map(int, shape)))
for name in output_arrays:
model_flags.output_arrays.append(name)
data = toco_convert_protos(
model_flags.SerializeToString(),
toco_flags.SerializeToString(),
input_data.SerializeToString(),
enable_mlir_converter=enable_mlir_converter)
return data
def toco_convert_impl(input_data, input_tensors, output_tensors,
enable_mlir_converter, *args, **kwargs):
model_flags, toco_flags, debug_info = build_toco_convert_protos(
input_tensors, output_tensors, *args, **kwargs)
debug_info_str = debug_info.SerializeToString() if debug_info else None
data = toco_convert_protos(
model_flags.SerializeToString(),
toco_flags.SerializeToString(),
input_data.SerializeToString(),
debug_info_str=debug_info_str,
enable_mlir_converter=enable_mlir_converter)
return data
@_tf_export(v1=["lite.toco_convert"])
@deprecation.deprecated(None, "Use `lite.TFLiteConverter` instead.")
def toco_convert(input_data, input_tensors, output_tensors, *args, **kwargs):
enable_mlir_converter = kwargs.get("enable_mlir_converter", False)
return toco_convert_impl(input_data, input_tensors, output_tensors,
enable_mlir_converter, *args, **kwargs)
| true | true |
f719f728d45f799dab957ca3faa6158730bf0f3b | 1,609 | py | Python | BDSP-Scripts/utils/pokeTwilio.py | leecbryant/BDSP-PythonBot | db77b08e023ce3942cfff3c6d3e9a32f0d63f3dc | [
"MIT"
] | 4 | 2022-03-28T21:00:00.000Z | 2022-03-29T00:03:20.000Z | BDSP-Scripts/utils/pokeTwilio.py | leecbryant/BDSP-PythonBot | db77b08e023ce3942cfff3c6d3e9a32f0d63f3dc | [
"MIT"
] | null | null | null | BDSP-Scripts/utils/pokeTwilio.py | leecbryant/BDSP-PythonBot | db77b08e023ce3942cfff3c6d3e9a32f0d63f3dc | [
"MIT"
] | 1 | 2022-03-30T05:12:46.000Z | 2022-03-30T05:12:46.000Z | import os
from twilio.rest import Client
#import twilioConfig from one folder up and inside Config_Files folder
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
try:
from Config_Files import twilioConfig
except ImportError:
from Config_Files import twilioConfig_default as twilioConfig
# This file holds a function to call a player with a statement. In this case, finding a shiny.
#
# Setup:
# Create a config.py folder that includes the following varibles:
# to_phone_number = 'your number'
# from_phone_number = 'Twilio number'
# account_sid = 'from Twilio'
# auth_token = 'from Twilio'
def found_shiny_text(found_pokemon = '', to_num = twilioConfig.to_phone_number, from_num = twilioConfig.from_phone_number):
# This function calls a user and says the message "You Found a Shiny!". Usage: found_shiny_call(to_num, from_num). Num format: Country Code + Area Code + Number (example: '+12223333333')
try:
sentence = 'You Found a Shiny ' + found_pokemon
formatted = '<Response><Say>' + sentence + '</Say></Response>'
account_sid = twilioConfig.account_sid
auth_token = twilioConfig.auth_token
client = Client(account_sid, auth_token)
message = client.messages.create(
body=sentence,
from_=from_num,
to=to_num)
# client.calls.create(twiml=formatted, to = to_num, from_ = from_num)
print("Texting Phone Number: "+str(to_num))
except:
print("Twilio is not configured properly. Please check your twilioConfig_default.py file.") | 43.486486 | 190 | 0.709136 | import os
from twilio.rest import Client
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
try:
from Config_Files import twilioConfig
except ImportError:
from Config_Files import twilioConfig_default as twilioConfig
def found_shiny_text(found_pokemon = '', to_num = twilioConfig.to_phone_number, from_num = twilioConfig.from_phone_number):
try:
sentence = 'You Found a Shiny ' + found_pokemon
formatted = '<Response><Say>' + sentence + '</Say></Response>'
account_sid = twilioConfig.account_sid
auth_token = twilioConfig.auth_token
client = Client(account_sid, auth_token)
message = client.messages.create(
body=sentence,
from_=from_num,
to=to_num)
print("Texting Phone Number: "+str(to_num))
except:
print("Twilio is not configured properly. Please check your twilioConfig_default.py file.") | true | true |
f719f928dccc27ae9f21364a24c6d3cb460a18a2 | 9,079 | py | Python | stacker/tests/test_plan.py | GoodRx/stacker | 0cf1df67b4ae5aeda5845442c84905909101c238 | [
"BSD-2-Clause"
] | 1 | 2021-11-06T17:01:01.000Z | 2021-11-06T17:01:01.000Z | stacker/tests/test_plan.py | GoodRx/stacker | 0cf1df67b4ae5aeda5845442c84905909101c238 | [
"BSD-2-Clause"
] | null | null | null | stacker/tests/test_plan.py | GoodRx/stacker | 0cf1df67b4ae5aeda5845442c84905909101c238 | [
"BSD-2-Clause"
] | 1 | 2021-11-06T17:00:53.000Z | 2021-11-06T17:00:53.000Z | import unittest
import mock
from stacker.context import Context
from stacker.exceptions import ImproperlyConfigured
from stacker.plan import (
Step,
Plan,
)
from stacker.status import (
COMPLETE,
SKIPPED,
SUBMITTED,
)
from stacker.stack import Stack
from .factories import generate_definition
count = 0
class TestStep(unittest.TestCase):
def setUp(self):
self.context = Context({"namespace": "namespace"})
stack = Stack(
definition=generate_definition("vpc", 1),
context=self.context,
)
self.step = Step(
stack=stack,
run_func=lambda x, y: (x, y),
)
def test_status(self):
self.assertFalse(self.step.submitted)
self.assertFalse(self.step.completed)
self.step.submit()
self.assertTrue(self.step.submitted)
self.assertFalse(self.step.completed)
self.step.complete()
self.assertTrue(self.step.submitted)
self.assertTrue(self.step.completed)
class TestPlan(unittest.TestCase):
def setUp(self):
self.count = 0
self.environment = {"namespace": "namespace"}
self.context = Context(self.environment)
def _run_func(self, stack, **kwargs):
self.count += 1
if not self.count % 2:
return COMPLETE
elif self.count == 9:
return SKIPPED
return SUBMITTED
def test_execute_plan(self):
plan = Plan(description="Test", sleep_time=0)
previous_stack = None
for i in range(5):
overrides = {}
if previous_stack:
overrides["requires"] = [previous_stack.fqn]
stack = Stack(
definition=generate_definition("vpc", i, **overrides),
context=self.context,
)
previous_stack = stack
plan.add(
stack=stack,
run_func=self._run_func,
requires=stack.requires,
)
plan.execute()
self.assertEqual(self.count, 9)
self.assertEqual(len(plan.list_skipped()), 1)
@mock.patch("stacker.plan.multiprocessing")
def test_execute_plan_with_watchers(self, patched_multiprocessing):
watch_func = mock.MagicMock()
plan = Plan(description="Test", sleep_time=0, watch_func=watch_func)
previous_stack = None
for i in range(5):
overrides = {}
if previous_stack:
overrides["requires"] = [previous_stack.fqn]
stack = Stack(
definition=generate_definition("vpc", i, **overrides),
context=self.context,
)
previous_stack = stack
plan.add(
stack=stack,
run_func=self._run_func,
requires=stack.requires,
)
plan.execute()
self.assertEqual(self.count, 9)
self.assertEqual(len(plan.list_skipped()), 1)
self.assertEqual(patched_multiprocessing.Process().start.call_count, 5)
# verify we terminate the process when the stack is finished and also
# redundantly terminate the process after execution
self.assertEqual(
patched_multiprocessing.Process().terminate.call_count, 10)
def test_step_must_return_status(self):
plan = Plan(description="Test", sleep_time=0)
stack = Stack(definition=generate_definition("vpc", 1),
context=mock.MagicMock())
plan.add(
stack=stack,
run_func=lambda x, **kwargs: (x),
)
with self.assertRaises(ValueError):
plan.execute()
def test_execute_plan_ensure_parallel_builds(self):
# key: stack_name, value: current iteration
work_states = {}
submitted_state = 0
# It takes 4 iterations for each task to finish
finished_state = 3
def _run_func(stack, *args, **kwargs):
if stack.name not in work_states:
work_states[stack.name] = submitted_state
return SUBMITTED
if work_states[stack.name] == finished_state:
return COMPLETE
work_states[stack.name] += 1
return SUBMITTED
vpc_stack = Stack(definition=generate_definition("vpc", 1),
context=self.context)
web_stack = Stack(
definition=generate_definition("web", 2, requires=[vpc_stack.fqn]),
context=self.context,
)
db_stack = Stack(
definition=generate_definition("db", 3, requires=[vpc_stack.fqn]),
context=self.context,
)
plan = Plan(description="Test", sleep_time=0)
for stack in [vpc_stack, web_stack, db_stack]:
plan.add(
stack=stack,
run_func=_run_func,
requires=stack.requires,
)
parallel_success = False
while not plan._single_run():
vpc_step = plan[vpc_stack.fqn]
web_step = plan[web_stack.fqn]
db_step = plan[db_stack.fqn]
if not vpc_step.completed:
self.assertFalse(web_step.submitted)
self.assertFalse(db_step.submitted)
else:
# If the vpc step is complete, and we see both the web & db
# steps submitted during the same run, then parallel running
# works
if web_step.status == SUBMITTED and \
db_step.status == SUBMITTED:
parallel_success = True
self.assertTrue(parallel_success)
def test_plan_wait_func_must_be_function(self):
with self.assertRaises(ImproperlyConfigured):
Plan(description="Test", wait_func="invalid")
def test_plan_steps_listed_with_fqn(self):
plan = Plan(description="Test", sleep_time=0)
stack = Stack(definition=generate_definition("vpc", 1),
context=self.context)
plan.add(stack=stack, run_func=lambda x, y: (x, y))
steps = plan.list_pending()
self.assertEqual(steps[0][0], stack.fqn)
def test_execute_plan_wait_func_not_called_if_complete(self):
wait_func = mock.MagicMock()
plan = Plan(description="Test", wait_func=wait_func)
def run_func(*args, **kwargs):
return COMPLETE
for i in range(2):
stack = Stack(definition=generate_definition("vpc", i),
context=self.context)
plan.add(
stack=stack,
run_func=run_func,
requires=stack.requires,
)
plan.execute()
self.assertEqual(wait_func.call_count, 0)
def test_reset_plan(self):
plan = Plan(description="Test", sleep_time=0)
previous_stack = None
for i in range(5):
overrides = {}
if previous_stack:
overrides["requires"] = [previous_stack.fqn]
stack = Stack(
definition=generate_definition("vpc", i, **overrides),
context=self.context,
)
previous_stack = stack
plan.add(
stack=stack,
run_func=self._run_func,
requires=stack.requires,
)
plan.execute()
self.assertEqual(self.count, 9)
self.assertEqual(len(plan.list_skipped()), 1)
plan.reset()
self.assertEqual(len(plan.list_pending()), len(plan))
def test_reset_after_outline(self):
plan = Plan(description="Test", sleep_time=0)
previous_stack = None
for i in range(5):
overrides = {}
if previous_stack:
overrides["requires"] = [previous_stack.fqn]
stack = Stack(
definition=generate_definition("vpc", i, **overrides),
context=self.context,
)
previous_stack = stack
plan.add(
stack=stack,
run_func=self._run_func,
requires=stack.requires,
)
plan.outline()
self.assertEqual(len(plan.list_pending()), len(plan))
@mock.patch("stacker.plan.os")
@mock.patch("stacker.plan.open", mock.mock_open(), create=True)
def test_reset_after_dump(self, *args):
plan = Plan(description="Test", sleep_time=0)
previous_stack = None
for i in range(5):
overrides = {}
if previous_stack:
overrides["requires"] = [previous_stack.fqn]
stack = Stack(
definition=generate_definition("vpc", i, **overrides),
context=self.context,
)
previous_stack = stack
plan.add(
stack=stack,
run_func=self._run_func,
requires=stack.requires,
)
plan.dump("test")
self.assertEqual(len(plan.list_pending()), len(plan))
| 32.894928 | 79 | 0.566142 | import unittest
import mock
from stacker.context import Context
from stacker.exceptions import ImproperlyConfigured
from stacker.plan import (
Step,
Plan,
)
from stacker.status import (
COMPLETE,
SKIPPED,
SUBMITTED,
)
from stacker.stack import Stack
from .factories import generate_definition
count = 0
class TestStep(unittest.TestCase):
def setUp(self):
self.context = Context({"namespace": "namespace"})
stack = Stack(
definition=generate_definition("vpc", 1),
context=self.context,
)
self.step = Step(
stack=stack,
run_func=lambda x, y: (x, y),
)
def test_status(self):
self.assertFalse(self.step.submitted)
self.assertFalse(self.step.completed)
self.step.submit()
self.assertTrue(self.step.submitted)
self.assertFalse(self.step.completed)
self.step.complete()
self.assertTrue(self.step.submitted)
self.assertTrue(self.step.completed)
class TestPlan(unittest.TestCase):
def setUp(self):
self.count = 0
self.environment = {"namespace": "namespace"}
self.context = Context(self.environment)
def _run_func(self, stack, **kwargs):
self.count += 1
if not self.count % 2:
return COMPLETE
elif self.count == 9:
return SKIPPED
return SUBMITTED
def test_execute_plan(self):
plan = Plan(description="Test", sleep_time=0)
previous_stack = None
for i in range(5):
overrides = {}
if previous_stack:
overrides["requires"] = [previous_stack.fqn]
stack = Stack(
definition=generate_definition("vpc", i, **overrides),
context=self.context,
)
previous_stack = stack
plan.add(
stack=stack,
run_func=self._run_func,
requires=stack.requires,
)
plan.execute()
self.assertEqual(self.count, 9)
self.assertEqual(len(plan.list_skipped()), 1)
@mock.patch("stacker.plan.multiprocessing")
def test_execute_plan_with_watchers(self, patched_multiprocessing):
watch_func = mock.MagicMock()
plan = Plan(description="Test", sleep_time=0, watch_func=watch_func)
previous_stack = None
for i in range(5):
overrides = {}
if previous_stack:
overrides["requires"] = [previous_stack.fqn]
stack = Stack(
definition=generate_definition("vpc", i, **overrides),
context=self.context,
)
previous_stack = stack
plan.add(
stack=stack,
run_func=self._run_func,
requires=stack.requires,
)
plan.execute()
self.assertEqual(self.count, 9)
self.assertEqual(len(plan.list_skipped()), 1)
self.assertEqual(patched_multiprocessing.Process().start.call_count, 5)
self.assertEqual(
patched_multiprocessing.Process().terminate.call_count, 10)
def test_step_must_return_status(self):
plan = Plan(description="Test", sleep_time=0)
stack = Stack(definition=generate_definition("vpc", 1),
context=mock.MagicMock())
plan.add(
stack=stack,
run_func=lambda x, **kwargs: (x),
)
with self.assertRaises(ValueError):
plan.execute()
def test_execute_plan_ensure_parallel_builds(self):
work_states = {}
submitted_state = 0
finished_state = 3
def _run_func(stack, *args, **kwargs):
if stack.name not in work_states:
work_states[stack.name] = submitted_state
return SUBMITTED
if work_states[stack.name] == finished_state:
return COMPLETE
work_states[stack.name] += 1
return SUBMITTED
vpc_stack = Stack(definition=generate_definition("vpc", 1),
context=self.context)
web_stack = Stack(
definition=generate_definition("web", 2, requires=[vpc_stack.fqn]),
context=self.context,
)
db_stack = Stack(
definition=generate_definition("db", 3, requires=[vpc_stack.fqn]),
context=self.context,
)
plan = Plan(description="Test", sleep_time=0)
for stack in [vpc_stack, web_stack, db_stack]:
plan.add(
stack=stack,
run_func=_run_func,
requires=stack.requires,
)
parallel_success = False
while not plan._single_run():
vpc_step = plan[vpc_stack.fqn]
web_step = plan[web_stack.fqn]
db_step = plan[db_stack.fqn]
if not vpc_step.completed:
self.assertFalse(web_step.submitted)
self.assertFalse(db_step.submitted)
else:
if web_step.status == SUBMITTED and \
db_step.status == SUBMITTED:
parallel_success = True
self.assertTrue(parallel_success)
def test_plan_wait_func_must_be_function(self):
with self.assertRaises(ImproperlyConfigured):
Plan(description="Test", wait_func="invalid")
def test_plan_steps_listed_with_fqn(self):
plan = Plan(description="Test", sleep_time=0)
stack = Stack(definition=generate_definition("vpc", 1),
context=self.context)
plan.add(stack=stack, run_func=lambda x, y: (x, y))
steps = plan.list_pending()
self.assertEqual(steps[0][0], stack.fqn)
def test_execute_plan_wait_func_not_called_if_complete(self):
wait_func = mock.MagicMock()
plan = Plan(description="Test", wait_func=wait_func)
def run_func(*args, **kwargs):
return COMPLETE
for i in range(2):
stack = Stack(definition=generate_definition("vpc", i),
context=self.context)
plan.add(
stack=stack,
run_func=run_func,
requires=stack.requires,
)
plan.execute()
self.assertEqual(wait_func.call_count, 0)
def test_reset_plan(self):
plan = Plan(description="Test", sleep_time=0)
previous_stack = None
for i in range(5):
overrides = {}
if previous_stack:
overrides["requires"] = [previous_stack.fqn]
stack = Stack(
definition=generate_definition("vpc", i, **overrides),
context=self.context,
)
previous_stack = stack
plan.add(
stack=stack,
run_func=self._run_func,
requires=stack.requires,
)
plan.execute()
self.assertEqual(self.count, 9)
self.assertEqual(len(plan.list_skipped()), 1)
plan.reset()
self.assertEqual(len(plan.list_pending()), len(plan))
def test_reset_after_outline(self):
plan = Plan(description="Test", sleep_time=0)
previous_stack = None
for i in range(5):
overrides = {}
if previous_stack:
overrides["requires"] = [previous_stack.fqn]
stack = Stack(
definition=generate_definition("vpc", i, **overrides),
context=self.context,
)
previous_stack = stack
plan.add(
stack=stack,
run_func=self._run_func,
requires=stack.requires,
)
plan.outline()
self.assertEqual(len(plan.list_pending()), len(plan))
@mock.patch("stacker.plan.os")
@mock.patch("stacker.plan.open", mock.mock_open(), create=True)
def test_reset_after_dump(self, *args):
plan = Plan(description="Test", sleep_time=0)
previous_stack = None
for i in range(5):
overrides = {}
if previous_stack:
overrides["requires"] = [previous_stack.fqn]
stack = Stack(
definition=generate_definition("vpc", i, **overrides),
context=self.context,
)
previous_stack = stack
plan.add(
stack=stack,
run_func=self._run_func,
requires=stack.requires,
)
plan.dump("test")
self.assertEqual(len(plan.list_pending()), len(plan))
| true | true |
f719f96e68fd7b17d73ed6b9460ebade8987ebf6 | 4,908 | py | Python | parseepo/serialize.py | cverluise/parseEPO | be1171a0f8e6fcafa711fa291aebb1fc2260d5e6 | [
"MIT"
] | null | null | null | parseepo/serialize.py | cverluise/parseEPO | be1171a0f8e6fcafa711fa291aebb1fc2260d5e6 | [
"MIT"
] | 3 | 2021-02-02T22:38:50.000Z | 2021-08-23T20:41:10.000Z | parseepo/serialize.py | cverluise/parseEPO | be1171a0f8e6fcafa711fa291aebb1fc2260d5e6 | [
"MIT"
] | null | null | null | import html2text
import pandas as pd
from wasabi import Printer
from parseepo import validate
from parseepo.exception import SingleAttrException
from parseepo.utils import prepare_name
h = html2text.HTML2Text()
msg = Printer()
NAMES = ["EP", "Num", "Ext", "publication_date", "language", "attr", "text"]
NESTED_ATTR = ["TITLE", "CLAIM", "AMEND", "title", "claims", "amendment"]
def format_patent_df(
data: list, prepare_names: bool = False, handle_html: bool = False
):
"""
Return data as a prepared DataFrame from a list of rows
Nb: Input is [publication_number[Row]].
E.g. [['EP','0700059 A1','1996-03-06','de','TITLE',' Elektroma...'],
['EP','0700059 A1','1996-03-06','en','TITLE',' Electroma...'],
...
:param data: List[List]
:param prepare_names: bool, True if you want to prepare names for BQ compatibility
:param handle_html: bool, True if you want to handle html
:return: pd.DataFrame
publication_date language attr text publication_number
0 1996-03-06 ... ... ... EP-0700059-A1
1 1996-03-06 ... ... ... EP-0700059-A1
2 1996-03-06 ... ... ... EP-0700059-A1
3 1996-03-06 ... ... ... EP-0700059-A1
4 1996-03-06 ... ... ... EP-0700059-A1
5 1996-03-06 ... ... ... EP-0700059-A1
6 1996-03-06 ... ... ... EP-0700059-A1
"""
df_ = pd.DataFrame(data, columns=NAMES)
df_["publication_number"] = df_["EP"] + "-" + df_["Num"] + "-" + df_["Ext"]
df_ = df_.drop(["EP", "Num", "Ext"], axis=1)
if prepare_names:
df_["attr"] = df_["attr"].apply(lambda x: prepare_name(x, True))
if handle_html:
df_["text"] = df_["text"].apply(lambda x: h.handle(x))
return df_
def unnest_attr(patent_dict: dict, publication_number: str):
"""
Unnest flat attributes returned as nested by the batch aggregation operation in
serialize_patent.
Raises warning if expected flat attributes has multiple values.
:param patent_dict: dict, returned by serialize_patent
:param publication_number: str, e.g. 'EP-0600083-A1'
:return: dict
In:
{ ...,
'PDFEP': {'language': ['en'],
'text': ['https://data.epo.org/publication-server/...']},
}
Out:
{...,
'PDFEP': 'https://data.epo.org/publication-server/...',}
"""
attrs = list(filter(lambda x: x not in NESTED_ATTR, patent_dict.keys()))
for attr in attrs:
val = patent_dict[attr]["text"]
try:
validate.single_attr(val, attr, publication_number)
except SingleAttrException:
msg.warn(
f"{publication_number}: {attr} has more than 1 value. Only the first value "
f"was kept. Add {attr} to the list NESTED_ATTR to fix this behavior."
)
patent_dict.update(
{
attr: {
"text": patent_dict[attr]["text"][0],
"language": patent_dict[attr]["language"][0],
}
}
)
def serialize_patent_df(patent_df: pd.DataFrame):
"""
Return the serialized patent
:param patent_df: pd.DataFrame, returned by format_patent_df
:return: dict
{'ABSTR': '<p id="pa01" num="0001">A device ...',
'CLAIM': {'language': ['en'],
'text': ['<claim id="c-en-0001" ...']},
'DESCR': '<heading id="h0001">Field of ...',
'PDFEP': 'https://data.epo.org/publication-server/...',
'TITLE': {'language': ['de', 'en', 'fr'],
'text': ['VORRICHTUNG ZUM ...',
'DEVICE FOR CONVEYING ...',
"DISPOSITIF D'ACHEMINEMENT ...']},
'publication_date': '1994-06-08',
'publication_number': 'EP-0600083-A1'}
"""
publication_number = patent_df["publication_number"].values[0]
publication_date = patent_df["publication_date"].values[0]
out = (
patent_df.drop(["publication_number", "publication_date"], axis=1)
.groupby("attr")
.aggregate(list)
.T.to_dict()
)
unnest_attr(out, publication_number)
out.update({"publication_number": publication_number})
out.update({"publication_date": publication_date})
return out
def serialize_patent(
data: list, prepare_names: bool = False, handle_html: bool = False
):
"""
Return the serialized patent
:param data: List[List[str]], E.g.
[['EP','0700059 A1','1996-03-06','de','TITLE',' Elektroma...'],
['EP','0700059 A1','1996-03-06','en','TITLE',' Electroma...'],
:param prepare_names: bool, True if you want to prepare names for BQ compatibility
:param handle_html: bool, True if you want to handle html
:return: dict
"""
out = format_patent_df(data, prepare_names, handle_html)
out = serialize_patent_df(out)
return out
| 36.355556 | 92 | 0.581296 | import html2text
import pandas as pd
from wasabi import Printer
from parseepo import validate
from parseepo.exception import SingleAttrException
from parseepo.utils import prepare_name
h = html2text.HTML2Text()
msg = Printer()
NAMES = ["EP", "Num", "Ext", "publication_date", "language", "attr", "text"]
NESTED_ATTR = ["TITLE", "CLAIM", "AMEND", "title", "claims", "amendment"]
def format_patent_df(
data: list, prepare_names: bool = False, handle_html: bool = False
):
df_ = pd.DataFrame(data, columns=NAMES)
df_["publication_number"] = df_["EP"] + "-" + df_["Num"] + "-" + df_["Ext"]
df_ = df_.drop(["EP", "Num", "Ext"], axis=1)
if prepare_names:
df_["attr"] = df_["attr"].apply(lambda x: prepare_name(x, True))
if handle_html:
df_["text"] = df_["text"].apply(lambda x: h.handle(x))
return df_
def unnest_attr(patent_dict: dict, publication_number: str):
attrs = list(filter(lambda x: x not in NESTED_ATTR, patent_dict.keys()))
for attr in attrs:
val = patent_dict[attr]["text"]
try:
validate.single_attr(val, attr, publication_number)
except SingleAttrException:
msg.warn(
f"{publication_number}: {attr} has more than 1 value. Only the first value "
f"was kept. Add {attr} to the list NESTED_ATTR to fix this behavior."
)
patent_dict.update(
{
attr: {
"text": patent_dict[attr]["text"][0],
"language": patent_dict[attr]["language"][0],
}
}
)
def serialize_patent_df(patent_df: pd.DataFrame):
publication_number = patent_df["publication_number"].values[0]
publication_date = patent_df["publication_date"].values[0]
out = (
patent_df.drop(["publication_number", "publication_date"], axis=1)
.groupby("attr")
.aggregate(list)
.T.to_dict()
)
unnest_attr(out, publication_number)
out.update({"publication_number": publication_number})
out.update({"publication_date": publication_date})
return out
def serialize_patent(
data: list, prepare_names: bool = False, handle_html: bool = False
):
out = format_patent_df(data, prepare_names, handle_html)
out = serialize_patent_df(out)
return out
| true | true |
f719fb0a5fa90c220d27a523e8d540e39d655557 | 5,183 | py | Python | pyampd/ampd.py | luigiluz/pyampd | cd247030f5a4ccd971da837b9b873cacbd7adfb3 | [
"MIT"
] | 25 | 2019-04-13T06:39:33.000Z | 2022-03-11T22:38:46.000Z | pyampd/ampd.py | luigiluz/pyampd | cd247030f5a4ccd971da837b9b873cacbd7adfb3 | [
"MIT"
] | 5 | 2018-12-05T10:07:20.000Z | 2021-02-17T09:08:10.000Z | pyampd/ampd.py | luigiluz/pyampd | cd247030f5a4ccd971da837b9b873cacbd7adfb3 | [
"MIT"
] | 5 | 2020-10-18T12:42:14.000Z | 2021-07-01T05:32:50.000Z | import numpy as np
from scipy.ndimage import uniform_filter1d
from scipy.signal import detrend
def find_peaks_original(x, scale=None, debug=False):
"""Find peaks in quasi-periodic noisy signals using AMPD algorithm.
Automatic Multi-Scale Peak Detection originally proposed in
"An Efficient Algorithm for Automatic Peak Detection in
Noisy Periodic and Quasi-Periodic Signals", Algorithms 2012, 5, 588-603
https://doi.org/10.1109/ICRERA.2016.7884365
Optimized implementation by Igor Gotlibovych, 2018
Parameters
----------
x : ndarray
1-D array on which to find peaks
scale : int, optional
specify maximum scale window size of (2 * scale + 1)
debug : bool, optional
if set to True, return the Local Scalogram Matrix, `LSM`,
and scale with most local maxima, `l`,
together with peak locations
Returns
-------
pks: ndarray
The ordered array of peak indices found in `x`
"""
x = detrend(x)
N = len(x)
L = N // 2
if scale:
L = min(scale, L)
# create LSM matix
LSM = np.zeros((L, N), dtype=bool)
for k in np.arange(1, L):
LSM[k - 1, k:N - k] = (
(x[0:N - 2 * k] < x[k:N - k]) & (x[k:N - k] > x[2 * k:N])
)
# Find scale with most maxima
G = LSM.sum(axis=1)
l_scale = np.argmax(G)
# find peaks that persist on all scales up to l
pks_logical = np.min(LSM[0:l_scale, :], axis=0)
pks = np.flatnonzero(pks_logical)
if debug:
return pks, LSM, l_scale
return pks
def find_peaks(x, scale=None, debug=False):
"""Find peaks in quasi-periodic noisy signals using AMPD algorithm.
Extended implementation handles peaks near start/end of the signal.
Optimized implementation by Igor Gotlibovych, 2018
Parameters
----------
x : ndarray
1-D array on which to find peaks
scale : int, optional
specify maximum scale window size of (2 * scale + 1)
debug : bool, optional
if set to True, return the Local Scalogram Matrix, `LSM`,
weigted number of maxima, 'G',
and scale at which G is maximized, `l`,
together with peak locations
Returns
-------
pks: ndarray
The ordered array of peak indices found in `x`
"""
x = detrend(x)
N = len(x)
L = N // 2
if scale:
L = min(scale, L)
# create LSM matix
LSM = np.ones((L, N), dtype=bool)
for k in np.arange(1, L + 1):
LSM[k - 1, 0:N - k] &= (x[0:N - k] > x[k:N]
) # compare to right neighbours
LSM[k - 1, k:N] &= (x[k:N] > x[0:N - k]) # compare to left neighbours
# Find scale with most maxima
G = LSM.sum(axis=1)
G = G * np.arange(
N // 2, N // 2 - L, -1
) # normalize to adjust for new edge regions
l_scale = np.argmax(G)
# find peaks that persist on all scales up to l
pks_logical = np.min(LSM[0:l_scale, :], axis=0)
pks = np.flatnonzero(pks_logical)
if debug:
return pks, LSM, G, l_scale
return pks
def find_peaks_adaptive(x, window=None, debug=False):
"""Find peaks in quasi-periodic noisy signals using ASS-AMPD algorithm.
Adaptive Scale Selection Automatic Multi-Scale Peak Detection,
an extension of AMPD -
"An Efficient Algorithm for Automatic Peak Detection in
Noisy Periodic and Quasi-Periodic Signals", Algorithms 2012, 5, 588-603
https://doi.org/10.1109/ICRERA.2016.7884365
Optimized implementation by Igor Gotlibovych, 2018
Parameters
----------
x : ndarray
1-D array on which to find peaks
window : int, optional
sliding window size for adaptive scale selection
debug : bool, optional
if set to True, return the Local Scalogram Matrix, `LSM`,
and `adaptive_scale`,
together with peak locations
Returns
-------
pks: ndarray
The ordered array of peak indices found in `x`
"""
x = detrend(x)
N = len(x)
if not window:
window = N
if window > N:
window = N
L = window // 2
# create LSM matix
LSM = np.ones((L, N), dtype=bool)
for k in np.arange(1, L + 1):
LSM[k - 1, 0:N - k] &= (x[0:N - k] > x[k:N]
) # compare to right neighbours
LSM[k - 1, k:N] &= (x[k:N] > x[0:N - k]) # compare to left neighbours
# Create continuos adaptive LSM
ass_LSM = uniform_filter1d(LSM * window, window, axis=1, mode='nearest')
normalization = np.arange(L, 0, -1) # scale normalization weight
ass_LSM = ass_LSM * normalization.reshape(-1, 1)
# Find adaptive scale at each point
adaptive_scale = ass_LSM.argmax(axis=0)
# construct reduced LSM
LSM_reduced = LSM[:adaptive_scale.max(), :]
mask = (np.indices(LSM_reduced.shape)[0] > adaptive_scale
) # these elements are outside scale of interest
LSM_reduced[mask] = 1
# find peaks that persist on all scales up to l
pks_logical = np.min(LSM_reduced, axis=0)
pks = np.flatnonzero(pks_logical)
if debug:
return pks, ass_LSM, adaptive_scale
return pks
| 29.282486 | 78 | 0.605248 | import numpy as np
from scipy.ndimage import uniform_filter1d
from scipy.signal import detrend
def find_peaks_original(x, scale=None, debug=False):
x = detrend(x)
N = len(x)
L = N // 2
if scale:
L = min(scale, L)
LSM = np.zeros((L, N), dtype=bool)
for k in np.arange(1, L):
LSM[k - 1, k:N - k] = (
(x[0:N - 2 * k] < x[k:N - k]) & (x[k:N - k] > x[2 * k:N])
)
G = LSM.sum(axis=1)
l_scale = np.argmax(G)
pks_logical = np.min(LSM[0:l_scale, :], axis=0)
pks = np.flatnonzero(pks_logical)
if debug:
return pks, LSM, l_scale
return pks
def find_peaks(x, scale=None, debug=False):
x = detrend(x)
N = len(x)
L = N // 2
if scale:
L = min(scale, L)
LSM = np.ones((L, N), dtype=bool)
for k in np.arange(1, L + 1):
LSM[k - 1, 0:N - k] &= (x[0:N - k] > x[k:N]
)
LSM[k - 1, k:N] &= (x[k:N] > x[0:N - k])
G = LSM.sum(axis=1)
G = G * np.arange(
N // 2, N // 2 - L, -1
)
l_scale = np.argmax(G)
pks_logical = np.min(LSM[0:l_scale, :], axis=0)
pks = np.flatnonzero(pks_logical)
if debug:
return pks, LSM, G, l_scale
return pks
def find_peaks_adaptive(x, window=None, debug=False):
x = detrend(x)
N = len(x)
if not window:
window = N
if window > N:
window = N
L = window // 2
LSM = np.ones((L, N), dtype=bool)
for k in np.arange(1, L + 1):
LSM[k - 1, 0:N - k] &= (x[0:N - k] > x[k:N]
)
LSM[k - 1, k:N] &= (x[k:N] > x[0:N - k])
ass_LSM = uniform_filter1d(LSM * window, window, axis=1, mode='nearest')
normalization = np.arange(L, 0, -1)
ass_LSM = ass_LSM * normalization.reshape(-1, 1)
adaptive_scale = ass_LSM.argmax(axis=0)
LSM_reduced = LSM[:adaptive_scale.max(), :]
mask = (np.indices(LSM_reduced.shape)[0] > adaptive_scale
)
LSM_reduced[mask] = 1
pks_logical = np.min(LSM_reduced, axis=0)
pks = np.flatnonzero(pks_logical)
if debug:
return pks, ass_LSM, adaptive_scale
return pks
| true | true |
f719fc3ddd0729538402b3d0087f650db4bf9a87 | 3,272 | py | Python | extract_features.py | bionlplab/heart_failure_mortality | f3bbfe65fe6f2c2a076acb38697133b472bf2231 | [
"BSD-3-Clause"
] | 4 | 2021-06-06T17:50:44.000Z | 2021-12-27T11:45:34.000Z | extract_features.py | bionlplab/heart_failure_mortality | f3bbfe65fe6f2c2a076acb38697133b472bf2231 | [
"BSD-3-Clause"
] | 1 | 2021-11-28T00:39:50.000Z | 2021-12-08T13:58:56.000Z | extract_features.py | bionlplab/heart_failure_mortality | f3bbfe65fe6f2c2a076acb38697133b472bf2231 | [
"BSD-3-Clause"
] | null | null | null | import pandas as pd
import numpy as np
from utils import *
from sklearn.preprocessing import StandardScaler
from collections import defaultdict
import re
def format_labels(file_path, timelines, mapping):
most_recent = mapping.sort_values(["subject_id", "ordering_date"], ascending=False).drop_duplicates("subject_id", keep="first")
label_features = pd.read_csv(file_path)
formatted_features = reformat4pycox(["report_id"], label_features)
#Connect subject to report
data_frames = [timelines, most_recent]
data_df = reduce(lambda left,right: pd.merge(left,right,on="subject_id"), data_frames)
#Connect report to labels
data_frames = [data_df, formatted_features]
data_df = reduce(lambda left,right: pd.merge(left,right,on="report_id"), data_frames)
for i in ["ordering_date", "report_id"]:
del data_df[i]
return data_df
def format_hidden_features(file_path, timelines, mapping):
loaded = np.load(file_path)
most_recent = mapping.sort_values(["subject_id", "ordering_date"], ascending=False).drop_duplicates("subject_id", keep="first")
report_ids = list(most_recent['report_id'])
mutable_file = {}
for id in report_ids:
mutable_file[id] = loaded[id].flatten()
loaded = mutable_file
label_features = pd.DataFrame(loaded.values(), index=loaded)
cols = list(label_features.columns)
xcols = ["x" + str(i) for i in cols]
rename_dict = dict(zip(cols,xcols))
rename_dict["index"] = "report_id"
label_features = label_features.reset_index().rename(columns=rename_dict)
#Connect subject to report
data_frames = [timelines, most_recent]
data_df = reduce(lambda left,right: pd.merge(left,right,on="subject_id"), data_frames)
#Connect report to labels
data_frames = [data_df, label_features]
data_df = reduce(lambda left,right: pd.merge(left,right,on="report_id"), data_frames)
for i in ["ordering_date", "report_id"]:
del data_df[i]
return data_df
def format_hf_sequence(file_path, timelines, mapping):
loaded = np.load(file_path)
top3_reports = mapping.sort_values(["subject_id", "ordering_date"], ascending=True).groupby("subject_id").tail(3)
#Create a list of report ids
report_dict = top3_reports.groupby("subject_id")["report_id"].apply(list).to_dict()
#Create a dict of report arrays. Format: key: array of report embeddings
embedding_dict = defaultdict(list)
for k,v in report_dict.items():
for vi in v:
embedding_dict[k].append(loaded[vi])
embedding_dict[k] = np.vstack(embedding_dict[k])
#Converting embedding dict into dataframe
label_features = pd.DataFrame(embedding_dict.values(), index=embedding_dict)
label_features[0] = label_features[0].apply(lambda x: add_paddings(x))
list2d = label_features[0]
merged = list(itertools.chain(*list2d))
scaler = StandardScaler()
scaler.fit(merged)
label_features[0] = label_features[0].apply(lambda x: scaler.transform(x))
cols = list(label_features.columns)
xcols = ["x" + str(i) for i in cols]
rename_dict = dict(zip(cols,xcols))
label_features = label_features.rename(columns=rename_dict)
label_features = label_features.reset_index().rename(columns={"index": "subject_id"})
data_frames = [timelines, label_features]
data_df = reduce(lambda left,right: pd.merge(left,right,on="subject_id"), data_frames)
return data_df
| 32.078431 | 128 | 0.755501 | import pandas as pd
import numpy as np
from utils import *
from sklearn.preprocessing import StandardScaler
from collections import defaultdict
import re
def format_labels(file_path, timelines, mapping):
most_recent = mapping.sort_values(["subject_id", "ordering_date"], ascending=False).drop_duplicates("subject_id", keep="first")
label_features = pd.read_csv(file_path)
formatted_features = reformat4pycox(["report_id"], label_features)
data_frames = [timelines, most_recent]
data_df = reduce(lambda left,right: pd.merge(left,right,on="subject_id"), data_frames)
data_frames = [data_df, formatted_features]
data_df = reduce(lambda left,right: pd.merge(left,right,on="report_id"), data_frames)
for i in ["ordering_date", "report_id"]:
del data_df[i]
return data_df
def format_hidden_features(file_path, timelines, mapping):
loaded = np.load(file_path)
most_recent = mapping.sort_values(["subject_id", "ordering_date"], ascending=False).drop_duplicates("subject_id", keep="first")
report_ids = list(most_recent['report_id'])
mutable_file = {}
for id in report_ids:
mutable_file[id] = loaded[id].flatten()
loaded = mutable_file
label_features = pd.DataFrame(loaded.values(), index=loaded)
cols = list(label_features.columns)
xcols = ["x" + str(i) for i in cols]
rename_dict = dict(zip(cols,xcols))
rename_dict["index"] = "report_id"
label_features = label_features.reset_index().rename(columns=rename_dict)
data_frames = [timelines, most_recent]
data_df = reduce(lambda left,right: pd.merge(left,right,on="subject_id"), data_frames)
data_frames = [data_df, label_features]
data_df = reduce(lambda left,right: pd.merge(left,right,on="report_id"), data_frames)
for i in ["ordering_date", "report_id"]:
del data_df[i]
return data_df
def format_hf_sequence(file_path, timelines, mapping):
loaded = np.load(file_path)
top3_reports = mapping.sort_values(["subject_id", "ordering_date"], ascending=True).groupby("subject_id").tail(3)
report_dict = top3_reports.groupby("subject_id")["report_id"].apply(list).to_dict()
embedding_dict = defaultdict(list)
for k,v in report_dict.items():
for vi in v:
embedding_dict[k].append(loaded[vi])
embedding_dict[k] = np.vstack(embedding_dict[k])
label_features = pd.DataFrame(embedding_dict.values(), index=embedding_dict)
label_features[0] = label_features[0].apply(lambda x: add_paddings(x))
list2d = label_features[0]
merged = list(itertools.chain(*list2d))
scaler = StandardScaler()
scaler.fit(merged)
label_features[0] = label_features[0].apply(lambda x: scaler.transform(x))
cols = list(label_features.columns)
xcols = ["x" + str(i) for i in cols]
rename_dict = dict(zip(cols,xcols))
label_features = label_features.rename(columns=rename_dict)
label_features = label_features.reset_index().rename(columns={"index": "subject_id"})
data_frames = [timelines, label_features]
data_df = reduce(lambda left,right: pd.merge(left,right,on="subject_id"), data_frames)
return data_df
| true | true |
f719fd14389a9547c6251cef99f54bae3af19a6e | 221 | py | Python | output/models/ms_data/datatypes/facets/non_negative_integer/non_negative_integer_min_exclusive004_xsd/__init__.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | 1 | 2021-08-14T17:59:21.000Z | 2021-08-14T17:59:21.000Z | output/models/ms_data/datatypes/facets/non_negative_integer/non_negative_integer_min_exclusive004_xsd/__init__.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | 4 | 2020-02-12T21:30:44.000Z | 2020-04-15T20:06:46.000Z | output/models/ms_data/datatypes/facets/non_negative_integer/non_negative_integer_min_exclusive004_xsd/__init__.py | tefra/xsdata-w3c-tests | b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f | [
"MIT"
] | null | null | null | from output.models.ms_data.datatypes.facets.non_negative_integer.non_negative_integer_min_exclusive004_xsd.non_negative_integer_min_exclusive004 import (
FooType,
Test,
)
__all__ = [
"FooType",
"Test",
]
| 22.1 | 153 | 0.773756 | from output.models.ms_data.datatypes.facets.non_negative_integer.non_negative_integer_min_exclusive004_xsd.non_negative_integer_min_exclusive004 import (
FooType,
Test,
)
__all__ = [
"FooType",
"Test",
]
| true | true |
f719fd37c128d9a9db10d9a47902af2a5eb5d61e | 3,283 | py | Python | lektor/markdown/__init__.py | uk0/lektor | 21bdf99aa1183b4398043f87ba8ed137fad529ce | [
"BSD-3-Clause"
] | null | null | null | lektor/markdown/__init__.py | uk0/lektor | 21bdf99aa1183b4398043f87ba8ed137fad529ce | [
"BSD-3-Clause"
] | null | null | null | lektor/markdown/__init__.py | uk0/lektor | 21bdf99aa1183b4398043f87ba8ed137fad529ce | [
"BSD-3-Clause"
] | null | null | null | import sys
from typing import Any
from typing import Dict
from typing import Hashable
from typing import Type
from typing import TYPE_CHECKING
from weakref import ref as weakref
from deprecated import deprecated
from markupsafe import Markup
from lektor.markdown.controller import ControllerCache
from lektor.markdown.controller import FieldOptions
from lektor.markdown.controller import MarkdownController
from lektor.markdown.controller import Meta
from lektor.markdown.controller import RenderResult
from lektor.sourceobj import SourceObject
if sys.version_info >= (3, 8):
from importlib.metadata import version
else:
from importlib_metadata import version
if TYPE_CHECKING: # pragma: no cover
from lektor.environment import Environment
controller_class: Type[MarkdownController]
MISTUNE_VERSION = version("mistune")
if MISTUNE_VERSION.startswith("0."):
from lektor.markdown.mistune0 import MarkdownController0 as controller_class
elif MISTUNE_VERSION.startswith("2."):
from lektor.markdown.mistune2 import MarkdownController2 as controller_class
else: # pragma: no cover
raise ImportError("Unsupported version of mistune")
get_controller = ControllerCache(controller_class)
@deprecated
def make_markdown(env: "Environment") -> Any: # (Environment) -> mistune.Markdown
return get_controller(env).make_parser()
@deprecated
def markdown_to_html(
text: str, record: SourceObject, field_options: FieldOptions
) -> RenderResult:
return get_controller().render(text, record, field_options)
class Markdown:
def __init__(
self, source: str, record: SourceObject, field_options: FieldOptions
) -> None:
self.source = source
self.__record = weakref(record)
self.__field_options = field_options
self.__cache: Dict[Hashable, RenderResult] = {}
def __bool__(self) -> bool:
return bool(self.source)
__nonzero__ = __bool__
@property
def record(self) -> SourceObject:
record = self.__record()
if record is None:
raise RuntimeError("Record has gone away")
return record
def __render(self) -> RenderResult:
# When the markdown instance is attached to a cached object we
# can end up in the situation where, e.g., the base_url has
# changed from the time we were put into the cache to the time
# where we got referenced by something elsewhere. Since this
# affects the processing of relative links, in that case we
# need to re-process our markdown.
controller = get_controller()
key = controller.get_cache_key()
result = self.__cache.get(key) if key is not None else None
if result is None:
result = controller.render(self.source, self.record, self.__field_options)
if key is not None:
self.__cache[key] = result
return result
@property
def meta(self) -> Meta:
return self.__render().meta
@property
def html(self) -> Markup:
return Markup(self.__render().html)
def __getitem__(self, name: str) -> Any:
return self.meta[name]
def __str__(self) -> str:
return self.__render().html
def __html__(self) -> Markup:
return self.html
| 30.682243 | 86 | 0.709108 | import sys
from typing import Any
from typing import Dict
from typing import Hashable
from typing import Type
from typing import TYPE_CHECKING
from weakref import ref as weakref
from deprecated import deprecated
from markupsafe import Markup
from lektor.markdown.controller import ControllerCache
from lektor.markdown.controller import FieldOptions
from lektor.markdown.controller import MarkdownController
from lektor.markdown.controller import Meta
from lektor.markdown.controller import RenderResult
from lektor.sourceobj import SourceObject
if sys.version_info >= (3, 8):
from importlib.metadata import version
else:
from importlib_metadata import version
if TYPE_CHECKING:
from lektor.environment import Environment
controller_class: Type[MarkdownController]
MISTUNE_VERSION = version("mistune")
if MISTUNE_VERSION.startswith("0."):
from lektor.markdown.mistune0 import MarkdownController0 as controller_class
elif MISTUNE_VERSION.startswith("2."):
from lektor.markdown.mistune2 import MarkdownController2 as controller_class
else:
raise ImportError("Unsupported version of mistune")
get_controller = ControllerCache(controller_class)
@deprecated
def make_markdown(env: "Environment") -> Any:
return get_controller(env).make_parser()
@deprecated
def markdown_to_html(
text: str, record: SourceObject, field_options: FieldOptions
) -> RenderResult:
return get_controller().render(text, record, field_options)
class Markdown:
def __init__(
self, source: str, record: SourceObject, field_options: FieldOptions
) -> None:
self.source = source
self.__record = weakref(record)
self.__field_options = field_options
self.__cache: Dict[Hashable, RenderResult] = {}
def __bool__(self) -> bool:
return bool(self.source)
__nonzero__ = __bool__
@property
def record(self) -> SourceObject:
record = self.__record()
if record is None:
raise RuntimeError("Record has gone away")
return record
def __render(self) -> RenderResult:
controller = get_controller()
key = controller.get_cache_key()
result = self.__cache.get(key) if key is not None else None
if result is None:
result = controller.render(self.source, self.record, self.__field_options)
if key is not None:
self.__cache[key] = result
return result
@property
def meta(self) -> Meta:
return self.__render().meta
@property
def html(self) -> Markup:
return Markup(self.__render().html)
def __getitem__(self, name: str) -> Any:
return self.meta[name]
def __str__(self) -> str:
return self.__render().html
def __html__(self) -> Markup:
return self.html
| true | true |
f719fec77a658c0d0bd1fb9dff8594c94cc357ad | 59,113 | py | Python | venv/lib/python3.6/site-packages/bioblend/galaxy/objects/wrappers.py | usegalaxy-no/usegalaxy | 75dad095769fe918eb39677f2c887e681a747f3a | [
"MIT"
] | 1 | 2020-01-22T13:11:23.000Z | 2020-01-22T13:11:23.000Z | venv/lib/python3.6/site-packages/bioblend/galaxy/objects/wrappers.py | usegalaxy-no/usegalaxy | 75dad095769fe918eb39677f2c887e681a747f3a | [
"MIT"
] | 12 | 2020-02-21T07:24:52.000Z | 2020-04-14T09:54:32.000Z | venv/lib/python3.6/site-packages/bioblend/galaxy/objects/wrappers.py | usegalaxy-no/usegalaxy | 75dad095769fe918eb39677f2c887e681a747f3a | [
"MIT"
] | null | null | null | # pylint: disable=W0622,E1101
"""
A basic object-oriented interface for Galaxy entities.
"""
import abc
import json
from collections.abc import (
Iterable,
Mapping,
Sequence,
)
from typing import Tuple
import bioblend
from bioblend.util import abstractclass
__all__ = (
'Wrapper',
'Step',
'Workflow',
'LibraryContentInfo',
'HistoryContentInfo',
'DatasetContainer',
'History',
'Library',
'Folder',
'Dataset',
'HistoryDatasetAssociation',
'DatasetCollection',
'HistoryDatasetCollectionAssociation',
'LibraryDatasetDatasetAssociation',
'LibraryDataset',
'Tool',
'Job',
'LibraryPreview',
'HistoryPreview',
'WorkflowPreview',
)
@abstractclass
class Wrapper:
"""
Abstract base class for Galaxy entity wrappers.
Wrapper instances wrap deserialized JSON dictionaries such as the
ones obtained by the Galaxy web API, converting key-based access to
attribute-based access (e.g., ``library['name'] -> library.name``).
Dict keys that are converted to attributes are listed in the
``BASE_ATTRS`` class variable: this is the 'stable' interface.
Note that the wrapped dictionary is accessible via the ``wrapped``
attribute.
"""
BASE_ATTRS: Tuple[str, ...] = ('id', )
def __init__(self, wrapped, parent=None, gi=None):
"""
:type wrapped: dict
:param wrapped: JSON-serializable dictionary
:type parent: :class:`Wrapper`
:param parent: the parent of this wrapper
:type gi: :class:`GalaxyInstance`
:param gi: the GalaxyInstance through which we can access this wrapper
"""
if not isinstance(wrapped, Mapping):
raise TypeError('wrapped object must be a mapping type')
# loads(dumps(x)) is a bit faster than deepcopy and allows type checks
try:
dumped = json.dumps(wrapped)
except (TypeError, ValueError):
raise ValueError('wrapped object must be JSON-serializable')
object.__setattr__(self, 'wrapped', json.loads(dumped))
for k in self.BASE_ATTRS:
object.__setattr__(self, k, self.wrapped.get(k))
object.__setattr__(self, '_cached_parent', parent)
object.__setattr__(self, 'is_modified', False)
object.__setattr__(self, 'gi', gi)
@property
def parent(self):
"""
The parent of this wrapper.
"""
return self._cached_parent
@property
def is_mapped(self):
"""
``True`` if this wrapper is mapped to an actual Galaxy entity.
"""
return self.id is not None
def unmap(self):
"""
Disconnect this wrapper from Galaxy.
"""
object.__setattr__(self, 'id', None)
def clone(self):
"""
Return an independent copy of this wrapper.
"""
return self.__class__(self.wrapped)
def touch(self):
"""
Mark this wrapper as having been modified since its creation.
"""
object.__setattr__(self, 'is_modified', True)
if self.parent:
self.parent.touch()
def to_json(self):
"""
Return a JSON dump of this wrapper.
"""
return json.dumps(self.wrapped)
@classmethod
def from_json(cls, jdef):
"""
Build a new wrapper from a JSON dump.
"""
return cls(json.loads(jdef))
# FIXME: things like self.x[0] = 'y' do NOT call self.__setattr__
def __setattr__(self, name, value):
if name not in self.wrapped:
raise AttributeError("can't set attribute")
else:
self.wrapped[name] = value
object.__setattr__(self, name, value)
self.touch()
def __repr__(self):
return f"{self.__class__.__name__}({self.wrapped!r})"
class Step(Wrapper):
"""
Workflow step.
Steps are the main building blocks of a Galaxy workflow. A step can be: an
input (type ``data_collection_input``, ``data_input`` or
``parameter_input``), a computational tool (type ``tool``), a subworkflow
(type ``subworkflow``) or a pause (type ``pause``).
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'input_steps',
'name',
'tool_id',
'tool_inputs',
'tool_version',
'type',
)
def __init__(self, step_dict, parent):
super().__init__(step_dict, parent=parent, gi=parent.gi)
try:
stype = step_dict['type']
except KeyError:
raise ValueError('not a step dict')
if stype not in {'data_collection_input', 'data_input', 'parameter_input', 'pause', 'subworkflow', 'tool'}:
raise ValueError(f"Unknown step type: {stype!r}")
class InvocationStep(Wrapper):
"""
Invocation step.
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'action',
'job_id',
'order_index',
'state',
'update_time',
'workflow_step_id',
'workflow_step_label',
'workflow_step_uuid',
)
class Workflow(Wrapper):
"""
Workflows represent ordered sequences of computations on Galaxy.
A workflow defines a sequence of steps that produce one or more
results from an input dataset.
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'deleted',
'inputs',
'latest_workflow_uuid',
'name',
'owner',
'published',
'steps',
'tags',
)
POLLING_INTERVAL = 10 # for output state monitoring
def __init__(self, wf_dict, gi=None):
super().__init__(wf_dict, gi=gi)
missing_ids = []
if gi:
tools_list_by_id = [t.id for t in gi.tools.get_previews()]
else:
tools_list_by_id = []
tool_labels_to_ids = {}
for k, v in self.steps.items():
# convert step ids to str for consistency with outer keys
v['id'] = str(v['id'])
for i in v['input_steps'].values():
i['source_step'] = str(i['source_step'])
step = Step(v, self)
self.steps[k] = step
if step.type == 'tool':
if not step.tool_inputs or step.tool_id not in tools_list_by_id:
missing_ids.append(k)
tool_labels_to_ids.setdefault(step.tool_id, set()).add(step.id)
input_labels_to_ids = {}
for id_, d in self.inputs.items():
input_labels_to_ids.setdefault(d['label'], set()).add(id_)
object.__setattr__(self, 'input_labels_to_ids', input_labels_to_ids)
object.__setattr__(self, 'tool_labels_to_ids', tool_labels_to_ids)
dag, inv_dag = self._get_dag()
heads, tails = set(dag), set(inv_dag)
object.__setattr__(self, 'dag', dag)
object.__setattr__(self, 'inv_dag', inv_dag)
object.__setattr__(self, 'source_ids', heads - tails)
assert set(self.inputs) == self.data_collection_input_ids | self.data_input_ids | self.parameter_input_ids, \
f"inputs is {self.inputs!r}, while data_collection_input_ids is {self.data_collection_input_ids!r}, data_input_ids is {self.data_input_ids!r} and parameter_input_ids is {self.parameter_input_ids!r}"
object.__setattr__(self, 'sink_ids', tails - heads)
object.__setattr__(self, 'missing_ids', missing_ids)
def _get_dag(self):
"""
Return the workflow's DAG.
For convenience, this method computes a 'direct' (step =>
successors) and an 'inverse' (step => predecessors)
representation of the same DAG.
For instance, a workflow with a single tool *c*, two inputs
*a, b* and three outputs *d, e, f* is represented by (direct)::
{'a': {'c'}, 'b': {'c'}, 'c': {'d', 'e', 'f'}}
and by (inverse)::
{'c': {'a', 'b'}, 'd': {'c'}, 'e': {'c'}, 'f': {'c'}}
"""
dag, inv_dag = {}, {}
for s in self.steps.values():
for i in s.input_steps.values():
head, tail = i['source_step'], s.id
dag.setdefault(head, set()).add(tail)
inv_dag.setdefault(tail, set()).add(head)
return dag, inv_dag
def sorted_step_ids(self):
"""
Return a topological sort of the workflow's DAG.
"""
ids = []
source_ids = self.source_ids.copy()
inv_dag = {k: v.copy() for k, v in self.inv_dag.items()}
while source_ids:
head = source_ids.pop()
ids.append(head)
for tail in self.dag.get(head, []):
incoming = inv_dag[tail]
incoming.remove(head)
if not incoming:
source_ids.add(tail)
return ids
@property
def data_input_ids(self):
"""
Return the ids of data input steps for this workflow.
"""
return {id_ for id_, s in self.steps.items() if s.type == 'data_input'}
@property
def data_collection_input_ids(self):
"""
Return the ids of data collection input steps for this workflow.
"""
return {id_ for id_, s in self.steps.items() if s.type == 'data_collection_input'}
@property
def parameter_input_ids(self):
"""
Return the ids of parameter input steps for this workflow.
"""
return {id_ for id_, s in self.steps.items() if s.type == 'parameter_input'}
@property
def tool_ids(self):
"""
Return the ids of tool steps for this workflow.
"""
return {id_ for id_, s in self.steps.items() if s.type == 'tool'}
@property
def input_labels(self):
"""
Return the labels of this workflow's input steps.
"""
return set(self.input_labels_to_ids)
@property
def is_runnable(self):
"""
Return True if the workflow can be run on Galaxy.
A workflow is considered runnable on a Galaxy instance if all
of the tools it uses are installed in that instance.
"""
return not self.missing_ids
def convert_input_map(self, input_map):
"""
Convert ``input_map`` to the format required by the Galaxy web API.
:type input_map: dict
:param input_map: a mapping from input labels to datasets
:rtype: dict
:return: a mapping from input slot ids to dataset ids in the
format required by the Galaxy web API.
"""
m = {}
for label, slot_ids in self.input_labels_to_ids.items():
datasets = input_map.get(label, [])
if not isinstance(datasets, Iterable):
datasets = [datasets]
if len(datasets) < len(slot_ids):
raise RuntimeError(f'not enough datasets for "{label}"')
for id_, ds in zip(slot_ids, datasets):
m[id_] = {'id': ds.id, 'src': ds.SRC}
return m
def preview(self):
getf = self.gi.workflows.get_previews
try:
p = [_ for _ in getf(published=True) if _.id == self.id][0]
except IndexError:
raise ValueError(f"no object for id {self.id}")
return p
def run(self, input_map=None, history='', params=None, import_inputs=False,
replacement_params=None, wait=False,
polling_interval=POLLING_INTERVAL, break_on_error=True):
"""
Run the workflow in the current Galaxy instance.
.. deprecated:: 0.16.0
Use :meth:`invoke` instead.
:type input_map: dict
:param input_map: a mapping from workflow input labels to
datasets, e.g.: ``dict(zip(workflow.input_labels,
library.get_datasets()))``
:type history: :class:`History` or str
:param history: either a valid history object (results will be
stored there) or a string (a new history will be created with
the given name).
:type params: dict
:param params: a mapping of non-datasets tool parameters (see below)
:type import_inputs: bool
:param import_inputs: If ``True``, workflow inputs will be imported into
the history; if ``False``, only workflow outputs will be visible in
the history.
:type replacement_params: dict
:param replacement_params: pattern-based replacements for
post-job actions (see the docs for
:meth:`~bioblend.galaxy.workflows.WorkflowClient.invoke_workflow`)
:type wait: bool
:param wait: whether to wait while the returned datasets are
in a pending state
:type polling_interval: float
:param polling_interval: polling interval in seconds
:type break_on_error: bool
:param break_on_error: whether to break as soon as at least one
of the returned datasets is in the 'error' state
:rtype: tuple
:return: list of output datasets, output history
The ``params`` dict should be specified as follows::
{STEP_ID: PARAM_DICT, ...}
where PARAM_DICT is::
{PARAM_NAME: VALUE, ...}
For backwards compatibility, the following (deprecated) format is
also supported for ``params``::
{TOOL_ID: PARAM_DICT, ...}
in which case PARAM_DICT affects all steps with the given tool id.
If both by-tool-id and by-step-id specifications are used, the
latter takes precedence.
Finally (again, for backwards compatibility), PARAM_DICT can also
be specified as::
{'param': PARAM_NAME, 'value': VALUE}
Note that this format allows only one parameter to be set per step.
Example: set 'a' to 1 for the third workflow step::
params = {workflow.steps[2].id: {'a': 1}}
.. warning::
This is a blocking operation that can take a very long time. If
``wait`` is set to ``False``, the method will return as soon as the
workflow has been *scheduled*, otherwise it will wait until the
workflow has been *run*. With a large number of steps, however, the
delay may not be negligible even in the former case (e.g. minutes for
100 steps).
"""
if not self.is_mapped:
raise RuntimeError('workflow is not mapped to a Galaxy object')
if not self.is_runnable:
missing_tools_str = ', '.join(f"{self.steps[step_id].tool_id}[{step_id}]" for step_id in self.missing_ids)
raise RuntimeError(f"workflow has missing tools: {missing_tools_str}")
kwargs = {
'dataset_map': self.convert_input_map(input_map or {}),
'params': params,
'import_inputs_to_history': import_inputs,
'replacement_params': replacement_params,
}
if isinstance(history, History):
try:
kwargs['history_id'] = history.id
except AttributeError:
raise RuntimeError('history does not have an id')
elif isinstance(history, str):
kwargs['history_name'] = history
else:
raise TypeError(
'history must be either a history wrapper or a string')
res = self.gi.gi.workflows.run_workflow(self.id, **kwargs)
# res structure: {'history': HIST_ID, 'outputs': [CI_ID, CI_ID, ...]}
out_hist = self.gi.histories.get(res['history'])
content_infos_dict = {ci.id: ci for ci in out_hist.content_infos}
outputs = []
for output_id in res['outputs']:
if content_infos_dict[output_id].type == 'file':
outputs.append(out_hist.get_dataset(output_id))
elif content_infos_dict[output_id].type == 'collection':
outputs.append(out_hist.get_dataset_collection(output_id))
if wait:
self.gi._wait_datasets(outputs, polling_interval=polling_interval,
break_on_error=break_on_error)
return outputs, out_hist
def export(self):
"""
Export a re-importable representation of the workflow.
:rtype: dict
:return: a JSON-serializable dump of the workflow
"""
return self.gi.gi.workflows.export_workflow_dict(self.id)
def delete(self):
"""
Delete this workflow.
.. warning::
Deleting a workflow is irreversible - all of the data from
the workflow will be permanently deleted.
"""
self.gi.workflows.delete(id_=self.id)
self.unmap()
def invoke(self, inputs=None, params=None, history=None,
import_inputs_to_history=None, replacement_params=None,
allow_tool_state_corrections=True, inputs_by=None,
parameters_normalized=False):
"""
Invoke the workflow. This will cause a workflow to be scheduled
and return an object describing the workflow invocation.
:type inputs: dict
:param inputs: A mapping of workflow inputs to datasets and dataset collections.
The datasets source can be a LibraryDatasetDatasetAssociation (``ldda``),
LibraryDataset (``ld``), HistoryDatasetAssociation (``hda``), or
HistoryDatasetCollectionAssociation (``hdca``).
The map must be in the following format:
``{'<input_index>': {'id': <encoded dataset ID>, 'src': '[ldda, ld, hda, hdca]'}}``
(e.g. ``{'2': {'id': '29beef4fadeed09f', 'src': 'hda'}}``)
This map may also be indexed by the UUIDs of the workflow steps,
as indicated by the ``uuid`` property of steps returned from the
Galaxy API. Alternatively workflow steps may be addressed by
the label that can be set in the workflow editor. If using
uuid or label you need to also set the ``inputs_by`` parameter
to ``step_uuid`` or ``name``.
:type params: dict
:param params: A mapping of non-datasets tool parameters (see below)
:type history: str
:param history: The history in which to store the workflow
output.
:type import_inputs_to_history: bool
:param import_inputs_to_history: If ``True``, used workflow inputs will
be imported into the history. If ``False``, only workflow outputs will
be visible in the given history.
:type allow_tool_state_corrections: bool
:param allow_tool_state_corrections: If True, allow Galaxy to fill in
missing tool state when running workflows. This may be useful for
workflows using tools that have changed over time or for workflows
built outside of Galaxy with only a subset of inputs defined.
:type replacement_params: dict
:param replacement_params: pattern-based replacements for post-job
actions (see below)
:type inputs_by: str
:param inputs_by: Determines how inputs are referenced. Can be
"step_index|step_uuid" (default), "step_index", "step_id", "step_uuid", or "name".
:type parameters_normalized: bool
:param parameters_normalized: Whether Galaxy should normalize ``params``
to ensure everything is referenced by a numeric step ID. Default is
``False``, but when setting ``params`` for a subworkflow, ``True`` is
required.
:rtype: Invocation
:return: the workflow invocation
The ``params`` dict should be specified as follows::
{STEP_ID: PARAM_DICT, ...}
where PARAM_DICT is::
{PARAM_NAME: VALUE, ...}
For backwards compatibility, the following (deprecated) format is
also supported for ``params``::
{TOOL_ID: PARAM_DICT, ...}
in which case PARAM_DICT affects all steps with the given tool id.
If both by-tool-id and by-step-id specifications are used, the
latter takes precedence.
Finally (again, for backwards compatibility), PARAM_DICT can also
be specified as::
{'param': PARAM_NAME, 'value': VALUE}
Note that this format allows only one parameter to be set per step.
For a ``repeat`` parameter, the names of the contained parameters needs
to be specified as ``<repeat name>_<repeat index>|<param name>``, with
the repeat index starting at 0. For example, if the tool XML contains::
<repeat name="cutoff" title="Parameters used to filter cells" min="1">
<param name="name" type="text" value="n_genes" label="Name of param...">
<option value="n_genes">n_genes</option>
<option value="n_counts">n_counts</option>
</param>
<param name="min" type="float" min="0" value="0" label="Min value"/>
</repeat>
then the PARAM_DICT should be something like::
{...
"cutoff_0|name": "n_genes",
"cutoff_0|min": "2",
"cutoff_1|name": "n_counts",
"cutoff_1|min": "4",
...}
At the time of this writing, it is not possible to change the number of
times the contained parameters are repeated. Therefore, the parameter
indexes can go from 0 to n-1, where n is the number of times the
repeated element was added when the workflow was saved in the Galaxy UI.
The ``replacement_params`` dict should map parameter names in
post-job actions (PJAs) to their runtime values. For
instance, if the final step has a PJA like the following::
{'RenameDatasetActionout_file1': {'action_arguments': {'newname': '${output}'},
'action_type': 'RenameDatasetAction',
'output_name': 'out_file1'}}
then the following renames the output dataset to 'foo'::
replacement_params = {'output': 'foo'}
see also `this email thread
<http://lists.bx.psu.edu/pipermail/galaxy-dev/2011-September/006875.html>`_.
.. warning::
Historically, the ``run_workflow`` method consumed a ``dataset_map``
data structure that was indexed by unencoded workflow step IDs. These
IDs would not be stable across Galaxy instances. The new ``inputs``
property is instead indexed by either the ``order_index`` property
(which is stable across workflow imports) or the step UUID which is
also stable.
"""
inv_dict = self.gi.gi.workflows.invoke_workflow(
workflow_id=self.id,
inputs=inputs,
params=params,
history_id=history.id,
import_inputs_to_history=import_inputs_to_history,
replacement_params=replacement_params,
allow_tool_state_corrections=allow_tool_state_corrections,
inputs_by=inputs_by,
parameters_normalized=parameters_normalized
)
return self.gi.invocations.get(inv_dict['id'])
class Invocation(Wrapper):
"""
Invocation of a workflow.
This causes the steps of a workflow to be executed in sequential order.
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'history_id',
'inputs',
'state',
'steps',
'update_time',
'uuid',
'workflow_id',
)
def __init__(self, inv_dict, gi=None):
super().__init__(inv_dict, gi=gi)
self.steps = [InvocationStep(step, self) for step in self.steps]
self.inputs = [{**v, 'label': k} for k, v in self.inputs.items()]
def sorted_step_ids(self):
"""
Get the step IDs sorted based on this order index.
:rtype: list of str
:param: sorted step IDs
"""
return [step.id for step in sorted(self.steps, key=lambda step: step.order_index)]
def step_states(self):
"""
Get the set of step states for this invocation.
:rtype: set
:param: step states
"""
return {step.state for step in self.steps}
def number_of_steps(self):
"""
Get the number of steps for this invocation.
:rtype: int
:param: number of steps
"""
return len(self.steps)
def sorted_steps_by(self, indices=None, states=None, step_ids=None):
"""
Get steps for this invocation, or get a subset by specifying
optional parameters for filtering.
:type indices: list of int
:param indices: return steps that have matching order_index
:type states: list of str
:param states: return steps that have matching states
:type step_ids: list of str
:param step_ids: return steps that have matching step_ids
:rtype: list of InvocationStep
:param: invocation steps
"""
steps = self.steps
if indices is not None:
steps = filter(lambda step: step.order_index in indices, steps)
if states is not None:
steps = filter(lambda step: step.state in states, steps)
if step_ids is not None:
steps = filter(lambda step: step.id in step_ids, steps)
return sorted(steps, key=lambda step: step.order_index)
def cancel(self):
"""
Cancel this invocation.
.. note::
On success, this method updates the Invocation object's internal variables.
"""
inv_dict = self.gi.gi.invocations.cancel_invocation(self.id)
self.__init__(inv_dict, gi=self.gi)
def refresh(self):
"""
Update this invocation with the latest information from the server.
.. note::
On success, this method updates the Invocation object's internal variables.
"""
inv_dict = self.gi.gi.invocations.show_invocation(self.id)
self.__init__(inv_dict, gi=self.gi)
def run_step_actions(self, steps, actions):
"""
Run actions for active steps of this invocation.
:type steps: list of InvocationStep
:param steps: list of steps to run actions on
:type actions: list of str
:param actions: list of actions to run
.. note::
On success, this method updates the Invocation object's internal step variables.
"""
if not len(steps) == len(actions):
raise RuntimeError(f'Different number of ``steps`` ({len(steps)}) and ``actions`` ({len(actions)}) in ``{self}.run_step_actions()``')
step_dict_list = [self.gi.gi.invocations.run_invocation_step_action(self.id, step.id, action) for step, action in zip(steps, actions)]
for step, step_dict in zip(steps, step_dict_list):
step.__init__(step_dict, parent=self)
def summary(self):
"""
Get a summary for this invocation.
:rtype: dict
:param: invocation summary
"""
return self.gi.gi.invocations.get_invocation_summary(self.id)
def step_jobs_summary(self):
"""
Get a summary for this invocation's step jobs.
:rtype: list of dicts
:param: step job summaries
"""
return self.gi.gi.invocations.get_invocation_step_jobs_summary(self.id)
def report(self):
"""
Get a dictionary containing a Markdown report for this invocation.
:rtype: dict
:param: invocation report
"""
return self.gi.gi.invocations.get_invocation_report(self.id)
def save_report_pdf(self, file_path, chunk_size=bioblend.CHUNK_SIZE):
"""
Download a PDF report for this invocation.
:type file_path: str
:param file_path: path to save the report
:type chunk_size: int
:param chunk_size: chunk size in bytes for reading remote data
"""
self.gi.gi.invocations.get_invocation_report_pdf(self.id, file_path, chunk_size)
def biocompute_object(self):
"""
Get a BioCompute object for this invocation.
:rtype: dict
:param: BioCompute object
"""
return self.gi.gi.invocations.get_invocation_biocompute_object(self.id)
def wait(self, maxwait=12000, interval=3, check=True):
"""
Wait for this invocation to reach a terminal state.
:type maxwait: float
:param maxwait: upper limit on waiting time
:type interval: float
:param interval: polling interval in secconds
:type check: bool
:param check: if ``true``, raise an error if the terminal state is not 'scheduled'
.. note::
On success, this method updates the Invocation object's internal variables.
"""
inv_dict = self.gi.gi.invocations.wait_for_invocation(self.id, maxwait=maxwait, interval=interval, check=check)
self.__init__(inv_dict, gi=self.gi)
class Dataset(Wrapper, metaclass=abc.ABCMeta):
"""
Abstract base class for Galaxy datasets.
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'data_type',
'file_ext',
'file_name',
'file_size',
'genome_build',
'misc_info',
'name',
'state',
)
POLLING_INTERVAL = 1 # for state monitoring
def __init__(self, ds_dict, container, gi=None):
super().__init__(ds_dict, gi=gi)
object.__setattr__(self, 'container', container)
@property
@abc.abstractmethod
def _stream_url(self):
"""
Return the URL to stream this dataset.
"""
pass
def get_stream(self, chunk_size=bioblend.CHUNK_SIZE):
"""
Open dataset for reading and return an iterator over its contents.
:type chunk_size: int
:param chunk_size: read this amount of bytes at a time
"""
kwargs = {'stream': True}
if isinstance(self, LibraryDataset):
kwargs['params'] = {'ld_ids%5B%5D': self.id}
r = self.gi.gi.make_get_request(self._stream_url, **kwargs)
if isinstance(self, LibraryDataset) and r.status_code == 500:
# compatibility with older Galaxy releases
kwargs['params'] = {'ldda_ids%5B%5D': self.id}
r = self.gi.gi.make_get_request(self._stream_url, **kwargs)
r.raise_for_status()
return r.iter_content(chunk_size) # FIXME: client can't close r
def peek(self, chunk_size=bioblend.CHUNK_SIZE):
"""
Open dataset for reading and return the first chunk.
See :meth:`.get_stream` for param info.
"""
try:
return next(self.get_stream(chunk_size=chunk_size))
except StopIteration:
return b''
def download(self, file_object, chunk_size=bioblend.CHUNK_SIZE):
"""
Open dataset for reading and save its contents to ``file_object``.
:type file_object: file
:param file_object: output file object
See :meth:`.get_stream` for info on other params.
"""
for chunk in self.get_stream(chunk_size=chunk_size):
file_object.write(chunk)
def get_contents(self, chunk_size=bioblend.CHUNK_SIZE):
"""
Open dataset for reading and return its **full** contents.
See :meth:`.get_stream` for param info.
"""
return b''.join(self.get_stream(chunk_size=chunk_size))
def refresh(self):
"""
Re-fetch the attributes pertaining to this object.
Returns: self
"""
gi_client = getattr(self.gi.gi, self.container.API_MODULE)
ds_dict = gi_client.show_dataset(self.container.id, self.id)
self.__init__(ds_dict, self.container, self.gi)
return self
def wait(self, polling_interval=POLLING_INTERVAL, break_on_error=True):
"""
Wait for this dataset to come out of the pending states.
:type polling_interval: float
:param polling_interval: polling interval in seconds
:type break_on_error: bool
:param break_on_error: if ``True``, raise a RuntimeError exception if
the dataset ends in the 'error' state.
.. warning::
This is a blocking operation that can take a very long time. Also,
note that this method does not return anything; however, this dataset
is refreshed (possibly multiple times) during the execution.
"""
self.gi._wait_datasets([self], polling_interval=polling_interval,
break_on_error=break_on_error)
class HistoryDatasetAssociation(Dataset):
"""
Maps to a Galaxy ``HistoryDatasetAssociation``.
"""
BASE_ATTRS = Dataset.BASE_ATTRS + ('annotation', 'deleted', 'purged', 'tags', 'visible')
SRC = 'hda'
@property
def _stream_url(self):
base_url = self.gi.gi.histories._make_url(module_id=self.container.id, contents=True)
return f"{base_url}/{self.id}/display"
def update(self, **kwds):
"""
Update this history dataset metadata. Some of the attributes that can be
modified are documented below.
:type name: str
:param name: Replace history dataset name with the given string
:type genome_build: str
:param genome_build: Replace history dataset genome build (dbkey)
:type annotation: str
:param annotation: Replace history dataset annotation with given string
:type deleted: bool
:param deleted: Mark or unmark history dataset as deleted
:type visible: bool
:param visible: Mark or unmark history dataset as visible
"""
res = self.gi.gi.histories.update_dataset(self.container.id, self.id, **kwds)
# Refresh also the history because the dataset may have been (un)deleted
self.container.refresh()
self.__init__(res, self.container, gi=self.gi)
return self
def delete(self, purge=False):
"""
Delete this history dataset.
:type purge: bool
:param purge: if ``True``, also purge (permanently delete) the dataset
.. note::
For the purge option to work, the Galaxy instance must have the
``allow_user_dataset_purge`` option set to ``true`` in the
``config/galaxy.yml`` configuration file.
"""
self.gi.gi.histories.delete_dataset(self.container.id, self.id, purge=purge)
self.container.refresh()
self.refresh()
class DatasetCollection(Wrapper, metaclass=abc.ABCMeta):
"""
Abstract base class for Galaxy dataset collections.
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'collection_type',
'deleted',
'name',
'state',
)
def __init__(self, dsc_dict, container, gi=None):
super().__init__(dsc_dict, gi=gi)
object.__setattr__(self, 'container', container)
def refresh(self):
"""
Re-fetch the attributes pertaining to this object.
Returns: self
"""
gi_client = getattr(self.gi.gi, self.container.API_MODULE)
dsc_dict = gi_client.show_dataset_collection(self.container.id, self.id)
self.__init__(dsc_dict, self.container, self.gi)
return self
@abc.abstractmethod
def delete(self):
pass
class HistoryDatasetCollectionAssociation(DatasetCollection):
"""
Maps to a Galaxy ``HistoryDatasetCollectionAssociation``.
"""
BASE_ATTRS = DatasetCollection.BASE_ATTRS + ('tags', 'visible', 'elements')
SRC = 'hdca'
def delete(self):
"""
Delete this dataset collection.
"""
self.gi.gi.histories.delete_dataset_collection(self.container.id, self.id)
self.container.refresh()
self.refresh()
@abstractclass
class LibRelatedDataset(Dataset):
"""
Base class for LibraryDatasetDatasetAssociation and LibraryDataset classes.
"""
@property
def _stream_url(self):
base_url = self.gi.gi.libraries._make_url()
return f"{base_url}/datasets/download/uncompressed"
class LibraryDatasetDatasetAssociation(LibRelatedDataset):
"""
Maps to a Galaxy ``LibraryDatasetDatasetAssociation``.
"""
BASE_ATTRS = LibRelatedDataset.BASE_ATTRS + ('deleted',)
SRC = 'ldda'
class LibraryDataset(LibRelatedDataset):
"""
Maps to a Galaxy ``LibraryDataset``.
"""
SRC = 'ld'
def delete(self, purged=False):
"""
Delete this library dataset.
:type purged: bool
:param purged: if ``True``, also purge (permanently delete) the dataset
"""
self.gi.gi.libraries.delete_library_dataset(
self.container.id, self.id, purged=purged)
self.container.refresh()
self.refresh()
def update(self, **kwds):
"""
Update this library dataset metadata. Some of the attributes that can be
modified are documented below.
:type name: str
:param name: Replace history dataset name with the given string
:type genome_build: str
:param genome_build: Replace history dataset genome build (dbkey)
"""
res = self.gi.gi.libraries.update_library_dataset(self.id, **kwds)
self.container.refresh()
self.__init__(res, self.container, gi=self.gi)
return self
@abstractclass
class ContentInfo(Wrapper):
"""
Instances of this class wrap dictionaries obtained by getting
``/api/{histories,libraries}/<ID>/contents`` from Galaxy.
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'name',
'type',
)
class LibraryContentInfo(ContentInfo):
"""
Instances of this class wrap dictionaries obtained by getting
``/api/libraries/<ID>/contents`` from Galaxy.
"""
class HistoryContentInfo(ContentInfo):
"""
Instances of this class wrap dictionaries obtained by getting
``/api/histories/<ID>/contents`` from Galaxy.
"""
BASE_ATTRS = ContentInfo.BASE_ATTRS + ('deleted', 'state', 'visible')
class DatasetContainer(Wrapper, metaclass=abc.ABCMeta):
"""
Abstract base class for dataset containers (histories and libraries).
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'deleted',
'name',
)
def __init__(self, c_dict, content_infos=None, gi=None):
"""
:type content_infos: list of :class:`ContentInfo`
:param content_infos: info objects for the container's contents
"""
super().__init__(c_dict, gi=gi)
if content_infos is None:
content_infos = []
object.__setattr__(self, 'content_infos', content_infos)
object.__setattr__(self, 'obj_gi_client', getattr(self.gi, self.API_MODULE))
@property
@abc.abstractmethod
def API_MODULE(self):
pass
@property
def dataset_ids(self):
"""
Return the ids of the contained datasets.
"""
return [_.id for _ in self.content_infos if _.type == 'file']
def preview(self):
getf = self.obj_gi_client.get_previews
# self.state could be stale: check both regular and deleted containers
try:
p = [_ for _ in getf() if _.id == self.id][0]
except IndexError:
try:
p = [_ for _ in getf(deleted=True) if _.id == self.id][0]
except IndexError:
raise ValueError(f"no object for id {self.id}")
return p
def refresh(self):
"""
Re-fetch the attributes pertaining to this object.
Returns: self
"""
fresh = self.obj_gi_client.get(self.id)
self.__init__(
fresh.wrapped, content_infos=fresh.content_infos, gi=self.gi)
return self
def get_dataset(self, ds_id):
"""
Retrieve the dataset corresponding to the given id.
:type ds_id: str
:param ds_id: dataset id
:rtype: :class:`~.HistoryDatasetAssociation` or
:class:`~.LibraryDataset`
:return: the dataset corresponding to ``ds_id``
"""
gi_client = getattr(self.gi.gi, self.API_MODULE)
ds_dict = gi_client.show_dataset(self.id, ds_id)
return self.DS_TYPE(ds_dict, self, gi=self.gi)
def get_datasets(self, name=None):
"""
Get all datasets contained inside this dataset container.
:type name: str
:param name: return only datasets with this name
:rtype: list of :class:`~.HistoryDatasetAssociation` or list of
:class:`~.LibraryDataset`
:return: datasets with the given name contained inside this
container
.. note::
when filtering library datasets by name, specify their full
paths starting from the library's root folder, e.g.,
``/seqdata/reads.fastq``. Full paths are available through
the ``content_infos`` attribute of
:class:`~.Library` objects.
"""
if name is None:
ds_ids = self.dataset_ids
else:
ds_ids = [_.id for _ in self.content_infos if _.name == name]
return [self.get_dataset(_) for _ in ds_ids]
class History(DatasetContainer):
"""
Maps to a Galaxy history.
"""
BASE_ATTRS = DatasetContainer.BASE_ATTRS + ('annotation', 'published', 'state', 'state_ids', 'state_details', 'tags')
DS_TYPE = HistoryDatasetAssociation
DSC_TYPE = HistoryDatasetCollectionAssociation
CONTENT_INFO_TYPE = HistoryContentInfo
API_MODULE = 'histories'
def update(self, **kwds):
"""
Update history metadata information. Some of the attributes that can be
modified are documented below.
:type name: str
:param name: Replace history name with the given string
:type annotation: str
:param annotation: Replace history annotation with the given string
:type deleted: bool
:param deleted: Mark or unmark history as deleted
:type purged: bool
:param purged: If True, mark history as purged (permanently deleted).
:type published: bool
:param published: Mark or unmark history as published
:type importable: bool
:param importable: Mark or unmark history as importable
:type tags: list
:param tags: Replace history tags with the given list
"""
# TODO: wouldn't it be better if name and annotation were attributes?
self.gi.gi.histories.update_history(self.id, **kwds)
self.refresh()
return self
def delete(self, purge=False):
"""
Delete this history.
:type purge: bool
:param purge: if ``True``, also purge (permanently delete) the history
.. note::
For the purge option to work, the Galaxy instance must have the
``allow_user_dataset_purge`` option set to ``true`` in the
``config/galaxy.yml`` configuration file.
"""
self.gi.histories.delete(id_=self.id, purge=purge)
self.refresh()
self.unmap()
def import_dataset(self, lds):
"""
Import a dataset into the history from a library.
:type lds: :class:`~.LibraryDataset`
:param lds: the library dataset to import
:rtype: :class:`~.HistoryDatasetAssociation`
:return: the imported history dataset
"""
if not self.is_mapped:
raise RuntimeError('history is not mapped to a Galaxy object')
if not isinstance(lds, LibraryDataset):
raise TypeError('lds is not a LibraryDataset')
res = self.gi.gi.histories.upload_dataset_from_library(self.id, lds.id)
if not isinstance(res, Mapping):
raise RuntimeError(
f"upload_dataset_from_library: unexpected reply: {res!r}"
)
self.refresh()
return self.get_dataset(res['id'])
def upload_file(self, path, **kwargs):
"""
Upload the file specified by ``path`` to this history.
:type path: str
:param path: path of the file to upload
See :meth:`~bioblend.galaxy.tools.ToolClient.upload_file` for
the optional parameters.
:rtype: :class:`~.HistoryDatasetAssociation`
:return: the uploaded dataset
"""
out_dict = self.gi.gi.tools.upload_file(path, self.id, **kwargs)
self.refresh()
return self.get_dataset(out_dict['outputs'][0]['id'])
upload_dataset = upload_file
def upload_from_ftp(self, path, **kwargs):
"""
Upload the file specified by ``path`` from the user's FTP directory to
this history.
:type path: str
:param path: path of the file in the user's FTP directory
See :meth:`~bioblend.galaxy.tools.ToolClient.upload_file` for
the optional parameters.
:rtype: :class:`~.HistoryDatasetAssociation`
:return: the uploaded dataset
"""
out_dict = self.gi.gi.tools.upload_from_ftp(path, self.id, **kwargs)
self.refresh()
return self.get_dataset(out_dict['outputs'][0]['id'])
def paste_content(self, content, **kwargs):
"""
Upload a string to a new dataset in this history.
:type content: str
:param content: content of the new dataset to upload
See :meth:`~bioblend.galaxy.tools.ToolClient.upload_file` for
the optional parameters (except file_name).
:rtype: :class:`~.HistoryDatasetAssociation`
:return: the uploaded dataset
"""
out_dict = self.gi.gi.tools.paste_content(content, self.id, **kwargs)
self.refresh()
return self.get_dataset(out_dict['outputs'][0]['id'])
def export(self, gzip=True, include_hidden=False, include_deleted=False,
wait=False, maxwait=None):
"""
Start a job to create an export archive for this history. See
:meth:`~bioblend.galaxy.histories.HistoryClient.export_history`
for parameter and return value info.
"""
return self.gi.gi.histories.export_history(
self.id, gzip=gzip, include_hidden=include_hidden,
include_deleted=include_deleted, wait=wait, maxwait=maxwait)
def download(self, jeha_id, outf, chunk_size=bioblend.CHUNK_SIZE):
"""
Download an export archive for this history. Use :meth:`export`
to create an export and get the required ``jeha_id``. See
:meth:`~bioblend.galaxy.histories.HistoryClient.download_history`
for parameter and return value info.
"""
return self.gi.gi.histories.download_history(
self.id, jeha_id, outf, chunk_size=chunk_size)
def create_dataset_collection(self, collection_description):
"""
Create a new dataset collection in the history by providing a collection description.
:type collection_description: bioblend.galaxy.dataset_collections.CollectionDescription
:param collection_description: a description of the dataset collection
:rtype: :class:`~.HistoryDatasetCollectionAssociation`
:return: the new dataset collection
"""
dataset_collection = self.gi.gi.histories.create_dataset_collection(self.id, collection_description)
self.refresh()
return self.get_dataset_collection(dataset_collection['id'])
def get_dataset_collection(self, dsc_id):
"""
Retrieve the dataset collection corresponding to the given id.
:type dsc_id: str
:param dsc_id: dataset collection id
:rtype: :class:`~.HistoryDatasetCollectionAssociation`
:return: the dataset collection corresponding to ``dsc_id``
"""
dsc_dict = self.gi.gi.histories.show_dataset_collection(self.id, dsc_id)
return self.DSC_TYPE(dsc_dict, self, gi=self.gi)
class Library(DatasetContainer):
"""
Maps to a Galaxy library.
"""
BASE_ATTRS = DatasetContainer.BASE_ATTRS + ('description', 'synopsis')
DS_TYPE = LibraryDataset
CONTENT_INFO_TYPE = LibraryContentInfo
API_MODULE = 'libraries'
@property
def folder_ids(self):
"""
Return the ids of the contained folders.
"""
return [_.id for _ in self.content_infos if _.type == 'folder']
def delete(self):
"""
Delete this library.
"""
self.gi.libraries.delete(id_=self.id)
self.refresh()
self.unmap()
def _pre_upload(self, folder):
"""
Return the id of the given folder, after sanity checking.
"""
if not self.is_mapped:
raise RuntimeError('library is not mapped to a Galaxy object')
return None if folder is None else folder.id
def upload_data(self, data, folder=None, **kwargs):
"""
Upload data to this library.
:type data: str
:param data: dataset contents
:type folder: :class:`~.Folder`
:param folder: a folder object, or ``None`` to upload to the root folder
:rtype: :class:`~.LibraryDataset`
:return: the dataset object that represents the uploaded content
Optional keyword arguments: ``file_type``, ``dbkey``.
"""
fid = self._pre_upload(folder)
res = self.gi.gi.libraries.upload_file_contents(
self.id, data, folder_id=fid, **kwargs)
self.refresh()
return self.get_dataset(res[0]['id'])
def upload_from_url(self, url, folder=None, **kwargs):
"""
Upload data to this library from the given URL.
:type url: str
:param url: URL from which data should be read
See :meth:`.upload_data` for info on other params.
"""
fid = self._pre_upload(folder)
res = self.gi.gi.libraries.upload_file_from_url(
self.id, url, folder_id=fid, **kwargs)
self.refresh()
return self.get_dataset(res[0]['id'])
def upload_from_local(self, path, folder=None, **kwargs):
"""
Upload data to this library from a local file.
:type path: str
:param path: local file path from which data should be read
See :meth:`.upload_data` for info on other params.
"""
fid = self._pre_upload(folder)
res = self.gi.gi.libraries.upload_file_from_local_path(
self.id, path, folder_id=fid, **kwargs)
self.refresh()
return self.get_dataset(res[0]['id'])
def upload_from_galaxy_fs(self, paths, folder=None, link_data_only=None, **kwargs):
"""
Upload data to this library from filesystem paths on the server.
.. note::
For this method to work, the Galaxy instance must have the
``allow_path_paste`` option set to ``true`` in the
``config/galaxy.yml`` configuration file.
:type paths: str or :class:`~collections.abc.Iterable` of str
:param paths: server-side file paths from which data should be read
:type link_data_only: str
:param link_data_only: either 'copy_files' (default) or
'link_to_files'. Setting to 'link_to_files' symlinks instead of
copying the files
:rtype: list of :class:`~.LibraryDataset`
:return: the dataset objects that represent the uploaded content
See :meth:`.upload_data` for info on other params.
"""
fid = self._pre_upload(folder)
if isinstance(paths, str):
paths = (paths,)
paths = '\n'.join(paths)
res = self.gi.gi.libraries.upload_from_galaxy_filesystem(
self.id, paths, folder_id=fid, link_data_only=link_data_only,
**kwargs)
if res is None:
raise RuntimeError('upload_from_galaxy_filesystem: no reply')
if not isinstance(res, Sequence):
raise RuntimeError(
f"upload_from_galaxy_filesystem: unexpected reply: {res!r}"
)
new_datasets = [
self.get_dataset(ds_info['id']) for ds_info in res
]
self.refresh()
return new_datasets
def copy_from_dataset(self, hda, folder=None, message=''):
"""
Copy a history dataset into this library.
:type hda: :class:`~.HistoryDatasetAssociation`
:param hda: history dataset to copy into the library
See :meth:`.upload_data` for info on other params.
"""
fid = self._pre_upload(folder)
res = self.gi.gi.libraries.copy_from_dataset(
self.id, hda.id, folder_id=fid, message=message)
self.refresh()
return self.get_dataset(res['library_dataset_id'])
def create_folder(self, name, description=None, base_folder=None):
"""
Create a folder in this library.
:type name: str
:param name: folder name
:type description: str
:param description: optional folder description
:type base_folder: :class:`~.Folder`
:param base_folder: parent folder, or ``None`` to create in the root
folder
:rtype: :class:`~.Folder`
:return: the folder just created
"""
bfid = None if base_folder is None else base_folder.id
res = self.gi.gi.libraries.create_folder(
self.id, name, description=description, base_folder_id=bfid)
self.refresh()
return self.get_folder(res[0]['id'])
def get_folder(self, f_id):
"""
Retrieve the folder corresponding to the given id.
:rtype: :class:`~.Folder`
:return: the folder corresponding to ``f_id``
"""
f_dict = self.gi.gi.libraries.show_folder(self.id, f_id)
return Folder(f_dict, self, gi=self.gi)
@property
def root_folder(self):
"""
The root folder of this library.
:rtype: :class:`~.Folder`
:return: the root folder of this library
"""
return self.get_folder(self.gi.gi.libraries._get_root_folder_id(self.id))
class Folder(Wrapper):
"""
Maps to a folder in a Galaxy library.
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'deleted',
'description',
'item_count',
'name',
)
def __init__(self, f_dict, container, gi=None):
super().__init__(f_dict, gi=gi)
object.__setattr__(self, 'container', container)
@property
def parent(self):
"""
The parent folder of this folder. The parent of the root folder is
``None``.
:rtype: :class:`~.Folder`
:return: the parent of this folder
"""
if self._cached_parent is None:
object.__setattr__(self,
'_cached_parent',
self._get_parent())
return self._cached_parent
def _get_parent(self):
"""
Return the parent folder of this folder.
"""
parent_id = self.wrapped['parent_id']
if parent_id is None:
return None
return self.container.get_folder(parent_id)
def refresh(self):
"""
Re-fetch the attributes pertaining to this object.
Returns: self
"""
f_dict = self.gi.gi.libraries.show_folder(self.container.id, self.id)
self.__init__(f_dict, self.container, gi=self.gi)
return self
class Tool(Wrapper):
"""
Maps to a Galaxy tool.
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'name',
'version',
)
POLLING_INTERVAL = 10 # for output state monitoring
def run(self, inputs, history, wait=False,
polling_interval=POLLING_INTERVAL):
"""
Execute this tool in the given history with inputs from dict
``inputs``.
:type inputs: dict
:param inputs: dictionary of input datasets and parameters for
the tool (see below)
:type history: :class:`History`
:param history: the history where to execute the tool
:type wait: bool
:param wait: whether to wait while the returned datasets are
in a pending state
:type polling_interval: float
:param polling_interval: polling interval in seconds
:rtype: list of :class:`HistoryDatasetAssociation`
:return: list of output datasets
The ``inputs`` dict should contain input datasets and parameters
in the (largely undocumented) format used by the Galaxy API.
Some examples can be found in `Galaxy's API test suite
<https://github.com/galaxyproject/galaxy/blob/dev/lib/galaxy_test/api/test_tools.py>`_.
The value of an input dataset can also be a :class:`Dataset`
object, which will be automatically converted to the needed
format.
"""
for k, v in inputs.items():
if isinstance(v, Dataset):
inputs[k] = {'src': v.SRC, 'id': v.id}
out_dict = self.gi.gi.tools.run_tool(history.id, self.id, inputs)
outputs = [history.get_dataset(_['id']) for _ in out_dict['outputs']]
if wait:
self.gi._wait_datasets(outputs, polling_interval=polling_interval)
return outputs
class Job(Wrapper):
"""
Maps to a Galaxy job.
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + ('state',)
@abstractclass
class DatasetContainerPreview(Wrapper):
"""
Abstract base class for dataset container (history and library) 'previews'.
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'deleted',
'name',
)
class LibraryPreview(DatasetContainerPreview):
"""
Models Galaxy library 'previews'.
Instances of this class wrap dictionaries obtained by getting
``/api/libraries`` from Galaxy.
"""
class HistoryPreview(DatasetContainerPreview):
"""
Models Galaxy history 'previews'.
Instances of this class wrap dictionaries obtained by getting
``/api/histories`` from Galaxy.
"""
BASE_ATTRS = DatasetContainerPreview.BASE_ATTRS + (
'annotation',
'published',
'purged',
'tags',
)
class WorkflowPreview(Wrapper):
"""
Models Galaxy workflow 'previews'.
Instances of this class wrap dictionaries obtained by getting
``/api/workflows`` from Galaxy.
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'deleted',
'latest_workflow_uuid',
'name',
'number_of_steps',
'owner',
'published',
'show_in_tool_panel',
'tags',
)
class InvocationPreview(Wrapper):
"""
Models Galaxy invocation 'previews'.
Instances of this class wrap dictionaries obtained by getting
``/api/invocations`` from Galaxy.
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'history_id',
'id',
'state',
'update_time',
'uuid',
'workflow_id',
)
class JobPreview(Wrapper):
"""
Models Galaxy job 'previews'.
Instances of this class wrap dictionaries obtained by getting
``/api/jobs`` from Galaxy.
"""
BASE_ATTRS = Wrapper.BASE_ATTRS + ('state',)
| 33.434955 | 210 | 0.612319 |
import abc
import json
from collections.abc import (
Iterable,
Mapping,
Sequence,
)
from typing import Tuple
import bioblend
from bioblend.util import abstractclass
__all__ = (
'Wrapper',
'Step',
'Workflow',
'LibraryContentInfo',
'HistoryContentInfo',
'DatasetContainer',
'History',
'Library',
'Folder',
'Dataset',
'HistoryDatasetAssociation',
'DatasetCollection',
'HistoryDatasetCollectionAssociation',
'LibraryDatasetDatasetAssociation',
'LibraryDataset',
'Tool',
'Job',
'LibraryPreview',
'HistoryPreview',
'WorkflowPreview',
)
@abstractclass
class Wrapper:
BASE_ATTRS: Tuple[str, ...] = ('id', )
def __init__(self, wrapped, parent=None, gi=None):
if not isinstance(wrapped, Mapping):
raise TypeError('wrapped object must be a mapping type')
try:
dumped = json.dumps(wrapped)
except (TypeError, ValueError):
raise ValueError('wrapped object must be JSON-serializable')
object.__setattr__(self, 'wrapped', json.loads(dumped))
for k in self.BASE_ATTRS:
object.__setattr__(self, k, self.wrapped.get(k))
object.__setattr__(self, '_cached_parent', parent)
object.__setattr__(self, 'is_modified', False)
object.__setattr__(self, 'gi', gi)
@property
def parent(self):
return self._cached_parent
@property
def is_mapped(self):
return self.id is not None
def unmap(self):
object.__setattr__(self, 'id', None)
def clone(self):
return self.__class__(self.wrapped)
def touch(self):
object.__setattr__(self, 'is_modified', True)
if self.parent:
self.parent.touch()
def to_json(self):
return json.dumps(self.wrapped)
@classmethod
def from_json(cls, jdef):
return cls(json.loads(jdef))
def __setattr__(self, name, value):
if name not in self.wrapped:
raise AttributeError("can't set attribute")
else:
self.wrapped[name] = value
object.__setattr__(self, name, value)
self.touch()
def __repr__(self):
return f"{self.__class__.__name__}({self.wrapped!r})"
class Step(Wrapper):
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'input_steps',
'name',
'tool_id',
'tool_inputs',
'tool_version',
'type',
)
def __init__(self, step_dict, parent):
super().__init__(step_dict, parent=parent, gi=parent.gi)
try:
stype = step_dict['type']
except KeyError:
raise ValueError('not a step dict')
if stype not in {'data_collection_input', 'data_input', 'parameter_input', 'pause', 'subworkflow', 'tool'}:
raise ValueError(f"Unknown step type: {stype!r}")
class InvocationStep(Wrapper):
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'action',
'job_id',
'order_index',
'state',
'update_time',
'workflow_step_id',
'workflow_step_label',
'workflow_step_uuid',
)
class Workflow(Wrapper):
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'deleted',
'inputs',
'latest_workflow_uuid',
'name',
'owner',
'published',
'steps',
'tags',
)
POLLING_INTERVAL = 10 # for output state monitoring
def __init__(self, wf_dict, gi=None):
super().__init__(wf_dict, gi=gi)
missing_ids = []
if gi:
tools_list_by_id = [t.id for t in gi.tools.get_previews()]
else:
tools_list_by_id = []
tool_labels_to_ids = {}
for k, v in self.steps.items():
# convert step ids to str for consistency with outer keys
v['id'] = str(v['id'])
for i in v['input_steps'].values():
i['source_step'] = str(i['source_step'])
step = Step(v, self)
self.steps[k] = step
if step.type == 'tool':
if not step.tool_inputs or step.tool_id not in tools_list_by_id:
missing_ids.append(k)
tool_labels_to_ids.setdefault(step.tool_id, set()).add(step.id)
input_labels_to_ids = {}
for id_, d in self.inputs.items():
input_labels_to_ids.setdefault(d['label'], set()).add(id_)
object.__setattr__(self, 'input_labels_to_ids', input_labels_to_ids)
object.__setattr__(self, 'tool_labels_to_ids', tool_labels_to_ids)
dag, inv_dag = self._get_dag()
heads, tails = set(dag), set(inv_dag)
object.__setattr__(self, 'dag', dag)
object.__setattr__(self, 'inv_dag', inv_dag)
object.__setattr__(self, 'source_ids', heads - tails)
assert set(self.inputs) == self.data_collection_input_ids | self.data_input_ids | self.parameter_input_ids, \
f"inputs is {self.inputs!r}, while data_collection_input_ids is {self.data_collection_input_ids!r}, data_input_ids is {self.data_input_ids!r} and parameter_input_ids is {self.parameter_input_ids!r}"
object.__setattr__(self, 'sink_ids', tails - heads)
object.__setattr__(self, 'missing_ids', missing_ids)
def _get_dag(self):
dag, inv_dag = {}, {}
for s in self.steps.values():
for i in s.input_steps.values():
head, tail = i['source_step'], s.id
dag.setdefault(head, set()).add(tail)
inv_dag.setdefault(tail, set()).add(head)
return dag, inv_dag
def sorted_step_ids(self):
ids = []
source_ids = self.source_ids.copy()
inv_dag = {k: v.copy() for k, v in self.inv_dag.items()}
while source_ids:
head = source_ids.pop()
ids.append(head)
for tail in self.dag.get(head, []):
incoming = inv_dag[tail]
incoming.remove(head)
if not incoming:
source_ids.add(tail)
return ids
@property
def data_input_ids(self):
return {id_ for id_, s in self.steps.items() if s.type == 'data_input'}
@property
def data_collection_input_ids(self):
return {id_ for id_, s in self.steps.items() if s.type == 'data_collection_input'}
@property
def parameter_input_ids(self):
return {id_ for id_, s in self.steps.items() if s.type == 'parameter_input'}
@property
def tool_ids(self):
return {id_ for id_, s in self.steps.items() if s.type == 'tool'}
@property
def input_labels(self):
return set(self.input_labels_to_ids)
@property
def is_runnable(self):
return not self.missing_ids
def convert_input_map(self, input_map):
m = {}
for label, slot_ids in self.input_labels_to_ids.items():
datasets = input_map.get(label, [])
if not isinstance(datasets, Iterable):
datasets = [datasets]
if len(datasets) < len(slot_ids):
raise RuntimeError(f'not enough datasets for "{label}"')
for id_, ds in zip(slot_ids, datasets):
m[id_] = {'id': ds.id, 'src': ds.SRC}
return m
def preview(self):
getf = self.gi.workflows.get_previews
try:
p = [_ for _ in getf(published=True) if _.id == self.id][0]
except IndexError:
raise ValueError(f"no object for id {self.id}")
return p
def run(self, input_map=None, history='', params=None, import_inputs=False,
replacement_params=None, wait=False,
polling_interval=POLLING_INTERVAL, break_on_error=True):
if not self.is_mapped:
raise RuntimeError('workflow is not mapped to a Galaxy object')
if not self.is_runnable:
missing_tools_str = ', '.join(f"{self.steps[step_id].tool_id}[{step_id}]" for step_id in self.missing_ids)
raise RuntimeError(f"workflow has missing tools: {missing_tools_str}")
kwargs = {
'dataset_map': self.convert_input_map(input_map or {}),
'params': params,
'import_inputs_to_history': import_inputs,
'replacement_params': replacement_params,
}
if isinstance(history, History):
try:
kwargs['history_id'] = history.id
except AttributeError:
raise RuntimeError('history does not have an id')
elif isinstance(history, str):
kwargs['history_name'] = history
else:
raise TypeError(
'history must be either a history wrapper or a string')
res = self.gi.gi.workflows.run_workflow(self.id, **kwargs)
# res structure: {'history': HIST_ID, 'outputs': [CI_ID, CI_ID, ...]}
out_hist = self.gi.histories.get(res['history'])
content_infos_dict = {ci.id: ci for ci in out_hist.content_infos}
outputs = []
for output_id in res['outputs']:
if content_infos_dict[output_id].type == 'file':
outputs.append(out_hist.get_dataset(output_id))
elif content_infos_dict[output_id].type == 'collection':
outputs.append(out_hist.get_dataset_collection(output_id))
if wait:
self.gi._wait_datasets(outputs, polling_interval=polling_interval,
break_on_error=break_on_error)
return outputs, out_hist
def export(self):
return self.gi.gi.workflows.export_workflow_dict(self.id)
def delete(self):
self.gi.workflows.delete(id_=self.id)
self.unmap()
def invoke(self, inputs=None, params=None, history=None,
import_inputs_to_history=None, replacement_params=None,
allow_tool_state_corrections=True, inputs_by=None,
parameters_normalized=False):
inv_dict = self.gi.gi.workflows.invoke_workflow(
workflow_id=self.id,
inputs=inputs,
params=params,
history_id=history.id,
import_inputs_to_history=import_inputs_to_history,
replacement_params=replacement_params,
allow_tool_state_corrections=allow_tool_state_corrections,
inputs_by=inputs_by,
parameters_normalized=parameters_normalized
)
return self.gi.invocations.get(inv_dict['id'])
class Invocation(Wrapper):
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'history_id',
'inputs',
'state',
'steps',
'update_time',
'uuid',
'workflow_id',
)
def __init__(self, inv_dict, gi=None):
super().__init__(inv_dict, gi=gi)
self.steps = [InvocationStep(step, self) for step in self.steps]
self.inputs = [{**v, 'label': k} for k, v in self.inputs.items()]
def sorted_step_ids(self):
return [step.id for step in sorted(self.steps, key=lambda step: step.order_index)]
def step_states(self):
return {step.state for step in self.steps}
def number_of_steps(self):
return len(self.steps)
def sorted_steps_by(self, indices=None, states=None, step_ids=None):
steps = self.steps
if indices is not None:
steps = filter(lambda step: step.order_index in indices, steps)
if states is not None:
steps = filter(lambda step: step.state in states, steps)
if step_ids is not None:
steps = filter(lambda step: step.id in step_ids, steps)
return sorted(steps, key=lambda step: step.order_index)
def cancel(self):
inv_dict = self.gi.gi.invocations.cancel_invocation(self.id)
self.__init__(inv_dict, gi=self.gi)
def refresh(self):
inv_dict = self.gi.gi.invocations.show_invocation(self.id)
self.__init__(inv_dict, gi=self.gi)
def run_step_actions(self, steps, actions):
if not len(steps) == len(actions):
raise RuntimeError(f'Different number of ``steps`` ({len(steps)}) and ``actions`` ({len(actions)}) in ``{self}.run_step_actions()``')
step_dict_list = [self.gi.gi.invocations.run_invocation_step_action(self.id, step.id, action) for step, action in zip(steps, actions)]
for step, step_dict in zip(steps, step_dict_list):
step.__init__(step_dict, parent=self)
def summary(self):
return self.gi.gi.invocations.get_invocation_summary(self.id)
def step_jobs_summary(self):
return self.gi.gi.invocations.get_invocation_step_jobs_summary(self.id)
def report(self):
return self.gi.gi.invocations.get_invocation_report(self.id)
def save_report_pdf(self, file_path, chunk_size=bioblend.CHUNK_SIZE):
self.gi.gi.invocations.get_invocation_report_pdf(self.id, file_path, chunk_size)
def biocompute_object(self):
return self.gi.gi.invocations.get_invocation_biocompute_object(self.id)
def wait(self, maxwait=12000, interval=3, check=True):
inv_dict = self.gi.gi.invocations.wait_for_invocation(self.id, maxwait=maxwait, interval=interval, check=check)
self.__init__(inv_dict, gi=self.gi)
class Dataset(Wrapper, metaclass=abc.ABCMeta):
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'data_type',
'file_ext',
'file_name',
'file_size',
'genome_build',
'misc_info',
'name',
'state',
)
POLLING_INTERVAL = 1 # for state monitoring
def __init__(self, ds_dict, container, gi=None):
super().__init__(ds_dict, gi=gi)
object.__setattr__(self, 'container', container)
@property
@abc.abstractmethod
def _stream_url(self):
pass
def get_stream(self, chunk_size=bioblend.CHUNK_SIZE):
kwargs = {'stream': True}
if isinstance(self, LibraryDataset):
kwargs['params'] = {'ld_ids%5B%5D': self.id}
r = self.gi.gi.make_get_request(self._stream_url, **kwargs)
if isinstance(self, LibraryDataset) and r.status_code == 500:
# compatibility with older Galaxy releases
kwargs['params'] = {'ldda_ids%5B%5D': self.id}
r = self.gi.gi.make_get_request(self._stream_url, **kwargs)
r.raise_for_status()
return r.iter_content(chunk_size) # FIXME: client can't close r
def peek(self, chunk_size=bioblend.CHUNK_SIZE):
try:
return next(self.get_stream(chunk_size=chunk_size))
except StopIteration:
return b''
def download(self, file_object, chunk_size=bioblend.CHUNK_SIZE):
for chunk in self.get_stream(chunk_size=chunk_size):
file_object.write(chunk)
def get_contents(self, chunk_size=bioblend.CHUNK_SIZE):
return b''.join(self.get_stream(chunk_size=chunk_size))
def refresh(self):
gi_client = getattr(self.gi.gi, self.container.API_MODULE)
ds_dict = gi_client.show_dataset(self.container.id, self.id)
self.__init__(ds_dict, self.container, self.gi)
return self
def wait(self, polling_interval=POLLING_INTERVAL, break_on_error=True):
self.gi._wait_datasets([self], polling_interval=polling_interval,
break_on_error=break_on_error)
class HistoryDatasetAssociation(Dataset):
BASE_ATTRS = Dataset.BASE_ATTRS + ('annotation', 'deleted', 'purged', 'tags', 'visible')
SRC = 'hda'
@property
def _stream_url(self):
base_url = self.gi.gi.histories._make_url(module_id=self.container.id, contents=True)
return f"{base_url}/{self.id}/display"
def update(self, **kwds):
res = self.gi.gi.histories.update_dataset(self.container.id, self.id, **kwds)
self.container.refresh()
self.__init__(res, self.container, gi=self.gi)
return self
def delete(self, purge=False):
self.gi.gi.histories.delete_dataset(self.container.id, self.id, purge=purge)
self.container.refresh()
self.refresh()
class DatasetCollection(Wrapper, metaclass=abc.ABCMeta):
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'collection_type',
'deleted',
'name',
'state',
)
def __init__(self, dsc_dict, container, gi=None):
super().__init__(dsc_dict, gi=gi)
object.__setattr__(self, 'container', container)
def refresh(self):
gi_client = getattr(self.gi.gi, self.container.API_MODULE)
dsc_dict = gi_client.show_dataset_collection(self.container.id, self.id)
self.__init__(dsc_dict, self.container, self.gi)
return self
@abc.abstractmethod
def delete(self):
pass
class HistoryDatasetCollectionAssociation(DatasetCollection):
BASE_ATTRS = DatasetCollection.BASE_ATTRS + ('tags', 'visible', 'elements')
SRC = 'hdca'
def delete(self):
self.gi.gi.histories.delete_dataset_collection(self.container.id, self.id)
self.container.refresh()
self.refresh()
@abstractclass
class LibRelatedDataset(Dataset):
@property
def _stream_url(self):
base_url = self.gi.gi.libraries._make_url()
return f"{base_url}/datasets/download/uncompressed"
class LibraryDatasetDatasetAssociation(LibRelatedDataset):
BASE_ATTRS = LibRelatedDataset.BASE_ATTRS + ('deleted',)
SRC = 'ldda'
class LibraryDataset(LibRelatedDataset):
SRC = 'ld'
def delete(self, purged=False):
self.gi.gi.libraries.delete_library_dataset(
self.container.id, self.id, purged=purged)
self.container.refresh()
self.refresh()
def update(self, **kwds):
res = self.gi.gi.libraries.update_library_dataset(self.id, **kwds)
self.container.refresh()
self.__init__(res, self.container, gi=self.gi)
return self
@abstractclass
class ContentInfo(Wrapper):
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'name',
'type',
)
class LibraryContentInfo(ContentInfo):
class HistoryContentInfo(ContentInfo):
BASE_ATTRS = ContentInfo.BASE_ATTRS + ('deleted', 'state', 'visible')
class DatasetContainer(Wrapper, metaclass=abc.ABCMeta):
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'deleted',
'name',
)
def __init__(self, c_dict, content_infos=None, gi=None):
super().__init__(c_dict, gi=gi)
if content_infos is None:
content_infos = []
object.__setattr__(self, 'content_infos', content_infos)
object.__setattr__(self, 'obj_gi_client', getattr(self.gi, self.API_MODULE))
@property
@abc.abstractmethod
def API_MODULE(self):
pass
@property
def dataset_ids(self):
return [_.id for _ in self.content_infos if _.type == 'file']
def preview(self):
getf = self.obj_gi_client.get_previews
try:
p = [_ for _ in getf() if _.id == self.id][0]
except IndexError:
try:
p = [_ for _ in getf(deleted=True) if _.id == self.id][0]
except IndexError:
raise ValueError(f"no object for id {self.id}")
return p
def refresh(self):
fresh = self.obj_gi_client.get(self.id)
self.__init__(
fresh.wrapped, content_infos=fresh.content_infos, gi=self.gi)
return self
def get_dataset(self, ds_id):
gi_client = getattr(self.gi.gi, self.API_MODULE)
ds_dict = gi_client.show_dataset(self.id, ds_id)
return self.DS_TYPE(ds_dict, self, gi=self.gi)
def get_datasets(self, name=None):
if name is None:
ds_ids = self.dataset_ids
else:
ds_ids = [_.id for _ in self.content_infos if _.name == name]
return [self.get_dataset(_) for _ in ds_ids]
class History(DatasetContainer):
BASE_ATTRS = DatasetContainer.BASE_ATTRS + ('annotation', 'published', 'state', 'state_ids', 'state_details', 'tags')
DS_TYPE = HistoryDatasetAssociation
DSC_TYPE = HistoryDatasetCollectionAssociation
CONTENT_INFO_TYPE = HistoryContentInfo
API_MODULE = 'histories'
def update(self, **kwds):
self.gi.gi.histories.update_history(self.id, **kwds)
self.refresh()
return self
def delete(self, purge=False):
self.gi.histories.delete(id_=self.id, purge=purge)
self.refresh()
self.unmap()
def import_dataset(self, lds):
if not self.is_mapped:
raise RuntimeError('history is not mapped to a Galaxy object')
if not isinstance(lds, LibraryDataset):
raise TypeError('lds is not a LibraryDataset')
res = self.gi.gi.histories.upload_dataset_from_library(self.id, lds.id)
if not isinstance(res, Mapping):
raise RuntimeError(
f"upload_dataset_from_library: unexpected reply: {res!r}"
)
self.refresh()
return self.get_dataset(res['id'])
def upload_file(self, path, **kwargs):
out_dict = self.gi.gi.tools.upload_file(path, self.id, **kwargs)
self.refresh()
return self.get_dataset(out_dict['outputs'][0]['id'])
upload_dataset = upload_file
def upload_from_ftp(self, path, **kwargs):
out_dict = self.gi.gi.tools.upload_from_ftp(path, self.id, **kwargs)
self.refresh()
return self.get_dataset(out_dict['outputs'][0]['id'])
def paste_content(self, content, **kwargs):
out_dict = self.gi.gi.tools.paste_content(content, self.id, **kwargs)
self.refresh()
return self.get_dataset(out_dict['outputs'][0]['id'])
def export(self, gzip=True, include_hidden=False, include_deleted=False,
wait=False, maxwait=None):
return self.gi.gi.histories.export_history(
self.id, gzip=gzip, include_hidden=include_hidden,
include_deleted=include_deleted, wait=wait, maxwait=maxwait)
def download(self, jeha_id, outf, chunk_size=bioblend.CHUNK_SIZE):
return self.gi.gi.histories.download_history(
self.id, jeha_id, outf, chunk_size=chunk_size)
def create_dataset_collection(self, collection_description):
dataset_collection = self.gi.gi.histories.create_dataset_collection(self.id, collection_description)
self.refresh()
return self.get_dataset_collection(dataset_collection['id'])
def get_dataset_collection(self, dsc_id):
dsc_dict = self.gi.gi.histories.show_dataset_collection(self.id, dsc_id)
return self.DSC_TYPE(dsc_dict, self, gi=self.gi)
class Library(DatasetContainer):
BASE_ATTRS = DatasetContainer.BASE_ATTRS + ('description', 'synopsis')
DS_TYPE = LibraryDataset
CONTENT_INFO_TYPE = LibraryContentInfo
API_MODULE = 'libraries'
@property
def folder_ids(self):
return [_.id for _ in self.content_infos if _.type == 'folder']
def delete(self):
self.gi.libraries.delete(id_=self.id)
self.refresh()
self.unmap()
def _pre_upload(self, folder):
if not self.is_mapped:
raise RuntimeError('library is not mapped to a Galaxy object')
return None if folder is None else folder.id
def upload_data(self, data, folder=None, **kwargs):
fid = self._pre_upload(folder)
res = self.gi.gi.libraries.upload_file_contents(
self.id, data, folder_id=fid, **kwargs)
self.refresh()
return self.get_dataset(res[0]['id'])
def upload_from_url(self, url, folder=None, **kwargs):
fid = self._pre_upload(folder)
res = self.gi.gi.libraries.upload_file_from_url(
self.id, url, folder_id=fid, **kwargs)
self.refresh()
return self.get_dataset(res[0]['id'])
def upload_from_local(self, path, folder=None, **kwargs):
fid = self._pre_upload(folder)
res = self.gi.gi.libraries.upload_file_from_local_path(
self.id, path, folder_id=fid, **kwargs)
self.refresh()
return self.get_dataset(res[0]['id'])
def upload_from_galaxy_fs(self, paths, folder=None, link_data_only=None, **kwargs):
fid = self._pre_upload(folder)
if isinstance(paths, str):
paths = (paths,)
paths = '\n'.join(paths)
res = self.gi.gi.libraries.upload_from_galaxy_filesystem(
self.id, paths, folder_id=fid, link_data_only=link_data_only,
**kwargs)
if res is None:
raise RuntimeError('upload_from_galaxy_filesystem: no reply')
if not isinstance(res, Sequence):
raise RuntimeError(
f"upload_from_galaxy_filesystem: unexpected reply: {res!r}"
)
new_datasets = [
self.get_dataset(ds_info['id']) for ds_info in res
]
self.refresh()
return new_datasets
def copy_from_dataset(self, hda, folder=None, message=''):
fid = self._pre_upload(folder)
res = self.gi.gi.libraries.copy_from_dataset(
self.id, hda.id, folder_id=fid, message=message)
self.refresh()
return self.get_dataset(res['library_dataset_id'])
def create_folder(self, name, description=None, base_folder=None):
bfid = None if base_folder is None else base_folder.id
res = self.gi.gi.libraries.create_folder(
self.id, name, description=description, base_folder_id=bfid)
self.refresh()
return self.get_folder(res[0]['id'])
def get_folder(self, f_id):
f_dict = self.gi.gi.libraries.show_folder(self.id, f_id)
return Folder(f_dict, self, gi=self.gi)
@property
def root_folder(self):
return self.get_folder(self.gi.gi.libraries._get_root_folder_id(self.id))
class Folder(Wrapper):
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'deleted',
'description',
'item_count',
'name',
)
def __init__(self, f_dict, container, gi=None):
super().__init__(f_dict, gi=gi)
object.__setattr__(self, 'container', container)
@property
def parent(self):
if self._cached_parent is None:
object.__setattr__(self,
'_cached_parent',
self._get_parent())
return self._cached_parent
def _get_parent(self):
parent_id = self.wrapped['parent_id']
if parent_id is None:
return None
return self.container.get_folder(parent_id)
def refresh(self):
f_dict = self.gi.gi.libraries.show_folder(self.container.id, self.id)
self.__init__(f_dict, self.container, gi=self.gi)
return self
class Tool(Wrapper):
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'name',
'version',
)
POLLING_INTERVAL = 10 # for output state monitoring
def run(self, inputs, history, wait=False,
polling_interval=POLLING_INTERVAL):
for k, v in inputs.items():
if isinstance(v, Dataset):
inputs[k] = {'src': v.SRC, 'id': v.id}
out_dict = self.gi.gi.tools.run_tool(history.id, self.id, inputs)
outputs = [history.get_dataset(_['id']) for _ in out_dict['outputs']]
if wait:
self.gi._wait_datasets(outputs, polling_interval=polling_interval)
return outputs
class Job(Wrapper):
BASE_ATTRS = Wrapper.BASE_ATTRS + ('state',)
@abstractclass
class DatasetContainerPreview(Wrapper):
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'deleted',
'name',
)
class LibraryPreview(DatasetContainerPreview):
class HistoryPreview(DatasetContainerPreview):
BASE_ATTRS = DatasetContainerPreview.BASE_ATTRS + (
'annotation',
'published',
'purged',
'tags',
)
class WorkflowPreview(Wrapper):
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'deleted',
'latest_workflow_uuid',
'name',
'number_of_steps',
'owner',
'published',
'show_in_tool_panel',
'tags',
)
class InvocationPreview(Wrapper):
BASE_ATTRS = Wrapper.BASE_ATTRS + (
'history_id',
'id',
'state',
'update_time',
'uuid',
'workflow_id',
)
class JobPreview(Wrapper):
BASE_ATTRS = Wrapper.BASE_ATTRS + ('state',)
| true | true |
f719fecd156687882e482eac8d27cf8aaffcf379 | 177 | py | Python | python/positive.py | scienceacademy/apcsp_2021 | 11efd0216d3042e556e726268c622d8f0d568c18 | [
"MIT"
] | null | null | null | python/positive.py | scienceacademy/apcsp_2021 | 11efd0216d3042e556e726268c622d8f0d568c18 | [
"MIT"
] | null | null | null | python/positive.py | scienceacademy/apcsp_2021 | 11efd0216d3042e556e726268c622d8f0d568c18 | [
"MIT"
] | null | null | null | def main():
n = get_positive_int()
def get_positive_int():
while True:
n = int(input("Enter a positive number: "))
if n > 0:
return n
main() | 19.666667 | 51 | 0.542373 | def main():
n = get_positive_int()
def get_positive_int():
while True:
n = int(input("Enter a positive number: "))
if n > 0:
return n
main() | true | true |
f719fee29c71e4ea44c3434fb019c8f5e47ff986 | 16,096 | py | Python | tests/test_brew_views.py | zgoda/brewlog | 13a930b328f81d01a2be9aca07d3b14703b80faa | [
"BSD-3-Clause"
] | 3 | 2019-03-11T04:30:06.000Z | 2020-01-26T03:21:52.000Z | tests/test_brew_views.py | zgoda/brewlog | 13a930b328f81d01a2be9aca07d3b14703b80faa | [
"BSD-3-Clause"
] | 23 | 2019-02-06T20:37:37.000Z | 2020-06-01T07:08:35.000Z | tests/test_brew_views.py | zgoda/brewlog | 13a930b328f81d01a2be9aca07d3b14703b80faa | [
"BSD-3-Clause"
] | null | null | null | import datetime
import pytest
from flask import url_for
from brewlog.ext import db
from brewlog.models import Brew
from . import BrewlogTests
class BrewViewTests(BrewlogTests):
@pytest.fixture(autouse=True)
def set_up(self, user_factory, brewery_factory):
self.public_user = user_factory(
first_name='John', last_name='Public'
)
self.public_brewery = brewery_factory(
name='public brewery', brewer=self.public_user
)
self.hidden_user = user_factory(
is_public=False, first_name='Rebecca', last_name='Hidden'
)
self.hidden_brewery = brewery_factory(
name='hidden brewery', brewer=self.hidden_user
)
@pytest.mark.usefixtures('client_class')
class TestBrewDetailsView(BrewViewTests):
def url(self, brew):
return url_for('brew.details', brew_id=brew.id)
def test_get_404(self):
rv = self.client.get(url_for('brew.details', brew_id=666))
assert rv.status_code == 404
def test_get_no_access_hidden_brewery(self, brew_factory):
brew = brew_factory(brewery=self.hidden_brewery, name='hb1')
self.login(self.public_user.email)
rv = self.client.get(self.url(brew))
assert rv.status_code == 404
def test_get_no_access_hidden_brew(self, brew_factory):
brew = brew_factory(
brewery=self.public_brewery, is_public=False, name='hb1'
)
self.login(self.hidden_user.email)
rv = self.client.get(self.url(brew))
assert rv.status_code == 404
def test_post_anon(self, brew_factory):
brew = brew_factory(
brewery=self.public_brewery, name='pb1', code='xxx'
)
data = {
'name': brew.name,
'brewery': brew.brewery.id,
'code': '001',
'carbonation_level': 'low',
'carbonation_type': 'bottles with priming',
}
rv = self.client.post(self.url(brew), data=data)
assert rv.status_code == 403
def test_post_non_brewer(self, brew_factory):
brew = brew_factory(
brewery=self.public_brewery, name='pb1', code='xxx'
)
self.login(self.hidden_user.email)
data = {
'name': brew.name,
'brewery': brew.brewery.id,
'code': '001',
'carbonation_level': 'low',
'carbonation_type': 'bottles with priming',
}
rv = self.client.post(self.url(brew), data=data, follow_redirects=True)
assert rv.status_code == 403
def test_post_data_ok(self, brew_factory):
brew = brew_factory(
brewery=self.public_brewery, name='pb1', code='xxx'
)
self.login(self.public_user.email)
data = {
'name': brew.name,
'brewery': brew.brewery.id,
'code': '001',
'carbonation_level': 'low',
'carbonation_type': 'bottles with priming',
}
rv = self.client.post(self.url(brew), data=data, follow_redirects=True)
assert rv.status_code == 200
assert 'data updated' in rv.text
assert Brew.query.get(brew.id).code == data['code']
def test_post_data_missing(self, brew_factory):
brew = brew_factory(brewery=self.public_brewery, name='pb1', code='xxx')
self.login(self.public_user.email)
data = {
'name': None,
'brewery': brew.brewery.id,
'code': '001',
'carbonation_level': 'low',
'carbonation_type': 'bottles with priming',
}
rv = self.client.post(self.url(brew), data=data, follow_redirects=True)
assert rv.status_code == 200
assert 'field is required' in rv.text
assert 'data updated' not in rv.text
def test_state_form_present(self, brew_factory):
brewed = datetime.date(1992, 12, 4)
bottled = datetime.date(1993, 1, 12)
taped = datetime.date(1993, 3, 8)
brew = brew_factory(
brewery=self.public_brewery, name='pb1', date_brewed=brewed,
bottling_date=bottled, tapped=taped
)
self.login(self.public_user.email)
rv = self.client.get(self.url(brew))
assert url_for('brew.chgstate', brew_id=brew.id) in rv.text
def test_attenuation_display_none(self, brew_factory):
brew = brew_factory(brewery=self.public_brewery, name='pb1')
self.login(self.public_user.email)
rv = self.client.get(self.url(brew))
assert 'apparent' not in rv.text
@pytest.mark.usefixtures('client_class')
class TestBrewDetailsNavigation(BrewViewTests):
def url(self, brew):
return url_for('brew.details', brew_id=brew.id)
@pytest.mark.parametrize('anon', [
False, True,
], ids=['authenticated', 'anonymous'])
def test_brew_navigation_non_owner(self, anon, brew_factory):
p2_brew = brew_factory(brewery=self.public_brewery)
p1_brew = brew_factory(brewery=self.public_brewery, is_public=False)
brew = brew_factory(brewery=self.public_brewery)
n1_brew = brew_factory(brewery=self.public_brewery, is_public=False)
n2_brew = brew_factory(brewery=self.public_brewery)
if not anon:
self.login(self.hidden_user.email)
rv = self.client.get(self.url(brew))
assert f'href="{self.url(p2_brew)}"' in rv.text
assert f'href="{self.url(p1_brew)}"' not in rv.text
assert f'href="{self.url(n1_brew)}"' not in rv.text
assert f'href="{self.url(n2_brew)}"' in rv.text
def test_brew_navigation_owner(self, brew_factory):
p1_brew = brew_factory(brewery=self.public_brewery, is_public=False)
brew = brew_factory(brewery=self.public_brewery)
n1_brew = brew_factory(brewery=self.public_brewery, is_public=False)
self.login(self.public_user.email)
rv = self.client.get(self.url(brew))
assert f'href="{self.url(p1_brew)}"' in rv.text
assert f'href="{self.url(n1_brew)}"' in rv.text
@pytest.mark.usefixtures('client_class')
class TestBrewListView(BrewViewTests):
@pytest.fixture(autouse=True)
def set_up2(self):
self.url = url_for('brew.all')
def details_url(self, brew):
return url_for('brew.details', brew_id=brew.id)
def delete_url(self, brew):
return url_for('brew.delete', brew_id=brew.id)
def test_anon(self, brew_factory):
hb_hb = brew_factory(brewery=self.hidden_brewery, is_public=False)
pb_hb = brew_factory(brewery=self.hidden_brewery, is_public=True)
pb_pb = brew_factory(brewery=self.public_brewery, is_public=True)
hb_pb = brew_factory(brewery=self.public_brewery, is_public=False)
rv = self.client.get(self.url)
assert url_for('brew.details', brew_id=pb_pb.id) in rv.text
assert url_for('brew.delete', brew_id=pb_pb.id) not in rv.text
assert url_for('brew.details', brew_id=hb_hb.id) not in rv.text
assert url_for('brew.details', brew_id=pb_hb.id) not in rv.text
assert url_for('brew.details', brew_id=hb_pb.id) not in rv.text
def test_authenticated(self, user_factory, brewery_factory, brew_factory):
user2 = user_factory(first_name='Ivory', last_name='Tower')
brewery2 = brewery_factory(brewer=user2, name='brewery2')
pb1 = brew_factory(brewery=self.public_brewery)
pb2 = brew_factory(brewery=brewery2)
hb1 = brew_factory(name='hidden1', brewery=self.public_brewery, is_public=False)
hb2 = brew_factory(name='hidden2', brewery=brewery2, is_public=False)
hb3 = brew_factory(name='hidden3', brewery=self.hidden_brewery)
hb4 = brew_factory(name='hidden4', brewery=self.hidden_brewery, is_public=False)
self.login(email=self.public_user.email)
rv = self.client.get(self.url)
assert f'href="{self.details_url(pb1)}"' in rv.text
assert f'href="{self.delete_url(pb1)}"' in rv.text
assert f'href="{self.details_url(pb2)}"' in rv.text
assert f'href="{self.delete_url(pb2)}"' not in rv.text
assert f'href="{self.details_url(hb1)}"' in rv.text
assert f'href="{self.details_url(hb2)}"' not in rv.text
assert f'href="{self.details_url(hb3)}"' not in rv.text
assert f'href="{self.details_url(hb4)}"' not in rv.text
@pytest.mark.usefixtures('client_class')
class TestJsonViews(BrewViewTests):
def test_prefetch_anon(self, brew_factory):
brew1 = brew_factory(brewery=self.public_brewery, name='pb1')
brew_factory(brewery=self.hidden_brewery, name='hb2')
rv = self.client.get(url_for('brew.search'))
data = rv.get_json()
assert len(data) == 1
assert data[0]['name'] == brew1.name
def test_prefetch_auth(self, brew_factory):
brew_factory(brewery=self.public_brewery, name='pb1')
brew_h = brew_factory(brewery=self.public_brewery, name='hb2', is_public=False)
self.login(self.public_user.email)
rv = self.client.get(url_for('brew.search'))
data = rv.get_json()
assert len(data) == 2
names = [x['name'] for x in data]
assert brew_h.name in names
def test_search_anon(self, brew_factory):
brew_p = brew_factory(brewery=self.public_brewery, name='pb1')
brew_h = brew_factory(brewery=self.public_brewery, name='hb2', is_public=False)
rv = self.client.get(url_for('brew.search', q=brew_p.name))
data = rv.get_json()
assert len(data) == 1
assert data[0]['name'] == brew_p.name
rv = self.client.get(url_for('brew.search', q=brew_h.name))
data = rv.get_json()
assert len(data) == 0
def test_search_auth(self, brew_factory):
brew_p = brew_factory(brewery=self.public_brewery, name='pb1')
brew_h = brew_factory(brewery=self.public_brewery, name='hb2', is_public=False)
self.login(self.public_user.email)
rv = self.client.get(url_for('brew.search', q=brew_p.name))
data = rv.get_json()
assert len(data) == 1
assert data[0]['name'] == brew_p.name
rv = self.client.get(url_for('brew.search', q=brew_h.name))
data = rv.get_json()
assert len(data) == 1
assert data[0]['name'] == brew_h.name
@pytest.mark.usefixtures('client_class')
class TestStateChangeView(BrewViewTests):
@pytest.fixture(autouse=True)
def set_up2(self, brew_factory):
self.brew = brew_factory(
brewery=self.public_brewery,
name='pale ale',
date_brewed=datetime.date.today() - datetime.timedelta(days=30),
bottling_date=datetime.date.today() - datetime.timedelta(days=10),
)
self.url = url_for('brew.chgstate', brew_id=self.brew.id)
def test_brew_tap_anon(self):
rv = self.client.post(self.url, data={'action': 'tap'})
assert url_for('auth.select') in rv.headers['Location']
def test_brew_tap_nonbrewer(self):
self.login(self.hidden_user.email)
rv = self.client.post(self.url, data={'action': 'tap'}, follow_redirects=True)
assert rv.status_code == 403
assert "You don't have permission to access this page" in rv.text
def test_brew_tap_brewer(self):
self.login(self.public_user.email)
rv = self.client.post(self.url, data={'action': 'tap'}, follow_redirects=True)
assert f'</strong>: {Brew.STATE_TAPPED}' in rv.text
assert 'state changed' in rv.text
def test_brew_untap_brewer(self):
self.brew.tapped = datetime.datetime.today() - datetime.timedelta(days=2)
db.session.add(self.brew)
db.session.commit()
self.login(self.public_user.email)
rv = self.client.post(
self.url, data={'action': 'untap'}, follow_redirects=True
)
assert f'</strong>: {Brew.STATE_MATURING}' in rv.text
assert 'state changed' in rv.text
def test_brew_finish_brewer(self):
self.login(self.public_user.email)
rv = self.client.post(
self.url, data={'action': 'finish'}, follow_redirects=True
)
assert f'</strong>: {Brew.STATE_FINISHED}' in rv.text
assert 'state changed' in rv.text
assert self.brew.tapped is None
def test_invalid_state(self):
self.login(self.public_user.email)
rv = self.client.post(
self.url, data={'action': 'dummy'}, follow_redirects=True
)
assert 'invalid state' in rv.text
@pytest.mark.usefixtures('client_class')
class TestBrewAddView(BrewViewTests):
@pytest.fixture(autouse=True)
def set_up2(self):
self.url = url_for('brew.add')
def test_get_anon(self):
rv = self.client.get(self.url)
assert rv.status_code == 302
assert url_for('auth.select') in rv.headers['location']
def test_get_authenticated(self):
self.login(email=self.public_user.email)
rv = self.client.get(self.url)
assert f'action="{self.url}"' in rv.text
def test_post_anon(self):
data = {
'name': 'pale ale',
'brewery': self.public_brewery.id,
'carbonation_type': 'keg with priming',
'carbonation_level': 'low',
}
rv = self.client.post(self.url, data=data)
assert rv.status_code == 302
assert url_for('auth.select') in rv.headers['location']
def test_post_authenticated_own_brewery(self):
name = 'pale ale'
data = {
'name': name,
'brewery': self.public_brewery.id,
'carbonation_type': 'keg with priming',
'carbonation_level': 'low',
}
self.login(email=self.public_user.email)
rv = self.client.post(self.url, data=data, follow_redirects=True)
assert f'{name} created' in rv.text
def test_post_authenticated_other_brewery(self):
data = {
'name': 'pale ale',
'brewery': self.public_brewery.id,
'carbonation_type': 'keg with priming',
'carbonation_level': 'low',
}
self.login(email=self.hidden_user.email)
rv = self.client.post(self.url, data=data)
assert rv.status_code == 200
assert 'Not a valid choice' in rv.text
assert Brew.query.filter_by(name=data['name']).first() is None
@pytest.mark.usefixtures('client_class')
class TestBrewDeleteView(BrewViewTests):
@pytest.fixture(autouse=True)
def set_up2(self, brew_factory):
self.brew = brew_factory(
brewery=self.public_brewery,
name='pale ale',
date_brewed=datetime.date.today() - datetime.timedelta(days=30),
bottling_date=datetime.date.today() - datetime.timedelta(days=10),
)
self.url = url_for('brew.delete', brew_id=self.brew.id)
def test_get_anon(self):
rv = self.client.get(self.url)
assert rv.status_code == 302
assert url_for('auth.select') in rv.headers['Location']
def test_get_owner(self):
self.login(email=self.public_user.email)
rv = self.client.get(self.url)
assert f'action="{self.url}"' in rv.text
def test_get_non_owner(self):
self.login(email=self.hidden_user.email)
rv = self.client.get(self.url)
assert rv.status_code == 403
def test_post_anon(self):
rv = self.client.post(self.url, data={'delete_it': True})
assert rv.status_code == 302
assert url_for('auth.select') in rv.headers['Location']
assert Brew.query.get(self.brew.id) is not None
def test_post_owner(self):
self.login(email=self.public_user.email)
rv = self.client.post(self.url, data={'delete_it': True}, follow_redirects=True)
assert rv.status_code == 200
assert Brew.query.get(self.brew.id) is None
def test_post_non_owner(self):
self.login(email=self.hidden_user.email)
rv = self.client.post(self.url, data={'delete_it': True}, follow_redirects=True)
assert rv.status_code == 403
| 38.879227 | 88 | 0.636245 | import datetime
import pytest
from flask import url_for
from brewlog.ext import db
from brewlog.models import Brew
from . import BrewlogTests
class BrewViewTests(BrewlogTests):
@pytest.fixture(autouse=True)
def set_up(self, user_factory, brewery_factory):
self.public_user = user_factory(
first_name='John', last_name='Public'
)
self.public_brewery = brewery_factory(
name='public brewery', brewer=self.public_user
)
self.hidden_user = user_factory(
is_public=False, first_name='Rebecca', last_name='Hidden'
)
self.hidden_brewery = brewery_factory(
name='hidden brewery', brewer=self.hidden_user
)
@pytest.mark.usefixtures('client_class')
class TestBrewDetailsView(BrewViewTests):
def url(self, brew):
return url_for('brew.details', brew_id=brew.id)
def test_get_404(self):
rv = self.client.get(url_for('brew.details', brew_id=666))
assert rv.status_code == 404
def test_get_no_access_hidden_brewery(self, brew_factory):
brew = brew_factory(brewery=self.hidden_brewery, name='hb1')
self.login(self.public_user.email)
rv = self.client.get(self.url(brew))
assert rv.status_code == 404
def test_get_no_access_hidden_brew(self, brew_factory):
brew = brew_factory(
brewery=self.public_brewery, is_public=False, name='hb1'
)
self.login(self.hidden_user.email)
rv = self.client.get(self.url(brew))
assert rv.status_code == 404
def test_post_anon(self, brew_factory):
brew = brew_factory(
brewery=self.public_brewery, name='pb1', code='xxx'
)
data = {
'name': brew.name,
'brewery': brew.brewery.id,
'code': '001',
'carbonation_level': 'low',
'carbonation_type': 'bottles with priming',
}
rv = self.client.post(self.url(brew), data=data)
assert rv.status_code == 403
def test_post_non_brewer(self, brew_factory):
brew = brew_factory(
brewery=self.public_brewery, name='pb1', code='xxx'
)
self.login(self.hidden_user.email)
data = {
'name': brew.name,
'brewery': brew.brewery.id,
'code': '001',
'carbonation_level': 'low',
'carbonation_type': 'bottles with priming',
}
rv = self.client.post(self.url(brew), data=data, follow_redirects=True)
assert rv.status_code == 403
def test_post_data_ok(self, brew_factory):
brew = brew_factory(
brewery=self.public_brewery, name='pb1', code='xxx'
)
self.login(self.public_user.email)
data = {
'name': brew.name,
'brewery': brew.brewery.id,
'code': '001',
'carbonation_level': 'low',
'carbonation_type': 'bottles with priming',
}
rv = self.client.post(self.url(brew), data=data, follow_redirects=True)
assert rv.status_code == 200
assert 'data updated' in rv.text
assert Brew.query.get(brew.id).code == data['code']
def test_post_data_missing(self, brew_factory):
brew = brew_factory(brewery=self.public_brewery, name='pb1', code='xxx')
self.login(self.public_user.email)
data = {
'name': None,
'brewery': brew.brewery.id,
'code': '001',
'carbonation_level': 'low',
'carbonation_type': 'bottles with priming',
}
rv = self.client.post(self.url(brew), data=data, follow_redirects=True)
assert rv.status_code == 200
assert 'field is required' in rv.text
assert 'data updated' not in rv.text
def test_state_form_present(self, brew_factory):
brewed = datetime.date(1992, 12, 4)
bottled = datetime.date(1993, 1, 12)
taped = datetime.date(1993, 3, 8)
brew = brew_factory(
brewery=self.public_brewery, name='pb1', date_brewed=brewed,
bottling_date=bottled, tapped=taped
)
self.login(self.public_user.email)
rv = self.client.get(self.url(brew))
assert url_for('brew.chgstate', brew_id=brew.id) in rv.text
def test_attenuation_display_none(self, brew_factory):
brew = brew_factory(brewery=self.public_brewery, name='pb1')
self.login(self.public_user.email)
rv = self.client.get(self.url(brew))
assert 'apparent' not in rv.text
@pytest.mark.usefixtures('client_class')
class TestBrewDetailsNavigation(BrewViewTests):
def url(self, brew):
return url_for('brew.details', brew_id=brew.id)
@pytest.mark.parametrize('anon', [
False, True,
], ids=['authenticated', 'anonymous'])
def test_brew_navigation_non_owner(self, anon, brew_factory):
p2_brew = brew_factory(brewery=self.public_brewery)
p1_brew = brew_factory(brewery=self.public_brewery, is_public=False)
brew = brew_factory(brewery=self.public_brewery)
n1_brew = brew_factory(brewery=self.public_brewery, is_public=False)
n2_brew = brew_factory(brewery=self.public_brewery)
if not anon:
self.login(self.hidden_user.email)
rv = self.client.get(self.url(brew))
assert f'href="{self.url(p2_brew)}"' in rv.text
assert f'href="{self.url(p1_brew)}"' not in rv.text
assert f'href="{self.url(n1_brew)}"' not in rv.text
assert f'href="{self.url(n2_brew)}"' in rv.text
def test_brew_navigation_owner(self, brew_factory):
p1_brew = brew_factory(brewery=self.public_brewery, is_public=False)
brew = brew_factory(brewery=self.public_brewery)
n1_brew = brew_factory(brewery=self.public_brewery, is_public=False)
self.login(self.public_user.email)
rv = self.client.get(self.url(brew))
assert f'href="{self.url(p1_brew)}"' in rv.text
assert f'href="{self.url(n1_brew)}"' in rv.text
@pytest.mark.usefixtures('client_class')
class TestBrewListView(BrewViewTests):
@pytest.fixture(autouse=True)
def set_up2(self):
self.url = url_for('brew.all')
def details_url(self, brew):
return url_for('brew.details', brew_id=brew.id)
def delete_url(self, brew):
return url_for('brew.delete', brew_id=brew.id)
def test_anon(self, brew_factory):
hb_hb = brew_factory(brewery=self.hidden_brewery, is_public=False)
pb_hb = brew_factory(brewery=self.hidden_brewery, is_public=True)
pb_pb = brew_factory(brewery=self.public_brewery, is_public=True)
hb_pb = brew_factory(brewery=self.public_brewery, is_public=False)
rv = self.client.get(self.url)
assert url_for('brew.details', brew_id=pb_pb.id) in rv.text
assert url_for('brew.delete', brew_id=pb_pb.id) not in rv.text
assert url_for('brew.details', brew_id=hb_hb.id) not in rv.text
assert url_for('brew.details', brew_id=pb_hb.id) not in rv.text
assert url_for('brew.details', brew_id=hb_pb.id) not in rv.text
def test_authenticated(self, user_factory, brewery_factory, brew_factory):
user2 = user_factory(first_name='Ivory', last_name='Tower')
brewery2 = brewery_factory(brewer=user2, name='brewery2')
pb1 = brew_factory(brewery=self.public_brewery)
pb2 = brew_factory(brewery=brewery2)
hb1 = brew_factory(name='hidden1', brewery=self.public_brewery, is_public=False)
hb2 = brew_factory(name='hidden2', brewery=brewery2, is_public=False)
hb3 = brew_factory(name='hidden3', brewery=self.hidden_brewery)
hb4 = brew_factory(name='hidden4', brewery=self.hidden_brewery, is_public=False)
self.login(email=self.public_user.email)
rv = self.client.get(self.url)
assert f'href="{self.details_url(pb1)}"' in rv.text
assert f'href="{self.delete_url(pb1)}"' in rv.text
assert f'href="{self.details_url(pb2)}"' in rv.text
assert f'href="{self.delete_url(pb2)}"' not in rv.text
assert f'href="{self.details_url(hb1)}"' in rv.text
assert f'href="{self.details_url(hb2)}"' not in rv.text
assert f'href="{self.details_url(hb3)}"' not in rv.text
assert f'href="{self.details_url(hb4)}"' not in rv.text
@pytest.mark.usefixtures('client_class')
class TestJsonViews(BrewViewTests):
def test_prefetch_anon(self, brew_factory):
brew1 = brew_factory(brewery=self.public_brewery, name='pb1')
brew_factory(brewery=self.hidden_brewery, name='hb2')
rv = self.client.get(url_for('brew.search'))
data = rv.get_json()
assert len(data) == 1
assert data[0]['name'] == brew1.name
def test_prefetch_auth(self, brew_factory):
brew_factory(brewery=self.public_brewery, name='pb1')
brew_h = brew_factory(brewery=self.public_brewery, name='hb2', is_public=False)
self.login(self.public_user.email)
rv = self.client.get(url_for('brew.search'))
data = rv.get_json()
assert len(data) == 2
names = [x['name'] for x in data]
assert brew_h.name in names
def test_search_anon(self, brew_factory):
brew_p = brew_factory(brewery=self.public_brewery, name='pb1')
brew_h = brew_factory(brewery=self.public_brewery, name='hb2', is_public=False)
rv = self.client.get(url_for('brew.search', q=brew_p.name))
data = rv.get_json()
assert len(data) == 1
assert data[0]['name'] == brew_p.name
rv = self.client.get(url_for('brew.search', q=brew_h.name))
data = rv.get_json()
assert len(data) == 0
def test_search_auth(self, brew_factory):
brew_p = brew_factory(brewery=self.public_brewery, name='pb1')
brew_h = brew_factory(brewery=self.public_brewery, name='hb2', is_public=False)
self.login(self.public_user.email)
rv = self.client.get(url_for('brew.search', q=brew_p.name))
data = rv.get_json()
assert len(data) == 1
assert data[0]['name'] == brew_p.name
rv = self.client.get(url_for('brew.search', q=brew_h.name))
data = rv.get_json()
assert len(data) == 1
assert data[0]['name'] == brew_h.name
@pytest.mark.usefixtures('client_class')
class TestStateChangeView(BrewViewTests):
@pytest.fixture(autouse=True)
def set_up2(self, brew_factory):
self.brew = brew_factory(
brewery=self.public_brewery,
name='pale ale',
date_brewed=datetime.date.today() - datetime.timedelta(days=30),
bottling_date=datetime.date.today() - datetime.timedelta(days=10),
)
self.url = url_for('brew.chgstate', brew_id=self.brew.id)
def test_brew_tap_anon(self):
rv = self.client.post(self.url, data={'action': 'tap'})
assert url_for('auth.select') in rv.headers['Location']
def test_brew_tap_nonbrewer(self):
self.login(self.hidden_user.email)
rv = self.client.post(self.url, data={'action': 'tap'}, follow_redirects=True)
assert rv.status_code == 403
assert "You don't have permission to access this page" in rv.text
def test_brew_tap_brewer(self):
self.login(self.public_user.email)
rv = self.client.post(self.url, data={'action': 'tap'}, follow_redirects=True)
assert f'</strong>: {Brew.STATE_TAPPED}' in rv.text
assert 'state changed' in rv.text
def test_brew_untap_brewer(self):
self.brew.tapped = datetime.datetime.today() - datetime.timedelta(days=2)
db.session.add(self.brew)
db.session.commit()
self.login(self.public_user.email)
rv = self.client.post(
self.url, data={'action': 'untap'}, follow_redirects=True
)
assert f'</strong>: {Brew.STATE_MATURING}' in rv.text
assert 'state changed' in rv.text
def test_brew_finish_brewer(self):
self.login(self.public_user.email)
rv = self.client.post(
self.url, data={'action': 'finish'}, follow_redirects=True
)
assert f'</strong>: {Brew.STATE_FINISHED}' in rv.text
assert 'state changed' in rv.text
assert self.brew.tapped is None
def test_invalid_state(self):
self.login(self.public_user.email)
rv = self.client.post(
self.url, data={'action': 'dummy'}, follow_redirects=True
)
assert 'invalid state' in rv.text
@pytest.mark.usefixtures('client_class')
class TestBrewAddView(BrewViewTests):
@pytest.fixture(autouse=True)
def set_up2(self):
self.url = url_for('brew.add')
def test_get_anon(self):
rv = self.client.get(self.url)
assert rv.status_code == 302
assert url_for('auth.select') in rv.headers['location']
def test_get_authenticated(self):
self.login(email=self.public_user.email)
rv = self.client.get(self.url)
assert f'action="{self.url}"' in rv.text
def test_post_anon(self):
data = {
'name': 'pale ale',
'brewery': self.public_brewery.id,
'carbonation_type': 'keg with priming',
'carbonation_level': 'low',
}
rv = self.client.post(self.url, data=data)
assert rv.status_code == 302
assert url_for('auth.select') in rv.headers['location']
def test_post_authenticated_own_brewery(self):
name = 'pale ale'
data = {
'name': name,
'brewery': self.public_brewery.id,
'carbonation_type': 'keg with priming',
'carbonation_level': 'low',
}
self.login(email=self.public_user.email)
rv = self.client.post(self.url, data=data, follow_redirects=True)
assert f'{name} created' in rv.text
def test_post_authenticated_other_brewery(self):
data = {
'name': 'pale ale',
'brewery': self.public_brewery.id,
'carbonation_type': 'keg with priming',
'carbonation_level': 'low',
}
self.login(email=self.hidden_user.email)
rv = self.client.post(self.url, data=data)
assert rv.status_code == 200
assert 'Not a valid choice' in rv.text
assert Brew.query.filter_by(name=data['name']).first() is None
@pytest.mark.usefixtures('client_class')
class TestBrewDeleteView(BrewViewTests):
@pytest.fixture(autouse=True)
def set_up2(self, brew_factory):
self.brew = brew_factory(
brewery=self.public_brewery,
name='pale ale',
date_brewed=datetime.date.today() - datetime.timedelta(days=30),
bottling_date=datetime.date.today() - datetime.timedelta(days=10),
)
self.url = url_for('brew.delete', brew_id=self.brew.id)
def test_get_anon(self):
rv = self.client.get(self.url)
assert rv.status_code == 302
assert url_for('auth.select') in rv.headers['Location']
def test_get_owner(self):
self.login(email=self.public_user.email)
rv = self.client.get(self.url)
assert f'action="{self.url}"' in rv.text
def test_get_non_owner(self):
self.login(email=self.hidden_user.email)
rv = self.client.get(self.url)
assert rv.status_code == 403
def test_post_anon(self):
rv = self.client.post(self.url, data={'delete_it': True})
assert rv.status_code == 302
assert url_for('auth.select') in rv.headers['Location']
assert Brew.query.get(self.brew.id) is not None
def test_post_owner(self):
self.login(email=self.public_user.email)
rv = self.client.post(self.url, data={'delete_it': True}, follow_redirects=True)
assert rv.status_code == 200
assert Brew.query.get(self.brew.id) is None
def test_post_non_owner(self):
self.login(email=self.hidden_user.email)
rv = self.client.post(self.url, data={'delete_it': True}, follow_redirects=True)
assert rv.status_code == 403
| true | true |
f719ffebb722b8308f0638a092a790eb9e2845a8 | 18,480 | py | Python | mindmeld/converter/dialogflow.py | derekmpham/mindmeld | 18189f956e4e3eb92df61fde95ec82f73b9efa91 | [
"Apache-2.0"
] | null | null | null | mindmeld/converter/dialogflow.py | derekmpham/mindmeld | 18189f956e4e3eb92df61fde95ec82f73b9efa91 | [
"Apache-2.0"
] | null | null | null | mindmeld/converter/dialogflow.py | derekmpham/mindmeld | 18189f956e4e3eb92df61fde95ec82f73b9efa91 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
#
# Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains the DialogflowConverter class used to convert Dialogflow projects
into Mindmeld projects"""
import json
import logging
import os
import re
from sklearn.model_selection import train_test_split
from mindmeld.converter.converter import Converter
logger = logging.getLogger(__name__)
class DialogflowConverter(Converter):
"""The class is a sub class of the abstract Converter class. This class
contains the methods required to convert a Dialogflow project into a MindMeld project
"""
sys_entity_map = {
"@sys.date-time": "sys_interval",
"@sys.date": "sys_time",
"@sys.date-period": "sys_interval",
"@sys.time": "sys_time",
"@sys.time-period": "sys_duration",
"@sys.duration": "sys_duration",
"@sys.number": "sys_number",
"@sys.cardinal": "sys_number",
"@sys.ordinal": "sys_ordinal",
"@sys.unit-currency": "sys_amount-of-money",
"@sys.unit-volume": "sys_volume",
"@sys.email": "sys_email",
"@sys.phone-number": "sys_phone-number",
"@sys.url": "sys_url",
}
# TODO: provide support for entities listed in sys_entity_map_todo
sys_entity_map_todo = [
"@sys.number-integer",
"@sys.number-sequence",
"@sys.flight-number",
"@sys.unit-area",
"@sys.unit-length",
"@sys.unit-speed",
"@sys.unit-information",
"@sys.percentage",
"@sys.temperature",
"@sys.duration",
"@sys.age",
"@sys.currency-name",
"@sys.unit-area-name",
"@sys.unit-length-name",
"@sys.unit-speed-name",
"@sys.unit-volume-name",
"@sys.unit-weight-name",
"@sys.unit-information-name",
"@sys.address",
"@sys.zip-code",
"@sys.geo-capital",
"@sys.geo-country",
"@sys.geo-country-code",
"@sys.geo-city",
"@sys.geo-state",
"@sys.geo-city",
"@sys.geo-state",
"@sys.place-attraction",
"@sys.airport",
"@sys.location",
"@sys.given-name",
"@sys.last-name",
"@sys.person",
"@sys.music-artist",
"@sys.music-genre",
"@sys.color",
"@sys.language",
"@sys.any",
]
def __init__(self, dialogflow_project_directory, mindmeld_project_directory):
if os.path.exists(os.path.dirname(dialogflow_project_directory)):
self.dialogflow_project_directory = dialogflow_project_directory
self.mindmeld_project_directory = mindmeld_project_directory
self.directory = os.path.dirname(os.path.realpath(__file__))
self.entities_list = set()
self.intents_list = set()
else:
msg = "`{dialogflow_project_directory}` does not exist. Please verify."
msg = msg.format(dialogflow_project_directory=dialogflow_project_directory)
raise FileNotFoundError(msg)
def create_mindmeld_directory(self):
self.create_directory(self.mindmeld_project_directory)
self.create_directory(os.path.join(self.mindmeld_project_directory, "data"))
self.create_directory(os.path.join(self.mindmeld_project_directory, "domains"))
self.create_directory(
os.path.join(self.mindmeld_project_directory, "domains", "general")
)
self.create_directory(os.path.join(self.mindmeld_project_directory, "entities"))
# =========================
# create training data (entities, intents)
# =========================
def _create_entities_directories(self, entities):
""" Creates directories + files for all languages/files.
Currently does not use meta data in entityName.json files (the keys in var entities).
"""
for languages in entities.values():
for sub in languages.values():
dialogflow_entity_file = os.path.join(
self.dialogflow_project_directory, "entities", sub + ".json"
)
mindmeld_entity_directory_name = self.clean_check(
sub, self.entities_list
)
mindmeld_entity_directory = os.path.join(
self.mindmeld_project_directory,
"entities",
mindmeld_entity_directory_name,
)
self.create_directory(mindmeld_entity_directory)
self._create_entity_file(
dialogflow_entity_file, mindmeld_entity_directory
)
@staticmethod
def _create_entity_file(dialogflow_entity_file, mindmeld_entity_directory):
source_en = open(dialogflow_entity_file, "r")
target_gazetteer = open(
os.path.join(mindmeld_entity_directory, "gazetteer.txt"), "w"
)
target_mapping = open(
os.path.join(mindmeld_entity_directory, "mapping.json"), "w"
)
datastore = json.load(source_en)
mapping_dict = {"entities": []}
for item in datastore:
new_dict = {}
while ("value" in item) and (item["value"] in item["synonyms"]):
item["synonyms"].remove(item["value"])
new_dict["whitelist"] = item["synonyms"]
new_dict["cname"] = item["value"]
mapping_dict["entities"].append(new_dict)
target_gazetteer.write(item["value"] + "\n")
json.dump(mapping_dict, target_mapping, ensure_ascii=False, indent=2)
source_en.close()
target_gazetteer.close()
target_mapping.close()
def _create_intents_directories(self, intents):
""" Creates directories + files for all languages/files."""
for languages in intents.values():
for language, sub in languages.items():
dialogflow_intent_file = os.path.join(
self.dialogflow_project_directory, "intents", sub + ".json"
)
mindmeld_intent_directory_name = self.clean_check(
sub, self.intents_list
)
mindmeld_intent_directory = os.path.join(
self.mindmeld_project_directory,
"domains",
"general",
mindmeld_intent_directory_name,
)
self.create_directory(mindmeld_intent_directory)
self._create_intent_file(
dialogflow_intent_file, mindmeld_intent_directory, language
)
def _create_intent_file(
self, dialogflow_intent_file, mindmeld_intent_directory, language
):
source_en = open(dialogflow_intent_file, "r")
target_test = open(os.path.join(mindmeld_intent_directory, "test.txt"), "w")
target_train = open(os.path.join(mindmeld_intent_directory, "train.txt"), "w")
datastore = json.load(source_en)
all_text = []
for usersay in datastore:
sentence = ""
for texts in usersay["data"]:
df_text = texts["text"]
if "meta" in texts and texts["meta"] != "@sys.ignore":
df_meta = texts["meta"]
if re.match(
"(@sys.).+", df_meta
): # if text is a dialogflow sys entity
if df_meta in DialogflowConverter.sys_entity_map:
mm_meta = DialogflowConverter.sys_entity_map[df_meta]
else:
mm_meta = "[DNE: {sysEntity}]".format(sysEntity=df_meta[1:])
logger.info(
"Unfortunately mindmeld does not currently support"
"%s as a sys entity."
"Please create an entity for this.",
df_meta[1:],
)
entity_type = self.clean_name(mm_meta) + "_entries_" + language
part = "{" + df_text + "|" + entity_type + "}"
else:
entity_type = (
self.clean_name(df_meta[1:]) + "_entries_" + language
)
part = "{" + df_text + "|" + entity_type + "}"
else:
part = df_text
sentence += part
all_text.append(sentence)
train, test = train_test_split(all_text, test_size=0.2)
target_test.write("\n".join(test))
target_train.write("\n".join(train))
source_en.close()
target_test.close()
target_train.close()
def _get_file_names(self, level):
""" Gets the names of the entities from Dialogflow as a dictionary.
levels (str): either "entities" or "intents"
ex. if we had the following files in our entities directory:
["test.json", "test_entries_en.json", "test_entries_de.json"]
it returns:
{'test': {'en': 'test_entries_en', 'de': 'test_entries_de'}} """
directory = os.path.join(self.dialogflow_project_directory, level)
files = os.listdir(directory)
w = {"entities": "entries", "intents": "usersays"}
p = r".+(?<=(_" + w[level] + "_))(.*)(?=(.json))"
info = {}
for name in files:
match = re.match(p, name)
if match:
isbase = False
base = name[: match.start(1)]
language = match.group(2)
else:
isbase = True
base = name[:-5]
if base not in info:
info[base] = {}
if not isbase:
info[base][language] = name[:-5]
return info
def create_mindmeld_training_data(self):
entities = self._get_file_names("entities")
self._create_entities_directories(entities)
intents = self._get_file_names("intents")
self._create_intents_directories(intents)
# =========================
# create init
# =========================
@staticmethod
def create_handle(params):
return "@app.handle(" + params + ")"
@staticmethod
def create_header(function_name):
return "def " + function_name + "(request, responder):"
@staticmethod
def create_function(handles, function_name, replies):
assert isinstance(handles, list)
result = ""
for handle in handles:
result += DialogflowConverter.create_handle(handle) + "\n"
result += DialogflowConverter.create_header(function_name) + "\n"
result += " " + "replies = {}".format(replies) + "\n"
result += " " + "responder.reply(replies)"
return result
@staticmethod
def clean_name(name):
""" Takes in a string and returns a valid folder name (no spaces, all lowercase)."""
name = re.sub(r"[^\w\s-]", "", name).strip().lower()
name = re.sub(r"[-\s]+", "_", name)
return name
def clean_check(self, name, lst):
""" Takes in a list of strings and a name.
Returns name cleaned if the cleaned name is not found in lst."""
cleaned = self.clean_name(name)
if cleaned not in lst:
lst.add(cleaned)
return cleaned
else:
logger.error(
"%s name has been created twice. Please ensure there "
"are no duplicate names in the dialogflow files and "
"filenames are valid (no spaces or special characters)",
cleaned,
)
def create_mindmeld_init(self):
with open(
os.path.join(self.mindmeld_project_directory, "__init__.py"), "w"
) as target:
begin_info = [
"# -*- coding: utf-8 -*-",
'"""This module contains the MindMeld application"""',
"from mindmeld import Application",
"app = Application(__name__)",
"__all__ = ['app']",
]
for info, spacing in zip(begin_info, [1, 2, 1, 1, 0]):
target.write(info + "\n" * spacing)
intents = self._get_file_names("intents")
for i, main in enumerate(intents.keys()):
df_main = os.path.join(
self.dialogflow_project_directory, "intents", main + ".json"
)
with open(df_main) as source:
if "usersays" in df_main:
logger.error(
"Please check if your intent file"
"names are correctly labeled."
)
datastore = json.load(source)
replies = []
for response in datastore["responses"]:
for message in response["messages"]:
language = message["lang"]
if "speech" in message:
data = message["speech"]
replies = data if isinstance(data, list) else [data]
if datastore["fallbackIntent"]:
function_name = "default" + "_" + language
if language == "en":
# TODO: support multiple defaults for languages
handles = [
"default=True",
"intent='unsupported'",
]
else:
handles = ["intent='unsupported'"]
else:
function_name = "renameMe" + str(i) + "_" + language
handles = [
"intent="
+ "'"
+ self.clean_name(datastore["name"])
+ "_usersays_"
+ language
+ "'"
]
target.write(
"\n\n\n"
+ self.create_function(
handles=handles,
function_name=function_name,
replies=replies,
)
)
target.write("\n")
# =========================
# convert project
# =========================
def convert_project(self):
""" Converts a Dialogflow project into a MindMeld project.
Dialogflow projects consist of entities and intents.
note on languages:
Dialogflow supports multiple languages and locales. They store their training
data for different languages in different files. So, the name of each training
file ends with a meta tag, two letters long for language, and an additional
two letters for dialect (if applicable). For example, a file ending in "_en-au"
indicates it's in English (Australia). Below we use "la" to represent this
meta tag.
entities folder contains:
entityName.json - Meta data about entityName for all languages.
entityName_entries_la.json - One for each language, contains entitiy mappings.
intents folder contain:
intentName.json - Contains rules, information about conversation flow, meta data.
Contains previously mentioned information and responses for all languages.
intentName_usersays_la.json - one for each language,
contains training data to recognize intentName
Limitations:
- The converter is unable to create an entity when it encounters an
unrecognized entity (an entity not defined under entities folder
or system entities), and labels such entities as DNE in training data.
- The converter currently does not automatically convert features like
slot filling, contexts, and follow-up intents. Users can still implement such
features and more.
- Information in agent.json are not copied over.
- There is no official support for different languages. Users can still
implement this. The converter is able to successfully convert dialogflow
bots that support multiple languages.
Mindmeld:
- Users can store data locally
- Users can build a knowledge base (currently beta in Dialogflow).
- Users can configure the machine learning models to best suit their needs.
- Users have more flexibility in defining their own features, including
ones like slot filling, contexts, and follow-up intents.
"""
logger.info("Converting project.")
# Create project directory with sub folders
self.create_mindmeld_directory()
# Transfer over test data from Dialogflow project and reformat to Mindmeld project
self.create_mindmeld_training_data()
file_loc = os.path.dirname(os.path.realpath(__file__))
self.create_config(self.mindmeld_project_directory, file_loc)
self.create_main(self.mindmeld_project_directory, file_loc)
self.create_mindmeld_init()
logger.info("Project converted.")
| 39.069767 | 97 | 0.541288 |
import json
import logging
import os
import re
from sklearn.model_selection import train_test_split
from mindmeld.converter.converter import Converter
logger = logging.getLogger(__name__)
class DialogflowConverter(Converter):
sys_entity_map = {
"@sys.date-time": "sys_interval",
"@sys.date": "sys_time",
"@sys.date-period": "sys_interval",
"@sys.time": "sys_time",
"@sys.time-period": "sys_duration",
"@sys.duration": "sys_duration",
"@sys.number": "sys_number",
"@sys.cardinal": "sys_number",
"@sys.ordinal": "sys_ordinal",
"@sys.unit-currency": "sys_amount-of-money",
"@sys.unit-volume": "sys_volume",
"@sys.email": "sys_email",
"@sys.phone-number": "sys_phone-number",
"@sys.url": "sys_url",
}
sys_entity_map_todo = [
"@sys.number-integer",
"@sys.number-sequence",
"@sys.flight-number",
"@sys.unit-area",
"@sys.unit-length",
"@sys.unit-speed",
"@sys.unit-information",
"@sys.percentage",
"@sys.temperature",
"@sys.duration",
"@sys.age",
"@sys.currency-name",
"@sys.unit-area-name",
"@sys.unit-length-name",
"@sys.unit-speed-name",
"@sys.unit-volume-name",
"@sys.unit-weight-name",
"@sys.unit-information-name",
"@sys.address",
"@sys.zip-code",
"@sys.geo-capital",
"@sys.geo-country",
"@sys.geo-country-code",
"@sys.geo-city",
"@sys.geo-state",
"@sys.geo-city",
"@sys.geo-state",
"@sys.place-attraction",
"@sys.airport",
"@sys.location",
"@sys.given-name",
"@sys.last-name",
"@sys.person",
"@sys.music-artist",
"@sys.music-genre",
"@sys.color",
"@sys.language",
"@sys.any",
]
def __init__(self, dialogflow_project_directory, mindmeld_project_directory):
if os.path.exists(os.path.dirname(dialogflow_project_directory)):
self.dialogflow_project_directory = dialogflow_project_directory
self.mindmeld_project_directory = mindmeld_project_directory
self.directory = os.path.dirname(os.path.realpath(__file__))
self.entities_list = set()
self.intents_list = set()
else:
msg = "`{dialogflow_project_directory}` does not exist. Please verify."
msg = msg.format(dialogflow_project_directory=dialogflow_project_directory)
raise FileNotFoundError(msg)
def create_mindmeld_directory(self):
self.create_directory(self.mindmeld_project_directory)
self.create_directory(os.path.join(self.mindmeld_project_directory, "data"))
self.create_directory(os.path.join(self.mindmeld_project_directory, "domains"))
self.create_directory(
os.path.join(self.mindmeld_project_directory, "domains", "general")
)
self.create_directory(os.path.join(self.mindmeld_project_directory, "entities"))
def _create_entities_directories(self, entities):
for languages in entities.values():
for sub in languages.values():
dialogflow_entity_file = os.path.join(
self.dialogflow_project_directory, "entities", sub + ".json"
)
mindmeld_entity_directory_name = self.clean_check(
sub, self.entities_list
)
mindmeld_entity_directory = os.path.join(
self.mindmeld_project_directory,
"entities",
mindmeld_entity_directory_name,
)
self.create_directory(mindmeld_entity_directory)
self._create_entity_file(
dialogflow_entity_file, mindmeld_entity_directory
)
@staticmethod
def _create_entity_file(dialogflow_entity_file, mindmeld_entity_directory):
source_en = open(dialogflow_entity_file, "r")
target_gazetteer = open(
os.path.join(mindmeld_entity_directory, "gazetteer.txt"), "w"
)
target_mapping = open(
os.path.join(mindmeld_entity_directory, "mapping.json"), "w"
)
datastore = json.load(source_en)
mapping_dict = {"entities": []}
for item in datastore:
new_dict = {}
while ("value" in item) and (item["value"] in item["synonyms"]):
item["synonyms"].remove(item["value"])
new_dict["whitelist"] = item["synonyms"]
new_dict["cname"] = item["value"]
mapping_dict["entities"].append(new_dict)
target_gazetteer.write(item["value"] + "\n")
json.dump(mapping_dict, target_mapping, ensure_ascii=False, indent=2)
source_en.close()
target_gazetteer.close()
target_mapping.close()
def _create_intents_directories(self, intents):
for languages in intents.values():
for language, sub in languages.items():
dialogflow_intent_file = os.path.join(
self.dialogflow_project_directory, "intents", sub + ".json"
)
mindmeld_intent_directory_name = self.clean_check(
sub, self.intents_list
)
mindmeld_intent_directory = os.path.join(
self.mindmeld_project_directory,
"domains",
"general",
mindmeld_intent_directory_name,
)
self.create_directory(mindmeld_intent_directory)
self._create_intent_file(
dialogflow_intent_file, mindmeld_intent_directory, language
)
def _create_intent_file(
self, dialogflow_intent_file, mindmeld_intent_directory, language
):
source_en = open(dialogflow_intent_file, "r")
target_test = open(os.path.join(mindmeld_intent_directory, "test.txt"), "w")
target_train = open(os.path.join(mindmeld_intent_directory, "train.txt"), "w")
datastore = json.load(source_en)
all_text = []
for usersay in datastore:
sentence = ""
for texts in usersay["data"]:
df_text = texts["text"]
if "meta" in texts and texts["meta"] != "@sys.ignore":
df_meta = texts["meta"]
if re.match(
"(@sys.).+", df_meta
):
if df_meta in DialogflowConverter.sys_entity_map:
mm_meta = DialogflowConverter.sys_entity_map[df_meta]
else:
mm_meta = "[DNE: {sysEntity}]".format(sysEntity=df_meta[1:])
logger.info(
"Unfortunately mindmeld does not currently support"
"%s as a sys entity."
"Please create an entity for this.",
df_meta[1:],
)
entity_type = self.clean_name(mm_meta) + "_entries_" + language
part = "{" + df_text + "|" + entity_type + "}"
else:
entity_type = (
self.clean_name(df_meta[1:]) + "_entries_" + language
)
part = "{" + df_text + "|" + entity_type + "}"
else:
part = df_text
sentence += part
all_text.append(sentence)
train, test = train_test_split(all_text, test_size=0.2)
target_test.write("\n".join(test))
target_train.write("\n".join(train))
source_en.close()
target_test.close()
target_train.close()
def _get_file_names(self, level):
directory = os.path.join(self.dialogflow_project_directory, level)
files = os.listdir(directory)
w = {"entities": "entries", "intents": "usersays"}
p = r".+(?<=(_" + w[level] + "_))(.*)(?=(.json))"
info = {}
for name in files:
match = re.match(p, name)
if match:
isbase = False
base = name[: match.start(1)]
language = match.group(2)
else:
isbase = True
base = name[:-5]
if base not in info:
info[base] = {}
if not isbase:
info[base][language] = name[:-5]
return info
def create_mindmeld_training_data(self):
entities = self._get_file_names("entities")
self._create_entities_directories(entities)
intents = self._get_file_names("intents")
self._create_intents_directories(intents)
@staticmethod
def create_handle(params):
return "@app.handle(" + params + ")"
@staticmethod
def create_header(function_name):
return "def " + function_name + "(request, responder):"
@staticmethod
def create_function(handles, function_name, replies):
assert isinstance(handles, list)
result = ""
for handle in handles:
result += DialogflowConverter.create_handle(handle) + "\n"
result += DialogflowConverter.create_header(function_name) + "\n"
result += " " + "replies = {}".format(replies) + "\n"
result += " " + "responder.reply(replies)"
return result
@staticmethod
def clean_name(name):
name = re.sub(r"[^\w\s-]", "", name).strip().lower()
name = re.sub(r"[-\s]+", "_", name)
return name
def clean_check(self, name, lst):
cleaned = self.clean_name(name)
if cleaned not in lst:
lst.add(cleaned)
return cleaned
else:
logger.error(
"%s name has been created twice. Please ensure there "
"are no duplicate names in the dialogflow files and "
"filenames are valid (no spaces or special characters)",
cleaned,
)
def create_mindmeld_init(self):
with open(
os.path.join(self.mindmeld_project_directory, "__init__.py"), "w"
) as target:
begin_info = [
"# -*- coding: utf-8 -*-",
'"""This module contains the MindMeld application"""',
"from mindmeld import Application",
"app = Application(__name__)",
"__all__ = ['app']",
]
for info, spacing in zip(begin_info, [1, 2, 1, 1, 0]):
target.write(info + "\n" * spacing)
intents = self._get_file_names("intents")
for i, main in enumerate(intents.keys()):
df_main = os.path.join(
self.dialogflow_project_directory, "intents", main + ".json"
)
with open(df_main) as source:
if "usersays" in df_main:
logger.error(
"Please check if your intent file"
"names are correctly labeled."
)
datastore = json.load(source)
replies = []
for response in datastore["responses"]:
for message in response["messages"]:
language = message["lang"]
if "speech" in message:
data = message["speech"]
replies = data if isinstance(data, list) else [data]
if datastore["fallbackIntent"]:
function_name = "default" + "_" + language
if language == "en":
handles = [
"default=True",
"intent='unsupported'",
]
else:
handles = ["intent='unsupported'"]
else:
function_name = "renameMe" + str(i) + "_" + language
handles = [
"intent="
+ "'"
+ self.clean_name(datastore["name"])
+ "_usersays_"
+ language
+ "'"
]
target.write(
"\n\n\n"
+ self.create_function(
handles=handles,
function_name=function_name,
replies=replies,
)
)
target.write("\n")
def convert_project(self):
logger.info("Converting project.")
self.create_mindmeld_directory()
self.create_mindmeld_training_data()
file_loc = os.path.dirname(os.path.realpath(__file__))
self.create_config(self.mindmeld_project_directory, file_loc)
self.create_main(self.mindmeld_project_directory, file_loc)
self.create_mindmeld_init()
logger.info("Project converted.")
| true | true |
f71a00fd7c45368e46d3c54f89b23447c46a85a7 | 406 | py | Python | 001085StepikPythonIntrO/Stepik001085PythonIntrOсh01p03_20200410.py | SafonovMikhail/python_000577 | 739f764e80f1ca354386f00b8e9db1df8c96531d | [
"Apache-2.0"
] | null | null | null | 001085StepikPythonIntrO/Stepik001085PythonIntrOсh01p03_20200410.py | SafonovMikhail/python_000577 | 739f764e80f1ca354386f00b8e9db1df8c96531d | [
"Apache-2.0"
] | null | null | null | 001085StepikPythonIntrO/Stepik001085PythonIntrOсh01p03_20200410.py | SafonovMikhail/python_000577 | 739f764e80f1ca354386f00b8e9db1df8c96531d | [
"Apache-2.0"
] | null | null | null | # print(int("a"))
print(int(995.23)) # отбрасывание дробной части
print(float(42)) # приведение к виду с плавающей точкой
print(2 ** 2018) # поддержка длинной арифметики
pow = str(2 ** 2018) # количество цифр
print(pow)
# for i in pow:
# print(pow(i))
print(len(pow))
print("Yin" + " " + "Yang")
print("because " * 42)
pow2=int((str(2) * 100)) ** 2
print(pow2)
print(str(2))
print(len(str(pow2))) | 23.882353 | 56 | 0.642857 |
print(int(995.23))
print(float(42))
print(2 ** 2018)
pow = str(2 ** 2018)
print(pow)
print(len(pow))
print("Yin" + " " + "Yang")
print("because " * 42)
pow2=int((str(2) * 100)) ** 2
print(pow2)
print(str(2))
print(len(str(pow2))) | true | true |
f71a011d3e1d15a38ea8652521b28f6d01d84fa7 | 23,145 | py | Python | library.py | whitehead421/library | 2d1d3ef50127560ad6da76b5763ff45bb6d25761 | [
"MIT"
] | null | null | null | library.py | whitehead421/library | 2d1d3ef50127560ad6da76b5763ff45bb6d25761 | [
"MIT"
] | null | null | null | library.py | whitehead421/library | 2d1d3ef50127560ad6da76b5763ff45bb6d25761 | [
"MIT"
] | null | null | null | import time
import string
import random
import os
from termcolor import colored
from collections import Counter
clean_the_screen = ("cls" if os.name == "nt" else "clear")
# Function for listing books with their full information.
def listBooks():
file = open("books.txt", "r")
lines = file.readlines()
file.close()
for i in lines:
splitted = i.split(",")
numberISBN = colored(f"{splitted[0]}", "blue")
nameBook = colored(f"{splitted[1]}", "magenta", "on_grey")
nameAuthor = colored(f"{splitted[2]}", "yellow")
checkOut = splitted[3]
if checkOut == "T\n":
checkOut = colored("Book is not in the library.", "red")
if checkOut == "F\n":
checkOut = colored("Book is in the library.", "green")
print("-" * 115)
print(f"Name: {nameBook} - Author: {nameAuthor} - Status: {checkOut} - ISBN: {numberISBN}\n")
# Function for showing the books those are checked out by students.
def listBooksChecked():
file = open("books.txt", "r")
lines = file.readlines()
file.close()
a = 0
for i in lines:
splitted = i.split(",")
numberISBN = colored(f"{splitted[0]}", "blue")
nameBook = colored(f"{splitted[1]}", "magenta", "on_grey")
nameAuthor = colored(f"{splitted[2]}", "yellow")
checkOut = splitted[3]
if checkOut == "T\n":
a += 1
print("-" * 115)
print(f"Name: {nameBook} - Author: {nameAuthor} - ISBN: {numberISBN}\n")
if a == 0:
print("-" * 115)
print(colored("\tUhm..- Nobody reads books these days.\n", "blue"))
print("There is no checked out book. All the books are in the library.")
# Function for adding new books to library's data.
def addBook():
file = open("books.txt", "r")
lines = file.readlines()
file.close()
isbn = input("Please enter the ISBN number: ")
nameBook = input("Please enter the name of book: ")
nameAuthor = input("Please enter the author name: ")
for i in lines:
splitted = i.split(",")
isbnBook = splitted[0]
nBook = splitted[1]
if isbn == isbnBook:
print(colored("There is already a book with this ISBN.", "red"))
print(f"\t{isbn} - {nBook}")
break
else:
print(colored("\nThe book succesfully added to the data.", "green"))
status = "F\n"
file = open("books.txt", "a+")
file.write(f"{isbn},{nameBook},{nameAuthor},{status}")
file.close()
# Function for searching books by their ISBN numbers in data.
def searchBookISBN():
file = open("books.txt", "r")
lines = file.readlines()
file.close()
searchingISBN = input("Enter the ISBN number of book which you are looking for.\n> ")
a = 0
for i in lines:
splitted = i.split(",")
numberISBN = colored(f"{splitted[0]}", "blue")
nameBook = colored(f"{splitted[1]}", "magenta", "on_grey")
nameAuthor = colored(f"{splitted[2]}", "yellow")
checkOut = splitted[3]
if checkOut == "T\n":
checkOut = colored("is not in the library.", "red")
if checkOut == "F\n":
checkOut = colored("is in the library.", "green")
if searchingISBN.upper() in numberISBN:
print("-" * 95)
print(colored(f"{numberISBN}", "blue"), "-", f"'{nameBook}' by {nameAuthor} {checkOut}")
print("-" * 95)
a += 1
if a == 0:
print("Sorry. There is no book with this ISBN number.")
# Function for searching books by their names in data.
def searchBookName():
file = open("books.txt", "r")
lines = file.readlines()
file.close()
searchingName = input("Enter the name of book which you are looking for.\n> ")
a = 0
for i in lines:
splitted = i.split(",")
numberISBN = colored(f"{splitted[0]}", "blue")
nameBook = colored(f"{splitted[1]}", "magenta", "on_grey")
nameAuthor = colored(f"{splitted[2]}", "yellow")
checkOut = splitted[3]
if checkOut == "T\n":
checkOut = colored("Book is not in the library.", "red")
if checkOut == "F\n":
checkOut = colored("Book is in the library.", "green")
if searchingName.lower() in nameBook.lower():
a += 1
print(colored("-" * 95, "cyan"))
print(f"ISBN: {numberISBN} - Name : {nameBook} - Author: {nameAuthor} - Status: {checkOut}\n")
print(colored("-" * 95, "magenta"))
if a == 0:
print("Sorry. There is no book with this name.")
# Function for searching books by their authors' name in data.
def searchBookAuthor():
file = open("books.txt", "r")
lines = file.readlines()
file.close()
searchingAuthor = input("Enter the author name which you are looking for: ")
a = 0
for i in lines:
splitted = i.split(",")
numberISBN = colored(f"{splitted[0]}", "blue")
nameBook = colored(f"{splitted[1]}", "magenta", "on_grey")
nameAuthor = colored(f"{splitted[2]}", "yellow")
checkOut = splitted[3]
if checkOut == "T\n":
checkOut = colored("Book is not in the library.", "red")
if checkOut == "F\n":
checkOut = colored("Book is in the library.", "green")
if searchingAuthor.lower() in nameAuthor.lower():
a += 1
print("-" * 95)
print(f"Author: {nameAuthor} - Name : {nameBook} - ISBN: {numberISBN} - Status: {checkOut}\n")
if a == 0:
print(colored("Sorry. There is no author with this name.", "red"))
# Function for generating tickets when checking out a book to check in book with.
# Possibility of 2.176.782.336 tickets.
def ticketGenerator(student_id, book_name):
chars = string.digits + string.ascii_uppercase
ticket = "".join(random.sample(chars, 6))
file = open("tickets.txt", "a+")
lines = file.readlines()
for i in lines:
splitted = i.split("-")
ticket2 = splitted[0]
if ticket == ticket2:
return ticketGenerator()
else:
file.write(f"{ticket}-{book_name}-{student_id}\n")
file.close()
return ticket
# Function for checking out books to students' data.
def checkOutBook():
file = open("books.txt", "rt")
dataBooksLines = file.readlines()
file.close()
file = open("students.txt", "r")
dataStudentsLines = file.readlines()
file.close()
dataCheckOut = open("checkouts.txt", "a")
bookToCheckOut = input("Please enter the ISBN number of book that you want to check out: ")
isBookToCheckOut = False
isBookToStudent = False
# Controlling if there is a book with this ISBN or not.
for i in dataBooksLines:
splitted = i.split(",")
numberISBN = splitted[0]
if bookToCheckOut == splitted[0]:
isBookToCheckOut = True
break
else:
print(colored("There is no book with this ISBN number.", "red"))
pass
if isBookToCheckOut == True:
bookToStudent = input("Please enter the student ID to check out: ")
for i in dataStudentsLines:
splitted = i.split(maxsplit= 1)
studentID = splitted[0]
studentName = splitted[1]
if bookToStudent == studentID:
isBookToStudent = True
break
else:
print(colored("There is no student with this ID. Try again.", "red"))
pass
if isBookToStudent == True:
for i in dataBooksLines:
splitted = i.split(",")
numberISBN = splitted[0]
nameBook = splitted[1]
nameAuthor = splitted[2]
checkOut = splitted[3]
if bookToCheckOut == numberISBN:
if checkOut == "T\n":
print(colored("Oops! This book is already checked out.", "red"))
else:
print(colored("Are you sure to check out this book?\n", "blue", "on_grey"))
print("ISBN:", colored(numberISBN, "blue"), "-", "Name :", colored(nameBook, "magenta", "on_grey"), "-", "Author:", colored(nameAuthor, "yellow"))
print(f"\nThis book will checked out to: " + colored(studentName, "white", "on_grey", attrs=['blink']))
verify = ""
while verify != "Y" or verify != "N" or verify != "y" or verify != "n":
verify = input("\nEnter Y or N\n" + colored("> ", "grey", attrs=['blink']))
if verify == "N" or verify == "n":
break
if verify == "Y" or verify == "y":
# Generating ticket and giving it to student.
ticketnumber = ticketGenerator(student_id= bookToStudent, book_name= nameBook)
os.system(clean_the_screen)
print(f"""
____/ \ / \____
/| ------------- | ----------- |\
||| ------------- | --->{colored(ticketnumber, "red", "on_cyan", attrs=['reverse', 'blink'])} |||
||| ------------- | ------------- |||
||| ------- ----- | --Here is---- |||
||| ------------- | -your-ticket--|||
||| ------------- | ----number.---|||
||| ------------ | --Use-it------|||
||| ------------- | -when-you--- |||
||| ------------- | -checking-in--|||
||| ------------- | ---the-book.--|||
||| ------------ | ------------- |||
|||_____________ | _____________|||
/_____/--------\\_//--------\_____\
""")
dataCheckOut.write(f"{numberISBN}-{ticketnumber}-{bookToStudent}-{nameBook}-{nameAuthor}\n")
dataCheckOut.close()
print(colored("\nThe book succesfully checked out to the student.", "green"))
# TO WRITE "T" ON BOOKS FILE WHEN CHANGED
for i in dataBooksLines:
splitted = i.split(",")
numberISBN = splitted[0]
nameBook = splitted[1]
nameAuthor = splitted[2]
checkOut = splitted[3]
if bookToCheckOut == numberISBN:
file = open("books.txt", "r")
content = file.read()
content = content.replace("{},{},{},{}".format(numberISBN, nameBook, nameAuthor, checkOut), "{},{},{},T\n".format(numberISBN, nameBook, nameAuthor))
file.close()
file = open("books.txt", "w")
file.write(content)
file.close()
break
# Function for listing students by their names with the books they checked out under their names.
def listStudents():
file = open("checkouts.txt", "r")
checkOutsLines = file.readlines()
file.close()
file = open("students.txt", "r")
studentsLines = file.readlines()
file.close()
file = open("checkins.txt", "r")
checkInsLines = file.readlines()
file.close()
isCheckInsLines = False
if len(checkInsLines) == 0:
isCheckInsLines = True
for i in studentsLines:
splitted = i.split()
sNumber = splitted[0]
sName = splitted[1]
sLastname = splitted[2]
print(colored("-" * 80, "grey"))
print(colored(f"{sName} {sLastname}", "blue"))
for x in checkOutsLines:
splitted = x.split("-")
nameBook = splitted[3]
scNumber = splitted[2]
ticket1 = splitted[1]
if isCheckInsLines:
if sNumber == scNumber:
print(colored("-" * 80, "grey"))
print(colored(f"\t-{nameBook}", "magenta", "on_grey"))
else:
for z in checkInsLines:
splitted = z.split("-")
ticket2 = splitted[1]
if ticket1 == ticket2:
break
else:
if sNumber == scNumber and ticket1 != ticket2:
print(colored("-" * 80, "grey"))
print(colored(f"\t-{nameBook}", "magenta", "on_grey"))
# Function for printing the top three most checked out books.
def topThreeBook():
file = open("checkouts.txt", "r")
checkoutsLines = file.readlines()
file.close()
file = open("books.txt", "r")
booksLines = file.readlines()
file.close()
isbns = []
for i in checkoutsLines:
splitted = i.split("-")
isbn = splitted[0]
isbns.append(isbn)
dictionary = Counter(isbns)
val_list = list(dictionary.values())
for i in range(3):
print("_" * 105)
if i == 0:
print(colored("THE MOST CHECKED OUT BOOK(S)!", "red", "on_yellow", attrs=['blink']))
elif i == 1:
print(colored("THE SECOND MOST CHECKED OUT BOOK(S)!", "red", "on_yellow", attrs=['blink']))
elif i == 2:
print(colored("THE THIRD MOST CHECKED OUT BOOK(S)!", "red", "on_yellow", attrs=['blink']))
try:
if len(val_list) != 0:
print("_" * 105)
print(colored(f"This/these book(s) has/have checked out for [{str(max(val_list))}] time(s)!", "cyan"))
print("_" * 105)
print("\n")
if val_list.count(max(val_list)) > 1:
for key, value in dictionary.items():
if max(val_list) == value:
for z in booksLines:
splitted2 = z.split(",")
bookISBN = splitted2[0]
bookName = splitted2[1]
if key == bookISBN:
key = bookName # key = isbn
print(key)
for i in range(val_list.count(max(val_list))):
val_list.remove(max(val_list))
elif val_list.count(max(val_list)) == 1:
for key, value in dictionary.items():
if max(val_list) == value:
for z in booksLines:
splitted2 = z.split(",")
bookISBN = splitted2[0]
bookName = splitted2[1]
if key == bookISBN:
key = bookName # key = isbn
print(key)
val_list.remove(max(val_list))
break
except:
print("There is no other books.")
# Function for printing top three students who checked out most.
def topThreeStudents():
dataCheckOut = open("checkouts.txt", "r")
dataCheckOutsLines = dataCheckOut.readlines()
dataCheckOut.close()
dataStudents = open("students.txt", "r")
dataStudentsLines = dataStudents.readlines()
dataStudents.close()
studentNumbers = []
for i in dataCheckOutsLines:
splitted = i.split("-")
stNumber = splitted[2]
studentNumbers.append(stNumber)
studentNumbers = Counter(studentNumbers)
val_list = list(studentNumbers.values())
for i in range(3):
print("_" * 105)
if i == 0:
print(colored("THE TOP #1 STUDENT(S)!", "red", "on_yellow", attrs=['blink']))
elif i == 1:
print(colored("THE TOP #2 STUDENT(S)!", "red", "on_yellow", attrs=['blink']))
elif i == 2:
print(colored("THE TOP #3 STUDENT(S)!", "red", "on_yellow", attrs=['blink']))
try:
if len(val_list) != 0:
print("_" * 105)
print(colored(f"This/these student(s) has/have checked out for [{str(max(val_list))}] time(s)!", "cyan"))
print("_" * 105)
print("\n")
if val_list.count(max(val_list)) > 1:
for key, value in studentNumbers.items():
if max(val_list) == value:
for z in dataStudentsLines:
splitted2 = z.split(maxsplit= 1)
sNumber = splitted2[0]
sName = splitted2[1]
if key == sNumber:
key = sName
print(key)
for i in range(val_list.count(max(val_list))):
val_list.remove(max(val_list))
elif val_list.count(max(val_list)) == 1:
for key, value in studentNumbers.items():
if max(val_list) == value:
for z in dataStudentsLines:
splitted2 = z.split(maxsplit= 1)
sNumber = splitted2[0]
sName = splitted2[1]
if key == sNumber:
key = sName
print(key)
val_list.remove(max(val_list))
break
except:
print("There is no other students who has checked out before.")
# Function for adding new students to data.
def addStudent():
file = open("students.txt", "r")
lines = file.readlines()
file.close()
numberStudent = input("Please enter the ID of a student to add.\n> ")
nameStudent = input("\nPlease enter the name of a student to add.\n> ")
for i in lines:
splitted = i.split(maxsplit= 1)
nStudent = splitted[0]
naStudent = splitted[1]
if numberStudent == nStudent:
print("This student ID is already exist.")
print(f"\t{nStudent} - {naStudent}")
break
else:
print(colored("\nThe student succesfully added to the data.", "green"))
file = open("students.txt", "a+")
file.write(f"{numberStudent} {nameStudent}\n")
file.close()
# Function for checking in a book with the ticket given when checked out.
def checkInBook():
ticket = input("Please enter the ticket to check in book.\n> ")
dataBooks = open("books.txt", "r")
dataBooksLines = dataBooks.readlines()
dataBooks.close()
file = open("checkouts.txt", "r")
checkoutsLines = file.readlines()
file.close()
a = 0
for i in checkoutsLines:
splitted = i.split("-")
isbn = splitted[0]
tNumber = splitted[1]
studentID = splitted[2]
nameBook = splitted[3]
if ticket == tNumber:
a += 1
print(colored("Thank you for bringing back the book!", "green"))
file = open("checkins.txt", "a")
file.write(f"The book in-{ticket}-came back.\n")
file.close()
# TO WRITE "F" ON BOOKS FILE WHEN CHANGED
for i in dataBooksLines:
splitted = i.split(",")
numberISBN = splitted[0]
nameBook = splitted[1]
nameAuthor = splitted[2]
checkOut = splitted[3]
if isbn == numberISBN:
file = open("books.txt", "r")
content = file.read()
content = content.replace("{},{},{},{}".format(numberISBN, nameBook, nameAuthor, checkOut), "{},{},{},F\n".format(numberISBN, nameBook, nameAuthor))
file.close()
file = open("books.txt", "w")
file.write(content)
file.close()
break
if a == 0:
print(colored(f"Sorry. There is no ticket as '{ticket}'.", "red"))
maxims = [
"'I have always imagined that Paradise will be a kind of a Library.' - Jorge Luis Borges ",
"'Nothing is pleasanter than exploring a library.' - Walter Savage Landor ",
"'The only thing that you absolutely have to know, is the location of the library.' - Albert Einstein",
"'When in doubt go to the library.' - J.K. Rowling ",
"'I have found the most valuable thing in my wallet is my library card.' - Laura Bush",
"'Google can bring you back 100,000 answers, a librarian can bring you back the right one.' - Neil Gaiman",
"'The most important asset of any library goes home at night – the library staff.' - Timothy Healy",
"'Librarians are tour-guides for all of knowledge.' - Patrick Ness",
]
slider = colored("-" * 48, "red")
version = colored("library.py-v1.0", "green")
menu = f"""{version}
{random.choice(maxims)}
.--. .---.
.---|__| .-. |~~~|
.--|===|--|_ |_| |~~~|--.
| |===| |'\ .---!~| .--| |--|
|%%| | |.'\ |===| |--|%%| | |
|%%| | |\.'\ | | |__| | | |
| | | | \ \ |===| |==| | | |
| | |__| \.'\ | |_|__| |~~~|__|
| |===|--| \.'\|===|~|--|%%|~~~|--|
^--^---'--^ `-'`---^-^--^--^---'--'
{colored("HELLO FROM WORLD LIBRARY!", "white", "on_blue", attrs=['blink'])}
{colored("[1]", "blue")} List all the books in the library.
{colored("[2]", "blue")} List all the books those are checked out.
{colored("[3]", "blue")} Add a new book.
{colored("[4]", "blue")} Search a book by ISBN number.
{colored("[5]", "blue")} Search a book by name.
{colored("[6]", "blue")} Check out a book to a student.
{colored("[7]", "blue")} List all the students.
{slider}
{colored("[8] List top 3 most checked out books.", "cyan", attrs=['blink'])}
{colored("[9] List top 3 student.", "cyan", attrs=['blink'])}
{slider}
{colored("[10]", "blue")} Add new student.
{colored("[11]", "blue")} Search an author by name.
{colored("[12]", "blue")} Check in a book to a library.
{slider}
{colored("[0]", "red")} Exit
"""
password = "123456"
def login():
os.system(clean_the_screen)
print(colored("""
____________________________________________________
|____________________________________________________|
| __ __ ____ ___ || ____ ____ _ __ |
|| |__ |--|_| || |_| |||_|**|*|__|+|+||___| || | |
||==|^^||--| |=||=| |=*=||| |~~|~| |=|=|| | |~||==| |
|| |##|| | | || | | |||-| | |==|+|+||-|-|~||__| |
||__|__||__|_|_||_|_|___|||_|__|_|__|_|_||_|_|_||__|_|
||_______________________||__________________________|
| _____________________ || __ __ _ __ _ |
||=|=|=|=|=|=|=|=|=|=|=| __..\/ | |_| ||#||==| / /|
|| | | | | | | | | | | |/\ \ \\|++|=| || ||==| / / |
||_|_|_|_|_|_|_|_|_|_|_/_/\_.___\__|_|__||_||__|/_/__|
|____________________ /\~()/()~//\ __________________|
| __ __ _ _ \_ (_ . _/ _ ___ _____|
||~~|_|..|__| || |_ _ \ //\\ / |=|__|~|~|___| | | |
||--|+|^^|==| || | | |__/\ __ /\__| |==|x|x|+|+|=|=|=|
||__|_|__|__|_||_|_| / \ \ / / \_|__|_|_|_|_|_|_|_|
|_________________ _/ \/\/\/ \_ _______________|
| _____ _ __ |/ \../ \| __ __ ___|
||_____|_| |_|##|_|| | \/ __| ||_|==|_|++|_|-|||
||______||=|#|--| |\ \ o / /| | |~| | | |||
||______||_|_|__|_|_\ \ o / /_|_|__|_|__|_|_|||
|_________ __________\___\____/___/___________ ______|
|__ _ / ________ ______ /| _ _ _|
|\ \ |=|/ // /| // / / / | / ||%|%|%|
| \/\ |*/ .//____//.// /__/__/ (_) / ||=|=|=|
__| \/\|/ /(____|/ // / /||~|~|~|__
|___\_/ /________// ________ / / ||_|_|_|
|___ / (|________/ |\_______\ / /| |______|
/ \|________) / / | |
""", "yellow"))
login = input("Please enter the password to log in.\n> ")
if password == login:
print(colored("Succesfully logged in!", "green", attrs=['reverse', 'blink']))
time.sleep(2)
global isLogIn
isLogIn = True
else:
print(colored("Wrong password!", "red", attrs=['reverse', 'blink']))
print("Exiting...")
time.sleep(2)
os.system(clean_the_screen)
exit()
enterToGo = colored("Press 'Enter' to continue to the menu...", "white", "on_grey", attrs=['blink'])
if True:
isLogIn = False
login()
while isLogIn:
os.system(clean_the_screen)
print(menu)
choice = input("What would you like to do?\n> ")
choice_list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "10", "11", "12"]
if choice in choice_list:
if choice == "1":
os.system(clean_the_screen)
listBooks()
print("-" * 112)
input(enterToGo)
elif choice == "2":
os.system(clean_the_screen)
listBooksChecked()
print("-" * 115)
input(enterToGo)
elif choice == "3":
os.system(clean_the_screen)
addBook()
input(enterToGo)
elif choice == "4":
os.system(clean_the_screen)
searchBookISBN()
input(enterToGo)
elif choice == "5":
os.system(clean_the_screen)
searchBookName()
input(enterToGo)
elif choice == "6":
os.system(clean_the_screen)
checkOutBook()
input(enterToGo)
elif choice == "7":
os.system(clean_the_screen)
listStudents()
print("-" * 80)
input(enterToGo)
elif choice == "8":
os.system(clean_the_screen)
topThreeBook()
print("-" * 80)
input(enterToGo)
elif choice == "9":
os.system(clean_the_screen)
topThreeStudents()
print("-" * 80)
input(enterToGo)
elif choice == "10":
os.system(clean_the_screen)
addStudent()
print("-" * 80)
input(enterToGo)
elif choice == "11":
os.system(clean_the_screen)
searchBookAuthor()
print("-" * 80)
input(enterToGo)
elif choice == "12":
os.system(clean_the_screen)
checkInBook()
print("-" * 80)
input(enterToGo)
elif choice == "0":
print("Saving all the changes...")
time.sleep(3)
os.system(clean_the_screen)
print("See you soon!\n")
exit()
else:
print("Please enter a number in menu. (1-12)")
input(enterToGo) | 32.87642 | 158 | 0.572391 | import time
import string
import random
import os
from termcolor import colored
from collections import Counter
clean_the_screen = ("cls" if os.name == "nt" else "clear")
def listBooks():
file = open("books.txt", "r")
lines = file.readlines()
file.close()
for i in lines:
splitted = i.split(",")
numberISBN = colored(f"{splitted[0]}", "blue")
nameBook = colored(f"{splitted[1]}", "magenta", "on_grey")
nameAuthor = colored(f"{splitted[2]}", "yellow")
checkOut = splitted[3]
if checkOut == "T\n":
checkOut = colored("Book is not in the library.", "red")
if checkOut == "F\n":
checkOut = colored("Book is in the library.", "green")
print("-" * 115)
print(f"Name: {nameBook} - Author: {nameAuthor} - Status: {checkOut} - ISBN: {numberISBN}\n")
def listBooksChecked():
file = open("books.txt", "r")
lines = file.readlines()
file.close()
a = 0
for i in lines:
splitted = i.split(",")
numberISBN = colored(f"{splitted[0]}", "blue")
nameBook = colored(f"{splitted[1]}", "magenta", "on_grey")
nameAuthor = colored(f"{splitted[2]}", "yellow")
checkOut = splitted[3]
if checkOut == "T\n":
a += 1
print("-" * 115)
print(f"Name: {nameBook} - Author: {nameAuthor} - ISBN: {numberISBN}\n")
if a == 0:
print("-" * 115)
print(colored("\tUhm..- Nobody reads books these days.\n", "blue"))
print("There is no checked out book. All the books are in the library.")
def addBook():
file = open("books.txt", "r")
lines = file.readlines()
file.close()
isbn = input("Please enter the ISBN number: ")
nameBook = input("Please enter the name of book: ")
nameAuthor = input("Please enter the author name: ")
for i in lines:
splitted = i.split(",")
isbnBook = splitted[0]
nBook = splitted[1]
if isbn == isbnBook:
print(colored("There is already a book with this ISBN.", "red"))
print(f"\t{isbn} - {nBook}")
break
else:
print(colored("\nThe book succesfully added to the data.", "green"))
status = "F\n"
file = open("books.txt", "a+")
file.write(f"{isbn},{nameBook},{nameAuthor},{status}")
file.close()
# Function for searching books by their ISBN numbers in data.
def searchBookISBN():
file = open("books.txt", "r")
lines = file.readlines()
file.close()
searchingISBN = input("Enter the ISBN number of book which you are looking for.\n> ")
a = 0
for i in lines:
splitted = i.split(",")
numberISBN = colored(f"{splitted[0]}", "blue")
nameBook = colored(f"{splitted[1]}", "magenta", "on_grey")
nameAuthor = colored(f"{splitted[2]}", "yellow")
checkOut = splitted[3]
if checkOut == "T\n":
checkOut = colored("is not in the library.", "red")
if checkOut == "F\n":
checkOut = colored("is in the library.", "green")
if searchingISBN.upper() in numberISBN:
print("-" * 95)
print(colored(f"{numberISBN}", "blue"), "-", f"'{nameBook}' by {nameAuthor} {checkOut}")
print("-" * 95)
a += 1
if a == 0:
print("Sorry. There is no book with this ISBN number.")
# Function for searching books by their names in data.
def searchBookName():
file = open("books.txt", "r")
lines = file.readlines()
file.close()
searchingName = input("Enter the name of book which you are looking for.\n> ")
a = 0
for i in lines:
splitted = i.split(",")
numberISBN = colored(f"{splitted[0]}", "blue")
nameBook = colored(f"{splitted[1]}", "magenta", "on_grey")
nameAuthor = colored(f"{splitted[2]}", "yellow")
checkOut = splitted[3]
if checkOut == "T\n":
checkOut = colored("Book is not in the library.", "red")
if checkOut == "F\n":
checkOut = colored("Book is in the library.", "green")
if searchingName.lower() in nameBook.lower():
a += 1
print(colored("-" * 95, "cyan"))
print(f"ISBN: {numberISBN} - Name : {nameBook} - Author: {nameAuthor} - Status: {checkOut}\n")
print(colored("-" * 95, "magenta"))
if a == 0:
print("Sorry. There is no book with this name.")
# Function for searching books by their authors' name in data.
def searchBookAuthor():
file = open("books.txt", "r")
lines = file.readlines()
file.close()
searchingAuthor = input("Enter the author name which you are looking for: ")
a = 0
for i in lines:
splitted = i.split(",")
numberISBN = colored(f"{splitted[0]}", "blue")
nameBook = colored(f"{splitted[1]}", "magenta", "on_grey")
nameAuthor = colored(f"{splitted[2]}", "yellow")
checkOut = splitted[3]
if checkOut == "T\n":
checkOut = colored("Book is not in the library.", "red")
if checkOut == "F\n":
checkOut = colored("Book is in the library.", "green")
if searchingAuthor.lower() in nameAuthor.lower():
a += 1
print("-" * 95)
print(f"Author: {nameAuthor} - Name : {nameBook} - ISBN: {numberISBN} - Status: {checkOut}\n")
if a == 0:
print(colored("Sorry. There is no author with this name.", "red"))
def ticketGenerator(student_id, book_name):
chars = string.digits + string.ascii_uppercase
ticket = "".join(random.sample(chars, 6))
file = open("tickets.txt", "a+")
lines = file.readlines()
for i in lines:
splitted = i.split("-")
ticket2 = splitted[0]
if ticket == ticket2:
return ticketGenerator()
else:
file.write(f"{ticket}-{book_name}-{student_id}\n")
file.close()
return ticket
def checkOutBook():
file = open("books.txt", "rt")
dataBooksLines = file.readlines()
file.close()
file = open("students.txt", "r")
dataStudentsLines = file.readlines()
file.close()
dataCheckOut = open("checkouts.txt", "a")
bookToCheckOut = input("Please enter the ISBN number of book that you want to check out: ")
isBookToCheckOut = False
isBookToStudent = False
# Controlling if there is a book with this ISBN or not.
for i in dataBooksLines:
splitted = i.split(",")
numberISBN = splitted[0]
if bookToCheckOut == splitted[0]:
isBookToCheckOut = True
break
else:
print(colored("There is no book with this ISBN number.", "red"))
pass
if isBookToCheckOut == True:
bookToStudent = input("Please enter the student ID to check out: ")
for i in dataStudentsLines:
splitted = i.split(maxsplit= 1)
studentID = splitted[0]
studentName = splitted[1]
if bookToStudent == studentID:
isBookToStudent = True
break
else:
print(colored("There is no student with this ID. Try again.", "red"))
pass
if isBookToStudent == True:
for i in dataBooksLines:
splitted = i.split(",")
numberISBN = splitted[0]
nameBook = splitted[1]
nameAuthor = splitted[2]
checkOut = splitted[3]
if bookToCheckOut == numberISBN:
if checkOut == "T\n":
print(colored("Oops! This book is already checked out.", "red"))
else:
print(colored("Are you sure to check out this book?\n", "blue", "on_grey"))
print("ISBN:", colored(numberISBN, "blue"), "-", "Name :", colored(nameBook, "magenta", "on_grey"), "-", "Author:", colored(nameAuthor, "yellow"))
print(f"\nThis book will checked out to: " + colored(studentName, "white", "on_grey", attrs=['blink']))
verify = ""
while verify != "Y" or verify != "N" or verify != "y" or verify != "n":
verify = input("\nEnter Y or N\n" + colored("> ", "grey", attrs=['blink']))
if verify == "N" or verify == "n":
break
if verify == "Y" or verify == "y":
# Generating ticket and giving it to student.
ticketnumber = ticketGenerator(student_id= bookToStudent, book_name= nameBook)
os.system(clean_the_screen)
print(f"""
____/ \ / \____
/| ------------- | ----------- |\
||| ------------- | --->{colored(ticketnumber, "red", "on_cyan", attrs=['reverse', 'blink'])} |||
||| ------------- | ------------- |||
||| ------- ----- | --Here is---- |||
||| ------------- | -your-ticket--|||
||| ------------- | ----number.---|||
||| ------------ | --Use-it------|||
||| ------------- | -when-you--- |||
||| ------------- | -checking-in--|||
||| ------------- | ---the-book.--|||
||| ------------ | ------------- |||
|||_____________ | _____________|||
/_____/--------\\_//--------\_____\
""")
dataCheckOut.write(f"{numberISBN}-{ticketnumber}-{bookToStudent}-{nameBook}-{nameAuthor}\n")
dataCheckOut.close()
print(colored("\nThe book succesfully checked out to the student.", "green"))
# TO WRITE "T" ON BOOKS FILE WHEN CHANGED
for i in dataBooksLines:
splitted = i.split(",")
numberISBN = splitted[0]
nameBook = splitted[1]
nameAuthor = splitted[2]
checkOut = splitted[3]
if bookToCheckOut == numberISBN:
file = open("books.txt", "r")
content = file.read()
content = content.replace("{},{},{},{}".format(numberISBN, nameBook, nameAuthor, checkOut), "{},{},{},T\n".format(numberISBN, nameBook, nameAuthor))
file.close()
file = open("books.txt", "w")
file.write(content)
file.close()
break
# Function for listing students by their names with the books they checked out under their names.
def listStudents():
file = open("checkouts.txt", "r")
checkOutsLines = file.readlines()
file.close()
file = open("students.txt", "r")
studentsLines = file.readlines()
file.close()
file = open("checkins.txt", "r")
checkInsLines = file.readlines()
file.close()
isCheckInsLines = False
if len(checkInsLines) == 0:
isCheckInsLines = True
for i in studentsLines:
splitted = i.split()
sNumber = splitted[0]
sName = splitted[1]
sLastname = splitted[2]
print(colored("-" * 80, "grey"))
print(colored(f"{sName} {sLastname}", "blue"))
for x in checkOutsLines:
splitted = x.split("-")
nameBook = splitted[3]
scNumber = splitted[2]
ticket1 = splitted[1]
if isCheckInsLines:
if sNumber == scNumber:
print(colored("-" * 80, "grey"))
print(colored(f"\t-{nameBook}", "magenta", "on_grey"))
else:
for z in checkInsLines:
splitted = z.split("-")
ticket2 = splitted[1]
if ticket1 == ticket2:
break
else:
if sNumber == scNumber and ticket1 != ticket2:
print(colored("-" * 80, "grey"))
print(colored(f"\t-{nameBook}", "magenta", "on_grey"))
# Function for printing the top three most checked out books.
def topThreeBook():
file = open("checkouts.txt", "r")
checkoutsLines = file.readlines()
file.close()
file = open("books.txt", "r")
booksLines = file.readlines()
file.close()
isbns = []
for i in checkoutsLines:
splitted = i.split("-")
isbn = splitted[0]
isbns.append(isbn)
dictionary = Counter(isbns)
val_list = list(dictionary.values())
for i in range(3):
print("_" * 105)
if i == 0:
print(colored("THE MOST CHECKED OUT BOOK(S)!", "red", "on_yellow", attrs=['blink']))
elif i == 1:
print(colored("THE SECOND MOST CHECKED OUT BOOK(S)!", "red", "on_yellow", attrs=['blink']))
elif i == 2:
print(colored("THE THIRD MOST CHECKED OUT BOOK(S)!", "red", "on_yellow", attrs=['blink']))
try:
if len(val_list) != 0:
print("_" * 105)
print(colored(f"This/these book(s) has/have checked out for [{str(max(val_list))}] time(s)!", "cyan"))
print("_" * 105)
print("\n")
if val_list.count(max(val_list)) > 1:
for key, value in dictionary.items():
if max(val_list) == value:
for z in booksLines:
splitted2 = z.split(",")
bookISBN = splitted2[0]
bookName = splitted2[1]
if key == bookISBN:
key = bookName # key = isbn
print(key)
for i in range(val_list.count(max(val_list))):
val_list.remove(max(val_list))
elif val_list.count(max(val_list)) == 1:
for key, value in dictionary.items():
if max(val_list) == value:
for z in booksLines:
splitted2 = z.split(",")
bookISBN = splitted2[0]
bookName = splitted2[1]
if key == bookISBN:
key = bookName # key = isbn
print(key)
val_list.remove(max(val_list))
break
except:
print("There is no other books.")
# Function for printing top three students who checked out most.
def topThreeStudents():
dataCheckOut = open("checkouts.txt", "r")
dataCheckOutsLines = dataCheckOut.readlines()
dataCheckOut.close()
dataStudents = open("students.txt", "r")
dataStudentsLines = dataStudents.readlines()
dataStudents.close()
studentNumbers = []
for i in dataCheckOutsLines:
splitted = i.split("-")
stNumber = splitted[2]
studentNumbers.append(stNumber)
studentNumbers = Counter(studentNumbers)
val_list = list(studentNumbers.values())
for i in range(3):
print("_" * 105)
if i == 0:
print(colored("THE TOP #1 STUDENT(S)!", "red", "on_yellow", attrs=['blink']))
elif i == 1:
print(colored("THE TOP #2 STUDENT(S)!", "red", "on_yellow", attrs=['blink']))
elif i == 2:
print(colored("THE TOP #3 STUDENT(S)!", "red", "on_yellow", attrs=['blink']))
try:
if len(val_list) != 0:
print("_" * 105)
print(colored(f"This/these student(s) has/have checked out for [{str(max(val_list))}] time(s)!", "cyan"))
print("_" * 105)
print("\n")
if val_list.count(max(val_list)) > 1:
for key, value in studentNumbers.items():
if max(val_list) == value:
for z in dataStudentsLines:
splitted2 = z.split(maxsplit= 1)
sNumber = splitted2[0]
sName = splitted2[1]
if key == sNumber:
key = sName
print(key)
for i in range(val_list.count(max(val_list))):
val_list.remove(max(val_list))
elif val_list.count(max(val_list)) == 1:
for key, value in studentNumbers.items():
if max(val_list) == value:
for z in dataStudentsLines:
splitted2 = z.split(maxsplit= 1)
sNumber = splitted2[0]
sName = splitted2[1]
if key == sNumber:
key = sName
print(key)
val_list.remove(max(val_list))
break
except:
print("There is no other students who has checked out before.")
# Function for adding new students to data.
def addStudent():
file = open("students.txt", "r")
lines = file.readlines()
file.close()
numberStudent = input("Please enter the ID of a student to add.\n> ")
nameStudent = input("\nPlease enter the name of a student to add.\n> ")
for i in lines:
splitted = i.split(maxsplit= 1)
nStudent = splitted[0]
naStudent = splitted[1]
if numberStudent == nStudent:
print("This student ID is already exist.")
print(f"\t{nStudent} - {naStudent}")
break
else:
print(colored("\nThe student succesfully added to the data.", "green"))
file = open("students.txt", "a+")
file.write(f"{numberStudent} {nameStudent}\n")
file.close()
# Function for checking in a book with the ticket given when checked out.
def checkInBook():
ticket = input("Please enter the ticket to check in book.\n> ")
dataBooks = open("books.txt", "r")
dataBooksLines = dataBooks.readlines()
dataBooks.close()
file = open("checkouts.txt", "r")
checkoutsLines = file.readlines()
file.close()
a = 0
for i in checkoutsLines:
splitted = i.split("-")
isbn = splitted[0]
tNumber = splitted[1]
studentID = splitted[2]
nameBook = splitted[3]
if ticket == tNumber:
a += 1
print(colored("Thank you for bringing back the book!", "green"))
file = open("checkins.txt", "a")
file.write(f"The book in-{ticket}-came back.\n")
file.close()
# TO WRITE "F" ON BOOKS FILE WHEN CHANGED
for i in dataBooksLines:
splitted = i.split(",")
numberISBN = splitted[0]
nameBook = splitted[1]
nameAuthor = splitted[2]
checkOut = splitted[3]
if isbn == numberISBN:
file = open("books.txt", "r")
content = file.read()
content = content.replace("{},{},{},{}".format(numberISBN, nameBook, nameAuthor, checkOut), "{},{},{},F\n".format(numberISBN, nameBook, nameAuthor))
file.close()
file = open("books.txt", "w")
file.write(content)
file.close()
break
if a == 0:
print(colored(f"Sorry. There is no ticket as '{ticket}'.", "red"))
maxims = [
"'I have always imagined that Paradise will be a kind of a Library.' - Jorge Luis Borges ",
"'Nothing is pleasanter than exploring a library.' - Walter Savage Landor ",
"'The only thing that you absolutely have to know, is the location of the library.' - Albert Einstein",
"'When in doubt go to the library.' - J.K. Rowling ",
"'I have found the most valuable thing in my wallet is my library card.' - Laura Bush",
"'Google can bring you back 100,000 answers, a librarian can bring you back the right one.' - Neil Gaiman",
"'The most important asset of any library goes home at night – the library staff.' - Timothy Healy",
"'Librarians are tour-guides for all of knowledge.' - Patrick Ness",
]
slider = colored("-" * 48, "red")
version = colored("library.py-v1.0", "green")
menu = f"""{version}
{random.choice(maxims)}
.--. .---.
.---|__| .-. |~~~|
.--|===|--|_ |_| |~~~|--.
| |===| |'\ .---!~| .--| |--|
|%%| | |.'\ |===| |--|%%| | |
|%%| | |\.'\ | | |__| | | |
| | | | \ \ |===| |==| | | |
| | |__| \.'\ | |_|__| |~~~|__|
| |===|--| \.'\|===|~|--|%%|~~~|--|
^--^---'--^ `-'`---^-^--^--^---'--'
{colored("HELLO FROM WORLD LIBRARY!", "white", "on_blue", attrs=['blink'])}
{colored("[1]", "blue")} List all the books in the library.
{colored("[2]", "blue")} List all the books those are checked out.
{colored("[3]", "blue")} Add a new book.
{colored("[4]", "blue")} Search a book by ISBN number.
{colored("[5]", "blue")} Search a book by name.
{colored("[6]", "blue")} Check out a book to a student.
{colored("[7]", "blue")} List all the students.
{slider}
{colored("[8] List top 3 most checked out books.", "cyan", attrs=['blink'])}
{colored("[9] List top 3 student.", "cyan", attrs=['blink'])}
{slider}
{colored("[10]", "blue")} Add new student.
{colored("[11]", "blue")} Search an author by name.
{colored("[12]", "blue")} Check in a book to a library.
{slider}
{colored("[0]", "red")} Exit
"""
password = "123456"
def login():
os.system(clean_the_screen)
print(colored("""
____________________________________________________
|____________________________________________________|
| __ __ ____ ___ || ____ ____ _ __ |
|| |__ |--|_| || |_| |||_|**|*|__|+|+||___| || | |
||==|^^||--| |=||=| |=*=||| |~~|~| |=|=|| | |~||==| |
|| |##|| | | || | | |||-| | |==|+|+||-|-|~||__| |
||__|__||__|_|_||_|_|___|||_|__|_|__|_|_||_|_|_||__|_|
||_______________________||__________________________|
| _____________________ || __ __ _ __ _ |
||=|=|=|=|=|=|=|=|=|=|=| __..\/ | |_| ||#||==| / /|
|| | | | | | | | | | | |/\ \ \\|++|=| || ||==| / / |
||_|_|_|_|_|_|_|_|_|_|_/_/\_.___\__|_|__||_||__|/_/__|
|____________________ /\~()/()~//\ __________________|
| __ __ _ _ \_ (_ . _/ _ ___ _____|
||~~|_|..|__| || |_ _ \ //\\ / |=|__|~|~|___| | | |
||--|+|^^|==| || | | |__/\ __ /\__| |==|x|x|+|+|=|=|=|
||__|_|__|__|_||_|_| / \ \ / / \_|__|_|_|_|_|_|_|_|
|_________________ _/ \/\/\/ \_ _______________|
| _____ _ __ |/ \../ \| __ __ ___|
||_____|_| |_|##|_|| | \/ __| ||_|==|_|++|_|-|||
||______||=|#|--| |\ \ o / /| | |~| | | |||
||______||_|_|__|_|_\ \ o / /_|_|__|_|__|_|_|||
|_________ __________\___\____/___/___________ ______|
|__ _ / ________ ______ /| _ _ _|
|\ \ |=|/ // /| // / / / | / ||%|%|%|
| \/\ |*/ .//____//.// /__/__/ (_) / ||=|=|=|
__| \/\|/ /(____|/ // / /||~|~|~|__
|___\_/ /________// ________ / / ||_|_|_|
|___ / (|________/ |\_______\ / /| |______|
/ \|________) / / | |
""", "yellow"))
login = input("Please enter the password to log in.\n> ")
if password == login:
print(colored("Succesfully logged in!", "green", attrs=['reverse', 'blink']))
time.sleep(2)
global isLogIn
isLogIn = True
else:
print(colored("Wrong password!", "red", attrs=['reverse', 'blink']))
print("Exiting...")
time.sleep(2)
os.system(clean_the_screen)
exit()
enterToGo = colored("Press 'Enter' to continue to the menu...", "white", "on_grey", attrs=['blink'])
if True:
isLogIn = False
login()
while isLogIn:
os.system(clean_the_screen)
print(menu)
choice = input("What would you like to do?\n> ")
choice_list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "10", "11", "12"]
if choice in choice_list:
if choice == "1":
os.system(clean_the_screen)
listBooks()
print("-" * 112)
input(enterToGo)
elif choice == "2":
os.system(clean_the_screen)
listBooksChecked()
print("-" * 115)
input(enterToGo)
elif choice == "3":
os.system(clean_the_screen)
addBook()
input(enterToGo)
elif choice == "4":
os.system(clean_the_screen)
searchBookISBN()
input(enterToGo)
elif choice == "5":
os.system(clean_the_screen)
searchBookName()
input(enterToGo)
elif choice == "6":
os.system(clean_the_screen)
checkOutBook()
input(enterToGo)
elif choice == "7":
os.system(clean_the_screen)
listStudents()
print("-" * 80)
input(enterToGo)
elif choice == "8":
os.system(clean_the_screen)
topThreeBook()
print("-" * 80)
input(enterToGo)
elif choice == "9":
os.system(clean_the_screen)
topThreeStudents()
print("-" * 80)
input(enterToGo)
elif choice == "10":
os.system(clean_the_screen)
addStudent()
print("-" * 80)
input(enterToGo)
elif choice == "11":
os.system(clean_the_screen)
searchBookAuthor()
print("-" * 80)
input(enterToGo)
elif choice == "12":
os.system(clean_the_screen)
checkInBook()
print("-" * 80)
input(enterToGo)
elif choice == "0":
print("Saving all the changes...")
time.sleep(3)
os.system(clean_the_screen)
print("See you soon!\n")
exit()
else:
print("Please enter a number in menu. (1-12)")
input(enterToGo) | true | true |
f71a0395c544caeb8e59eb6aa3e37e0cba7e4d34 | 325 | py | Python | test.py | deancolten/buzzsprout-manager | a630ee39171b7086ac738e29b721b73c39a1581f | [
"MIT"
] | null | null | null | test.py | deancolten/buzzsprout-manager | a630ee39171b7086ac738e29b721b73c39a1581f | [
"MIT"
] | null | null | null | test.py | deancolten/buzzsprout-manager | a630ee39171b7086ac738e29b721b73c39a1581f | [
"MIT"
] | null | null | null | from bsm import Manager, Episode, EpisodeGroup
from dotenv import load_dotenv
import os
load_dotenv()
ID = os.environ.get("ID")
TOKEN = os.environ.get("TOKEN")
manager = Manager(ID, TOKEN)
print(manager.test_api())
ep = Episode(**{'title': "test upload"})
res = manager.post_episode(ep, 'testfile.mp3', None)
print(res)
| 19.117647 | 52 | 0.723077 | from bsm import Manager, Episode, EpisodeGroup
from dotenv import load_dotenv
import os
load_dotenv()
ID = os.environ.get("ID")
TOKEN = os.environ.get("TOKEN")
manager = Manager(ID, TOKEN)
print(manager.test_api())
ep = Episode(**{'title': "test upload"})
res = manager.post_episode(ep, 'testfile.mp3', None)
print(res)
| true | true |
f71a03a12dbb6d843747f75d2f29f96ad24a5738 | 13,861 | py | Python | synapse/rest/media/v1/_base.py | Oliver-Hanikel/synapse | 6276e685345cff0b1dc32a02354914a39da911f0 | [
"Apache-2.0"
] | null | null | null | synapse/rest/media/v1/_base.py | Oliver-Hanikel/synapse | 6276e685345cff0b1dc32a02354914a39da911f0 | [
"Apache-2.0"
] | null | null | null | synapse/rest/media/v1/_base.py | Oliver-Hanikel/synapse | 6276e685345cff0b1dc32a02354914a39da911f0 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2019-2021 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import os
import urllib
from typing import Awaitable, Dict, Generator, List, Optional, Tuple
from twisted.internet.interfaces import IConsumer
from twisted.protocols.basic import FileSender
from twisted.web.http import Request
from synapse.api.errors import Codes, SynapseError, cs_error
from synapse.http.server import finish_request, respond_with_json
from synapse.logging.context import make_deferred_yieldable
from synapse.util.stringutils import is_ascii
logger = logging.getLogger(__name__)
# list all text content types that will have the charset default to UTF-8 when
# none is given
TEXT_CONTENT_TYPES = [
"text/css",
"text/csv",
"text/html",
"text/calendar",
"text/plain",
"text/javascript",
"application/json",
"application/ld+json",
"application/rtf",
"image/svg+xml",
"text/xml",
]
def parse_media_id(request: Request) -> Tuple[str, str, Optional[str]]:
try:
# This allows users to append e.g. /test.png to the URL. Useful for
# clients that parse the URL to see content type.
server_name, media_id = request.postpath[:2]
if isinstance(server_name, bytes):
server_name = server_name.decode("utf-8")
media_id = media_id.decode("utf8")
file_name = None
if len(request.postpath) > 2:
try:
file_name = urllib.parse.unquote(request.postpath[-1].decode("utf-8"))
except UnicodeDecodeError:
pass
return server_name, media_id, file_name
except Exception:
raise SynapseError(
404, "Invalid media id token %r" % (request.postpath,), Codes.UNKNOWN
)
def respond_404(request: Request) -> None:
respond_with_json(
request,
404,
cs_error("Not found %r" % (request.postpath,), code=Codes.NOT_FOUND),
send_cors=True,
)
async def respond_with_file(
request: Request,
media_type: str,
file_path: str,
file_size: Optional[int] = None,
upload_name: Optional[str] = None,
) -> None:
logger.debug("Responding with %r", file_path)
if os.path.isfile(file_path):
if file_size is None:
stat = os.stat(file_path)
file_size = stat.st_size
add_file_headers(request, media_type, file_size, upload_name)
with open(file_path, "rb") as f:
await make_deferred_yieldable(FileSender().beginFileTransfer(f, request))
finish_request(request)
else:
respond_404(request)
def add_file_headers(
request: Request,
media_type: str,
file_size: Optional[int],
upload_name: Optional[str],
) -> None:
"""Adds the correct response headers in preparation for responding with the
media.
Args:
request
media_type: The media/content type.
file_size: Size in bytes of the media, if known.
upload_name: The name of the requested file, if any.
"""
def _quote(x):
return urllib.parse.quote(x.encode("utf-8"))
# Default to a UTF-8 charset for text content types.
# ex, uses UTF-8 for 'text/css' but not 'text/css; charset=UTF-16'
if media_type.lower() in TEXT_CONTENT_TYPES:
content_type = media_type + "; charset=UTF-8"
else:
content_type = media_type
request.setHeader(b"Content-Type", content_type.encode("UTF-8"))
if upload_name:
# RFC6266 section 4.1 [1] defines both `filename` and `filename*`.
#
# `filename` is defined to be a `value`, which is defined by RFC2616
# section 3.6 [2] to be a `token` or a `quoted-string`, where a `token`
# is (essentially) a single US-ASCII word, and a `quoted-string` is a
# US-ASCII string surrounded by double-quotes, using backslash as an
# escape charater. Note that %-encoding is *not* permitted.
#
# `filename*` is defined to be an `ext-value`, which is defined in
# RFC5987 section 3.2.1 [3] to be `charset "'" [ language ] "'" value-chars`,
# where `value-chars` is essentially a %-encoded string in the given charset.
#
# [1]: https://tools.ietf.org/html/rfc6266#section-4.1
# [2]: https://tools.ietf.org/html/rfc2616#section-3.6
# [3]: https://tools.ietf.org/html/rfc5987#section-3.2.1
# We avoid the quoted-string version of `filename`, because (a) synapse didn't
# correctly interpret those as of 0.99.2 and (b) they are a bit of a pain and we
# may as well just do the filename* version.
if _can_encode_filename_as_token(upload_name):
disposition = "inline; filename=%s" % (upload_name,)
else:
disposition = "inline; filename*=utf-8''%s" % (_quote(upload_name),)
request.setHeader(b"Content-Disposition", disposition.encode("ascii"))
# cache for at least a day.
# XXX: we might want to turn this off for data we don't want to
# recommend caching as it's sensitive or private - or at least
# select private. don't bother setting Expires as all our
# clients are smart enough to be happy with Cache-Control
request.setHeader(b"Cache-Control", b"public,max-age=86400,s-maxage=86400")
if file_size is not None:
request.setHeader(b"Content-Length", b"%d" % (file_size,))
# Tell web crawlers to not index, archive, or follow links in media. This
# should help to prevent things in the media repo from showing up in web
# search results.
request.setHeader(b"X-Robots-Tag", "noindex, nofollow, noarchive, noimageindex")
# separators as defined in RFC2616. SP and HT are handled separately.
# see _can_encode_filename_as_token.
_FILENAME_SEPARATOR_CHARS = {
"(",
")",
"<",
">",
"@",
",",
";",
":",
"\\",
'"',
"/",
"[",
"]",
"?",
"=",
"{",
"}",
}
def _can_encode_filename_as_token(x: str) -> bool:
for c in x:
# from RFC2616:
#
# token = 1*<any CHAR except CTLs or separators>
#
# separators = "(" | ")" | "<" | ">" | "@"
# | "," | ";" | ":" | "\" | <">
# | "/" | "[" | "]" | "?" | "="
# | "{" | "}" | SP | HT
#
# CHAR = <any US-ASCII character (octets 0 - 127)>
#
# CTL = <any US-ASCII control character
# (octets 0 - 31) and DEL (127)>
#
if ord(c) >= 127 or ord(c) <= 32 or c in _FILENAME_SEPARATOR_CHARS:
return False
return True
async def respond_with_responder(
request: Request,
responder: "Optional[Responder]",
media_type: str,
file_size: Optional[int],
upload_name: Optional[str] = None,
) -> None:
"""Responds to the request with given responder. If responder is None then
returns 404.
Args:
request
responder
media_type: The media/content type.
file_size: Size in bytes of the media. If not known it should be None
upload_name: The name of the requested file, if any.
"""
if request._disconnected:
logger.warning(
"Not sending response to request %s, already disconnected.", request
)
return
if not responder:
respond_404(request)
return
logger.debug("Responding to media request with responder %s", responder)
add_file_headers(request, media_type, file_size, upload_name)
try:
with responder:
await responder.write_to_consumer(request)
except Exception as e:
# The majority of the time this will be due to the client having gone
# away. Unfortunately, Twisted simply throws a generic exception at us
# in that case.
logger.warning("Failed to write to consumer: %s %s", type(e), e)
# Unregister the producer, if it has one, so Twisted doesn't complain
if request.producer:
request.unregisterProducer()
finish_request(request)
class Responder:
"""Represents a response that can be streamed to the requester.
Responder is a context manager which *must* be used, so that any resources
held can be cleaned up.
"""
def write_to_consumer(self, consumer: IConsumer) -> Awaitable:
"""Stream response into consumer
Args:
consumer: The consumer to stream into.
Returns:
Resolves once the response has finished being written
"""
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
class FileInfo:
"""Details about a requested/uploaded file.
Attributes:
server_name (str): The server name where the media originated from,
or None if local.
file_id (str): The local ID of the file. For local files this is the
same as the media_id
url_cache (bool): If the file is for the url preview cache
thumbnail (bool): Whether the file is a thumbnail or not.
thumbnail_width (int)
thumbnail_height (int)
thumbnail_method (str)
thumbnail_type (str): Content type of thumbnail, e.g. image/png
thumbnail_length (int): The size of the media file, in bytes.
"""
def __init__(
self,
server_name,
file_id,
url_cache=False,
thumbnail=False,
thumbnail_width=None,
thumbnail_height=None,
thumbnail_method=None,
thumbnail_type=None,
thumbnail_length=None,
):
self.server_name = server_name
self.file_id = file_id
self.url_cache = url_cache
self.thumbnail = thumbnail
self.thumbnail_width = thumbnail_width
self.thumbnail_height = thumbnail_height
self.thumbnail_method = thumbnail_method
self.thumbnail_type = thumbnail_type
self.thumbnail_length = thumbnail_length
def get_filename_from_headers(headers: Dict[bytes, List[bytes]]) -> Optional[str]:
"""
Get the filename of the downloaded file by inspecting the
Content-Disposition HTTP header.
Args:
headers: The HTTP request headers.
Returns:
The filename, or None.
"""
content_disposition = headers.get(b"Content-Disposition", [b""])
# No header, bail out.
if not content_disposition[0]:
return None
_, params = _parse_header(content_disposition[0])
upload_name = None
# First check if there is a valid UTF-8 filename
upload_name_utf8 = params.get(b"filename*", None)
if upload_name_utf8:
if upload_name_utf8.lower().startswith(b"utf-8''"):
upload_name_utf8 = upload_name_utf8[7:]
# We have a filename*= section. This MUST be ASCII, and any UTF-8
# bytes are %-quoted.
try:
# Once it is decoded, we can then unquote the %-encoded
# parts strictly into a unicode string.
upload_name = urllib.parse.unquote(
upload_name_utf8.decode("ascii"), errors="strict"
)
except UnicodeDecodeError:
# Incorrect UTF-8.
pass
# If there isn't check for an ascii name.
if not upload_name:
upload_name_ascii = params.get(b"filename", None)
if upload_name_ascii and is_ascii(upload_name_ascii):
upload_name = upload_name_ascii.decode("ascii")
# This may be None here, indicating we did not find a matching name.
return upload_name
def _parse_header(line: bytes) -> Tuple[bytes, Dict[bytes, bytes]]:
"""Parse a Content-type like header.
Cargo-culted from `cgi`, but works on bytes rather than strings.
Args:
line: header to be parsed
Returns:
The main content-type, followed by the parameter dictionary
"""
parts = _parseparam(b";" + line)
key = next(parts)
pdict = {}
for p in parts:
i = p.find(b"=")
if i >= 0:
name = p[:i].strip().lower()
value = p[i + 1 :].strip()
# strip double-quotes
if len(value) >= 2 and value[0:1] == value[-1:] == b'"':
value = value[1:-1]
value = value.replace(b"\\\\", b"\\").replace(b'\\"', b'"')
pdict[name] = value
return key, pdict
def _parseparam(s: bytes) -> Generator[bytes, None, None]:
"""Generator which splits the input on ;, respecting double-quoted sequences
Cargo-culted from `cgi`, but works on bytes rather than strings.
Args:
s: header to be parsed
Returns:
The split input
"""
while s[:1] == b";":
s = s[1:]
# look for the next ;
end = s.find(b";")
# if there is an odd number of " marks between here and the next ;, skip to the
# next ; instead
while end > 0 and (s.count(b'"', 0, end) - s.count(b'\\"', 0, end)) % 2:
end = s.find(b";", end + 1)
if end < 0:
end = len(s)
f = s[:end]
yield f.strip()
s = s[end:]
| 32.011547 | 88 | 0.611283 |
import logging
import os
import urllib
from typing import Awaitable, Dict, Generator, List, Optional, Tuple
from twisted.internet.interfaces import IConsumer
from twisted.protocols.basic import FileSender
from twisted.web.http import Request
from synapse.api.errors import Codes, SynapseError, cs_error
from synapse.http.server import finish_request, respond_with_json
from synapse.logging.context import make_deferred_yieldable
from synapse.util.stringutils import is_ascii
logger = logging.getLogger(__name__)
TEXT_CONTENT_TYPES = [
"text/css",
"text/csv",
"text/html",
"text/calendar",
"text/plain",
"text/javascript",
"application/json",
"application/ld+json",
"application/rtf",
"image/svg+xml",
"text/xml",
]
def parse_media_id(request: Request) -> Tuple[str, str, Optional[str]]:
try:
server_name, media_id = request.postpath[:2]
if isinstance(server_name, bytes):
server_name = server_name.decode("utf-8")
media_id = media_id.decode("utf8")
file_name = None
if len(request.postpath) > 2:
try:
file_name = urllib.parse.unquote(request.postpath[-1].decode("utf-8"))
except UnicodeDecodeError:
pass
return server_name, media_id, file_name
except Exception:
raise SynapseError(
404, "Invalid media id token %r" % (request.postpath,), Codes.UNKNOWN
)
def respond_404(request: Request) -> None:
respond_with_json(
request,
404,
cs_error("Not found %r" % (request.postpath,), code=Codes.NOT_FOUND),
send_cors=True,
)
async def respond_with_file(
request: Request,
media_type: str,
file_path: str,
file_size: Optional[int] = None,
upload_name: Optional[str] = None,
) -> None:
logger.debug("Responding with %r", file_path)
if os.path.isfile(file_path):
if file_size is None:
stat = os.stat(file_path)
file_size = stat.st_size
add_file_headers(request, media_type, file_size, upload_name)
with open(file_path, "rb") as f:
await make_deferred_yieldable(FileSender().beginFileTransfer(f, request))
finish_request(request)
else:
respond_404(request)
def add_file_headers(
request: Request,
media_type: str,
file_size: Optional[int],
upload_name: Optional[str],
) -> None:
def _quote(x):
return urllib.parse.quote(x.encode("utf-8"))
if media_type.lower() in TEXT_CONTENT_TYPES:
content_type = media_type + "; charset=UTF-8"
else:
content_type = media_type
request.setHeader(b"Content-Type", content_type.encode("UTF-8"))
if upload_name:
correctly interpret those as of 0.99.2 and (b) they are a bit of a pain and we
# may as well just do the filename* version.
if _can_encode_filename_as_token(upload_name):
disposition = "inline; filename=%s" % (upload_name,)
else:
disposition = "inline; filename*=utf-8''%s" % (_quote(upload_name),)
request.setHeader(b"Content-Disposition", disposition.encode("ascii"))
# cache for at least a day.
# XXX: we might want to turn this off for data we don't want to
# select private. don't bother setting Expires as all our
request.setHeader(b"Cache-Control", b"public,max-age=86400,s-maxage=86400")
if file_size is not None:
request.setHeader(b"Content-Length", b"%d" % (file_size,))
request.setHeader(b"X-Robots-Tag", "noindex, nofollow, noarchive, noimageindex")
_FILENAME_SEPARATOR_CHARS = {
"(",
")",
"<",
">",
"@",
",",
";",
":",
"\\",
'"',
"/",
"[",
"]",
"?",
"=",
"{",
"}",
}
def _can_encode_filename_as_token(x: str) -> bool:
for c in x:
# from RFC2616:
#
# token = 1*<any CHAR except CTLs or separators>
#
# separators = "(" | ")" | "<" | ">" | "@"
# | "," | ";" | ":" | "\" | <">
if ord(c) >= 127 or ord(c) <= 32 or c in _FILENAME_SEPARATOR_CHARS:
return False
return True
async def respond_with_responder(
request: Request,
responder: "Optional[Responder]",
media_type: str,
file_size: Optional[int],
upload_name: Optional[str] = None,
) -> None:
if request._disconnected:
logger.warning(
"Not sending response to request %s, already disconnected.", request
)
return
if not responder:
respond_404(request)
return
logger.debug("Responding to media request with responder %s", responder)
add_file_headers(request, media_type, file_size, upload_name)
try:
with responder:
await responder.write_to_consumer(request)
except Exception as e:
logger.warning("Failed to write to consumer: %s %s", type(e), e)
if request.producer:
request.unregisterProducer()
finish_request(request)
class Responder:
def write_to_consumer(self, consumer: IConsumer) -> Awaitable:
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
class FileInfo:
def __init__(
self,
server_name,
file_id,
url_cache=False,
thumbnail=False,
thumbnail_width=None,
thumbnail_height=None,
thumbnail_method=None,
thumbnail_type=None,
thumbnail_length=None,
):
self.server_name = server_name
self.file_id = file_id
self.url_cache = url_cache
self.thumbnail = thumbnail
self.thumbnail_width = thumbnail_width
self.thumbnail_height = thumbnail_height
self.thumbnail_method = thumbnail_method
self.thumbnail_type = thumbnail_type
self.thumbnail_length = thumbnail_length
def get_filename_from_headers(headers: Dict[bytes, List[bytes]]) -> Optional[str]:
content_disposition = headers.get(b"Content-Disposition", [b""])
# No header, bail out.
if not content_disposition[0]:
return None
_, params = _parse_header(content_disposition[0])
upload_name = None
# First check if there is a valid UTF-8 filename
upload_name_utf8 = params.get(b"filename*", None)
if upload_name_utf8:
if upload_name_utf8.lower().startswith(b"utf-8''"):
upload_name_utf8 = upload_name_utf8[7:]
# We have a filename*= section. This MUST be ASCII, and any UTF-8
# bytes are %-quoted.
try:
# Once it is decoded, we can then unquote the %-encoded
# parts strictly into a unicode string.
upload_name = urllib.parse.unquote(
upload_name_utf8.decode("ascii"), errors="strict"
)
except UnicodeDecodeError:
# Incorrect UTF-8.
pass
# If there isn't check for an ascii name.
if not upload_name:
upload_name_ascii = params.get(b"filename", None)
if upload_name_ascii and is_ascii(upload_name_ascii):
upload_name = upload_name_ascii.decode("ascii")
return upload_name
def _parse_header(line: bytes) -> Tuple[bytes, Dict[bytes, bytes]]:
parts = _parseparam(b";" + line)
key = next(parts)
pdict = {}
for p in parts:
i = p.find(b"=")
if i >= 0:
name = p[:i].strip().lower()
value = p[i + 1 :].strip()
if len(value) >= 2 and value[0:1] == value[-1:] == b'"':
value = value[1:-1]
value = value.replace(b"\\\\", b"\\").replace(b'\\"', b'"')
pdict[name] = value
return key, pdict
def _parseparam(s: bytes) -> Generator[bytes, None, None]:
while s[:1] == b";":
s = s[1:]
# look for the next ;
end = s.find(b";")
# if there is an odd number of " marks between here and the next ;, skip to the
while end > 0 and (s.count(b'"', 0, end) - s.count(b'\\"', 0, end)) % 2:
end = s.find(b";", end + 1)
if end < 0:
end = len(s)
f = s[:end]
yield f.strip()
s = s[end:]
| true | true |
f71a053bb305614ab4f994386a8208bfe513245c | 1,996 | py | Python | dataslots/__init__.py | cl0ne/dataslots | a91634f33e25c09e48e834a46424b9f80153efa3 | [
"MIT"
] | null | null | null | dataslots/__init__.py | cl0ne/dataslots | a91634f33e25c09e48e834a46424b9f80153efa3 | [
"MIT"
] | null | null | null | dataslots/__init__.py | cl0ne/dataslots | a91634f33e25c09e48e834a46424b9f80153efa3 | [
"MIT"
] | null | null | null | from dataclasses import fields
from warnings import warn
__all__ = ['dataslots', 'with_slots']
def with_slots(*args, **kwargs):
warn("Use dataslots decorator instead of with_slots", category=PendingDeprecationWarning, stacklevel=2)
return dataslots(*args, **kwargs)
def dataslots(_cls=None, *, add_dict=False, add_weakref=False):
"""
Decorator to add __slots__ to class created by dataclass. Returns new class object as it's not possible
to add __slots__ after class creation.
"""
def _slots_setstate(self, state):
for param_dict in filter(None, state):
for slot, value in param_dict.items():
object.__setattr__(self, slot, value)
def wrap(cls):
cls_dict = dict(cls.__dict__)
# Create only missing slots
inherited_slots = set().union(*(getattr(c, '__slots__', set()) for c in cls.mro()))
field_names = set(tuple(f.name for f in fields(cls)))
if add_dict:
field_names.add('__dict__')
if add_weakref:
field_names.add('__weakref__')
cls_dict['__slots__'] = tuple(field_names - inherited_slots)
# Erase filed names from class __dict__
for f in field_names:
cls_dict.pop(f, None)
# Erase __dict__ and __weakref__
cls_dict.pop('__dict__', None)
cls_dict.pop('__weakref__', None)
# Pickle fix for frozen dataclass as mentioned in https://bugs.python.org/issue36424
# Use only if __getstate__ and __setstate__ are not declared and frozen=True
if all(param not in cls_dict for param in ['__getstate__', '__setstate__']) and \
cls.__dataclass_params__.frozen:
cls_dict['__setstate__'] = _slots_setstate
# Prepare new class with slots
new_cls = type(cls)(cls.__name__, cls.__bases__, cls_dict)
new_cls.__qualname__ = getattr(cls, '__qualname__')
return new_cls
return wrap if _cls is None else wrap(_cls)
| 35.642857 | 107 | 0.657816 | from dataclasses import fields
from warnings import warn
__all__ = ['dataslots', 'with_slots']
def with_slots(*args, **kwargs):
warn("Use dataslots decorator instead of with_slots", category=PendingDeprecationWarning, stacklevel=2)
return dataslots(*args, **kwargs)
def dataslots(_cls=None, *, add_dict=False, add_weakref=False):
def _slots_setstate(self, state):
for param_dict in filter(None, state):
for slot, value in param_dict.items():
object.__setattr__(self, slot, value)
def wrap(cls):
cls_dict = dict(cls.__dict__)
inherited_slots = set().union(*(getattr(c, '__slots__', set()) for c in cls.mro()))
field_names = set(tuple(f.name for f in fields(cls)))
if add_dict:
field_names.add('__dict__')
if add_weakref:
field_names.add('__weakref__')
cls_dict['__slots__'] = tuple(field_names - inherited_slots)
for f in field_names:
cls_dict.pop(f, None)
cls_dict.pop('__dict__', None)
cls_dict.pop('__weakref__', None)
if all(param not in cls_dict for param in ['__getstate__', '__setstate__']) and \
cls.__dataclass_params__.frozen:
cls_dict['__setstate__'] = _slots_setstate
new_cls = type(cls)(cls.__name__, cls.__bases__, cls_dict)
new_cls.__qualname__ = getattr(cls, '__qualname__')
return new_cls
return wrap if _cls is None else wrap(_cls)
| true | true |
f71a0540bc87f2ea7b4736b69e7e3edf50ca90fb | 4,050 | py | Python | benchmark/startQiskit_Class2296.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | benchmark/startQiskit_Class2296.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | benchmark/startQiskit_Class2296.py | UCLA-SEAL/QDiff | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | [
"BSD-3-Clause"
] | null | null | null | # qubit number=4
# total number=33
import cirq
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2
import numpy as np
import networkx as nx
def bitwise_xor(s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
def bitwise_dot(s: str, t: str) -> str:
length = len(s)
res = 0
for i in range(length):
res += int(s[i]) * int(t[i])
return str(res % 2)
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates
# https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.barrier()
return oracle
def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.cx(input_qubit[0],input_qubit[3]) # number=13
prog.cx(input_qubit[0],input_qubit[3]) # number=17
prog.x(input_qubit[3]) # number=18
prog.rx(-3.1101767270538954,input_qubit[1]) # number=27
prog.cx(input_qubit[0],input_qubit[3]) # number=19
prog.cx(input_qubit[0],input_qubit[3]) # number=15
prog.h(input_qubit[1]) # number=2
prog.h(input_qubit[2]) # number=3
prog.h(input_qubit[3]) # number=4
prog.y(input_qubit[3]) # number=12
prog.h(input_qubit[1]) # number=26
prog.h(input_qubit[0]) # number=5
oracle = build_oracle(n-1, f)
prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])
prog.h(input_qubit[1]) # number=6
prog.x(input_qubit[3]) # number=29
prog.h(input_qubit[2]) # number=7
prog.h(input_qubit[0]) # number=30
prog.cz(input_qubit[3],input_qubit[0]) # number=31
prog.h(input_qubit[0]) # number=32
prog.cx(input_qubit[3],input_qubit[0]) # number=23
prog.z(input_qubit[3]) # number=24
prog.cx(input_qubit[3],input_qubit[0]) # number=25
prog.cx(input_qubit[3],input_qubit[0]) # number=22
prog.h(input_qubit[3]) # number=8
prog.z(input_qubit[3]) # number=28
prog.h(input_qubit[0]) # number=9
prog.y(input_qubit[2]) # number=10
prog.y(input_qubit[2]) # number=11
# circuit end
return prog
if __name__ == '__main__':
a = "111"
b = "0"
f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)
prog = make_circuit(4,f)
backend = BasicAer.get_backend('statevector_simulator')
sample_shot =8000
info = execute(prog, backend=backend).result().get_statevector()
qubits = round(log2(len(info)))
info = {
np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)
for i in range(2 ** qubits)
}
backend = FakeVigo()
circuit1 = transpile(prog,backend,optimization_level=2)
writefile = open("../data/startQiskit_Class2296.csv","w")
print(info,file=writefile)
print("results end", file=writefile)
print(circuit1.__len__(),file=writefile)
print(circuit1,file=writefile)
writefile.close()
| 34.322034 | 140 | 0.647407 |
import cirq
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2
import numpy as np
import networkx as nx
def bitwise_xor(s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
def bitwise_dot(s: str, t: str) -> str:
length = len(s)
res = 0
for i in range(length):
res += int(s[i]) * int(t[i])
return str(res % 2)
def build_oracle(n: int, f) -> QuantumCircuit:
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
return oracle
def make_circuit(n:int,f) -> QuantumCircuit:
input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.cx(input_qubit[0],input_qubit[3])
prog.cx(input_qubit[0],input_qubit[3])
prog.x(input_qubit[3])
prog.rx(-3.1101767270538954,input_qubit[1])
prog.cx(input_qubit[0],input_qubit[3])
prog.cx(input_qubit[0],input_qubit[3])
prog.h(input_qubit[1])
prog.h(input_qubit[2])
prog.h(input_qubit[3])
prog.y(input_qubit[3])
prog.h(input_qubit[1])
prog.h(input_qubit[0])
oracle = build_oracle(n-1, f)
prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]])
prog.h(input_qubit[1])
prog.x(input_qubit[3])
prog.h(input_qubit[2])
prog.h(input_qubit[0])
prog.cz(input_qubit[3],input_qubit[0])
prog.h(input_qubit[0])
prog.cx(input_qubit[3],input_qubit[0])
prog.z(input_qubit[3])
prog.cx(input_qubit[3],input_qubit[0])
prog.cx(input_qubit[3],input_qubit[0])
prog.h(input_qubit[3])
prog.z(input_qubit[3])
prog.h(input_qubit[0])
prog.y(input_qubit[2])
prog.y(input_qubit[2])
return prog
if __name__ == '__main__':
a = "111"
b = "0"
f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b)
prog = make_circuit(4,f)
backend = BasicAer.get_backend('statevector_simulator')
sample_shot =8000
info = execute(prog, backend=backend).result().get_statevector()
qubits = round(log2(len(info)))
info = {
np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)
for i in range(2 ** qubits)
}
backend = FakeVigo()
circuit1 = transpile(prog,backend,optimization_level=2)
writefile = open("../data/startQiskit_Class2296.csv","w")
print(info,file=writefile)
print("results end", file=writefile)
print(circuit1.__len__(),file=writefile)
print(circuit1,file=writefile)
writefile.close()
| true | true |
f71a06034e69e3e7408c6a1366ef06e34015e677 | 7,238 | py | Python | complex_networks_keras_tf1/models/resnet_blocks_3d.py | QinggangSUN/keras_complex_valued_networks | e7a6c9238645e87a679328e9f8e8834ad0f716e2 | [
"MIT"
] | 8 | 2020-11-29T11:50:04.000Z | 2022-01-15T15:17:47.000Z | complex_networks_keras_tf1/models/resnet_blocks_3d.py | QinggangSUN/keras_complex_valued_networks | e7a6c9238645e87a679328e9f8e8834ad0f716e2 | [
"MIT"
] | null | null | null | complex_networks_keras_tf1/models/resnet_blocks_3d.py | QinggangSUN/keras_complex_valued_networks | e7a6c9238645e87a679328e9f8e8834ad0f716e2 | [
"MIT"
] | 1 | 2021-11-29T08:22:17.000Z | 2021-11-29T08:22:17.000Z | # -*- coding: utf-8 -*-
"""This module implements a number of popular two-dimensional complex valued residual blocks."""
# Authors: Qinggang Sun
#
# Reference:
# Allen Goodman, Allen Goodman, Claire McQuin, Hans Gaiser, et al. keras-resnet
# https://github.com/broadinstitute/keras-resnet
# pylint:disable=too-many-arguments, invalid-name, unused-argument
import keras.layers
import keras.regularizers
from ..layers.activations import layer_activation
from ..layers.bn import ComplexBatchNormalization
from ..layers.conv import ComplexConv3D
def basic_3d(filters,
stage=0,
block=0,
kernel_size=3,
numerical_name=False,
stride=None,
activation='crelu',
**kwargs,
):
"""
A two-dimensional basic block.
:param filters: int, the output’s feature space
:param stage: int, representing the stage of this block (starting from 0)
:param block: int, representing this block (starting from 0)
:param kernel_size: int or tuple/list of 2 integers, size of the kernel
:param numerical_name: bool, if true, uses numbers to represent blocks instead of chars (ResNet{18, 34})
:param stride: int, representing the stride used in the shortcut and the first conv layer,
default derives stride from block id
:param activation: str, the activation of convolution layer in residual blocks
Usage:
>>> from complex_networks_keras_tf1.models.resnet_models_3d import basic_3d
>>> basic_3d(64)
"""
if stride is None:
if block != 0 or stage == 0:
stride = 1
else:
stride = 2
axis = -1 if keras.backend.image_data_format() == "channels_last" else 1
if block > 0 and numerical_name:
block_char = f'b{block}'
else:
block_char = chr(ord('a') + block)
stage_char = str(stage + 2)
def f(inputs, **kwargs):
"""Method for block."""
outputs = keras.layers.ZeroPadding3D(padding=1, name=f'padding{stage_char}{block_char}_branch2a')(inputs)
outputs = ComplexConv3D(filters, kernel_size, strides=stride, use_bias=False, spectral_parametrization=False,
name=f'res{stage_char}{block_char}_branch2a', **kwargs)(outputs)
outputs = ComplexBatchNormalization(
axis=axis, epsilon=1e-5, name=f'bn{stage_char}{block_char}_branch2a')(outputs)
outputs = layer_activation(outputs, activation, name=f'res{stage_char}{block_char}_branch2a_{activation}')
outputs = keras.layers.ZeroPadding3D(padding=1, name=f'padding{stage_char}{block_char}_branch2b')(outputs)
outputs = ComplexConv3D(filters, kernel_size, use_bias=False, spectral_parametrization=False,
name=f'res{stage_char}{block_char}_branch2b', **kwargs)(outputs)
outputs = ComplexBatchNormalization(
axis=axis, epsilon=1e-5, name=f'bn{stage_char}{block_char}_branch2b')(outputs)
if block == 0:
shortcut = ComplexConv3D(filters, (1, 1), strides=stride, use_bias=False, spectral_parametrization=False,
name=f'res{stage_char}{block_char}_branch1', **kwargs)(inputs)
shortcut = ComplexBatchNormalization(
axis=axis, epsilon=1e-5, name=f'bn{stage_char}{block_char}_branch1')(shortcut)
else:
shortcut = inputs
outputs = keras.layers.add([outputs, shortcut], name=f'res{stage_char}{block_char}')
outputs = layer_activation(outputs, activation, name=f'res{stage_char}{block_char}_{activation}')
return outputs
return f
def bottleneck_3d(filters,
stage=0,
block=0,
kernel_size=3,
numerical_name=False,
stride=None,
activation='crelu',
**kwargs,
):
"""
A two-dimensional bottleneck block.
:param filters: int, the output’s feature space
:param stage: int, representing the stage of this block (starting from 0)
:param block: int, representing this block (starting from 0)
:param kernel_size: int or tuple/list of 2 integers, size of the kernel
:param numerical_name: bool, if true, uses numbers to represent blocks instead of chars (ResNet{101, 152, 200})
:param stride: int, representing the stride used in the shortcut and the first conv layer,
default derives stride from block id
:param activation: str, the activation of convolution layer in residual blocks
Usage:
>>> from complex_networks_keras_tf1.models.resnet_models_3d import bottleneck_3d
>>> bottleneck_3d(64)
"""
if stride is None:
if block != 0 or stage == 0:
stride = 1
else:
stride = 2
axis = -1 if keras.backend.image_data_format() == "channels_last" else 1
if block > 0 and numerical_name:
block_char = f'b{block}'
else:
block_char = chr(ord('a') + block)
stage_char = str(stage + 2)
def f(inputs, **kwargs):
"""Method for block."""
outputs = ComplexConv3D(filters, 1, strides=stride, use_bias=False, spectral_parametrization=False,
name=f'res{stage_char}{block_char}_branch2a', **kwargs)(inputs)
outputs = ComplexBatchNormalization(
axis=axis, epsilon=1e-5, name=f'bn{stage_char}{block_char}_branch2a')(outputs)
outputs = layer_activation(outputs, activation, name=f'res{stage_char}{block_char}_branch2a_{activation}')
outputs = keras.layers.ZeroPadding3D(padding=1, name=f'padding{stage_char}{block_char}_branch2b')(outputs)
outputs = ComplexConv3D(filters, kernel_size, use_bias=False, spectral_parametrization=False,
name=f'res{stage_char}{block_char}_branch2b', **kwargs)(outputs)
outputs = ComplexBatchNormalization(
axis=axis, epsilon=1e-5, name=f'bn{stage_char}{block_char}_branch2b')(outputs)
outputs = layer_activation(outputs, activation, name=f'res{stage_char}{block_char}_branch2b_{activation}')
outputs = ComplexConv3D(filters*4, 1, strides=(1, 1), use_bias=False, spectral_parametrization=False,
name=f'res{stage_char}{block_char}_branch2c', **kwargs)(outputs)
outputs = ComplexBatchNormalization(
axis=axis, epsilon=1e-5, name=f'bn{stage_char}{block_char}_branch2c')(outputs)
if block == 0:
shortcut = ComplexConv3D(filters*4, (1, 1), strides=stride, use_bias=False, spectral_parametrization=False,
name=f'res{stage_char}{block_char}_branch1', **kwargs)(inputs)
shortcut = ComplexBatchNormalization(
axis=axis, epsilon=1e-5, name=f'bn{stage_char}{block_char}_branch1')(shortcut)
else:
shortcut = inputs
outputs = keras.layers.add([outputs, shortcut], name=f'res{stage_char}{block_char}')
outputs = layer_activation(outputs, activation, name=f'res{stage_char}{block_char}_{activation}')
return outputs
return f
| 36.555556 | 119 | 0.644515 |
import keras.layers
import keras.regularizers
from ..layers.activations import layer_activation
from ..layers.bn import ComplexBatchNormalization
from ..layers.conv import ComplexConv3D
def basic_3d(filters,
stage=0,
block=0,
kernel_size=3,
numerical_name=False,
stride=None,
activation='crelu',
**kwargs,
):
if stride is None:
if block != 0 or stage == 0:
stride = 1
else:
stride = 2
axis = -1 if keras.backend.image_data_format() == "channels_last" else 1
if block > 0 and numerical_name:
block_char = f'b{block}'
else:
block_char = chr(ord('a') + block)
stage_char = str(stage + 2)
def f(inputs, **kwargs):
outputs = keras.layers.ZeroPadding3D(padding=1, name=f'padding{stage_char}{block_char}_branch2a')(inputs)
outputs = ComplexConv3D(filters, kernel_size, strides=stride, use_bias=False, spectral_parametrization=False,
name=f'res{stage_char}{block_char}_branch2a', **kwargs)(outputs)
outputs = ComplexBatchNormalization(
axis=axis, epsilon=1e-5, name=f'bn{stage_char}{block_char}_branch2a')(outputs)
outputs = layer_activation(outputs, activation, name=f'res{stage_char}{block_char}_branch2a_{activation}')
outputs = keras.layers.ZeroPadding3D(padding=1, name=f'padding{stage_char}{block_char}_branch2b')(outputs)
outputs = ComplexConv3D(filters, kernel_size, use_bias=False, spectral_parametrization=False,
name=f'res{stage_char}{block_char}_branch2b', **kwargs)(outputs)
outputs = ComplexBatchNormalization(
axis=axis, epsilon=1e-5, name=f'bn{stage_char}{block_char}_branch2b')(outputs)
if block == 0:
shortcut = ComplexConv3D(filters, (1, 1), strides=stride, use_bias=False, spectral_parametrization=False,
name=f'res{stage_char}{block_char}_branch1', **kwargs)(inputs)
shortcut = ComplexBatchNormalization(
axis=axis, epsilon=1e-5, name=f'bn{stage_char}{block_char}_branch1')(shortcut)
else:
shortcut = inputs
outputs = keras.layers.add([outputs, shortcut], name=f'res{stage_char}{block_char}')
outputs = layer_activation(outputs, activation, name=f'res{stage_char}{block_char}_{activation}')
return outputs
return f
def bottleneck_3d(filters,
stage=0,
block=0,
kernel_size=3,
numerical_name=False,
stride=None,
activation='crelu',
**kwargs,
):
if stride is None:
if block != 0 or stage == 0:
stride = 1
else:
stride = 2
axis = -1 if keras.backend.image_data_format() == "channels_last" else 1
if block > 0 and numerical_name:
block_char = f'b{block}'
else:
block_char = chr(ord('a') + block)
stage_char = str(stage + 2)
def f(inputs, **kwargs):
outputs = ComplexConv3D(filters, 1, strides=stride, use_bias=False, spectral_parametrization=False,
name=f'res{stage_char}{block_char}_branch2a', **kwargs)(inputs)
outputs = ComplexBatchNormalization(
axis=axis, epsilon=1e-5, name=f'bn{stage_char}{block_char}_branch2a')(outputs)
outputs = layer_activation(outputs, activation, name=f'res{stage_char}{block_char}_branch2a_{activation}')
outputs = keras.layers.ZeroPadding3D(padding=1, name=f'padding{stage_char}{block_char}_branch2b')(outputs)
outputs = ComplexConv3D(filters, kernel_size, use_bias=False, spectral_parametrization=False,
name=f'res{stage_char}{block_char}_branch2b', **kwargs)(outputs)
outputs = ComplexBatchNormalization(
axis=axis, epsilon=1e-5, name=f'bn{stage_char}{block_char}_branch2b')(outputs)
outputs = layer_activation(outputs, activation, name=f'res{stage_char}{block_char}_branch2b_{activation}')
outputs = ComplexConv3D(filters*4, 1, strides=(1, 1), use_bias=False, spectral_parametrization=False,
name=f'res{stage_char}{block_char}_branch2c', **kwargs)(outputs)
outputs = ComplexBatchNormalization(
axis=axis, epsilon=1e-5, name=f'bn{stage_char}{block_char}_branch2c')(outputs)
if block == 0:
shortcut = ComplexConv3D(filters*4, (1, 1), strides=stride, use_bias=False, spectral_parametrization=False,
name=f'res{stage_char}{block_char}_branch1', **kwargs)(inputs)
shortcut = ComplexBatchNormalization(
axis=axis, epsilon=1e-5, name=f'bn{stage_char}{block_char}_branch1')(shortcut)
else:
shortcut = inputs
outputs = keras.layers.add([outputs, shortcut], name=f'res{stage_char}{block_char}')
outputs = layer_activation(outputs, activation, name=f'res{stage_char}{block_char}_{activation}')
return outputs
return f
| true | true |
f71a06156e7e11289ee61b52977cfcf127cb084b | 1,966 | py | Python | test/docker/integration/kong_client.py | coolersport/kong-oidc | 56393b4f4cca051d2ed9fdba145e679d03aab116 | [
"Apache-2.0"
] | 3 | 2019-09-06T06:27:06.000Z | 2020-03-28T03:22:24.000Z | test/docker/integration/kong_client.py | coolersport/kong-oidc | 56393b4f4cca051d2ed9fdba145e679d03aab116 | [
"Apache-2.0"
] | 1 | 2020-10-30T16:23:27.000Z | 2020-10-30T16:23:27.000Z | test/docker/integration/kong_client.py | coolersport/kong-oidc | 56393b4f4cca051d2ed9fdba145e679d03aab116 | [
"Apache-2.0"
] | 5 | 2019-03-18T22:12:16.000Z | 2022-03-03T22:05:06.000Z | import requests
class KongClient:
def __init__(self, url):
self._endpoint = url
self._session = requests.session()
def create_service(self, name, upstream_url):
url = "{}/services".format(self._endpoint)
payload = {
"name": name,
"url": upstream_url,
}
res = self._session.post(url, json=payload)
res.raise_for_status()
return res.json()
def create_route(self, service_name, paths):
url = "{}/services/{}/routes".format(self._endpoint, service_name)
payload = {
"paths": paths,
}
res = self._session.post(url, json=payload)
res.raise_for_status()
return res.json()
def create_plugin(self, plugin_name, service_name, config):
url = "{}/services/{}/plugins".format(self._endpoint, service_name)
payload = {
"name": plugin_name,
"config": config,
}
res = self._session.post(url, json=payload)
try:
res.raise_for_status()
except Exception as e:
print(res.text)
raise e
return res.json()
def delete_service(self, name):
try:
routes = self.get_routes(name)
for route in routes:
self.delete_route(route)
except requests.exceptions.HTTPError:
pass
url = "{}/services/{}".format(self._endpoint, name)
self._session.delete(url).raise_for_status()
def delete_route(self, route_id):
url = "{}/routes/{}".format(self._endpoint, route_id)
self._session.delete(url).raise_for_status()
def get_routes(self, service_name):
url = "{}/services/{}/routes".format(self._endpoint, service_name)
res = self._session.get(url)
res.raise_for_status()
return map(lambda x: x['id'], res.json()['data'])
| 32.766667 | 76 | 0.558494 | import requests
class KongClient:
def __init__(self, url):
self._endpoint = url
self._session = requests.session()
def create_service(self, name, upstream_url):
url = "{}/services".format(self._endpoint)
payload = {
"name": name,
"url": upstream_url,
}
res = self._session.post(url, json=payload)
res.raise_for_status()
return res.json()
def create_route(self, service_name, paths):
url = "{}/services/{}/routes".format(self._endpoint, service_name)
payload = {
"paths": paths,
}
res = self._session.post(url, json=payload)
res.raise_for_status()
return res.json()
def create_plugin(self, plugin_name, service_name, config):
url = "{}/services/{}/plugins".format(self._endpoint, service_name)
payload = {
"name": plugin_name,
"config": config,
}
res = self._session.post(url, json=payload)
try:
res.raise_for_status()
except Exception as e:
print(res.text)
raise e
return res.json()
def delete_service(self, name):
try:
routes = self.get_routes(name)
for route in routes:
self.delete_route(route)
except requests.exceptions.HTTPError:
pass
url = "{}/services/{}".format(self._endpoint, name)
self._session.delete(url).raise_for_status()
def delete_route(self, route_id):
url = "{}/routes/{}".format(self._endpoint, route_id)
self._session.delete(url).raise_for_status()
def get_routes(self, service_name):
url = "{}/services/{}/routes".format(self._endpoint, service_name)
res = self._session.get(url)
res.raise_for_status()
return map(lambda x: x['id'], res.json()['data'])
| true | true |
f71a0625c1f550c878a13bf9475bc05dbf22e8a9 | 121 | py | Python | docker/optimization/pyOpt/tags/v1.2.0/pyOpt/pyFILTERSD/__init__.py | liujiamingustc/phd | 4f815a738abad43531d02ac66f5bd0d9a1def52a | [
"Apache-2.0"
] | 3 | 2021-01-06T03:01:18.000Z | 2022-03-21T03:02:55.000Z | docker/optimization/pyOpt/tags/v1.2.0/pyOpt/pyFILTERSD/__init__.py | liujiamingustc/phd | 4f815a738abad43531d02ac66f5bd0d9a1def52a | [
"Apache-2.0"
] | null | null | null | docker/optimization/pyOpt/tags/v1.2.0/pyOpt/pyFILTERSD/__init__.py | liujiamingustc/phd | 4f815a738abad43531d02ac66f5bd0d9a1def52a | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
try:
from pyFILTERSD import FILTERSD
__all__ = ['FILTERSD']
except:
__all__ = []
#end
| 13.444444 | 35 | 0.636364 |
try:
from pyFILTERSD import FILTERSD
__all__ = ['FILTERSD']
except:
__all__ = []
| true | true |
f71a062d2b5783e4fd92b44153a453460f29e699 | 53,902 | py | Python | Lib/http/client.py | treebee/cpython | e152169da95b52fa41931572bc90857253c4a5dd | [
"CNRI-Python-GPL-Compatible"
] | 1 | 2019-05-29T18:22:03.000Z | 2019-05-29T18:22:03.000Z | Lib/http/client.py | treebee/cpython | e152169da95b52fa41931572bc90857253c4a5dd | [
"CNRI-Python-GPL-Compatible"
] | 4 | 2022-03-30T01:50:22.000Z | 2022-03-30T01:50:28.000Z | Lib/http/client.py | treebee/cpython | e152169da95b52fa41931572bc90857253c4a5dd | [
"CNRI-Python-GPL-Compatible"
] | null | null | null | r"""HTTP/1.1 client library
<intro stuff goes here>
<other stuff, too>
HTTPConnection goes through a number of "states", which define when a client
may legally make another request or fetch the response for a particular
request. This diagram details these state transitions:
(null)
|
| HTTPConnection()
v
Idle
|
| putrequest()
v
Request-started
|
| ( putheader() )* endheaders()
v
Request-sent
|\_____________________________
| | getresponse() raises
| response = getresponse() | ConnectionError
v v
Unread-response Idle
[Response-headers-read]
|\____________________
| |
| response.read() | putrequest()
v v
Idle Req-started-unread-response
______/|
/ |
response.read() | | ( putheader() )* endheaders()
v v
Request-started Req-sent-unread-response
|
| response.read()
v
Request-sent
This diagram presents the following rules:
-- a second request may not be started until {response-headers-read}
-- a response [object] cannot be retrieved until {request-sent}
-- there is no differentiation between an unread response body and a
partially read response body
Note: this enforcement is applied by the HTTPConnection class. The
HTTPResponse class does not enforce this state machine, which
implies sophisticated clients may accelerate the request/response
pipeline. Caution should be taken, though: accelerating the states
beyond the above pattern may imply knowledge of the server's
connection-close behavior for certain requests. For example, it
is impossible to tell whether the server will close the connection
UNTIL the response headers have been read; this means that further
requests cannot be placed into the pipeline until it is known that
the server will NOT be closing the connection.
Logical State __state __response
------------- ------- ----------
Idle _CS_IDLE None
Request-started _CS_REQ_STARTED None
Request-sent _CS_REQ_SENT None
Unread-response _CS_IDLE <response_class>
Req-started-unread-response _CS_REQ_STARTED <response_class>
Req-sent-unread-response _CS_REQ_SENT <response_class>
"""
import email.parser
import email.message
import http
import io
import re
import socket
import collections.abc
from urllib.parse import urlsplit
# HTTPMessage, parse_headers(), and the HTTP status code constants are
# intentionally omitted for simplicity
__all__ = ["HTTPResponse", "HTTPConnection",
"HTTPException", "NotConnected", "UnknownProtocol",
"UnknownTransferEncoding", "UnimplementedFileMode",
"IncompleteRead", "InvalidURL", "ImproperConnectionState",
"CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
"BadStatusLine", "LineTooLong", "RemoteDisconnected", "error",
"responses"]
HTTP_PORT = 80
HTTPS_PORT = 443
_UNKNOWN = 'UNKNOWN'
# connection states
_CS_IDLE = 'Idle'
_CS_REQ_STARTED = 'Request-started'
_CS_REQ_SENT = 'Request-sent'
# hack to maintain backwards compatibility
globals().update(http.HTTPStatus.__members__)
# another hack to maintain backwards compatibility
# Mapping status codes to official W3C names
responses = {v: v.phrase for v in http.HTTPStatus.__members__.values()}
# maximal line length when calling readline().
_MAXLINE = 65536
_MAXHEADERS = 100
# Header name/value ABNF (http://tools.ietf.org/html/rfc7230#section-3.2)
#
# VCHAR = %x21-7E
# obs-text = %x80-FF
# header-field = field-name ":" OWS field-value OWS
# field-name = token
# field-value = *( field-content / obs-fold )
# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
# field-vchar = VCHAR / obs-text
#
# obs-fold = CRLF 1*( SP / HTAB )
# ; obsolete line folding
# ; see Section 3.2.4
# token = 1*tchar
#
# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
# / DIGIT / ALPHA
# ; any VCHAR, except delimiters
#
# VCHAR defined in http://tools.ietf.org/html/rfc5234#appendix-B.1
# the patterns for both name and value are more lenient than RFC
# definitions to allow for backwards compatibility
_is_legal_header_name = re.compile(rb'[^:\s][^:\r\n]*').fullmatch
_is_illegal_header_value = re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search
# These characters are not allowed within HTTP URL paths.
# See https://tools.ietf.org/html/rfc3986#section-3.3 and the
# https://tools.ietf.org/html/rfc3986#appendix-A pchar definition.
# Prevents CVE-2019-9740. Includes control characters such as \r\n.
# We don't restrict chars above \x7f as putrequest() limits us to ASCII.
_contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f]')
# Arguably only these _should_ allowed:
# _is_allowed_url_pchars_re = re.compile(r"^[/!$&'()*+,;=:@%a-zA-Z0-9._~-]+$")
# We are more lenient for assumed real world compatibility purposes.
# We always set the Content-Length header for these methods because some
# servers will otherwise respond with a 411
_METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
def _encode(data, name='data'):
"""Call data.encode("latin-1") but show a better error message."""
try:
return data.encode("latin-1")
except UnicodeEncodeError as err:
raise UnicodeEncodeError(
err.encoding,
err.object,
err.start,
err.end,
"%s (%.20r) is not valid Latin-1. Use %s.encode('utf-8') "
"if you want to send it encoded in UTF-8." %
(name.title(), data[err.start:err.end], name)) from None
class HTTPMessage(email.message.Message):
# XXX The only usage of this method is in
# http.server.CGIHTTPRequestHandler. Maybe move the code there so
# that it doesn't need to be part of the public API. The API has
# never been defined so this could cause backwards compatibility
# issues.
def getallmatchingheaders(self, name):
"""Find all header lines matching a given header name.
Look through the list of headers and find all lines matching a given
header name (and their continuation lines). A list of the lines is
returned, without interpretation. If the header does not occur, an
empty list is returned. If the header occurs multiple times, all
occurrences are returned. Case is not important in the header name.
"""
name = name.lower() + ':'
n = len(name)
lst = []
hit = 0
for line in self.keys():
if line[:n].lower() == name:
hit = 1
elif not line[:1].isspace():
hit = 0
if hit:
lst.append(line)
return lst
def parse_headers(fp, _class=HTTPMessage):
"""Parses only RFC2822 headers from a file pointer.
email Parser wants to see strings rather than bytes.
But a TextIOWrapper around self.rfile would buffer too many bytes
from the stream, bytes which we later need to read as bytes.
So we read the correct bytes here, as bytes, for email Parser
to parse.
"""
headers = []
while True:
line = fp.readline(_MAXLINE + 1)
if len(line) > _MAXLINE:
raise LineTooLong("header line")
headers.append(line)
if len(headers) > _MAXHEADERS:
raise HTTPException("got more than %d headers" % _MAXHEADERS)
if line in (b'\r\n', b'\n', b''):
break
hstring = b''.join(headers).decode('iso-8859-1')
return email.parser.Parser(_class=_class).parsestr(hstring)
class HTTPResponse(io.BufferedIOBase):
# See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
# The bytes from the socket object are iso-8859-1 strings.
# See RFC 2616 sec 2.2 which notes an exception for MIME-encoded
# text following RFC 2047. The basic status line parsing only
# accepts iso-8859-1.
def __init__(self, sock, debuglevel=0, method=None, url=None):
# If the response includes a content-length header, we need to
# make sure that the client doesn't read more than the
# specified number of bytes. If it does, it will block until
# the server times out and closes the connection. This will
# happen if a self.fp.read() is done (without a size) whether
# self.fp is buffered or not. So, no self.fp.read() by
# clients unless they know what they are doing.
self.fp = sock.makefile("rb")
self.debuglevel = debuglevel
self._method = method
# The HTTPResponse object is returned via urllib. The clients
# of http and urllib expect different attributes for the
# headers. headers is used here and supports urllib. msg is
# provided as a backwards compatibility layer for http
# clients.
self.headers = self.msg = None
# from the Status-Line of the response
self.version = _UNKNOWN # HTTP-Version
self.status = _UNKNOWN # Status-Code
self.reason = _UNKNOWN # Reason-Phrase
self.chunked = _UNKNOWN # is "chunked" being used?
self.chunk_left = _UNKNOWN # bytes left to read in current chunk
self.length = _UNKNOWN # number of bytes left in response
self.will_close = _UNKNOWN # conn will close at end of response
def _read_status(self):
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
if len(line) > _MAXLINE:
raise LineTooLong("status line")
if self.debuglevel > 0:
print("reply:", repr(line))
if not line:
# Presumably, the server closed the connection before
# sending a valid response.
raise RemoteDisconnected("Remote end closed connection without"
" response")
try:
version, status, reason = line.split(None, 2)
except ValueError:
try:
version, status = line.split(None, 1)
reason = ""
except ValueError:
# empty version will cause next test to fail.
version = ""
if not version.startswith("HTTP/"):
self._close_conn()
raise BadStatusLine(line)
# The status code is a three-digit number
try:
status = int(status)
if status < 100 or status > 999:
raise BadStatusLine(line)
except ValueError:
raise BadStatusLine(line)
return version, status, reason
def begin(self):
if self.headers is not None:
# we've already started reading the response
return
# read until we get a non-100 response
while True:
version, status, reason = self._read_status()
if status != CONTINUE:
break
# skip the header from the 100 response
while True:
skip = self.fp.readline(_MAXLINE + 1)
if len(skip) > _MAXLINE:
raise LineTooLong("header line")
skip = skip.strip()
if not skip:
break
if self.debuglevel > 0:
print("header:", skip)
self.code = self.status = status
self.reason = reason.strip()
if version in ("HTTP/1.0", "HTTP/0.9"):
# Some servers might still return "0.9", treat it as 1.0 anyway
self.version = 10
elif version.startswith("HTTP/1."):
self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
else:
raise UnknownProtocol(version)
self.headers = self.msg = parse_headers(self.fp)
if self.debuglevel > 0:
for hdr, val in self.headers.items():
print("header:", hdr + ":", val)
# are we using the chunked-style of transfer encoding?
tr_enc = self.headers.get("transfer-encoding")
if tr_enc and tr_enc.lower() == "chunked":
self.chunked = True
self.chunk_left = None
else:
self.chunked = False
# will the connection close at the end of the response?
self.will_close = self._check_close()
# do we have a Content-Length?
# NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
self.length = None
length = self.headers.get("content-length")
# are we using the chunked-style of transfer encoding?
tr_enc = self.headers.get("transfer-encoding")
if length and not self.chunked:
try:
self.length = int(length)
except ValueError:
self.length = None
else:
if self.length < 0: # ignore nonsensical negative lengths
self.length = None
else:
self.length = None
# does the body have a fixed length? (of zero)
if (status == NO_CONTENT or status == NOT_MODIFIED or
100 <= status < 200 or # 1xx codes
self._method == "HEAD"):
self.length = 0
# if the connection remains open, and we aren't using chunked, and
# a content-length was not provided, then assume that the connection
# WILL close.
if (not self.will_close and
not self.chunked and
self.length is None):
self.will_close = True
def _check_close(self):
conn = self.headers.get("connection")
if self.version == 11:
# An HTTP/1.1 proxy is assumed to stay open unless
# explicitly closed.
if conn and "close" in conn.lower():
return True
return False
# Some HTTP/1.0 implementations have support for persistent
# connections, using rules different than HTTP/1.1.
# For older HTTP, Keep-Alive indicates persistent connection.
if self.headers.get("keep-alive"):
return False
# At least Akamai returns a "Connection: Keep-Alive" header,
# which was supposed to be sent by the client.
if conn and "keep-alive" in conn.lower():
return False
# Proxy-Connection is a netscape hack.
pconn = self.headers.get("proxy-connection")
if pconn and "keep-alive" in pconn.lower():
return False
# otherwise, assume it will close
return True
def _close_conn(self):
fp = self.fp
self.fp = None
fp.close()
def close(self):
try:
super().close() # set "closed" flag
finally:
if self.fp:
self._close_conn()
# These implementations are for the benefit of io.BufferedReader.
# XXX This class should probably be revised to act more like
# the "raw stream" that BufferedReader expects.
def flush(self):
super().flush()
if self.fp:
self.fp.flush()
def readable(self):
"""Always returns True"""
return True
# End of "raw stream" methods
def isclosed(self):
"""True if the connection is closed."""
# NOTE: it is possible that we will not ever call self.close(). This
# case occurs when will_close is TRUE, length is None, and we
# read up to the last byte, but NOT past it.
#
# IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
# called, meaning self.isclosed() is meaningful.
return self.fp is None
def read(self, amt=None):
if self.fp is None:
return b""
if self._method == "HEAD":
self._close_conn()
return b""
if amt is not None:
# Amount is given, implement using readinto
b = bytearray(amt)
n = self.readinto(b)
return memoryview(b)[:n].tobytes()
else:
# Amount is not given (unbounded read) so we must check self.length
# and self.chunked
if self.chunked:
return self._readall_chunked()
if self.length is None:
s = self.fp.read()
else:
try:
s = self._safe_read(self.length)
except IncompleteRead:
self._close_conn()
raise
self.length = 0
self._close_conn() # we read everything
return s
def readinto(self, b):
"""Read up to len(b) bytes into bytearray b and return the number
of bytes read.
"""
if self.fp is None:
return 0
if self._method == "HEAD":
self._close_conn()
return 0
if self.chunked:
return self._readinto_chunked(b)
if self.length is not None:
if len(b) > self.length:
# clip the read to the "end of response"
b = memoryview(b)[0:self.length]
# we do not use _safe_read() here because this may be a .will_close
# connection, and the user is reading more bytes than will be provided
# (for example, reading in 1k chunks)
n = self.fp.readinto(b)
if not n and b:
# Ideally, we would raise IncompleteRead if the content-length
# wasn't satisfied, but it might break compatibility.
self._close_conn()
elif self.length is not None:
self.length -= n
if not self.length:
self._close_conn()
return n
def _read_next_chunk_size(self):
# Read the next chunk size from the file
line = self.fp.readline(_MAXLINE + 1)
if len(line) > _MAXLINE:
raise LineTooLong("chunk size")
i = line.find(b";")
if i >= 0:
line = line[:i] # strip chunk-extensions
try:
return int(line, 16)
except ValueError:
# close the connection as protocol synchronisation is
# probably lost
self._close_conn()
raise
def _read_and_discard_trailer(self):
# read and discard trailer up to the CRLF terminator
### note: we shouldn't have any trailers!
while True:
line = self.fp.readline(_MAXLINE + 1)
if len(line) > _MAXLINE:
raise LineTooLong("trailer line")
if not line:
# a vanishingly small number of sites EOF without
# sending the trailer
break
if line in (b'\r\n', b'\n', b''):
break
def _get_chunk_left(self):
# return self.chunk_left, reading a new chunk if necessary.
# chunk_left == 0: at the end of the current chunk, need to close it
# chunk_left == None: No current chunk, should read next.
# This function returns non-zero or None if the last chunk has
# been read.
chunk_left = self.chunk_left
if not chunk_left: # Can be 0 or None
if chunk_left is not None:
# We are at the end of chunk, discard chunk end
self._safe_read(2) # toss the CRLF at the end of the chunk
try:
chunk_left = self._read_next_chunk_size()
except ValueError:
raise IncompleteRead(b'')
if chunk_left == 0:
# last chunk: 1*("0") [ chunk-extension ] CRLF
self._read_and_discard_trailer()
# we read everything; close the "file"
self._close_conn()
chunk_left = None
self.chunk_left = chunk_left
return chunk_left
def _readall_chunked(self):
assert self.chunked != _UNKNOWN
value = []
try:
while True:
chunk_left = self._get_chunk_left()
if chunk_left is None:
break
value.append(self._safe_read(chunk_left))
self.chunk_left = 0
return b''.join(value)
except IncompleteRead:
raise IncompleteRead(b''.join(value))
def _readinto_chunked(self, b):
assert self.chunked != _UNKNOWN
total_bytes = 0
mvb = memoryview(b)
try:
while True:
chunk_left = self._get_chunk_left()
if chunk_left is None:
return total_bytes
if len(mvb) <= chunk_left:
n = self._safe_readinto(mvb)
self.chunk_left = chunk_left - n
return total_bytes + n
temp_mvb = mvb[:chunk_left]
n = self._safe_readinto(temp_mvb)
mvb = mvb[n:]
total_bytes += n
self.chunk_left = 0
except IncompleteRead:
raise IncompleteRead(bytes(b[0:total_bytes]))
def _safe_read(self, amt):
"""Read the number of bytes requested.
This function should be used when <amt> bytes "should" be present for
reading. If the bytes are truly not available (due to EOF), then the
IncompleteRead exception can be used to detect the problem.
"""
data = self.fp.read(amt)
if len(data) < amt:
raise IncompleteRead(data, amt-len(data))
return data
def _safe_readinto(self, b):
"""Same as _safe_read, but for reading into a buffer."""
amt = len(b)
n = self.fp.readinto(b)
if n < amt:
raise IncompleteRead(bytes(b[:n]), amt-n)
return n
def read1(self, n=-1):
"""Read with at most one underlying system call. If at least one
byte is buffered, return that instead.
"""
if self.fp is None or self._method == "HEAD":
return b""
if self.chunked:
return self._read1_chunked(n)
if self.length is not None and (n < 0 or n > self.length):
n = self.length
result = self.fp.read1(n)
if not result and n:
self._close_conn()
elif self.length is not None:
self.length -= len(result)
return result
def peek(self, n=-1):
# Having this enables IOBase.readline() to read more than one
# byte at a time
if self.fp is None or self._method == "HEAD":
return b""
if self.chunked:
return self._peek_chunked(n)
return self.fp.peek(n)
def readline(self, limit=-1):
if self.fp is None or self._method == "HEAD":
return b""
if self.chunked:
# Fallback to IOBase readline which uses peek() and read()
return super().readline(limit)
if self.length is not None and (limit < 0 or limit > self.length):
limit = self.length
result = self.fp.readline(limit)
if not result and limit:
self._close_conn()
elif self.length is not None:
self.length -= len(result)
return result
def _read1_chunked(self, n):
# Strictly speaking, _get_chunk_left() may cause more than one read,
# but that is ok, since that is to satisfy the chunked protocol.
chunk_left = self._get_chunk_left()
if chunk_left is None or n == 0:
return b''
if not (0 <= n <= chunk_left):
n = chunk_left # if n is negative or larger than chunk_left
read = self.fp.read1(n)
self.chunk_left -= len(read)
if not read:
raise IncompleteRead(b"")
return read
def _peek_chunked(self, n):
# Strictly speaking, _get_chunk_left() may cause more than one read,
# but that is ok, since that is to satisfy the chunked protocol.
try:
chunk_left = self._get_chunk_left()
except IncompleteRead:
return b'' # peek doesn't worry about protocol
if chunk_left is None:
return b'' # eof
# peek is allowed to return more than requested. Just request the
# entire chunk, and truncate what we get.
return self.fp.peek(chunk_left)[:chunk_left]
def fileno(self):
return self.fp.fileno()
def getheader(self, name, default=None):
'''Returns the value of the header matching *name*.
If there are multiple matching headers, the values are
combined into a single string separated by commas and spaces.
If no matching header is found, returns *default* or None if
the *default* is not specified.
If the headers are unknown, raises http.client.ResponseNotReady.
'''
if self.headers is None:
raise ResponseNotReady()
headers = self.headers.get_all(name) or default
if isinstance(headers, str) or not hasattr(headers, '__iter__'):
return headers
else:
return ', '.join(headers)
def getheaders(self):
"""Return list of (header, value) tuples."""
if self.headers is None:
raise ResponseNotReady()
return list(self.headers.items())
# We override IOBase.__iter__ so that it doesn't check for closed-ness
def __iter__(self):
return self
# For compatibility with old-style urllib responses.
def info(self):
'''Returns an instance of the class mimetools.Message containing
meta-information associated with the URL.
When the method is HTTP, these headers are those returned by
the server at the head of the retrieved HTML page (including
Content-Length and Content-Type).
When the method is FTP, a Content-Length header will be
present if (as is now usual) the server passed back a file
length in response to the FTP retrieval request. A
Content-Type header will be present if the MIME type can be
guessed.
When the method is local-file, returned headers will include
a Date representing the file's last-modified time, a
Content-Length giving file size, and a Content-Type
containing a guess at the file's type. See also the
description of the mimetools module.
'''
return self.headers
def geturl(self):
'''Return the real URL of the page.
In some cases, the HTTP server redirects a client to another
URL. The urlopen() function handles this transparently, but in
some cases the caller needs to know which URL the client was
redirected to. The geturl() method can be used to get at this
redirected URL.
'''
return self.url
def getcode(self):
'''Return the HTTP status code that was sent with the response,
or None if the URL is not an HTTP URL.
'''
return self.status
class HTTPConnection:
_http_vsn = 11
_http_vsn_str = 'HTTP/1.1'
response_class = HTTPResponse
default_port = HTTP_PORT
auto_open = 1
debuglevel = 0
@staticmethod
def _is_textIO(stream):
"""Test whether a file-like object is a text or a binary stream.
"""
return isinstance(stream, io.TextIOBase)
@staticmethod
def _get_content_length(body, method):
"""Get the content-length based on the body.
If the body is None, we set Content-Length: 0 for methods that expect
a body (RFC 7230, Section 3.3.2). We also set the Content-Length for
any method if the body is a str or bytes-like object and not a file.
"""
if body is None:
# do an explicit check for not None here to distinguish
# between unset and set but empty
if method.upper() in _METHODS_EXPECTING_BODY:
return 0
else:
return None
if hasattr(body, 'read'):
# file-like object.
return None
try:
# does it implement the buffer protocol (bytes, bytearray, array)?
mv = memoryview(body)
return mv.nbytes
except TypeError:
pass
if isinstance(body, str):
return len(body)
return None
def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, blocksize=8192):
self.timeout = timeout
self.source_address = source_address
self.blocksize = blocksize
self.sock = None
self._buffer = []
self.__response = None
self.__state = _CS_IDLE
self._method = None
self._tunnel_host = None
self._tunnel_port = None
self._tunnel_headers = {}
(self.host, self.port) = self._get_hostport(host, port)
# This is stored as an instance variable to allow unit
# tests to replace it with a suitable mockup
self._create_connection = socket.create_connection
def set_tunnel(self, host, port=None, headers=None):
"""Set up host and port for HTTP CONNECT tunnelling.
In a connection that uses HTTP CONNECT tunneling, the host passed to the
constructor is used as a proxy server that relays all communication to
the endpoint passed to `set_tunnel`. This done by sending an HTTP
CONNECT request to the proxy server when the connection is established.
This method must be called before the HTML connection has been
established.
The headers argument should be a mapping of extra HTTP headers to send
with the CONNECT request.
"""
if self.sock:
raise RuntimeError("Can't set up tunnel for established connection")
self._tunnel_host, self._tunnel_port = self._get_hostport(host, port)
if headers:
self._tunnel_headers = headers
else:
self._tunnel_headers.clear()
def _get_hostport(self, host, port):
if port is None:
i = host.rfind(':')
j = host.rfind(']') # ipv6 addresses have [...]
if i > j:
try:
port = int(host[i+1:])
except ValueError:
if host[i+1:] == "": # http://foo.com:/ == http://foo.com/
port = self.default_port
else:
raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
host = host[:i]
else:
port = self.default_port
if host and host[0] == '[' and host[-1] == ']':
host = host[1:-1]
return (host, port)
def set_debuglevel(self, level):
self.debuglevel = level
def _tunnel(self):
connect_str = "CONNECT %s:%d HTTP/1.0\r\n" % (self._tunnel_host,
self._tunnel_port)
connect_bytes = connect_str.encode("ascii")
self.send(connect_bytes)
for header, value in self._tunnel_headers.items():
header_str = "%s: %s\r\n" % (header, value)
header_bytes = header_str.encode("latin-1")
self.send(header_bytes)
self.send(b'\r\n')
response = self.response_class(self.sock, method=self._method)
(version, code, message) = response._read_status()
if code != http.HTTPStatus.OK:
self.close()
raise OSError("Tunnel connection failed: %d %s" % (code,
message.strip()))
while True:
line = response.fp.readline(_MAXLINE + 1)
if len(line) > _MAXLINE:
raise LineTooLong("header line")
if not line:
# for sites which EOF without sending a trailer
break
if line in (b'\r\n', b'\n', b''):
break
if self.debuglevel > 0:
print('header:', line.decode())
def connect(self):
"""Connect to the host and port specified in __init__."""
self.sock = self._create_connection(
(self.host,self.port), self.timeout, self.source_address)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if self._tunnel_host:
self._tunnel()
def close(self):
"""Close the connection to the HTTP server."""
self.__state = _CS_IDLE
try:
sock = self.sock
if sock:
self.sock = None
sock.close() # close it manually... there may be other refs
finally:
response = self.__response
if response:
self.__response = None
response.close()
def send(self, data):
"""Send `data' to the server.
``data`` can be a string object, a bytes object, an array object, a
file-like object that supports a .read() method, or an iterable object.
"""
if self.sock is None:
if self.auto_open:
self.connect()
else:
raise NotConnected()
if self.debuglevel > 0:
print("send:", repr(data))
if hasattr(data, "read") :
if self.debuglevel > 0:
print("sendIng a read()able")
encode = self._is_textIO(data)
if encode and self.debuglevel > 0:
print("encoding file using iso-8859-1")
while 1:
datablock = data.read(self.blocksize)
if not datablock:
break
if encode:
datablock = datablock.encode("iso-8859-1")
self.sock.sendall(datablock)
return
try:
self.sock.sendall(data)
except TypeError:
if isinstance(data, collections.abc.Iterable):
for d in data:
self.sock.sendall(d)
else:
raise TypeError("data should be a bytes-like object "
"or an iterable, got %r" % type(data))
def _output(self, s):
"""Add a line of output to the current request buffer.
Assumes that the line does *not* end with \\r\\n.
"""
self._buffer.append(s)
def _read_readable(self, readable):
if self.debuglevel > 0:
print("sendIng a read()able")
encode = self._is_textIO(readable)
if encode and self.debuglevel > 0:
print("encoding file using iso-8859-1")
while True:
datablock = readable.read(self.blocksize)
if not datablock:
break
if encode:
datablock = datablock.encode("iso-8859-1")
yield datablock
def _send_output(self, message_body=None, encode_chunked=False):
"""Send the currently buffered request and clear the buffer.
Appends an extra \\r\\n to the buffer.
A message_body may be specified, to be appended to the request.
"""
self._buffer.extend((b"", b""))
msg = b"\r\n".join(self._buffer)
del self._buffer[:]
self.send(msg)
if message_body is not None:
# create a consistent interface to message_body
if hasattr(message_body, 'read'):
# Let file-like take precedence over byte-like. This
# is needed to allow the current position of mmap'ed
# files to be taken into account.
chunks = self._read_readable(message_body)
else:
try:
# this is solely to check to see if message_body
# implements the buffer API. it /would/ be easier
# to capture if PyObject_CheckBuffer was exposed
# to Python.
memoryview(message_body)
except TypeError:
try:
chunks = iter(message_body)
except TypeError:
raise TypeError("message_body should be a bytes-like "
"object or an iterable, got %r"
% type(message_body))
else:
# the object implements the buffer interface and
# can be passed directly into socket methods
chunks = (message_body,)
for chunk in chunks:
if not chunk:
if self.debuglevel > 0:
print('Zero length chunk ignored')
continue
if encode_chunked and self._http_vsn == 11:
# chunked encoding
chunk = f'{len(chunk):X}\r\n'.encode('ascii') + chunk \
+ b'\r\n'
self.send(chunk)
if encode_chunked and self._http_vsn == 11:
# end chunked transfer
self.send(b'0\r\n\r\n')
def putrequest(self, method, url, skip_host=False,
skip_accept_encoding=False):
"""Send a request to the server.
`method' specifies an HTTP request method, e.g. 'GET'.
`url' specifies the object being requested, e.g. '/index.html'.
`skip_host' if True does not add automatically a 'Host:' header
`skip_accept_encoding' if True does not add automatically an
'Accept-Encoding:' header
"""
# if a prior response has been completed, then forget about it.
if self.__response and self.__response.isclosed():
self.__response = None
# in certain cases, we cannot issue another request on this connection.
# this occurs when:
# 1) we are in the process of sending a request. (_CS_REQ_STARTED)
# 2) a response to a previous request has signalled that it is going
# to close the connection upon completion.
# 3) the headers for the previous response have not been read, thus
# we cannot determine whether point (2) is true. (_CS_REQ_SENT)
#
# if there is no prior response, then we can request at will.
#
# if point (2) is true, then we will have passed the socket to the
# response (effectively meaning, "there is no prior response"), and
# will open a new one when a new request is made.
#
# Note: if a prior response exists, then we *can* start a new request.
# We are not allowed to begin fetching the response to this new
# request, however, until that prior response is complete.
#
if self.__state == _CS_IDLE:
self.__state = _CS_REQ_STARTED
else:
raise CannotSendRequest(self.__state)
# Save the method we use, we need it later in the response phase
self._method = method
if not url:
url = '/'
# Prevent CVE-2019-9740.
if match := _contains_disallowed_url_pchar_re.search(url):
raise InvalidURL(f"URL can't contain control characters. {url!r} "
f"(found at least {match.group()!r})")
request = '%s %s %s' % (method, url, self._http_vsn_str)
# Non-ASCII characters should have been eliminated earlier
self._output(request.encode('ascii'))
if self._http_vsn == 11:
# Issue some standard headers for better HTTP/1.1 compliance
if not skip_host:
# this header is issued *only* for HTTP/1.1
# connections. more specifically, this means it is
# only issued when the client uses the new
# HTTPConnection() class. backwards-compat clients
# will be using HTTP/1.0 and those clients may be
# issuing this header themselves. we should NOT issue
# it twice; some web servers (such as Apache) barf
# when they see two Host: headers
# If we need a non-standard port,include it in the
# header. If the request is going through a proxy,
# but the host of the actual URL, not the host of the
# proxy.
netloc = ''
if url.startswith('http'):
nil, netloc, nil, nil, nil = urlsplit(url)
if netloc:
try:
netloc_enc = netloc.encode("ascii")
except UnicodeEncodeError:
netloc_enc = netloc.encode("idna")
self.putheader('Host', netloc_enc)
else:
if self._tunnel_host:
host = self._tunnel_host
port = self._tunnel_port
else:
host = self.host
port = self.port
try:
host_enc = host.encode("ascii")
except UnicodeEncodeError:
host_enc = host.encode("idna")
# As per RFC 273, IPv6 address should be wrapped with []
# when used as Host header
if host.find(':') >= 0:
host_enc = b'[' + host_enc + b']'
if port == self.default_port:
self.putheader('Host', host_enc)
else:
host_enc = host_enc.decode("ascii")
self.putheader('Host', "%s:%s" % (host_enc, port))
# note: we are assuming that clients will not attempt to set these
# headers since *this* library must deal with the
# consequences. this also means that when the supporting
# libraries are updated to recognize other forms, then this
# code should be changed (removed or updated).
# we only want a Content-Encoding of "identity" since we don't
# support encodings such as x-gzip or x-deflate.
if not skip_accept_encoding:
self.putheader('Accept-Encoding', 'identity')
# we can accept "chunked" Transfer-Encodings, but no others
# NOTE: no TE header implies *only* "chunked"
#self.putheader('TE', 'chunked')
# if TE is supplied in the header, then it must appear in a
# Connection header.
#self.putheader('Connection', 'TE')
else:
# For HTTP/1.0, the server will assume "not chunked"
pass
def putheader(self, header, *values):
"""Send a request header line to the server.
For example: h.putheader('Accept', 'text/html')
"""
if self.__state != _CS_REQ_STARTED:
raise CannotSendHeader()
if hasattr(header, 'encode'):
header = header.encode('ascii')
if not _is_legal_header_name(header):
raise ValueError('Invalid header name %r' % (header,))
values = list(values)
for i, one_value in enumerate(values):
if hasattr(one_value, 'encode'):
values[i] = one_value.encode('latin-1')
elif isinstance(one_value, int):
values[i] = str(one_value).encode('ascii')
if _is_illegal_header_value(values[i]):
raise ValueError('Invalid header value %r' % (values[i],))
value = b'\r\n\t'.join(values)
header = header + b': ' + value
self._output(header)
def endheaders(self, message_body=None, *, encode_chunked=False):
"""Indicate that the last header line has been sent to the server.
This method sends the request to the server. The optional message_body
argument can be used to pass a message body associated with the
request.
"""
if self.__state == _CS_REQ_STARTED:
self.__state = _CS_REQ_SENT
else:
raise CannotSendHeader()
self._send_output(message_body, encode_chunked=encode_chunked)
def request(self, method, url, body=None, headers={}, *,
encode_chunked=False):
"""Send a complete request to the server."""
self._send_request(method, url, body, headers, encode_chunked)
def _send_request(self, method, url, body, headers, encode_chunked):
# Honor explicitly requested Host: and Accept-Encoding: headers.
header_names = frozenset(k.lower() for k in headers)
skips = {}
if 'host' in header_names:
skips['skip_host'] = 1
if 'accept-encoding' in header_names:
skips['skip_accept_encoding'] = 1
self.putrequest(method, url, **skips)
# chunked encoding will happen if HTTP/1.1 is used and either
# the caller passes encode_chunked=True or the following
# conditions hold:
# 1. content-length has not been explicitly set
# 2. the body is a file or iterable, but not a str or bytes-like
# 3. Transfer-Encoding has NOT been explicitly set by the caller
if 'content-length' not in header_names:
# only chunk body if not explicitly set for backwards
# compatibility, assuming the client code is already handling the
# chunking
if 'transfer-encoding' not in header_names:
# if content-length cannot be automatically determined, fall
# back to chunked encoding
encode_chunked = False
content_length = self._get_content_length(body, method)
if content_length is None:
if body is not None:
if self.debuglevel > 0:
print('Unable to determine size of %r' % body)
encode_chunked = True
self.putheader('Transfer-Encoding', 'chunked')
else:
self.putheader('Content-Length', str(content_length))
else:
encode_chunked = False
for hdr, value in headers.items():
self.putheader(hdr, value)
if isinstance(body, str):
# RFC 2616 Section 3.7.1 says that text default has a
# default charset of iso-8859-1.
body = _encode(body, 'body')
self.endheaders(body, encode_chunked=encode_chunked)
def getresponse(self):
"""Get the response from the server.
If the HTTPConnection is in the correct state, returns an
instance of HTTPResponse or of whatever object is returned by
the response_class variable.
If a request has not been sent or if a previous response has
not be handled, ResponseNotReady is raised. If the HTTP
response indicates that the connection should be closed, then
it will be closed before the response is returned. When the
connection is closed, the underlying socket is closed.
"""
# if a prior response has been completed, then forget about it.
if self.__response and self.__response.isclosed():
self.__response = None
# if a prior response exists, then it must be completed (otherwise, we
# cannot read this response's header to determine the connection-close
# behavior)
#
# note: if a prior response existed, but was connection-close, then the
# socket and response were made independent of this HTTPConnection
# object since a new request requires that we open a whole new
# connection
#
# this means the prior response had one of two states:
# 1) will_close: this connection was reset and the prior socket and
# response operate independently
# 2) persistent: the response was retained and we await its
# isclosed() status to become true.
#
if self.__state != _CS_REQ_SENT or self.__response:
raise ResponseNotReady(self.__state)
if self.debuglevel > 0:
response = self.response_class(self.sock, self.debuglevel,
method=self._method)
else:
response = self.response_class(self.sock, method=self._method)
try:
try:
response.begin()
except ConnectionError:
self.close()
raise
assert response.will_close != _UNKNOWN
self.__state = _CS_IDLE
if response.will_close:
# this effectively passes the connection to the response
self.close()
else:
# remember this, so we can tell when it is complete
self.__response = response
return response
except:
response.close()
raise
try:
import ssl
except ImportError:
pass
else:
class HTTPSConnection(HTTPConnection):
"This class allows communication via SSL."
default_port = HTTPS_PORT
# XXX Should key_file and cert_file be deprecated in favour of context?
def __init__(self, host, port=None, key_file=None, cert_file=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, *, context=None,
check_hostname=None, blocksize=8192):
super(HTTPSConnection, self).__init__(host, port, timeout,
source_address,
blocksize=blocksize)
if (key_file is not None or cert_file is not None or
check_hostname is not None):
import warnings
warnings.warn("key_file, cert_file and check_hostname are "
"deprecated, use a custom context instead.",
DeprecationWarning, 2)
self.key_file = key_file
self.cert_file = cert_file
if context is None:
context = ssl._create_default_https_context()
will_verify = context.verify_mode != ssl.CERT_NONE
if check_hostname is None:
check_hostname = context.check_hostname
if check_hostname and not will_verify:
raise ValueError("check_hostname needs a SSL context with "
"either CERT_OPTIONAL or CERT_REQUIRED")
if key_file or cert_file:
context.load_cert_chain(cert_file, key_file)
self._context = context
if check_hostname is not None:
self._context.check_hostname = check_hostname
def connect(self):
"Connect to a host on a given (SSL) port."
super().connect()
if self._tunnel_host:
server_hostname = self._tunnel_host
else:
server_hostname = self.host
self.sock = self._context.wrap_socket(self.sock,
server_hostname=server_hostname)
__all__.append("HTTPSConnection")
class HTTPException(Exception):
# Subclasses that define an __init__ must call Exception.__init__
# or define self.args. Otherwise, str() will fail.
pass
class NotConnected(HTTPException):
pass
class InvalidURL(HTTPException):
pass
class UnknownProtocol(HTTPException):
def __init__(self, version):
self.args = version,
self.version = version
class UnknownTransferEncoding(HTTPException):
pass
class UnimplementedFileMode(HTTPException):
pass
class IncompleteRead(HTTPException):
def __init__(self, partial, expected=None):
self.args = partial,
self.partial = partial
self.expected = expected
def __repr__(self):
if self.expected is not None:
e = ', %i more expected' % self.expected
else:
e = ''
return '%s(%i bytes read%s)' % (self.__class__.__name__,
len(self.partial), e)
def __str__(self):
return repr(self)
class ImproperConnectionState(HTTPException):
pass
class CannotSendRequest(ImproperConnectionState):
pass
class CannotSendHeader(ImproperConnectionState):
pass
class ResponseNotReady(ImproperConnectionState):
pass
class BadStatusLine(HTTPException):
def __init__(self, line):
if not line:
line = repr(line)
self.args = line,
self.line = line
class LineTooLong(HTTPException):
def __init__(self, line_type):
HTTPException.__init__(self, "got more than %d bytes when reading %s"
% (_MAXLINE, line_type))
class RemoteDisconnected(ConnectionResetError, BadStatusLine):
def __init__(self, *pos, **kw):
BadStatusLine.__init__(self, "")
ConnectionResetError.__init__(self, *pos, **kw)
# for backwards compatibility
error = HTTPException
| 37.020604 | 82 | 0.571352 |
import email.parser
import email.message
import http
import io
import re
import socket
import collections.abc
from urllib.parse import urlsplit
__all__ = ["HTTPResponse", "HTTPConnection",
"HTTPException", "NotConnected", "UnknownProtocol",
"UnknownTransferEncoding", "UnimplementedFileMode",
"IncompleteRead", "InvalidURL", "ImproperConnectionState",
"CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
"BadStatusLine", "LineTooLong", "RemoteDisconnected", "error",
"responses"]
HTTP_PORT = 80
HTTPS_PORT = 443
_UNKNOWN = 'UNKNOWN'
_CS_IDLE = 'Idle'
_CS_REQ_STARTED = 'Request-started'
_CS_REQ_SENT = 'Request-sent'
globals().update(http.HTTPStatus.__members__)
responses = {v: v.phrase for v in http.HTTPStatus.__members__.values()}
_MAXLINE = 65536
_MAXHEADERS = 100
# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
# / DIGIT / ALPHA
# ; any VCHAR, except delimiters
#
# VCHAR defined in http://tools.ietf.org/html/rfc5234#appendix-B.1
# the patterns for both name and value are more lenient than RFC
# definitions to allow for backwards compatibility
_is_legal_header_name = re.compile(rb'[^:\s][^:\r\n]*').fullmatch
_is_illegal_header_value = re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search
# These characters are not allowed within HTTP URL paths.
# See https://tools.ietf.org/html/rfc3986#section-3.3 and the
# https://tools.ietf.org/html/rfc3986#appendix-A pchar definition.
# Prevents CVE-2019-9740. Includes control characters such as \r\n.
# We don't restrict chars above \x7f as putrequest() limits us to ASCII.
_contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f]')
# We are more lenient for assumed real world compatibility purposes.
# We always set the Content-Length header for these methods because some
# servers will otherwise respond with a 411
_METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
def _encode(data, name='data'):
try:
return data.encode("latin-1")
except UnicodeEncodeError as err:
raise UnicodeEncodeError(
err.encoding,
err.object,
err.start,
err.end,
"%s (%.20r) is not valid Latin-1. Use %s.encode('utf-8') "
"if you want to send it encoded in UTF-8." %
(name.title(), data[err.start:err.end], name)) from None
class HTTPMessage(email.message.Message):
# XXX The only usage of this method is in
# http.server.CGIHTTPRequestHandler. Maybe move the code there so
# that it doesn't need to be part of the public API. The API has
def getallmatchingheaders(self, name):
name = name.lower() + ':'
n = len(name)
lst = []
hit = 0
for line in self.keys():
if line[:n].lower() == name:
hit = 1
elif not line[:1].isspace():
hit = 0
if hit:
lst.append(line)
return lst
def parse_headers(fp, _class=HTTPMessage):
headers = []
while True:
line = fp.readline(_MAXLINE + 1)
if len(line) > _MAXLINE:
raise LineTooLong("header line")
headers.append(line)
if len(headers) > _MAXHEADERS:
raise HTTPException("got more than %d headers" % _MAXHEADERS)
if line in (b'\r\n', b'\n', b''):
break
hstring = b''.join(headers).decode('iso-8859-1')
return email.parser.Parser(_class=_class).parsestr(hstring)
class HTTPResponse(io.BufferedIOBase):
def __init__(self, sock, debuglevel=0, method=None, url=None):
# specified number of bytes. If it does, it will block until
# the server times out and closes the connection. This will
# happen if a self.fp.read() is done (without a size) whether
# self.fp is buffered or not. So, no self.fp.read() by
# clients unless they know what they are doing.
self.fp = sock.makefile("rb")
self.debuglevel = debuglevel
self._method = method
# The HTTPResponse object is returned via urllib. The clients
# of http and urllib expect different attributes for the
# headers. headers is used here and supports urllib. msg is
# provided as a backwards compatibility layer for http
# clients.
self.headers = self.msg = None
# from the Status-Line of the response
self.version = _UNKNOWN # HTTP-Version
self.status = _UNKNOWN # Status-Code
self.reason = _UNKNOWN # Reason-Phrase
self.chunked = _UNKNOWN # is "chunked" being used?
self.chunk_left = _UNKNOWN # bytes left to read in current chunk
self.length = _UNKNOWN # number of bytes left in response
self.will_close = _UNKNOWN # conn will close at end of response
def _read_status(self):
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
if len(line) > _MAXLINE:
raise LineTooLong("status line")
if self.debuglevel > 0:
print("reply:", repr(line))
if not line:
# Presumably, the server closed the connection before
# sending a valid response.
raise RemoteDisconnected("Remote end closed connection without"
" response")
try:
version, status, reason = line.split(None, 2)
except ValueError:
try:
version, status = line.split(None, 1)
reason = ""
except ValueError:
# empty version will cause next test to fail.
version = ""
if not version.startswith("HTTP/"):
self._close_conn()
raise BadStatusLine(line)
# The status code is a three-digit number
try:
status = int(status)
if status < 100 or status > 999:
raise BadStatusLine(line)
except ValueError:
raise BadStatusLine(line)
return version, status, reason
def begin(self):
if self.headers is not None:
# we've already started reading the response
return
while True:
version, status, reason = self._read_status()
if status != CONTINUE:
break
while True:
skip = self.fp.readline(_MAXLINE + 1)
if len(skip) > _MAXLINE:
raise LineTooLong("header line")
skip = skip.strip()
if not skip:
break
if self.debuglevel > 0:
print("header:", skip)
self.code = self.status = status
self.reason = reason.strip()
if version in ("HTTP/1.0", "HTTP/0.9"):
self.version = 10
elif version.startswith("HTTP/1."):
self.version = 11
else:
raise UnknownProtocol(version)
self.headers = self.msg = parse_headers(self.fp)
if self.debuglevel > 0:
for hdr, val in self.headers.items():
print("header:", hdr + ":", val)
tr_enc = self.headers.get("transfer-encoding")
if tr_enc and tr_enc.lower() == "chunked":
self.chunked = True
self.chunk_left = None
else:
self.chunked = False
self.will_close = self._check_close()
self.headers.get("content-length")
tr_enc = self.headers.get("transfer-encoding")
if length and not self.chunked:
try:
self.length = int(length)
except ValueError:
self.length = None
else:
if self.length < 0:
self.length = None
else:
self.length = None
if (status == NO_CONTENT or status == NOT_MODIFIED or
100 <= status < 200 or
self._method == "HEAD"):
self.length = 0
# a content-length was not provided, then assume that the connection
# WILL close.
if (not self.will_close and
not self.chunked and
self.length is None):
self.will_close = True
def _check_close(self):
conn = self.headers.get("connection")
if self.version == 11:
# An HTTP/1.1 proxy is assumed to stay open unless
# explicitly closed.
if conn and "close" in conn.lower():
return True
return False
# Some HTTP/1.0 implementations have support for persistent
# connections, using rules different than HTTP/1.1.
# For older HTTP, Keep-Alive indicates persistent connection.
if self.headers.get("keep-alive"):
return False
# At least Akamai returns a "Connection: Keep-Alive" header,
# which was supposed to be sent by the client.
if conn and "keep-alive" in conn.lower():
return False
# Proxy-Connection is a netscape hack.
pconn = self.headers.get("proxy-connection")
if pconn and "keep-alive" in pconn.lower():
return False
# otherwise, assume it will close
return True
def _close_conn(self):
fp = self.fp
self.fp = None
fp.close()
def close(self):
try:
super().close() # set "closed" flag
finally:
if self.fp:
self._close_conn()
# These implementations are for the benefit of io.BufferedReader.
# XXX This class should probably be revised to act more like
# the "raw stream" that BufferedReader expects.
def flush(self):
super().flush()
if self.fp:
self.fp.flush()
def readable(self):
return True
# End of "raw stream" methods
def isclosed(self):
# NOTE: it is possible that we will not ever call self.close(). This
# case occurs when will_close is TRUE, length is None, and we
# read up to the last byte, but NOT past it.
#
# IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
# called, meaning self.isclosed() is meaningful.
return self.fp is None
def read(self, amt=None):
if self.fp is None:
return b""
if self._method == "HEAD":
self._close_conn()
return b""
if amt is not None:
# Amount is given, implement using readinto
b = bytearray(amt)
n = self.readinto(b)
return memoryview(b)[:n].tobytes()
else:
# Amount is not given (unbounded read) so we must check self.length
# and self.chunked
if self.chunked:
return self._readall_chunked()
if self.length is None:
s = self.fp.read()
else:
try:
s = self._safe_read(self.length)
except IncompleteRead:
self._close_conn()
raise
self.length = 0
self._close_conn() # we read everything
return s
def readinto(self, b):
if self.fp is None:
return 0
if self._method == "HEAD":
self._close_conn()
return 0
if self.chunked:
return self._readinto_chunked(b)
if self.length is not None:
if len(b) > self.length:
# clip the read to the "end of response"
b = memoryview(b)[0:self.length]
# we do not use _safe_read() here because this may be a .will_close
# connection, and the user is reading more bytes than will be provided
# (for example, reading in 1k chunks)
n = self.fp.readinto(b)
if not n and b:
# Ideally, we would raise IncompleteRead if the content-length
# wasn't satisfied, but it might break compatibility.
self._close_conn()
elif self.length is not None:
self.length -= n
if not self.length:
self._close_conn()
return n
def _read_next_chunk_size(self):
line = self.fp.readline(_MAXLINE + 1)
if len(line) > _MAXLINE:
raise LineTooLong("chunk size")
i = line.find(b";")
if i >= 0:
line = line[:i]
try:
return int(line, 16)
except ValueError:
self._close_conn()
raise
def _read_and_discard_trailer(self):
if len(line) > _MAXLINE:
raise LineTooLong("trailer line")
if not line:
# a vanishingly small number of sites EOF without
# sending the trailer
break
if line in (b'\r\n', b'\n', b''):
break
def _get_chunk_left(self):
# return self.chunk_left, reading a new chunk if necessary.
# chunk_left == 0: at the end of the current chunk, need to close it
# chunk_left == None: No current chunk, should read next.
# This function returns non-zero or None if the last chunk has
# been read.
chunk_left = self.chunk_left
if not chunk_left: # Can be 0 or None
if chunk_left is not None:
# We are at the end of chunk, discard chunk end
self._safe_read(2) # toss the CRLF at the end of the chunk
try:
chunk_left = self._read_next_chunk_size()
except ValueError:
raise IncompleteRead(b'')
if chunk_left == 0:
# last chunk: 1*("0") [ chunk-extension ] CRLF
self._read_and_discard_trailer()
# we read everything; close the "file"
self._close_conn()
chunk_left = None
self.chunk_left = chunk_left
return chunk_left
def _readall_chunked(self):
assert self.chunked != _UNKNOWN
value = []
try:
while True:
chunk_left = self._get_chunk_left()
if chunk_left is None:
break
value.append(self._safe_read(chunk_left))
self.chunk_left = 0
return b''.join(value)
except IncompleteRead:
raise IncompleteRead(b''.join(value))
def _readinto_chunked(self, b):
assert self.chunked != _UNKNOWN
total_bytes = 0
mvb = memoryview(b)
try:
while True:
chunk_left = self._get_chunk_left()
if chunk_left is None:
return total_bytes
if len(mvb) <= chunk_left:
n = self._safe_readinto(mvb)
self.chunk_left = chunk_left - n
return total_bytes + n
temp_mvb = mvb[:chunk_left]
n = self._safe_readinto(temp_mvb)
mvb = mvb[n:]
total_bytes += n
self.chunk_left = 0
except IncompleteRead:
raise IncompleteRead(bytes(b[0:total_bytes]))
def _safe_read(self, amt):
data = self.fp.read(amt)
if len(data) < amt:
raise IncompleteRead(data, amt-len(data))
return data
def _safe_readinto(self, b):
amt = len(b)
n = self.fp.readinto(b)
if n < amt:
raise IncompleteRead(bytes(b[:n]), amt-n)
return n
def read1(self, n=-1):
if self.fp is None or self._method == "HEAD":
return b""
if self.chunked:
return self._read1_chunked(n)
if self.length is not None and (n < 0 or n > self.length):
n = self.length
result = self.fp.read1(n)
if not result and n:
self._close_conn()
elif self.length is not None:
self.length -= len(result)
return result
def peek(self, n=-1):
# Having this enables IOBase.readline() to read more than one
# byte at a time
if self.fp is None or self._method == "HEAD":
return b""
if self.chunked:
return self._peek_chunked(n)
return self.fp.peek(n)
def readline(self, limit=-1):
if self.fp is None or self._method == "HEAD":
return b""
if self.chunked:
# Fallback to IOBase readline which uses peek() and read()
return super().readline(limit)
if self.length is not None and (limit < 0 or limit > self.length):
limit = self.length
result = self.fp.readline(limit)
if not result and limit:
self._close_conn()
elif self.length is not None:
self.length -= len(result)
return result
def _read1_chunked(self, n):
# Strictly speaking, _get_chunk_left() may cause more than one read,
# but that is ok, since that is to satisfy the chunked protocol.
chunk_left = self._get_chunk_left()
if chunk_left is None or n == 0:
return b''
if not (0 <= n <= chunk_left):
n = chunk_left # if n is negative or larger than chunk_left
read = self.fp.read1(n)
self.chunk_left -= len(read)
if not read:
raise IncompleteRead(b"")
return read
def _peek_chunked(self, n):
# Strictly speaking, _get_chunk_left() may cause more than one read,
# but that is ok, since that is to satisfy the chunked protocol.
try:
chunk_left = self._get_chunk_left()
except IncompleteRead:
return b'' # peek doesn't worry about protocol
if chunk_left is None:
return b''
return self.fp.peek(chunk_left)[:chunk_left]
def fileno(self):
return self.fp.fileno()
def getheader(self, name, default=None):
if self.headers is None:
raise ResponseNotReady()
headers = self.headers.get_all(name) or default
if isinstance(headers, str) or not hasattr(headers, '__iter__'):
return headers
else:
return ', '.join(headers)
def getheaders(self):
if self.headers is None:
raise ResponseNotReady()
return list(self.headers.items())
def __iter__(self):
return self
# For compatibility with old-style urllib responses.
def info(self):
return self.headers
def geturl(self):
return self.url
def getcode(self):
return self.status
class HTTPConnection:
_http_vsn = 11
_http_vsn_str = 'HTTP/1.1'
response_class = HTTPResponse
default_port = HTTP_PORT
auto_open = 1
debuglevel = 0
@staticmethod
def _is_textIO(stream):
return isinstance(stream, io.TextIOBase)
@staticmethod
def _get_content_length(body, method):
if body is None:
# do an explicit check for not None here to distinguish
# between unset and set but empty
if method.upper() in _METHODS_EXPECTING_BODY:
return 0
else:
return None
if hasattr(body, 'read'):
# file-like object.
return None
try:
# does it implement the buffer protocol (bytes, bytearray, array)?
mv = memoryview(body)
return mv.nbytes
except TypeError:
pass
if isinstance(body, str):
return len(body)
return None
def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, blocksize=8192):
self.timeout = timeout
self.source_address = source_address
self.blocksize = blocksize
self.sock = None
self._buffer = []
self.__response = None
self.__state = _CS_IDLE
self._method = None
self._tunnel_host = None
self._tunnel_port = None
self._tunnel_headers = {}
(self.host, self.port) = self._get_hostport(host, port)
# This is stored as an instance variable to allow unit
# tests to replace it with a suitable mockup
self._create_connection = socket.create_connection
def set_tunnel(self, host, port=None, headers=None):
if self.sock:
raise RuntimeError("Can't set up tunnel for established connection")
self._tunnel_host, self._tunnel_port = self._get_hostport(host, port)
if headers:
self._tunnel_headers = headers
else:
self._tunnel_headers.clear()
def _get_hostport(self, host, port):
if port is None:
i = host.rfind(':')
j = host.rfind(']')
if i > j:
try:
port = int(host[i+1:])
except ValueError:
if host[i+1:] == "":
port = self.default_port
else:
raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
host = host[:i]
else:
port = self.default_port
if host and host[0] == '[' and host[-1] == ']':
host = host[1:-1]
return (host, port)
def set_debuglevel(self, level):
self.debuglevel = level
def _tunnel(self):
connect_str = "CONNECT %s:%d HTTP/1.0\r\n" % (self._tunnel_host,
self._tunnel_port)
connect_bytes = connect_str.encode("ascii")
self.send(connect_bytes)
for header, value in self._tunnel_headers.items():
header_str = "%s: %s\r\n" % (header, value)
header_bytes = header_str.encode("latin-1")
self.send(header_bytes)
self.send(b'\r\n')
response = self.response_class(self.sock, method=self._method)
(version, code, message) = response._read_status()
if code != http.HTTPStatus.OK:
self.close()
raise OSError("Tunnel connection failed: %d %s" % (code,
message.strip()))
while True:
line = response.fp.readline(_MAXLINE + 1)
if len(line) > _MAXLINE:
raise LineTooLong("header line")
if not line:
break
if line in (b'\r\n', b'\n', b''):
break
if self.debuglevel > 0:
print('header:', line.decode())
def connect(self):
self.sock = self._create_connection(
(self.host,self.port), self.timeout, self.source_address)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if self._tunnel_host:
self._tunnel()
def close(self):
self.__state = _CS_IDLE
try:
sock = self.sock
if sock:
self.sock = None
sock.close()
finally:
response = self.__response
if response:
self.__response = None
response.close()
def send(self, data):
if self.sock is None:
if self.auto_open:
self.connect()
else:
raise NotConnected()
if self.debuglevel > 0:
print("send:", repr(data))
if hasattr(data, "read") :
if self.debuglevel > 0:
print("sendIng a read()able")
encode = self._is_textIO(data)
if encode and self.debuglevel > 0:
print("encoding file using iso-8859-1")
while 1:
datablock = data.read(self.blocksize)
if not datablock:
break
if encode:
datablock = datablock.encode("iso-8859-1")
self.sock.sendall(datablock)
return
try:
self.sock.sendall(data)
except TypeError:
if isinstance(data, collections.abc.Iterable):
for d in data:
self.sock.sendall(d)
else:
raise TypeError("data should be a bytes-like object "
"or an iterable, got %r" % type(data))
def _output(self, s):
self._buffer.append(s)
def _read_readable(self, readable):
if self.debuglevel > 0:
print("sendIng a read()able")
encode = self._is_textIO(readable)
if encode and self.debuglevel > 0:
print("encoding file using iso-8859-1")
while True:
datablock = readable.read(self.blocksize)
if not datablock:
break
if encode:
datablock = datablock.encode("iso-8859-1")
yield datablock
def _send_output(self, message_body=None, encode_chunked=False):
self._buffer.extend((b"", b""))
msg = b"\r\n".join(self._buffer)
del self._buffer[:]
self.send(msg)
if message_body is not None:
if hasattr(message_body, 'read'):
# files to be taken into account.
chunks = self._read_readable(message_body)
else:
try:
# this is solely to check to see if message_body
# implements the buffer API. it /would/ be easier
# to capture if PyObject_CheckBuffer was exposed
# to Python.
memoryview(message_body)
except TypeError:
try:
chunks = iter(message_body)
except TypeError:
raise TypeError("message_body should be a bytes-like "
"object or an iterable, got %r"
% type(message_body))
else:
# the object implements the buffer interface and
# can be passed directly into socket methods
chunks = (message_body,)
for chunk in chunks:
if not chunk:
if self.debuglevel > 0:
print('Zero length chunk ignored')
continue
if encode_chunked and self._http_vsn == 11:
# chunked encoding
chunk = f'{len(chunk):X}\r\n'.encode('ascii') + chunk \
+ b'\r\n'
self.send(chunk)
if encode_chunked and self._http_vsn == 11:
# end chunked transfer
self.send(b'0\r\n\r\n')
def putrequest(self, method, url, skip_host=False,
skip_accept_encoding=False):
# if a prior response has been completed, then forget about it.
if self.__response and self.__response.isclosed():
self.__response = None
# in certain cases, we cannot issue another request on this connection.
# this occurs when:
# 1) we are in the process of sending a request. (_CS_REQ_STARTED)
# 2) a response to a previous request has signalled that it is going
# to close the connection upon completion.
# 3) the headers for the previous response have not been read, thus
# we cannot determine whether point (2) is true. (_CS_REQ_SENT)
#
# if there is no prior response, then we can request at will.
#
# if point (2) is true, then we will have passed the socket to the
# response (effectively meaning, "there is no prior response"), and
# will open a new one when a new request is made.
#
# Note: if a prior response exists, then we *can* start a new request.
# We are not allowed to begin fetching the response to this new
# request, however, until that prior response is complete.
#
if self.__state == _CS_IDLE:
self.__state = _CS_REQ_STARTED
else:
raise CannotSendRequest(self.__state)
# Save the method we use, we need it later in the response phase
self._method = method
if not url:
url = '/'
# Prevent CVE-2019-9740.
if match := _contains_disallowed_url_pchar_re.search(url):
raise InvalidURL(f"URL can't contain control characters. {url!r} "
f"(found at least {match.group()!r})")
request = '%s %s %s' % (method, url, self._http_vsn_str)
self._output(request.encode('ascii'))
if self._http_vsn == 11:
if not skip_host:
netloc = ''
if url.startswith('http'):
nil, netloc, nil, nil, nil = urlsplit(url)
if netloc:
try:
netloc_enc = netloc.encode("ascii")
except UnicodeEncodeError:
netloc_enc = netloc.encode("idna")
self.putheader('Host', netloc_enc)
else:
if self._tunnel_host:
host = self._tunnel_host
port = self._tunnel_port
else:
host = self.host
port = self.port
try:
host_enc = host.encode("ascii")
except UnicodeEncodeError:
host_enc = host.encode("idna")
if host.find(':') >= 0:
host_enc = b'[' + host_enc + b']'
if port == self.default_port:
self.putheader('Host', host_enc)
else:
host_enc = host_enc.decode("ascii")
self.putheader('Host', "%s:%s" % (host_enc, port))
# support encodings such as x-gzip or x-deflate.
if not skip_accept_encoding:
self.putheader('Accept-Encoding', 'identity')
# we can accept "chunked" Transfer-Encodings, but no others
# NOTE: no TE header implies *only* "chunked"
#self.putheader('TE', 'chunked')
# if TE is supplied in the header, then it must appear in a
# Connection header.
#self.putheader('Connection', 'TE')
else:
# For HTTP/1.0, the server will assume "not chunked"
pass
def putheader(self, header, *values):
if self.__state != _CS_REQ_STARTED:
raise CannotSendHeader()
if hasattr(header, 'encode'):
header = header.encode('ascii')
if not _is_legal_header_name(header):
raise ValueError('Invalid header name %r' % (header,))
values = list(values)
for i, one_value in enumerate(values):
if hasattr(one_value, 'encode'):
values[i] = one_value.encode('latin-1')
elif isinstance(one_value, int):
values[i] = str(one_value).encode('ascii')
if _is_illegal_header_value(values[i]):
raise ValueError('Invalid header value %r' % (values[i],))
value = b'\r\n\t'.join(values)
header = header + b': ' + value
self._output(header)
def endheaders(self, message_body=None, *, encode_chunked=False):
if self.__state == _CS_REQ_STARTED:
self.__state = _CS_REQ_SENT
else:
raise CannotSendHeader()
self._send_output(message_body, encode_chunked=encode_chunked)
def request(self, method, url, body=None, headers={}, *,
encode_chunked=False):
self._send_request(method, url, body, headers, encode_chunked)
def _send_request(self, method, url, body, headers, encode_chunked):
# Honor explicitly requested Host: and Accept-Encoding: headers.
header_names = frozenset(k.lower() for k in headers)
skips = {}
if 'host' in header_names:
skips['skip_host'] = 1
if 'accept-encoding' in header_names:
skips['skip_accept_encoding'] = 1
self.putrequest(method, url, **skips)
# chunked encoding will happen if HTTP/1.1 is used and either
# the caller passes encode_chunked=True or the following
# conditions hold:
# 1. content-length has not been explicitly set
# 2. the body is a file or iterable, but not a str or bytes-like
# 3. Transfer-Encoding has NOT been explicitly set by the caller
if 'content-length' not in header_names:
# only chunk body if not explicitly set for backwards
# compatibility, assuming the client code is already handling the
# chunking
if 'transfer-encoding' not in header_names:
# if content-length cannot be automatically determined, fall
# back to chunked encoding
encode_chunked = False
content_length = self._get_content_length(body, method)
if content_length is None:
if body is not None:
if self.debuglevel > 0:
print('Unable to determine size of %r' % body)
encode_chunked = True
self.putheader('Transfer-Encoding', 'chunked')
else:
self.putheader('Content-Length', str(content_length))
else:
encode_chunked = False
for hdr, value in headers.items():
self.putheader(hdr, value)
if isinstance(body, str):
# RFC 2616 Section 3.7.1 says that text default has a
# default charset of iso-8859-1.
body = _encode(body, 'body')
self.endheaders(body, encode_chunked=encode_chunked)
def getresponse(self):
# if a prior response has been completed, then forget about it.
if self.__response and self.__response.isclosed():
self.__response = None
# if a prior response exists, then it must be completed (otherwise, we
# cannot read this response's header to determine the connection-close
if self.__state != _CS_REQ_SENT or self.__response:
raise ResponseNotReady(self.__state)
if self.debuglevel > 0:
response = self.response_class(self.sock, self.debuglevel,
method=self._method)
else:
response = self.response_class(self.sock, method=self._method)
try:
try:
response.begin()
except ConnectionError:
self.close()
raise
assert response.will_close != _UNKNOWN
self.__state = _CS_IDLE
if response.will_close:
self.close()
else:
self.__response = response
return response
except:
response.close()
raise
try:
import ssl
except ImportError:
pass
else:
class HTTPSConnection(HTTPConnection):
"This class allows communication via SSL."
default_port = HTTPS_PORT
def __init__(self, host, port=None, key_file=None, cert_file=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, *, context=None,
check_hostname=None, blocksize=8192):
super(HTTPSConnection, self).__init__(host, port, timeout,
source_address,
blocksize=blocksize)
if (key_file is not None or cert_file is not None or
check_hostname is not None):
import warnings
warnings.warn("key_file, cert_file and check_hostname are "
"deprecated, use a custom context instead.",
DeprecationWarning, 2)
self.key_file = key_file
self.cert_file = cert_file
if context is None:
context = ssl._create_default_https_context()
will_verify = context.verify_mode != ssl.CERT_NONE
if check_hostname is None:
check_hostname = context.check_hostname
if check_hostname and not will_verify:
raise ValueError("check_hostname needs a SSL context with "
"either CERT_OPTIONAL or CERT_REQUIRED")
if key_file or cert_file:
context.load_cert_chain(cert_file, key_file)
self._context = context
if check_hostname is not None:
self._context.check_hostname = check_hostname
def connect(self):
"Connect to a host on a given (SSL) port."
super().connect()
if self._tunnel_host:
server_hostname = self._tunnel_host
else:
server_hostname = self.host
self.sock = self._context.wrap_socket(self.sock,
server_hostname=server_hostname)
__all__.append("HTTPSConnection")
class HTTPException(Exception):
pass
class NotConnected(HTTPException):
pass
class InvalidURL(HTTPException):
pass
class UnknownProtocol(HTTPException):
def __init__(self, version):
self.args = version,
self.version = version
class UnknownTransferEncoding(HTTPException):
pass
class UnimplementedFileMode(HTTPException):
pass
class IncompleteRead(HTTPException):
def __init__(self, partial, expected=None):
self.args = partial,
self.partial = partial
self.expected = expected
def __repr__(self):
if self.expected is not None:
e = ', %i more expected' % self.expected
else:
e = ''
return '%s(%i bytes read%s)' % (self.__class__.__name__,
len(self.partial), e)
def __str__(self):
return repr(self)
class ImproperConnectionState(HTTPException):
pass
class CannotSendRequest(ImproperConnectionState):
pass
class CannotSendHeader(ImproperConnectionState):
pass
class ResponseNotReady(ImproperConnectionState):
pass
class BadStatusLine(HTTPException):
def __init__(self, line):
if not line:
line = repr(line)
self.args = line,
self.line = line
class LineTooLong(HTTPException):
def __init__(self, line_type):
HTTPException.__init__(self, "got more than %d bytes when reading %s"
% (_MAXLINE, line_type))
class RemoteDisconnected(ConnectionResetError, BadStatusLine):
def __init__(self, *pos, **kw):
BadStatusLine.__init__(self, "")
ConnectionResetError.__init__(self, *pos, **kw)
error = HTTPException
| true | true |
f71a07d0760e6b2878001901d08de4bc02ae7c09 | 3,381 | py | Python | static_data/mk_lookup.py | flyingsymbols/arewebeatingcovid19 | 78370472432700bb84796035c93868fb1887c055 | [
"MIT"
] | 1 | 2020-04-18T08:41:00.000Z | 2020-04-18T08:41:00.000Z | static_data/mk_lookup.py | flyingsymbols/arewebeatingcovid19 | 78370472432700bb84796035c93868fb1887c055 | [
"MIT"
] | null | null | null | static_data/mk_lookup.py | flyingsymbols/arewebeatingcovid19 | 78370472432700bb84796035c93868fb1887c055 | [
"MIT"
] | null | null | null | import os
import csv
import copy
import json
DIR = os.path.dirname(__file__)
def rel(*p): return os.path.normpath(os.path.join(DIR, *p))
CENSUS_DATA = rel('nst-est2019-alldata.csv')
OUT_JSON = rel('state_data.json')
def main():
state_data = copy.deepcopy(STATE_DATA)
state_name_ind = {} # { name: ind of record in STATE_DATA }
state_abbrev_ind = {} # { abbrev: ind of records in STATE_DATA }
for i, v in enumerate(state_data):
state_name_ind[v['name']] = i
state_abbrev_ind[v['abbrev']] = i
with open(CENSUS_DATA, 'r') as f:
csv_r = csv.DictReader(f)
for row in csv_r:
name = row['NAME']
population = int(row['POPESTIMATE2019'])
if name not in state_name_ind:
continue
else:
data_row_i = state_name_ind[name]
state_data[data_row_i]['population'] = population
state_json_data = {
'name_ind': state_name_ind,
'abbrev_ind': state_abbrev_ind,
'data': state_data
}
state_json_str = json.dumps(state_json_data, indent=2)
with open(OUT_JSON, 'w') as f:
json.dump(state_json_data, f, indent=2)
STATE_DATA = [
{"name": "Alabama", "abbrev": "AL"},
{"name": "Alaska", "abbrev": "AK"},
{"name": "Arizona", "abbrev": "AZ"},
{"name": "Arkansas", "abbrev": "AR"},
{"name": "California", "abbrev": "CA"},
{"name": "Colorado", "abbrev": "CO"},
{"name": "Connecticut", "abbrev": "CT"},
{"name": "Delaware", "abbrev": "DE"},
{"name": "Florida", "abbrev": "FL"},
{"name": "Georgia", "abbrev": "GA"},
{"name": "Hawaii", "abbrev": "HI"},
{"name": "Idaho", "abbrev": "ID"},
{"name": "Illinois", "abbrev": "IL"},
{"name": "Indiana", "abbrev": "IN"},
{"name": "Iowa", "abbrev": "IA"},
{"name": "Kansas", "abbrev": "KS"},
{"name": "Kentucky", "abbrev": "KY"},
{"name": "Louisiana", "abbrev": "LA"},
{"name": "Maine", "abbrev": "ME"},
{"name": "Maryland", "abbrev": "MD"},
{"name": "Massachusetts", "abbrev": "MA"},
{"name": "Michigan", "abbrev": "MI"},
{"name": "Minnesota", "abbrev": "MN"},
{"name": "Mississippi", "abbrev": "MS"},
{"name": "Missouri", "abbrev": "MO"},
{"name": "Montana", "abbrev": "MT"},
{"name": "Nebraska", "abbrev": "NE"},
{"name": "Nevada", "abbrev": "NV"},
{"name": "New Hampshire", "abbrev": "NH"},
{"name": "New Jersey", "abbrev": "NJ"},
{"name": "New Mexico", "abbrev": "NM"},
{"name": "New York", "abbrev": "NY"},
{"name": "North Carolina", "abbrev": "NC"},
{"name": "North Dakota", "abbrev": "ND"},
{"name": "Ohio", "abbrev": "OH"},
{"name": "Oklahoma", "abbrev": "OK"},
{"name": "Oregon", "abbrev": "OR"},
{"name": "Pennsylvania", "abbrev": "PA"},
{"name": "Rhode Island", "abbrev": "RI"},
{"name": "South Carolina", "abbrev": "SC"},
{"name": "South Dakota", "abbrev": "SD"},
{"name": "Tennessee", "abbrev": "TN"},
{"name": "Texas", "abbrev": "TX"},
{"name": "Utah", "abbrev": "UT"},
{"name": "Vermont", "abbrev": "VT"},
{"name": "Virginia", "abbrev": "VA"},
{"name": "Washington", "abbrev": "WA"},
{"name": "West Virginia", "abbrev": "WV"},
{"name": "Wisconsin", "abbrev": "WI"},
{"name": "Wyoming", "abbrev": "WY"},
]
if __name__ == '__main__':
main()
| 33.147059 | 70 | 0.525288 | import os
import csv
import copy
import json
DIR = os.path.dirname(__file__)
def rel(*p): return os.path.normpath(os.path.join(DIR, *p))
CENSUS_DATA = rel('nst-est2019-alldata.csv')
OUT_JSON = rel('state_data.json')
def main():
state_data = copy.deepcopy(STATE_DATA)
state_name_ind = {}
state_abbrev_ind = {}
for i, v in enumerate(state_data):
state_name_ind[v['name']] = i
state_abbrev_ind[v['abbrev']] = i
with open(CENSUS_DATA, 'r') as f:
csv_r = csv.DictReader(f)
for row in csv_r:
name = row['NAME']
population = int(row['POPESTIMATE2019'])
if name not in state_name_ind:
continue
else:
data_row_i = state_name_ind[name]
state_data[data_row_i]['population'] = population
state_json_data = {
'name_ind': state_name_ind,
'abbrev_ind': state_abbrev_ind,
'data': state_data
}
state_json_str = json.dumps(state_json_data, indent=2)
with open(OUT_JSON, 'w') as f:
json.dump(state_json_data, f, indent=2)
STATE_DATA = [
{"name": "Alabama", "abbrev": "AL"},
{"name": "Alaska", "abbrev": "AK"},
{"name": "Arizona", "abbrev": "AZ"},
{"name": "Arkansas", "abbrev": "AR"},
{"name": "California", "abbrev": "CA"},
{"name": "Colorado", "abbrev": "CO"},
{"name": "Connecticut", "abbrev": "CT"},
{"name": "Delaware", "abbrev": "DE"},
{"name": "Florida", "abbrev": "FL"},
{"name": "Georgia", "abbrev": "GA"},
{"name": "Hawaii", "abbrev": "HI"},
{"name": "Idaho", "abbrev": "ID"},
{"name": "Illinois", "abbrev": "IL"},
{"name": "Indiana", "abbrev": "IN"},
{"name": "Iowa", "abbrev": "IA"},
{"name": "Kansas", "abbrev": "KS"},
{"name": "Kentucky", "abbrev": "KY"},
{"name": "Louisiana", "abbrev": "LA"},
{"name": "Maine", "abbrev": "ME"},
{"name": "Maryland", "abbrev": "MD"},
{"name": "Massachusetts", "abbrev": "MA"},
{"name": "Michigan", "abbrev": "MI"},
{"name": "Minnesota", "abbrev": "MN"},
{"name": "Mississippi", "abbrev": "MS"},
{"name": "Missouri", "abbrev": "MO"},
{"name": "Montana", "abbrev": "MT"},
{"name": "Nebraska", "abbrev": "NE"},
{"name": "Nevada", "abbrev": "NV"},
{"name": "New Hampshire", "abbrev": "NH"},
{"name": "New Jersey", "abbrev": "NJ"},
{"name": "New Mexico", "abbrev": "NM"},
{"name": "New York", "abbrev": "NY"},
{"name": "North Carolina", "abbrev": "NC"},
{"name": "North Dakota", "abbrev": "ND"},
{"name": "Ohio", "abbrev": "OH"},
{"name": "Oklahoma", "abbrev": "OK"},
{"name": "Oregon", "abbrev": "OR"},
{"name": "Pennsylvania", "abbrev": "PA"},
{"name": "Rhode Island", "abbrev": "RI"},
{"name": "South Carolina", "abbrev": "SC"},
{"name": "South Dakota", "abbrev": "SD"},
{"name": "Tennessee", "abbrev": "TN"},
{"name": "Texas", "abbrev": "TX"},
{"name": "Utah", "abbrev": "UT"},
{"name": "Vermont", "abbrev": "VT"},
{"name": "Virginia", "abbrev": "VA"},
{"name": "Washington", "abbrev": "WA"},
{"name": "West Virginia", "abbrev": "WV"},
{"name": "Wisconsin", "abbrev": "WI"},
{"name": "Wyoming", "abbrev": "WY"},
]
if __name__ == '__main__':
main()
| true | true |
f71a09128c188832b08bc19072a6ef2f2c8d9dde | 3,136 | py | Python | music_preprocessor/music_preprocessor.py | offy284/Keras-GAN | 6652c626ba584ffd1c25ca4e925e6f131077395c | [
"MIT"
] | null | null | null | music_preprocessor/music_preprocessor.py | offy284/Keras-GAN | 6652c626ba584ffd1c25ca4e925e6f131077395c | [
"MIT"
] | null | null | null | music_preprocessor/music_preprocessor.py | offy284/Keras-GAN | 6652c626ba584ffd1c25ca4e925e6f131077395c | [
"MIT"
] | null | null | null | import itertools
import shutil
import os
from os import listdir
from os.path import isfile, join
from tqdm import tqdm
import numpy as np
import scipy
from scipy.io.wavfile import write, read
from scipy.fftpack import fft
from scipy import signal
from scipy.fft import fftshift
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
RESOLUTION_SCALE = 10
def flatten_dir(dir):
print("Flattening MusicData directory...")
all_files = []
dups = 0
for root, _dirs, files in itertools.islice(os.walk(dir), 1, None):
try:
for filename in files:
all_files.append(os.path.join(root, filename))
except:
dups += 1
for filename in all_files:
try:
shutil.move(filename, dir)
except:
dups += 1
print(f"{dups} duplicate files removed")
def generate_big_music(resolution_scale=RESOLUTION_SCALE):
print("Generating big_music from MusicData directory...")
onlyfiles = [f for f in listdir("MusicData/") if isfile(join("MusicData/", f))]
print("Normalizing big_music...")
square_size = 28 * resolution_scale
big_music = np.empty((1)) # np.empty((len(onlyfiles), square_size, square_size, 1))
for i in tqdm(range(len(onlyfiles))):
file = onlyfiles[i]
if "-converted" in file:
x = scipy.io.wavfile.read(f"MusicData/{file}")
x = x[1]
#big_music = big_music.reshape(-1)
'''
print(f"Building spectrogram...")
plt.specgram(x, Fs=44100)
plt.savefig(f'MusicImageData/{file}.png')
x = x.reshape(-1, 1)
min_max_scaler = MinMaxScaler()
x = (min_max_scaler.fit_transform(x) - .5) * 2
samples = list(np.empty((int(x.shape[0] / square_size / square_size), square_size, square_size, 1)))
rows = np.zeros((square_size, square_size, 1))
cols = np.zeros((square_size, 1))
for samplei in tqdm(range(len(samples))):
for yi in range(square_size):
for xi in range(square_size):
cols[xi] = x[xi + yi * square_size + samplei * square_size * square_size]
rows[yi] = cols
samples[samplei] = rows
'''
print("Numpyifying x...")
big_music = np.concatenate([big_music, x])
print(f"big_music is of shape {big_music.shape}")
freqs, times, spectrogram = signal.spectrogram(big_music, 44100)
spectrogram = spectrogram.reshape((spectrogram.shape[1], spectrogram.shape[0]))
print(spectrogram.shape)
filename = f"spectrogram.npy"
print(f"Saving {filename}...")
np.save(f"{filename}", spectrogram)
filename = f"freqs.npy"
print(f"Saving {filename}...")
np.save(f"{filename}", freqs)
filename = f"times.npy"
print(f"Saving {filename}...")
np.save(f"{filename}", times)
if __name__ == '__main__':
print("Music Preprocessor v0.1")
#flatten_dir()
generate_big_music() | 29.866667 | 112 | 0.607781 | import itertools
import shutil
import os
from os import listdir
from os.path import isfile, join
from tqdm import tqdm
import numpy as np
import scipy
from scipy.io.wavfile import write, read
from scipy.fftpack import fft
from scipy import signal
from scipy.fft import fftshift
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
RESOLUTION_SCALE = 10
def flatten_dir(dir):
print("Flattening MusicData directory...")
all_files = []
dups = 0
for root, _dirs, files in itertools.islice(os.walk(dir), 1, None):
try:
for filename in files:
all_files.append(os.path.join(root, filename))
except:
dups += 1
for filename in all_files:
try:
shutil.move(filename, dir)
except:
dups += 1
print(f"{dups} duplicate files removed")
def generate_big_music(resolution_scale=RESOLUTION_SCALE):
print("Generating big_music from MusicData directory...")
onlyfiles = [f for f in listdir("MusicData/") if isfile(join("MusicData/", f))]
print("Normalizing big_music...")
square_size = 28 * resolution_scale
big_music = np.empty((1))
for i in tqdm(range(len(onlyfiles))):
file = onlyfiles[i]
if "-converted" in file:
x = scipy.io.wavfile.read(f"MusicData/{file}")
x = x[1]
print("Numpyifying x...")
big_music = np.concatenate([big_music, x])
print(f"big_music is of shape {big_music.shape}")
freqs, times, spectrogram = signal.spectrogram(big_music, 44100)
spectrogram = spectrogram.reshape((spectrogram.shape[1], spectrogram.shape[0]))
print(spectrogram.shape)
filename = f"spectrogram.npy"
print(f"Saving {filename}...")
np.save(f"{filename}", spectrogram)
filename = f"freqs.npy"
print(f"Saving {filename}...")
np.save(f"{filename}", freqs)
filename = f"times.npy"
print(f"Saving {filename}...")
np.save(f"{filename}", times)
if __name__ == '__main__':
print("Music Preprocessor v0.1")
generate_big_music() | true | true |
f71a09cfb0b4712bce6ade7ab4148ea05334dfee | 1,077 | py | Python | database/dbclient.py | sonudoo/password-manager | 6fa1d2ebeba5b0f9cff200b32a581321d109b9cd | [
"MIT"
] | null | null | null | database/dbclient.py | sonudoo/password-manager | 6fa1d2ebeba5b0f9cff200b32a581321d109b9cd | [
"MIT"
] | null | null | null | database/dbclient.py | sonudoo/password-manager | 6fa1d2ebeba5b0f9cff200b32a581321d109b9cd | [
"MIT"
] | null | null | null | import pymongo
class DbClient:
"""Creates an instance of pymongo client and stores it in a private variable.
The instance of this class is injected as a dependency for request validators and processors.
Attributes:
database (Database): The database object.
collection_list (list): List of collection names as str.
"""
database = None
collection_list = None
def __init__(self, mongo_uri, database):
"""
Args:
mongo_uri (str): Uri of the MongoDB database.
database (str): Name of the database.
"""
client = pymongo.MongoClient(mongo_uri)
self.database = client[database]
self.collection_list = [collection for collection in self.database.collection_names()]
def get_collection(self, collection):
"""
Args:
collection (str): Name of the collection to get.
Returns:
Collection: The collection by name.
"""
assert collection in self.collection_list
return self.database[collection] | 32.636364 | 97 | 0.637883 | import pymongo
class DbClient:
database = None
collection_list = None
def __init__(self, mongo_uri, database):
client = pymongo.MongoClient(mongo_uri)
self.database = client[database]
self.collection_list = [collection for collection in self.database.collection_names()]
def get_collection(self, collection):
assert collection in self.collection_list
return self.database[collection] | true | true |
f71a0a1f8ed72da50b25bdb3d34573679f492d53 | 4,542 | py | Python | tests/clvm/test_chialisp_deserialization.py | Tony4467/littlelambocoin-blockchain | 3d4f2b577cd5a2feb324fca50e0981a728583aee | [
"Apache-2.0"
] | 6 | 2021-07-15T16:52:46.000Z | 2021-09-27T16:57:08.000Z | tests/clvm/test_chialisp_deserialization.py | Tony4467/littlelambocoin-blockchain | 3d4f2b577cd5a2feb324fca50e0981a728583aee | [
"Apache-2.0"
] | 6 | 2021-07-27T08:17:34.000Z | 2021-11-30T11:39:19.000Z | tests/clvm/test_chialisp_deserialization.py | Tony4467/littlelambocoin-blockchain | 3d4f2b577cd5a2feb324fca50e0981a728583aee | [
"Apache-2.0"
] | 7 | 2021-08-15T15:10:58.000Z | 2021-10-04T16:47:39.000Z | from unittest import TestCase
from littlelambocoin.types.blockchain_format.program import Program, INFINITE_COST
from littlelambocoin.util.byte_types import hexstr_to_bytes
from littlelambocoin.wallet.puzzles.load_clvm import load_clvm
DESERIALIZE_MOD = load_clvm("littlelambocoinlisp_deserialisation.clvm", package_or_requirement="littlelambocoin.wallet.puzzles")
def serialized_atom_overflow(size):
if size == 0:
size_blob = b"\x80"
elif size < 0x40:
size_blob = bytes([0x80 | size])
elif size < 0x2000:
size_blob = bytes([0xC0 | (size >> 8), (size >> 0) & 0xFF])
elif size < 0x100000:
size_blob = bytes([0xE0 | (size >> 16), (size >> 8) & 0xFF, (size >> 0) & 0xFF])
elif size < 0x8000000:
size_blob = bytes(
[
0xF0 | (size >> 24),
(size >> 16) & 0xFF,
(size >> 8) & 0xFF,
(size >> 0) & 0xFF,
]
)
elif size < 0x400000000:
size_blob = bytes(
[
0xF8 | (size >> 32),
(size >> 24) & 0xFF,
(size >> 16) & 0xFF,
(size >> 8) & 0xFF,
(size >> 0) & 0xFF,
]
)
else:
size_blob = bytes(
[
0xFC | ((size >> 40) & 0xFF),
(size >> 32) & 0xFF,
(size >> 24) & 0xFF,
(size >> 16) & 0xFF,
(size >> 8) & 0xFF,
(size >> 0) & 0xFF,
]
)
extra_str = "01" * 1000
return size_blob.hex() + extra_str
class TestClvmNativeDeserialization(TestCase):
"""
Test clvm deserialization done from within the clvm
"""
def test_deserialization_simple_list(self):
# ("hello" "friend")
b = hexstr_to_bytes("ff8568656c6c6fff86667269656e6480")
cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b])
print(cost, output)
prog = Program.to(output)
assert prog == Program.from_bytes(b)
def test_deserialization_password_coin(self):
# (i (= (sha256 2) (q 0x2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824)) (c (q 51) (c 5 (c (q 100) (q ())))) (q "wrong password")) # noqa
b = hexstr_to_bytes(
"ff04ffff0affff0bff0280ffff01ffa02cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b98248080ffff05ffff01ff3380ffff05ff05ffff05ffff01ff6480ffff01ff8080808080ffff01ff8e77726f6e672070617373776f72648080" # noqa
) # noqa
cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b])
print(cost, output)
prog = Program.to(output)
assert prog == Program.from_bytes(b)
def test_deserialization_large_numbers(self):
# '(99999999999999999999999999999999999999999999999999999999999999999 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -99999999999999999999999999999999999999999999999999999999999999999999999999999)' # noqa
b = hexstr_to_bytes(
"ff9c00f316271c7fc3908a8bef464e3945ef7a253609ffffffffffffffffffb00fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa1ff22ea0179500526edb610f148ec0c614155678491902d6000000000000000000180" # noqa
) # noqa
cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b])
print(cost, output)
prog = Program.to(output)
assert prog == Program.from_bytes(b)
def test_overflow_atoms(self):
b = hexstr_to_bytes(serialized_atom_overflow(0xFFFFFFFF))
try:
cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b])
except Exception:
assert True
else:
assert False
b = hexstr_to_bytes(serialized_atom_overflow(0x3FFFFFFFF))
try:
cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b])
except Exception:
assert True
else:
assert False
b = hexstr_to_bytes(serialized_atom_overflow(0xFFFFFFFFFF))
try:
cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b])
except Exception:
assert True
else:
assert False
b = hexstr_to_bytes(serialized_atom_overflow(0x1FFFFFFFFFF))
try:
cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b])
except Exception:
assert True
else:
assert False
| 39.495652 | 264 | 0.624835 | from unittest import TestCase
from littlelambocoin.types.blockchain_format.program import Program, INFINITE_COST
from littlelambocoin.util.byte_types import hexstr_to_bytes
from littlelambocoin.wallet.puzzles.load_clvm import load_clvm
DESERIALIZE_MOD = load_clvm("littlelambocoinlisp_deserialisation.clvm", package_or_requirement="littlelambocoin.wallet.puzzles")
def serialized_atom_overflow(size):
if size == 0:
size_blob = b"\x80"
elif size < 0x40:
size_blob = bytes([0x80 | size])
elif size < 0x2000:
size_blob = bytes([0xC0 | (size >> 8), (size >> 0) & 0xFF])
elif size < 0x100000:
size_blob = bytes([0xE0 | (size >> 16), (size >> 8) & 0xFF, (size >> 0) & 0xFF])
elif size < 0x8000000:
size_blob = bytes(
[
0xF0 | (size >> 24),
(size >> 16) & 0xFF,
(size >> 8) & 0xFF,
(size >> 0) & 0xFF,
]
)
elif size < 0x400000000:
size_blob = bytes(
[
0xF8 | (size >> 32),
(size >> 24) & 0xFF,
(size >> 16) & 0xFF,
(size >> 8) & 0xFF,
(size >> 0) & 0xFF,
]
)
else:
size_blob = bytes(
[
0xFC | ((size >> 40) & 0xFF),
(size >> 32) & 0xFF,
(size >> 24) & 0xFF,
(size >> 16) & 0xFF,
(size >> 8) & 0xFF,
(size >> 0) & 0xFF,
]
)
extra_str = "01" * 1000
return size_blob.hex() + extra_str
class TestClvmNativeDeserialization(TestCase):
def test_deserialization_simple_list(self):
b = hexstr_to_bytes("ff8568656c6c6fff86667269656e6480")
cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b])
print(cost, output)
prog = Program.to(output)
assert prog == Program.from_bytes(b)
def test_deserialization_password_coin(self):
b = hexstr_to_bytes(
"ff04ffff0affff0bff0280ffff01ffa02cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b98248080ffff05ffff01ff3380ffff05ff05ffff05ffff01ff6480ffff01ff8080808080ffff01ff8e77726f6e672070617373776f72648080"
)
cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b])
print(cost, output)
prog = Program.to(output)
assert prog == Program.from_bytes(b)
def test_deserialization_large_numbers(self):
b = hexstr_to_bytes(
"ff9c00f316271c7fc3908a8bef464e3945ef7a253609ffffffffffffffffffb00fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa1ff22ea0179500526edb610f148ec0c614155678491902d6000000000000000000180"
)
cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b])
print(cost, output)
prog = Program.to(output)
assert prog == Program.from_bytes(b)
def test_overflow_atoms(self):
b = hexstr_to_bytes(serialized_atom_overflow(0xFFFFFFFF))
try:
cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b])
except Exception:
assert True
else:
assert False
b = hexstr_to_bytes(serialized_atom_overflow(0x3FFFFFFFF))
try:
cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b])
except Exception:
assert True
else:
assert False
b = hexstr_to_bytes(serialized_atom_overflow(0xFFFFFFFFFF))
try:
cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b])
except Exception:
assert True
else:
assert False
b = hexstr_to_bytes(serialized_atom_overflow(0x1FFFFFFFFFF))
try:
cost, output = DESERIALIZE_MOD.run_with_cost(INFINITE_COST, [b])
except Exception:
assert True
else:
assert False
| true | true |
f71a0aa7e2a9704ecbc6e1a45727204696ea1a5b | 2,036 | py | Python | Discord 1.0.0a - REWRITE/EstruturaBots/CogsSharding/main.py | Algueem/Discord-Bot-Python-Tutoriais | cd126828a21fba4be584ffb62f923fa12086307b | [
"MIT"
] | 1 | 2018-10-14T16:45:32.000Z | 2018-10-14T16:45:32.000Z | Discord 1.0.0a - REWRITE/EstruturaBots/CogsSharding/main.py | ikrost/Discord-Bot-Python-Tutoriais | cd126828a21fba4be584ffb62f923fa12086307b | [
"MIT"
] | null | null | null | Discord 1.0.0a - REWRITE/EstruturaBots/CogsSharding/main.py | ikrost/Discord-Bot-Python-Tutoriais | cd126828a21fba4be584ffb62f923fa12086307b | [
"MIT"
] | 2 | 2019-04-26T21:37:38.000Z | 2019-05-07T17:37:26.000Z | import discord
from discord.ext import commands
import json
#vamos abrir o setup json para pegar as informaçoes
with open('bot_setup.json') as vagner:
bot_settings =json.load(vagner)
#lista de comandos
# cmds.info o cmds que dizer o nome da pastar e o info o nome do arquivo
#pode fazer tbm cmds.adm.ban caso queria deixar mais organizado a cada . entra em um diretorio
cmd_open=['cmds.info','cmds.cooldown']
#vamos criar o setup do bot
class main(commands.AutoShardedBot):
def __init__(self):
super().__init__(command_prefix=bot_settings['prefixo'],
description="tutorial Cogs Rewrite",
pm_help=None,
#aqui iremos definir a quantidade de shards
shard_count=bot_settings['shard_count'])
self.token = bot_settings['token']
#Aqui é para remover aquele help padrão mo feio
self.remove_command('help')
#agora vamos ao eventos do bot
async def on_ready(self):
#carregar os comandos
for extension in cmd_open:
try:
bot.load_extension(extension)
print(f"Comando {extension} carregado com sucesso")
except Exception as e:
exc = '{}.{}'.format(type(e).__name__, e)
print('falha ao carregar extensoes {} . {} detalhes {}'.format(extension, e,exc))
await self.change_presence(activity=discord.Activity(name='tutorial vagner',type=discord.ActivityType.listening))
print("Logado.")
async def on_message(self,message):
#vamos bloquear o bot para n responder a bots
if message.author.bot:
pass
#vamos impedir comandos via dm
elif isinstance(message.channel, discord.abc.GuildChannel) is False:
return
else:
await bot.process_commands(message)
#funcão para logar o bot
def run(self):
super().run(bot.token, reconnect=True)
if __name__ =="__main__":
bot = main()
bot.run()
| 33.377049 | 121 | 0.632613 | import discord
from discord.ext import commands
import json
with open('bot_setup.json') as vagner:
bot_settings =json.load(vagner)
cmd_open=['cmds.info','cmds.cooldown']
class main(commands.AutoShardedBot):
def __init__(self):
super().__init__(command_prefix=bot_settings['prefixo'],
description="tutorial Cogs Rewrite",
pm_help=None,
shard_count=bot_settings['shard_count'])
self.token = bot_settings['token']
self.remove_command('help')
async def on_ready(self):
for extension in cmd_open:
try:
bot.load_extension(extension)
print(f"Comando {extension} carregado com sucesso")
except Exception as e:
exc = '{}.{}'.format(type(e).__name__, e)
print('falha ao carregar extensoes {} . {} detalhes {}'.format(extension, e,exc))
await self.change_presence(activity=discord.Activity(name='tutorial vagner',type=discord.ActivityType.listening))
print("Logado.")
async def on_message(self,message):
if message.author.bot:
pass
elif isinstance(message.channel, discord.abc.GuildChannel) is False:
return
else:
await bot.process_commands(message)
def run(self):
super().run(bot.token, reconnect=True)
if __name__ =="__main__":
bot = main()
bot.run()
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.