repository_name stringclasses 316 values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1 value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1 value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
RetailMeNotSandbox/acky | acky/ec2.py | ElasticIPCollection.associate | python | def associate(self, eip_or_aid,
instance_id='', network_interface_id='', private_ip=''):
if "." in eip_or_aid: # If an IP is given (Classic)
return self.call("AssociateAddress",
PublicIp=eip_or_aid,
InstanceId=instance_id,
NetworkInterfaceId=network_interface_id,
PrivateIpAddress=private_ip)
else: # If an AID is given (VPC)
return self.call("AssociateAddress",
AllocationId=eip_or_aid,
InstanceId=instance_id,
NetworkInterfaceId=network_interface_id,
PrivateIpAddress=private_ip) | Associate an EIP with a given instance or network interface. If
the EIP was allocated for a VPC instance, an AllocationId(aid) must
be provided instead of a PublicIp. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L169-L186 | [
"def call(self, operation, response_data_key=None, *args, **kwargs):\n log = logging.getLogger(__name__)\n op = self._service.get_operation(operation)\n log.debug(\"Calling {} action '{}'\".format(self._service, operation))\n resp, data = op.call(self._endpoint, *args, **kwargs)\n if not resp.ok:\n ... | class ElasticIPCollection(AwsCollection, EC2ApiClient):
"""Interface to get, create, destroy, associate, and disassociate EIPs for
classic EC2 domains and VPCs. (Amazon EC2 API Version 2014-06-15)
"""
def get(self, filters=None):
"""List EIPs and associated information."""
params = {}
if filters:
params["filters"] = make_filters(filters)
return self.call("DescribeAddresses",
response_data_key="Addresses",
**params)
def create(self, vpc=False):
"""Set vpc=True to allocate an EIP for a EC2-Classic instance.
Set vpc=False to allocate an EIP for a VPC instance.
"""
return self.call("AllocateAddress",
Domain="vpc" if vpc else "standard")
def destroy(self, eip_or_aid, disassociate=False):
"""Release an EIP. If the EIP was allocated for a VPC instance, an
AllocationId(aid) must be provided instead of a PublicIp. Setting
disassociate to True will attempt to disassociate the IP before
releasing it (required for associated nondefault VPC instances).
"""
if "." in eip_or_aid: # If an IP is given (Classic)
# NOTE: EIPs are automatically disassociated for Classic instances.
return "true" == self.call("ReleaseAddress",
response_data_key="return",
PublicIp=eip_or_aid)
else: # If an AID is given (VPC)
if disassociate:
self.disassociate(eip_or_aid)
return "true" == self.call("ReleaseAddress",
response_data_key="return",
AllocationId=eip_or_aid)
def disassociate(self, eip_or_aid):
"""Disassociates an EIP. If the EIP was allocated for a VPC instance,
an AllocationId(aid) must be provided instead of a PublicIp.
"""
if "." in eip_or_aid: # If an IP is given (Classic)
return "true" == self.call("DisassociateAddress",
response_data_key="return",
PublicIp=eip_or_aid)
else: # If an AID is given (VPC)
return "true" == self.call("DisassociateAddress",
response_data_key="return",
AllocationId=eip_or_aid)
|
RetailMeNotSandbox/acky | acky/ec2.py | ElasticIPCollection.disassociate | python | def disassociate(self, eip_or_aid):
if "." in eip_or_aid: # If an IP is given (Classic)
return "true" == self.call("DisassociateAddress",
response_data_key="return",
PublicIp=eip_or_aid)
else: # If an AID is given (VPC)
return "true" == self.call("DisassociateAddress",
response_data_key="return",
AllocationId=eip_or_aid) | Disassociates an EIP. If the EIP was allocated for a VPC instance,
an AllocationId(aid) must be provided instead of a PublicIp. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L188-L199 | [
"def call(self, operation, response_data_key=None, *args, **kwargs):\n log = logging.getLogger(__name__)\n op = self._service.get_operation(operation)\n log.debug(\"Calling {} action '{}'\".format(self._service, operation))\n resp, data = op.call(self._endpoint, *args, **kwargs)\n if not resp.ok:\n ... | class ElasticIPCollection(AwsCollection, EC2ApiClient):
"""Interface to get, create, destroy, associate, and disassociate EIPs for
classic EC2 domains and VPCs. (Amazon EC2 API Version 2014-06-15)
"""
def get(self, filters=None):
"""List EIPs and associated information."""
params = {}
if filters:
params["filters"] = make_filters(filters)
return self.call("DescribeAddresses",
response_data_key="Addresses",
**params)
def create(self, vpc=False):
"""Set vpc=True to allocate an EIP for a EC2-Classic instance.
Set vpc=False to allocate an EIP for a VPC instance.
"""
return self.call("AllocateAddress",
Domain="vpc" if vpc else "standard")
def destroy(self, eip_or_aid, disassociate=False):
"""Release an EIP. If the EIP was allocated for a VPC instance, an
AllocationId(aid) must be provided instead of a PublicIp. Setting
disassociate to True will attempt to disassociate the IP before
releasing it (required for associated nondefault VPC instances).
"""
if "." in eip_or_aid: # If an IP is given (Classic)
# NOTE: EIPs are automatically disassociated for Classic instances.
return "true" == self.call("ReleaseAddress",
response_data_key="return",
PublicIp=eip_or_aid)
else: # If an AID is given (VPC)
if disassociate:
self.disassociate(eip_or_aid)
return "true" == self.call("ReleaseAddress",
response_data_key="return",
AllocationId=eip_or_aid)
def associate(self, eip_or_aid,
instance_id='', network_interface_id='', private_ip=''):
"""Associate an EIP with a given instance or network interface. If
the EIP was allocated for a VPC instance, an AllocationId(aid) must
be provided instead of a PublicIp.
"""
if "." in eip_or_aid: # If an IP is given (Classic)
return self.call("AssociateAddress",
PublicIp=eip_or_aid,
InstanceId=instance_id,
NetworkInterfaceId=network_interface_id,
PrivateIpAddress=private_ip)
else: # If an AID is given (VPC)
return self.call("AssociateAddress",
AllocationId=eip_or_aid,
InstanceId=instance_id,
NetworkInterfaceId=network_interface_id,
PrivateIpAddress=private_ip)
|
RetailMeNotSandbox/acky | acky/ec2.py | InstanceCollection.get | python | def get(self, instance_ids=None, filters=None):
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
reservations = self.call("DescribeInstances",
response_data_key="Reservations",
**params)
if reservations:
return list(chain(*(r["Instances"] for r in reservations)))
return [] | List instance info. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L204-L216 | [
"def make_filters(data, key_name='Name', values_name='Values'):\n data = data.copy()\n for key, value in data.items():\n if isinstance(value, str) or not hasattr(value, '__iter__'):\n data[key] = [value]\n return make_map(data, key_name, values_name)\n",
"def call(self, operation, respo... | class InstanceCollection(AwsCollection, EC2ApiClient):
def create(self, ami, count, config=None):
"""Create an instance using the launcher."""
return self.Launcher(config=config).launch(ami, count)
def destroy(self, instance_id):
"""Terminate a single given instance."""
return self.control(instance_id, "terminate")
def control(self, instances, action):
"""Valid actions: start, stop, reboot, terminate, protect, and
unprotect.
"""
if not isinstance(instances, list) and\
not isinstance(instances, tuple):
instances = [instances]
actions = {'start': {'operation': "StartInstances",
'response_data_key': "StartingInstances",
'InstanceIds': instances},
'stop': {'operation': "StopInstances",
'response_data_key': "StoppingInstances",
'InstanceIds': instances},
'reboot': {'operation': "RebootInstances",
'response_data_key': "return",
'InstanceIds': instances},
'terminate': {'operation': "TerminateInstances",
'response_data_key': "TerminatingInstances",
'InstanceIds': instances},
'protect': {'operation': "ModifyInstanceAttribute",
'response_data_key': "return",
'Attribute': 'disableApiTermination',
'Value': 'true'},
'unprotect': {'operation': "ModifyInstanceAttribute",
'response_data_key': "return",
'Attribute': 'disableApiTermination',
'Value': 'false'}}
if (action in ('protect', 'unprotect')):
for instance in instances:
self.call(InstanceId=instance, **actions[action])
return "true"
else:
return self.call(**actions[action])
def Launcher(self, config=None):
"""Provides a configurable launcher for EC2 instances."""
class _launcher(EC2ApiClient):
"""Configurable launcher for EC2 instances. Create the Launcher
(passing an optional dict of its attributes), set its attributes
(as described in the RunInstances API docs), then launch().
"""
def __init__(self, aws, config):
super(_launcher, self).__init__(aws)
self.config = config
self._attr = list(self.__dict__.keys()) + ['_attr']
def launch(self, ami, min_count, max_count=0):
"""Use given AMI to launch min_count instances with the
current configuration. Returns instance info list.
"""
params = config.copy()
params.update(dict([i for i in self.__dict__.items()
if i[0] not in self._attr]))
return self.call("RunInstances",
ImageId=ami,
MinCount=min_count,
MaxCount=max_count or min_count,
response_data_key="Instances",
**params)
if not config:
config = {}
return _launcher(self._aws, config)
def status(self, all_instances=None, instance_ids=None, filters=None):
"""List instance info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
if all_instances is not None:
params['IncludeAllInstances'] = all_instances
statuses = self.call("DescribeInstanceStatus",
response_data_key="InstanceStatuses",
**params)
return statuses
def events(self, all_instances=None, instance_ids=None, filters=None):
"""a list of tuples containing instance Id's and event information"""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
statuses = self.status(all_instances, **params)
event_list = []
for status in statuses:
if status.get("Events"):
for event in status.get("Events"):
event[u"InstanceId"] = status.get('InstanceId')
event_list.append(event)
return event_list
|
RetailMeNotSandbox/acky | acky/ec2.py | InstanceCollection.create | python | def create(self, ami, count, config=None):
return self.Launcher(config=config).launch(ami, count) | Create an instance using the launcher. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L218-L220 | [
"def Launcher(self, config=None):\n \"\"\"Provides a configurable launcher for EC2 instances.\"\"\"\n class _launcher(EC2ApiClient):\n \"\"\"Configurable launcher for EC2 instances. Create the Launcher\n (passing an optional dict of its attributes), set its attributes\n (as described in t... | class InstanceCollection(AwsCollection, EC2ApiClient):
def get(self, instance_ids=None, filters=None):
"""List instance info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
reservations = self.call("DescribeInstances",
response_data_key="Reservations",
**params)
if reservations:
return list(chain(*(r["Instances"] for r in reservations)))
return []
def destroy(self, instance_id):
"""Terminate a single given instance."""
return self.control(instance_id, "terminate")
def control(self, instances, action):
"""Valid actions: start, stop, reboot, terminate, protect, and
unprotect.
"""
if not isinstance(instances, list) and\
not isinstance(instances, tuple):
instances = [instances]
actions = {'start': {'operation': "StartInstances",
'response_data_key': "StartingInstances",
'InstanceIds': instances},
'stop': {'operation': "StopInstances",
'response_data_key': "StoppingInstances",
'InstanceIds': instances},
'reboot': {'operation': "RebootInstances",
'response_data_key': "return",
'InstanceIds': instances},
'terminate': {'operation': "TerminateInstances",
'response_data_key': "TerminatingInstances",
'InstanceIds': instances},
'protect': {'operation': "ModifyInstanceAttribute",
'response_data_key': "return",
'Attribute': 'disableApiTermination',
'Value': 'true'},
'unprotect': {'operation': "ModifyInstanceAttribute",
'response_data_key': "return",
'Attribute': 'disableApiTermination',
'Value': 'false'}}
if (action in ('protect', 'unprotect')):
for instance in instances:
self.call(InstanceId=instance, **actions[action])
return "true"
else:
return self.call(**actions[action])
def Launcher(self, config=None):
"""Provides a configurable launcher for EC2 instances."""
class _launcher(EC2ApiClient):
"""Configurable launcher for EC2 instances. Create the Launcher
(passing an optional dict of its attributes), set its attributes
(as described in the RunInstances API docs), then launch().
"""
def __init__(self, aws, config):
super(_launcher, self).__init__(aws)
self.config = config
self._attr = list(self.__dict__.keys()) + ['_attr']
def launch(self, ami, min_count, max_count=0):
"""Use given AMI to launch min_count instances with the
current configuration. Returns instance info list.
"""
params = config.copy()
params.update(dict([i for i in self.__dict__.items()
if i[0] not in self._attr]))
return self.call("RunInstances",
ImageId=ami,
MinCount=min_count,
MaxCount=max_count or min_count,
response_data_key="Instances",
**params)
if not config:
config = {}
return _launcher(self._aws, config)
def status(self, all_instances=None, instance_ids=None, filters=None):
"""List instance info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
if all_instances is not None:
params['IncludeAllInstances'] = all_instances
statuses = self.call("DescribeInstanceStatus",
response_data_key="InstanceStatuses",
**params)
return statuses
def events(self, all_instances=None, instance_ids=None, filters=None):
"""a list of tuples containing instance Id's and event information"""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
statuses = self.status(all_instances, **params)
event_list = []
for status in statuses:
if status.get("Events"):
for event in status.get("Events"):
event[u"InstanceId"] = status.get('InstanceId')
event_list.append(event)
return event_list
|
RetailMeNotSandbox/acky | acky/ec2.py | InstanceCollection.control | python | def control(self, instances, action):
if not isinstance(instances, list) and\
not isinstance(instances, tuple):
instances = [instances]
actions = {'start': {'operation': "StartInstances",
'response_data_key': "StartingInstances",
'InstanceIds': instances},
'stop': {'operation': "StopInstances",
'response_data_key': "StoppingInstances",
'InstanceIds': instances},
'reboot': {'operation': "RebootInstances",
'response_data_key': "return",
'InstanceIds': instances},
'terminate': {'operation': "TerminateInstances",
'response_data_key': "TerminatingInstances",
'InstanceIds': instances},
'protect': {'operation': "ModifyInstanceAttribute",
'response_data_key': "return",
'Attribute': 'disableApiTermination',
'Value': 'true'},
'unprotect': {'operation': "ModifyInstanceAttribute",
'response_data_key': "return",
'Attribute': 'disableApiTermination',
'Value': 'false'}}
if (action in ('protect', 'unprotect')):
for instance in instances:
self.call(InstanceId=instance, **actions[action])
return "true"
else:
return self.call(**actions[action]) | Valid actions: start, stop, reboot, terminate, protect, and
unprotect. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L226-L258 | [
"def call(self, operation, response_data_key=None, *args, **kwargs):\n log = logging.getLogger(__name__)\n op = self._service.get_operation(operation)\n log.debug(\"Calling {} action '{}'\".format(self._service, operation))\n resp, data = op.call(self._endpoint, *args, **kwargs)\n if not resp.ok:\n ... | class InstanceCollection(AwsCollection, EC2ApiClient):
def get(self, instance_ids=None, filters=None):
"""List instance info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
reservations = self.call("DescribeInstances",
response_data_key="Reservations",
**params)
if reservations:
return list(chain(*(r["Instances"] for r in reservations)))
return []
def create(self, ami, count, config=None):
"""Create an instance using the launcher."""
return self.Launcher(config=config).launch(ami, count)
def destroy(self, instance_id):
"""Terminate a single given instance."""
return self.control(instance_id, "terminate")
def Launcher(self, config=None):
"""Provides a configurable launcher for EC2 instances."""
class _launcher(EC2ApiClient):
"""Configurable launcher for EC2 instances. Create the Launcher
(passing an optional dict of its attributes), set its attributes
(as described in the RunInstances API docs), then launch().
"""
def __init__(self, aws, config):
super(_launcher, self).__init__(aws)
self.config = config
self._attr = list(self.__dict__.keys()) + ['_attr']
def launch(self, ami, min_count, max_count=0):
"""Use given AMI to launch min_count instances with the
current configuration. Returns instance info list.
"""
params = config.copy()
params.update(dict([i for i in self.__dict__.items()
if i[0] not in self._attr]))
return self.call("RunInstances",
ImageId=ami,
MinCount=min_count,
MaxCount=max_count or min_count,
response_data_key="Instances",
**params)
if not config:
config = {}
return _launcher(self._aws, config)
def status(self, all_instances=None, instance_ids=None, filters=None):
"""List instance info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
if all_instances is not None:
params['IncludeAllInstances'] = all_instances
statuses = self.call("DescribeInstanceStatus",
response_data_key="InstanceStatuses",
**params)
return statuses
def events(self, all_instances=None, instance_ids=None, filters=None):
"""a list of tuples containing instance Id's and event information"""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
statuses = self.status(all_instances, **params)
event_list = []
for status in statuses:
if status.get("Events"):
for event in status.get("Events"):
event[u"InstanceId"] = status.get('InstanceId')
event_list.append(event)
return event_list
|
RetailMeNotSandbox/acky | acky/ec2.py | InstanceCollection.Launcher | python | def Launcher(self, config=None):
class _launcher(EC2ApiClient):
"""Configurable launcher for EC2 instances. Create the Launcher
(passing an optional dict of its attributes), set its attributes
(as described in the RunInstances API docs), then launch().
"""
def __init__(self, aws, config):
super(_launcher, self).__init__(aws)
self.config = config
self._attr = list(self.__dict__.keys()) + ['_attr']
def launch(self, ami, min_count, max_count=0):
"""Use given AMI to launch min_count instances with the
current configuration. Returns instance info list.
"""
params = config.copy()
params.update(dict([i for i in self.__dict__.items()
if i[0] not in self._attr]))
return self.call("RunInstances",
ImageId=ami,
MinCount=min_count,
MaxCount=max_count or min_count,
response_data_key="Instances",
**params)
if not config:
config = {}
return _launcher(self._aws, config) | Provides a configurable launcher for EC2 instances. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L260-L288 | null | class InstanceCollection(AwsCollection, EC2ApiClient):
def get(self, instance_ids=None, filters=None):
"""List instance info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
reservations = self.call("DescribeInstances",
response_data_key="Reservations",
**params)
if reservations:
return list(chain(*(r["Instances"] for r in reservations)))
return []
def create(self, ami, count, config=None):
"""Create an instance using the launcher."""
return self.Launcher(config=config).launch(ami, count)
def destroy(self, instance_id):
"""Terminate a single given instance."""
return self.control(instance_id, "terminate")
def control(self, instances, action):
"""Valid actions: start, stop, reboot, terminate, protect, and
unprotect.
"""
if not isinstance(instances, list) and\
not isinstance(instances, tuple):
instances = [instances]
actions = {'start': {'operation': "StartInstances",
'response_data_key': "StartingInstances",
'InstanceIds': instances},
'stop': {'operation': "StopInstances",
'response_data_key': "StoppingInstances",
'InstanceIds': instances},
'reboot': {'operation': "RebootInstances",
'response_data_key': "return",
'InstanceIds': instances},
'terminate': {'operation': "TerminateInstances",
'response_data_key': "TerminatingInstances",
'InstanceIds': instances},
'protect': {'operation': "ModifyInstanceAttribute",
'response_data_key': "return",
'Attribute': 'disableApiTermination',
'Value': 'true'},
'unprotect': {'operation': "ModifyInstanceAttribute",
'response_data_key': "return",
'Attribute': 'disableApiTermination',
'Value': 'false'}}
if (action in ('protect', 'unprotect')):
for instance in instances:
self.call(InstanceId=instance, **actions[action])
return "true"
else:
return self.call(**actions[action])
def status(self, all_instances=None, instance_ids=None, filters=None):
"""List instance info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
if all_instances is not None:
params['IncludeAllInstances'] = all_instances
statuses = self.call("DescribeInstanceStatus",
response_data_key="InstanceStatuses",
**params)
return statuses
def events(self, all_instances=None, instance_ids=None, filters=None):
"""a list of tuples containing instance Id's and event information"""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
statuses = self.status(all_instances, **params)
event_list = []
for status in statuses:
if status.get("Events"):
for event in status.get("Events"):
event[u"InstanceId"] = status.get('InstanceId')
event_list.append(event)
return event_list
|
RetailMeNotSandbox/acky | acky/ec2.py | InstanceCollection.status | python | def status(self, all_instances=None, instance_ids=None, filters=None):
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
if all_instances is not None:
params['IncludeAllInstances'] = all_instances
statuses = self.call("DescribeInstanceStatus",
response_data_key="InstanceStatuses",
**params)
return statuses | List instance info. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L290-L302 | [
"def make_filters(data, key_name='Name', values_name='Values'):\n data = data.copy()\n for key, value in data.items():\n if isinstance(value, str) or not hasattr(value, '__iter__'):\n data[key] = [value]\n return make_map(data, key_name, values_name)\n",
"def call(self, operation, respo... | class InstanceCollection(AwsCollection, EC2ApiClient):
def get(self, instance_ids=None, filters=None):
"""List instance info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
reservations = self.call("DescribeInstances",
response_data_key="Reservations",
**params)
if reservations:
return list(chain(*(r["Instances"] for r in reservations)))
return []
def create(self, ami, count, config=None):
"""Create an instance using the launcher."""
return self.Launcher(config=config).launch(ami, count)
def destroy(self, instance_id):
"""Terminate a single given instance."""
return self.control(instance_id, "terminate")
def control(self, instances, action):
"""Valid actions: start, stop, reboot, terminate, protect, and
unprotect.
"""
if not isinstance(instances, list) and\
not isinstance(instances, tuple):
instances = [instances]
actions = {'start': {'operation': "StartInstances",
'response_data_key': "StartingInstances",
'InstanceIds': instances},
'stop': {'operation': "StopInstances",
'response_data_key': "StoppingInstances",
'InstanceIds': instances},
'reboot': {'operation': "RebootInstances",
'response_data_key': "return",
'InstanceIds': instances},
'terminate': {'operation': "TerminateInstances",
'response_data_key': "TerminatingInstances",
'InstanceIds': instances},
'protect': {'operation': "ModifyInstanceAttribute",
'response_data_key': "return",
'Attribute': 'disableApiTermination',
'Value': 'true'},
'unprotect': {'operation': "ModifyInstanceAttribute",
'response_data_key': "return",
'Attribute': 'disableApiTermination',
'Value': 'false'}}
if (action in ('protect', 'unprotect')):
for instance in instances:
self.call(InstanceId=instance, **actions[action])
return "true"
else:
return self.call(**actions[action])
def Launcher(self, config=None):
"""Provides a configurable launcher for EC2 instances."""
class _launcher(EC2ApiClient):
"""Configurable launcher for EC2 instances. Create the Launcher
(passing an optional dict of its attributes), set its attributes
(as described in the RunInstances API docs), then launch().
"""
def __init__(self, aws, config):
super(_launcher, self).__init__(aws)
self.config = config
self._attr = list(self.__dict__.keys()) + ['_attr']
def launch(self, ami, min_count, max_count=0):
"""Use given AMI to launch min_count instances with the
current configuration. Returns instance info list.
"""
params = config.copy()
params.update(dict([i for i in self.__dict__.items()
if i[0] not in self._attr]))
return self.call("RunInstances",
ImageId=ami,
MinCount=min_count,
MaxCount=max_count or min_count,
response_data_key="Instances",
**params)
if not config:
config = {}
return _launcher(self._aws, config)
def events(self, all_instances=None, instance_ids=None, filters=None):
"""a list of tuples containing instance Id's and event information"""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
statuses = self.status(all_instances, **params)
event_list = []
for status in statuses:
if status.get("Events"):
for event in status.get("Events"):
event[u"InstanceId"] = status.get('InstanceId')
event_list.append(event)
return event_list
|
RetailMeNotSandbox/acky | acky/ec2.py | InstanceCollection.events | python | def events(self, all_instances=None, instance_ids=None, filters=None):
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
statuses = self.status(all_instances, **params)
event_list = []
for status in statuses:
if status.get("Events"):
for event in status.get("Events"):
event[u"InstanceId"] = status.get('InstanceId')
event_list.append(event)
return event_list | a list of tuples containing instance Id's and event information | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L304-L318 | [
"def make_filters(data, key_name='Name', values_name='Values'):\n data = data.copy()\n for key, value in data.items():\n if isinstance(value, str) or not hasattr(value, '__iter__'):\n data[key] = [value]\n return make_map(data, key_name, values_name)\n",
"def status(self, all_instances=... | class InstanceCollection(AwsCollection, EC2ApiClient):
def get(self, instance_ids=None, filters=None):
"""List instance info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
reservations = self.call("DescribeInstances",
response_data_key="Reservations",
**params)
if reservations:
return list(chain(*(r["Instances"] for r in reservations)))
return []
def create(self, ami, count, config=None):
"""Create an instance using the launcher."""
return self.Launcher(config=config).launch(ami, count)
def destroy(self, instance_id):
"""Terminate a single given instance."""
return self.control(instance_id, "terminate")
def control(self, instances, action):
"""Valid actions: start, stop, reboot, terminate, protect, and
unprotect.
"""
if not isinstance(instances, list) and\
not isinstance(instances, tuple):
instances = [instances]
actions = {'start': {'operation': "StartInstances",
'response_data_key': "StartingInstances",
'InstanceIds': instances},
'stop': {'operation': "StopInstances",
'response_data_key': "StoppingInstances",
'InstanceIds': instances},
'reboot': {'operation': "RebootInstances",
'response_data_key': "return",
'InstanceIds': instances},
'terminate': {'operation': "TerminateInstances",
'response_data_key': "TerminatingInstances",
'InstanceIds': instances},
'protect': {'operation': "ModifyInstanceAttribute",
'response_data_key': "return",
'Attribute': 'disableApiTermination',
'Value': 'true'},
'unprotect': {'operation': "ModifyInstanceAttribute",
'response_data_key': "return",
'Attribute': 'disableApiTermination',
'Value': 'false'}}
if (action in ('protect', 'unprotect')):
for instance in instances:
self.call(InstanceId=instance, **actions[action])
return "true"
else:
return self.call(**actions[action])
def Launcher(self, config=None):
"""Provides a configurable launcher for EC2 instances."""
class _launcher(EC2ApiClient):
"""Configurable launcher for EC2 instances. Create the Launcher
(passing an optional dict of its attributes), set its attributes
(as described in the RunInstances API docs), then launch().
"""
def __init__(self, aws, config):
super(_launcher, self).__init__(aws)
self.config = config
self._attr = list(self.__dict__.keys()) + ['_attr']
def launch(self, ami, min_count, max_count=0):
"""Use given AMI to launch min_count instances with the
current configuration. Returns instance info list.
"""
params = config.copy()
params.update(dict([i for i in self.__dict__.items()
if i[0] not in self._attr]))
return self.call("RunInstances",
ImageId=ami,
MinCount=min_count,
MaxCount=max_count or min_count,
response_data_key="Instances",
**params)
if not config:
config = {}
return _launcher(self._aws, config)
def status(self, all_instances=None, instance_ids=None, filters=None):
"""List instance info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
if all_instances is not None:
params['IncludeAllInstances'] = all_instances
statuses = self.call("DescribeInstanceStatus",
response_data_key="InstanceStatuses",
**params)
return statuses
|
RetailMeNotSandbox/acky | acky/ec2.py | IpPermissionsCollection.modify | python | def modify(self, api_action, sgid, other, proto_spec):
params = {'group_id': sgid, 'ip_permissions': []}
perm = {}
params['ip_permissions'].append(perm)
proto, from_port, to_port = proto_spec
perm['IpProtocol'] = proto
perm['FromPort'] = from_port or 0
perm['ToPort'] = to_port or from_port or 65535
if other.startswith("sg-"):
perm['UserIdGroupPairs'] = [{'GroupId': other}]
elif "/sg-" in other:
account, group_id = other.split("/", 1)
perm['UserIdGroupPairs'] = [{
'UserId': account,
'GroupId': group_id,
}]
else:
perm['IpRanges'] = [{'CidrIp': other}]
return self.call(api_action, **params) | Make a change to a security group. api_action is an EC2 API name.
Other is one of:
- a group (sg-nnnnnnnn)
- a group with account (<user id>/sg-nnnnnnnn)
- a CIDR block (n.n.n.n/n)
Proto spec is a triplet (<proto>, low_port, high_port). | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L411-L438 | [
"def call(self, operation, response_data_key=None, *args, **kwargs):\n log = logging.getLogger(__name__)\n op = self._service.get_operation(operation)\n log.debug(\"Calling {} action '{}'\".format(self._service, operation))\n resp, data = op.call(self._endpoint, *args, **kwargs)\n if not resp.ok:\n ... | class IpPermissionsCollection(AwsCollection, EC2ApiClient):
def get(self, filters=None):
# returns (sgr_info, ...)
# DescribeSecurityGroups
raise NotImplementedError()
def add(self, sgid, other, proto_spec, direction="in"):
"""Add a security group rule to group <sgid>.
Direction is either 'in' (ingress) or 'out' (egress).
See modify() for other parameters."""
# returns bool
# AuthorizeSecurityGroupIngress, AuthorizeSecurityGroupEgress
if direction == "in":
api = "AuthorizeSecurityGroupIngress"
elif direction == "out":
api = "AuthorizeSecurityGroupEgress"
else:
raise ValueError("direction must be one of ('in', 'out')")
return self.modify(api, sgid, other, proto_spec)
def remove(self, sgid, other, proto_spec, direction="in"):
"""Remove a security group rule from group <sgid>.
Direction is either 'in' (ingress) or 'out' (egress).
See modify() for other parameters."""
# returns (removed_sgr_info, ...)
# RevokeSecurityGroupIngress, RevokeSecurityGroupEgress
if direction == "in":
api = "RevokeSecurityGroupIngress"
elif direction == "out":
api = "RevokeSecurityGroupEgress"
else:
raise ValueError("direction must be one of ('in', 'out')")
return self.modify(api, sgid, other, proto_spec)
|
RetailMeNotSandbox/acky | acky/ec2.py | IpPermissionsCollection.add | python | def add(self, sgid, other, proto_spec, direction="in"):
# returns bool
# AuthorizeSecurityGroupIngress, AuthorizeSecurityGroupEgress
if direction == "in":
api = "AuthorizeSecurityGroupIngress"
elif direction == "out":
api = "AuthorizeSecurityGroupEgress"
else:
raise ValueError("direction must be one of ('in', 'out')")
return self.modify(api, sgid, other, proto_spec) | Add a security group rule to group <sgid>.
Direction is either 'in' (ingress) or 'out' (egress).
See modify() for other parameters. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L440-L452 | [
"def modify(self, api_action, sgid, other, proto_spec):\n \"\"\"Make a change to a security group. api_action is an EC2 API name.\n Other is one of:\n - a group (sg-nnnnnnnn)\n - a group with account (<user id>/sg-nnnnnnnn)\n - a CIDR block (n.n.n.n/n)\n Proto spec is a triplet (... | class IpPermissionsCollection(AwsCollection, EC2ApiClient):
def get(self, filters=None):
# returns (sgr_info, ...)
# DescribeSecurityGroups
raise NotImplementedError()
def modify(self, api_action, sgid, other, proto_spec):
"""Make a change to a security group. api_action is an EC2 API name.
Other is one of:
- a group (sg-nnnnnnnn)
- a group with account (<user id>/sg-nnnnnnnn)
- a CIDR block (n.n.n.n/n)
Proto spec is a triplet (<proto>, low_port, high_port)."""
params = {'group_id': sgid, 'ip_permissions': []}
perm = {}
params['ip_permissions'].append(perm)
proto, from_port, to_port = proto_spec
perm['IpProtocol'] = proto
perm['FromPort'] = from_port or 0
perm['ToPort'] = to_port or from_port or 65535
if other.startswith("sg-"):
perm['UserIdGroupPairs'] = [{'GroupId': other}]
elif "/sg-" in other:
account, group_id = other.split("/", 1)
perm['UserIdGroupPairs'] = [{
'UserId': account,
'GroupId': group_id,
}]
else:
perm['IpRanges'] = [{'CidrIp': other}]
return self.call(api_action, **params)
def remove(self, sgid, other, proto_spec, direction="in"):
"""Remove a security group rule from group <sgid>.
Direction is either 'in' (ingress) or 'out' (egress).
See modify() for other parameters."""
# returns (removed_sgr_info, ...)
# RevokeSecurityGroupIngress, RevokeSecurityGroupEgress
if direction == "in":
api = "RevokeSecurityGroupIngress"
elif direction == "out":
api = "RevokeSecurityGroupEgress"
else:
raise ValueError("direction must be one of ('in', 'out')")
return self.modify(api, sgid, other, proto_spec)
|
RetailMeNotSandbox/acky | acky/ec2.py | VolumeCollection.get | python | def get(self, volume_ids=None, filters=None):
params = {}
if filters:
params["filters"] = make_filters(filters)
if isinstance(volume_ids, str):
volume_ids = [volume_ids]
return self.call("DescribeVolumes",
VolumeIds=volume_ids,
response_data_key="Volumes",
**params) | List EBS Volume info. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L473-L483 | [
"def make_filters(data, key_name='Name', values_name='Values'):\n data = data.copy()\n for key, value in data.items():\n if isinstance(value, str) or not hasattr(value, '__iter__'):\n data[key] = [value]\n return make_map(data, key_name, values_name)\n",
"def call(self, operation, respo... | class VolumeCollection(AwsCollection, EC2ApiClient):
"""Interface to get, create, destroy, and attach for EBS Volumes.
(Amazon EC2 API Version 2014-06-15)
"""
def create(self, az, size_or_snap, volume_type=None, iops=None,
encrypted=True):
"""Create an EBS Volume using an availability-zone and size_or_snap
parameter, encrypted by default.
If the volume is crated from a snapshot, (str)size_or_snap denotes
the snapshot id. Otherwise, (int)size_or_snap denotes the amount of
GiB's to allocate. iops must be set if the volume type is io1.
"""
kwargs = {}
kwargs['encrypted'] = encrypted
if volume_type:
kwargs['VolumeType'] = volume_type
if iops:
kwargs['Iops'] = iops
is_snapshot_id = False
try:
size_or_snap = int(size_or_snap)
except ValueError:
is_snapshot_id = True
if is_snapshot_id:
return self.call("CreateVolume", AvailabilityZone=az,
SnapshotId=size_or_snap, **kwargs)
return self.call("CreateVolume", AvailabilityZone=az,
Size=size_or_snap, **kwargs)
def destroy(self, volume_id):
"""Delete a volume by volume-id and return success boolean."""
return 'true' == self.call("DeleteVolume", VolumeId=volume_id,
response_data_key="return")
def attach(self, volume_id, instance_id, device_path):
"""Attach a volume to an instance, exposing it with a device name."""
return self.call("AttachVolume",
VolumeId=volume_id, InstanceId=instance_id,
Device=device_path)
def detach(self, volume_id, instance_id='', device_path='', force=False):
"""Detach a volume from an instance."""
return self.call("DetachVolume",
VolumeId=volume_id, InstanceId=instance_id,
Device=device_path, force=force)
|
RetailMeNotSandbox/acky | acky/ec2.py | VolumeCollection.create | python | def create(self, az, size_or_snap, volume_type=None, iops=None,
encrypted=True):
kwargs = {}
kwargs['encrypted'] = encrypted
if volume_type:
kwargs['VolumeType'] = volume_type
if iops:
kwargs['Iops'] = iops
is_snapshot_id = False
try:
size_or_snap = int(size_or_snap)
except ValueError:
is_snapshot_id = True
if is_snapshot_id:
return self.call("CreateVolume", AvailabilityZone=az,
SnapshotId=size_or_snap, **kwargs)
return self.call("CreateVolume", AvailabilityZone=az,
Size=size_or_snap, **kwargs) | Create an EBS Volume using an availability-zone and size_or_snap
parameter, encrypted by default.
If the volume is crated from a snapshot, (str)size_or_snap denotes
the snapshot id. Otherwise, (int)size_or_snap denotes the amount of
GiB's to allocate. iops must be set if the volume type is io1. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L485-L508 | [
"def call(self, operation, response_data_key=None, *args, **kwargs):\n log = logging.getLogger(__name__)\n op = self._service.get_operation(operation)\n log.debug(\"Calling {} action '{}'\".format(self._service, operation))\n resp, data = op.call(self._endpoint, *args, **kwargs)\n if not resp.ok:\n ... | class VolumeCollection(AwsCollection, EC2ApiClient):
"""Interface to get, create, destroy, and attach for EBS Volumes.
(Amazon EC2 API Version 2014-06-15)
"""
def get(self, volume_ids=None, filters=None):
"""List EBS Volume info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if isinstance(volume_ids, str):
volume_ids = [volume_ids]
return self.call("DescribeVolumes",
VolumeIds=volume_ids,
response_data_key="Volumes",
**params)
def destroy(self, volume_id):
"""Delete a volume by volume-id and return success boolean."""
return 'true' == self.call("DeleteVolume", VolumeId=volume_id,
response_data_key="return")
def attach(self, volume_id, instance_id, device_path):
"""Attach a volume to an instance, exposing it with a device name."""
return self.call("AttachVolume",
VolumeId=volume_id, InstanceId=instance_id,
Device=device_path)
def detach(self, volume_id, instance_id='', device_path='', force=False):
"""Detach a volume from an instance."""
return self.call("DetachVolume",
VolumeId=volume_id, InstanceId=instance_id,
Device=device_path, force=force)
|
RetailMeNotSandbox/acky | acky/ec2.py | VolumeCollection.attach | python | def attach(self, volume_id, instance_id, device_path):
return self.call("AttachVolume",
VolumeId=volume_id, InstanceId=instance_id,
Device=device_path) | Attach a volume to an instance, exposing it with a device name. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L515-L519 | [
"def call(self, operation, response_data_key=None, *args, **kwargs):\n log = logging.getLogger(__name__)\n op = self._service.get_operation(operation)\n log.debug(\"Calling {} action '{}'\".format(self._service, operation))\n resp, data = op.call(self._endpoint, *args, **kwargs)\n if not resp.ok:\n ... | class VolumeCollection(AwsCollection, EC2ApiClient):
"""Interface to get, create, destroy, and attach for EBS Volumes.
(Amazon EC2 API Version 2014-06-15)
"""
def get(self, volume_ids=None, filters=None):
"""List EBS Volume info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if isinstance(volume_ids, str):
volume_ids = [volume_ids]
return self.call("DescribeVolumes",
VolumeIds=volume_ids,
response_data_key="Volumes",
**params)
def create(self, az, size_or_snap, volume_type=None, iops=None,
encrypted=True):
"""Create an EBS Volume using an availability-zone and size_or_snap
parameter, encrypted by default.
If the volume is crated from a snapshot, (str)size_or_snap denotes
the snapshot id. Otherwise, (int)size_or_snap denotes the amount of
GiB's to allocate. iops must be set if the volume type is io1.
"""
kwargs = {}
kwargs['encrypted'] = encrypted
if volume_type:
kwargs['VolumeType'] = volume_type
if iops:
kwargs['Iops'] = iops
is_snapshot_id = False
try:
size_or_snap = int(size_or_snap)
except ValueError:
is_snapshot_id = True
if is_snapshot_id:
return self.call("CreateVolume", AvailabilityZone=az,
SnapshotId=size_or_snap, **kwargs)
return self.call("CreateVolume", AvailabilityZone=az,
Size=size_or_snap, **kwargs)
def destroy(self, volume_id):
"""Delete a volume by volume-id and return success boolean."""
return 'true' == self.call("DeleteVolume", VolumeId=volume_id,
response_data_key="return")
def detach(self, volume_id, instance_id='', device_path='', force=False):
"""Detach a volume from an instance."""
return self.call("DetachVolume",
VolumeId=volume_id, InstanceId=instance_id,
Device=device_path, force=force)
|
RetailMeNotSandbox/acky | acky/ec2.py | VolumeCollection.detach | python | def detach(self, volume_id, instance_id='', device_path='', force=False):
return self.call("DetachVolume",
VolumeId=volume_id, InstanceId=instance_id,
Device=device_path, force=force) | Detach a volume from an instance. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/ec2.py#L521-L525 | [
"def call(self, operation, response_data_key=None, *args, **kwargs):\n log = logging.getLogger(__name__)\n op = self._service.get_operation(operation)\n log.debug(\"Calling {} action '{}'\".format(self._service, operation))\n resp, data = op.call(self._endpoint, *args, **kwargs)\n if not resp.ok:\n ... | class VolumeCollection(AwsCollection, EC2ApiClient):
"""Interface to get, create, destroy, and attach for EBS Volumes.
(Amazon EC2 API Version 2014-06-15)
"""
def get(self, volume_ids=None, filters=None):
"""List EBS Volume info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if isinstance(volume_ids, str):
volume_ids = [volume_ids]
return self.call("DescribeVolumes",
VolumeIds=volume_ids,
response_data_key="Volumes",
**params)
def create(self, az, size_or_snap, volume_type=None, iops=None,
encrypted=True):
"""Create an EBS Volume using an availability-zone and size_or_snap
parameter, encrypted by default.
If the volume is crated from a snapshot, (str)size_or_snap denotes
the snapshot id. Otherwise, (int)size_or_snap denotes the amount of
GiB's to allocate. iops must be set if the volume type is io1.
"""
kwargs = {}
kwargs['encrypted'] = encrypted
if volume_type:
kwargs['VolumeType'] = volume_type
if iops:
kwargs['Iops'] = iops
is_snapshot_id = False
try:
size_or_snap = int(size_or_snap)
except ValueError:
is_snapshot_id = True
if is_snapshot_id:
return self.call("CreateVolume", AvailabilityZone=az,
SnapshotId=size_or_snap, **kwargs)
return self.call("CreateVolume", AvailabilityZone=az,
Size=size_or_snap, **kwargs)
def destroy(self, volume_id):
"""Delete a volume by volume-id and return success boolean."""
return 'true' == self.call("DeleteVolume", VolumeId=volume_id,
response_data_key="return")
def attach(self, volume_id, instance_id, device_path):
"""Attach a volume to an instance, exposing it with a device name."""
return self.call("AttachVolume",
VolumeId=volume_id, InstanceId=instance_id,
Device=device_path)
|
RetailMeNotSandbox/acky | acky/s3.py | _parse_url | python | def _parse_url(url=None):
if url is None:
return ('', '')
scheme, netloc, path, _, _ = parse.urlsplit(url)
if scheme != 's3':
raise InvalidURL(url, "URL scheme must be s3://")
if path and not netloc:
raise InvalidURL(url)
return netloc, path[1:] | Split the path up into useful parts: bucket, obj_key | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/s3.py#L16-L29 | null | from acky.api import AwsApiClient
try:
from urllib import parse
except ImportError:
import urlparse as parse
class InvalidURL(Exception):
def __init__(self, url, msg=None):
self.url = url
if not msg:
msg = "Invalid URL: {0}".format(url)
super(InvalidURL, self).__init__(msg)
class S3(AwsApiClient):
"""Interface for managing S3 buckets. (API Version 2006-03-01)"""
service_name = "s3"
def get(self, url=None, delimiter="/"):
"""Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown.
"""
params = {'Delimiter': delimiter}
bucket, obj_key = _parse_url(url)
if bucket:
params['Bucket'] = bucket
else:
return self.call("ListBuckets", response_data_key="Buckets")
if obj_key:
params['Prefix'] = obj_key
objects = self.call("ListObjects", response_data_key="Contents",
**params)
if objects:
for obj in objects:
obj['url'] = "s3://{0}/{1}".format(bucket, obj['Key'])
return objects
def create(self, url):
"""Create a bucket, directory, or empty file."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
return self.call("CreateBucket", bucket=target)
def destroy(self, url, recursive=False):
"""Destroy a bucket, directory, or file. Specifying recursive=True
recursively deletes all subdirectories and files."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
if recursive:
for obj in self.get(url, delimiter=''):
self.destroy(obj['url'])
return self.call("DeleteBucket", bucket=target)
def upload(self, local_path, remote_url):
"""Copy a local file to an S3 location."""
bucket, key = _parse_url(remote_url)
with open(local_path, 'rb') as fp:
return self.call("PutObject", bucket=bucket, key=key, body=fp)
def download(self, remote_url, local_path, buffer_size=8 * 1024):
"""Copy S3 data to a local file."""
bucket, key = _parse_url(remote_url)
response_file = self.call("GetObject", bucket=bucket, key=key)['Body']
with open(local_path, 'wb') as fp:
buf = response_file.read(buffer_size)
while buf:
fp.write(buf)
buf = response_file.read(buffer_size)
def copy(self, src_url, dst_url):
"""Copy an S3 object to another S3 location."""
src_bucket, src_key = _parse_url(src_url)
dst_bucket, dst_key = _parse_url(dst_url)
if not dst_bucket:
dst_bucket = src_bucket
params = {
'copy_source': '/'.join((src_bucket, src_key)),
'bucket': dst_bucket,
'key': dst_key,
}
return self.call("CopyObject", **params)
def move(self, src_url, dst_url):
"""Copy a single S3 object to another S3 location, then delete the
original object."""
self.copy(src_url, dst_url)
self.destroy(src_url)
|
RetailMeNotSandbox/acky | acky/s3.py | S3.get | python | def get(self, url=None, delimiter="/"):
params = {'Delimiter': delimiter}
bucket, obj_key = _parse_url(url)
if bucket:
params['Bucket'] = bucket
else:
return self.call("ListBuckets", response_data_key="Buckets")
if obj_key:
params['Prefix'] = obj_key
objects = self.call("ListObjects", response_data_key="Contents",
**params)
if objects:
for obj in objects:
obj['url'] = "s3://{0}/{1}".format(bucket, obj['Key'])
return objects | Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/s3.py#L36-L58 | [
"def _parse_url(url=None):\n \"\"\"Split the path up into useful parts: bucket, obj_key\"\"\"\n if url is None:\n return ('', '')\n\n scheme, netloc, path, _, _ = parse.urlsplit(url)\n\n if scheme != 's3':\n raise InvalidURL(url, \"URL scheme must be s3://\")\n\n if path and not netloc:... | class S3(AwsApiClient):
"""Interface for managing S3 buckets. (API Version 2006-03-01)"""
service_name = "s3"
def create(self, url):
"""Create a bucket, directory, or empty file."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
return self.call("CreateBucket", bucket=target)
def destroy(self, url, recursive=False):
"""Destroy a bucket, directory, or file. Specifying recursive=True
recursively deletes all subdirectories and files."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
if recursive:
for obj in self.get(url, delimiter=''):
self.destroy(obj['url'])
return self.call("DeleteBucket", bucket=target)
def upload(self, local_path, remote_url):
"""Copy a local file to an S3 location."""
bucket, key = _parse_url(remote_url)
with open(local_path, 'rb') as fp:
return self.call("PutObject", bucket=bucket, key=key, body=fp)
def download(self, remote_url, local_path, buffer_size=8 * 1024):
"""Copy S3 data to a local file."""
bucket, key = _parse_url(remote_url)
response_file = self.call("GetObject", bucket=bucket, key=key)['Body']
with open(local_path, 'wb') as fp:
buf = response_file.read(buffer_size)
while buf:
fp.write(buf)
buf = response_file.read(buffer_size)
def copy(self, src_url, dst_url):
"""Copy an S3 object to another S3 location."""
src_bucket, src_key = _parse_url(src_url)
dst_bucket, dst_key = _parse_url(dst_url)
if not dst_bucket:
dst_bucket = src_bucket
params = {
'copy_source': '/'.join((src_bucket, src_key)),
'bucket': dst_bucket,
'key': dst_key,
}
return self.call("CopyObject", **params)
def move(self, src_url, dst_url):
"""Copy a single S3 object to another S3 location, then delete the
original object."""
self.copy(src_url, dst_url)
self.destroy(src_url)
|
RetailMeNotSandbox/acky | acky/s3.py | S3.create | python | def create(self, url):
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
return self.call("CreateBucket", bucket=target) | Create a bucket, directory, or empty file. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/s3.py#L60-L73 | [
"def _parse_url(url=None):\n \"\"\"Split the path up into useful parts: bucket, obj_key\"\"\"\n if url is None:\n return ('', '')\n\n scheme, netloc, path, _, _ = parse.urlsplit(url)\n\n if scheme != 's3':\n raise InvalidURL(url, \"URL scheme must be s3://\")\n\n if path and not netloc:... | class S3(AwsApiClient):
"""Interface for managing S3 buckets. (API Version 2006-03-01)"""
service_name = "s3"
def get(self, url=None, delimiter="/"):
"""Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown.
"""
params = {'Delimiter': delimiter}
bucket, obj_key = _parse_url(url)
if bucket:
params['Bucket'] = bucket
else:
return self.call("ListBuckets", response_data_key="Buckets")
if obj_key:
params['Prefix'] = obj_key
objects = self.call("ListObjects", response_data_key="Contents",
**params)
if objects:
for obj in objects:
obj['url'] = "s3://{0}/{1}".format(bucket, obj['Key'])
return objects
def destroy(self, url, recursive=False):
"""Destroy a bucket, directory, or file. Specifying recursive=True
recursively deletes all subdirectories and files."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
if recursive:
for obj in self.get(url, delimiter=''):
self.destroy(obj['url'])
return self.call("DeleteBucket", bucket=target)
def upload(self, local_path, remote_url):
"""Copy a local file to an S3 location."""
bucket, key = _parse_url(remote_url)
with open(local_path, 'rb') as fp:
return self.call("PutObject", bucket=bucket, key=key, body=fp)
def download(self, remote_url, local_path, buffer_size=8 * 1024):
"""Copy S3 data to a local file."""
bucket, key = _parse_url(remote_url)
response_file = self.call("GetObject", bucket=bucket, key=key)['Body']
with open(local_path, 'wb') as fp:
buf = response_file.read(buffer_size)
while buf:
fp.write(buf)
buf = response_file.read(buffer_size)
def copy(self, src_url, dst_url):
"""Copy an S3 object to another S3 location."""
src_bucket, src_key = _parse_url(src_url)
dst_bucket, dst_key = _parse_url(dst_url)
if not dst_bucket:
dst_bucket = src_bucket
params = {
'copy_source': '/'.join((src_bucket, src_key)),
'bucket': dst_bucket,
'key': dst_key,
}
return self.call("CopyObject", **params)
def move(self, src_url, dst_url):
"""Copy a single S3 object to another S3 location, then delete the
original object."""
self.copy(src_url, dst_url)
self.destroy(src_url)
|
RetailMeNotSandbox/acky | acky/s3.py | S3.destroy | python | def destroy(self, url, recursive=False):
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
if recursive:
for obj in self.get(url, delimiter=''):
self.destroy(obj['url'])
return self.call("DeleteBucket", bucket=target) | Destroy a bucket, directory, or file. Specifying recursive=True
recursively deletes all subdirectories and files. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/s3.py#L75-L93 | [
"def _parse_url(url=None):\n \"\"\"Split the path up into useful parts: bucket, obj_key\"\"\"\n if url is None:\n return ('', '')\n\n scheme, netloc, path, _, _ = parse.urlsplit(url)\n\n if scheme != 's3':\n raise InvalidURL(url, \"URL scheme must be s3://\")\n\n if path and not netloc:... | class S3(AwsApiClient):
"""Interface for managing S3 buckets. (API Version 2006-03-01)"""
service_name = "s3"
def get(self, url=None, delimiter="/"):
"""Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown.
"""
params = {'Delimiter': delimiter}
bucket, obj_key = _parse_url(url)
if bucket:
params['Bucket'] = bucket
else:
return self.call("ListBuckets", response_data_key="Buckets")
if obj_key:
params['Prefix'] = obj_key
objects = self.call("ListObjects", response_data_key="Contents",
**params)
if objects:
for obj in objects:
obj['url'] = "s3://{0}/{1}".format(bucket, obj['Key'])
return objects
def create(self, url):
"""Create a bucket, directory, or empty file."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
return self.call("CreateBucket", bucket=target)
def upload(self, local_path, remote_url):
"""Copy a local file to an S3 location."""
bucket, key = _parse_url(remote_url)
with open(local_path, 'rb') as fp:
return self.call("PutObject", bucket=bucket, key=key, body=fp)
def download(self, remote_url, local_path, buffer_size=8 * 1024):
"""Copy S3 data to a local file."""
bucket, key = _parse_url(remote_url)
response_file = self.call("GetObject", bucket=bucket, key=key)['Body']
with open(local_path, 'wb') as fp:
buf = response_file.read(buffer_size)
while buf:
fp.write(buf)
buf = response_file.read(buffer_size)
def copy(self, src_url, dst_url):
"""Copy an S3 object to another S3 location."""
src_bucket, src_key = _parse_url(src_url)
dst_bucket, dst_key = _parse_url(dst_url)
if not dst_bucket:
dst_bucket = src_bucket
params = {
'copy_source': '/'.join((src_bucket, src_key)),
'bucket': dst_bucket,
'key': dst_key,
}
return self.call("CopyObject", **params)
def move(self, src_url, dst_url):
"""Copy a single S3 object to another S3 location, then delete the
original object."""
self.copy(src_url, dst_url)
self.destroy(src_url)
|
RetailMeNotSandbox/acky | acky/s3.py | S3.upload | python | def upload(self, local_path, remote_url):
bucket, key = _parse_url(remote_url)
with open(local_path, 'rb') as fp:
return self.call("PutObject", bucket=bucket, key=key, body=fp) | Copy a local file to an S3 location. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/s3.py#L95-L100 | [
"def _parse_url(url=None):\n \"\"\"Split the path up into useful parts: bucket, obj_key\"\"\"\n if url is None:\n return ('', '')\n\n scheme, netloc, path, _, _ = parse.urlsplit(url)\n\n if scheme != 's3':\n raise InvalidURL(url, \"URL scheme must be s3://\")\n\n if path and not netloc:... | class S3(AwsApiClient):
"""Interface for managing S3 buckets. (API Version 2006-03-01)"""
service_name = "s3"
def get(self, url=None, delimiter="/"):
"""Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown.
"""
params = {'Delimiter': delimiter}
bucket, obj_key = _parse_url(url)
if bucket:
params['Bucket'] = bucket
else:
return self.call("ListBuckets", response_data_key="Buckets")
if obj_key:
params['Prefix'] = obj_key
objects = self.call("ListObjects", response_data_key="Contents",
**params)
if objects:
for obj in objects:
obj['url'] = "s3://{0}/{1}".format(bucket, obj['Key'])
return objects
def create(self, url):
"""Create a bucket, directory, or empty file."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
return self.call("CreateBucket", bucket=target)
def destroy(self, url, recursive=False):
"""Destroy a bucket, directory, or file. Specifying recursive=True
recursively deletes all subdirectories and files."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
if recursive:
for obj in self.get(url, delimiter=''):
self.destroy(obj['url'])
return self.call("DeleteBucket", bucket=target)
def download(self, remote_url, local_path, buffer_size=8 * 1024):
"""Copy S3 data to a local file."""
bucket, key = _parse_url(remote_url)
response_file = self.call("GetObject", bucket=bucket, key=key)['Body']
with open(local_path, 'wb') as fp:
buf = response_file.read(buffer_size)
while buf:
fp.write(buf)
buf = response_file.read(buffer_size)
def copy(self, src_url, dst_url):
"""Copy an S3 object to another S3 location."""
src_bucket, src_key = _parse_url(src_url)
dst_bucket, dst_key = _parse_url(dst_url)
if not dst_bucket:
dst_bucket = src_bucket
params = {
'copy_source': '/'.join((src_bucket, src_key)),
'bucket': dst_bucket,
'key': dst_key,
}
return self.call("CopyObject", **params)
def move(self, src_url, dst_url):
"""Copy a single S3 object to another S3 location, then delete the
original object."""
self.copy(src_url, dst_url)
self.destroy(src_url)
|
RetailMeNotSandbox/acky | acky/s3.py | S3.download | python | def download(self, remote_url, local_path, buffer_size=8 * 1024):
bucket, key = _parse_url(remote_url)
response_file = self.call("GetObject", bucket=bucket, key=key)['Body']
with open(local_path, 'wb') as fp:
buf = response_file.read(buffer_size)
while buf:
fp.write(buf)
buf = response_file.read(buffer_size) | Copy S3 data to a local file. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/s3.py#L102-L111 | [
"def _parse_url(url=None):\n \"\"\"Split the path up into useful parts: bucket, obj_key\"\"\"\n if url is None:\n return ('', '')\n\n scheme, netloc, path, _, _ = parse.urlsplit(url)\n\n if scheme != 's3':\n raise InvalidURL(url, \"URL scheme must be s3://\")\n\n if path and not netloc:... | class S3(AwsApiClient):
"""Interface for managing S3 buckets. (API Version 2006-03-01)"""
service_name = "s3"
def get(self, url=None, delimiter="/"):
"""Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown.
"""
params = {'Delimiter': delimiter}
bucket, obj_key = _parse_url(url)
if bucket:
params['Bucket'] = bucket
else:
return self.call("ListBuckets", response_data_key="Buckets")
if obj_key:
params['Prefix'] = obj_key
objects = self.call("ListObjects", response_data_key="Contents",
**params)
if objects:
for obj in objects:
obj['url'] = "s3://{0}/{1}".format(bucket, obj['Key'])
return objects
def create(self, url):
"""Create a bucket, directory, or empty file."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
return self.call("CreateBucket", bucket=target)
def destroy(self, url, recursive=False):
"""Destroy a bucket, directory, or file. Specifying recursive=True
recursively deletes all subdirectories and files."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
if recursive:
for obj in self.get(url, delimiter=''):
self.destroy(obj['url'])
return self.call("DeleteBucket", bucket=target)
def upload(self, local_path, remote_url):
"""Copy a local file to an S3 location."""
bucket, key = _parse_url(remote_url)
with open(local_path, 'rb') as fp:
return self.call("PutObject", bucket=bucket, key=key, body=fp)
def copy(self, src_url, dst_url):
"""Copy an S3 object to another S3 location."""
src_bucket, src_key = _parse_url(src_url)
dst_bucket, dst_key = _parse_url(dst_url)
if not dst_bucket:
dst_bucket = src_bucket
params = {
'copy_source': '/'.join((src_bucket, src_key)),
'bucket': dst_bucket,
'key': dst_key,
}
return self.call("CopyObject", **params)
def move(self, src_url, dst_url):
"""Copy a single S3 object to another S3 location, then delete the
original object."""
self.copy(src_url, dst_url)
self.destroy(src_url)
|
RetailMeNotSandbox/acky | acky/s3.py | S3.copy | python | def copy(self, src_url, dst_url):
src_bucket, src_key = _parse_url(src_url)
dst_bucket, dst_key = _parse_url(dst_url)
if not dst_bucket:
dst_bucket = src_bucket
params = {
'copy_source': '/'.join((src_bucket, src_key)),
'bucket': dst_bucket,
'key': dst_key,
}
return self.call("CopyObject", **params) | Copy an S3 object to another S3 location. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/s3.py#L113-L125 | [
"def _parse_url(url=None):\n \"\"\"Split the path up into useful parts: bucket, obj_key\"\"\"\n if url is None:\n return ('', '')\n\n scheme, netloc, path, _, _ = parse.urlsplit(url)\n\n if scheme != 's3':\n raise InvalidURL(url, \"URL scheme must be s3://\")\n\n if path and not netloc:... | class S3(AwsApiClient):
"""Interface for managing S3 buckets. (API Version 2006-03-01)"""
service_name = "s3"
def get(self, url=None, delimiter="/"):
"""Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown.
"""
params = {'Delimiter': delimiter}
bucket, obj_key = _parse_url(url)
if bucket:
params['Bucket'] = bucket
else:
return self.call("ListBuckets", response_data_key="Buckets")
if obj_key:
params['Prefix'] = obj_key
objects = self.call("ListObjects", response_data_key="Contents",
**params)
if objects:
for obj in objects:
obj['url'] = "s3://{0}/{1}".format(bucket, obj['Key'])
return objects
def create(self, url):
"""Create a bucket, directory, or empty file."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
return self.call("CreateBucket", bucket=target)
def destroy(self, url, recursive=False):
"""Destroy a bucket, directory, or file. Specifying recursive=True
recursively deletes all subdirectories and files."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
if recursive:
for obj in self.get(url, delimiter=''):
self.destroy(obj['url'])
return self.call("DeleteBucket", bucket=target)
def upload(self, local_path, remote_url):
"""Copy a local file to an S3 location."""
bucket, key = _parse_url(remote_url)
with open(local_path, 'rb') as fp:
return self.call("PutObject", bucket=bucket, key=key, body=fp)
def download(self, remote_url, local_path, buffer_size=8 * 1024):
"""Copy S3 data to a local file."""
bucket, key = _parse_url(remote_url)
response_file = self.call("GetObject", bucket=bucket, key=key)['Body']
with open(local_path, 'wb') as fp:
buf = response_file.read(buffer_size)
while buf:
fp.write(buf)
buf = response_file.read(buffer_size)
def move(self, src_url, dst_url):
"""Copy a single S3 object to another S3 location, then delete the
original object."""
self.copy(src_url, dst_url)
self.destroy(src_url)
|
RetailMeNotSandbox/acky | acky/s3.py | S3.move | python | def move(self, src_url, dst_url):
self.copy(src_url, dst_url)
self.destroy(src_url) | Copy a single S3 object to another S3 location, then delete the
original object. | train | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/s3.py#L127-L131 | [
"def destroy(self, url, recursive=False):\n \"\"\"Destroy a bucket, directory, or file. Specifying recursive=True\n recursively deletes all subdirectories and files.\"\"\"\n bucket, obj_key = _parse_url(url)\n\n if not bucket:\n raise InvalidURL(url,\n \"You must specify a... | class S3(AwsApiClient):
"""Interface for managing S3 buckets. (API Version 2006-03-01)"""
service_name = "s3"
def get(self, url=None, delimiter="/"):
"""Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown.
"""
params = {'Delimiter': delimiter}
bucket, obj_key = _parse_url(url)
if bucket:
params['Bucket'] = bucket
else:
return self.call("ListBuckets", response_data_key="Buckets")
if obj_key:
params['Prefix'] = obj_key
objects = self.call("ListObjects", response_data_key="Contents",
**params)
if objects:
for obj in objects:
obj['url'] = "s3://{0}/{1}".format(bucket, obj['Key'])
return objects
def create(self, url):
"""Create a bucket, directory, or empty file."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
return self.call("CreateBucket", bucket=target)
def destroy(self, url, recursive=False):
"""Destroy a bucket, directory, or file. Specifying recursive=True
recursively deletes all subdirectories and files."""
bucket, obj_key = _parse_url(url)
if not bucket:
raise InvalidURL(url,
"You must specify a bucket and (optional) path")
if obj_key:
target = "/".join((bucket, obj_key))
else:
target = bucket
if recursive:
for obj in self.get(url, delimiter=''):
self.destroy(obj['url'])
return self.call("DeleteBucket", bucket=target)
def upload(self, local_path, remote_url):
"""Copy a local file to an S3 location."""
bucket, key = _parse_url(remote_url)
with open(local_path, 'rb') as fp:
return self.call("PutObject", bucket=bucket, key=key, body=fp)
def download(self, remote_url, local_path, buffer_size=8 * 1024):
"""Copy S3 data to a local file."""
bucket, key = _parse_url(remote_url)
response_file = self.call("GetObject", bucket=bucket, key=key)['Body']
with open(local_path, 'wb') as fp:
buf = response_file.read(buffer_size)
while buf:
fp.write(buf)
buf = response_file.read(buffer_size)
def copy(self, src_url, dst_url):
"""Copy an S3 object to another S3 location."""
src_bucket, src_key = _parse_url(src_url)
dst_bucket, dst_key = _parse_url(dst_url)
if not dst_bucket:
dst_bucket = src_bucket
params = {
'copy_source': '/'.join((src_bucket, src_key)),
'bucket': dst_bucket,
'key': dst_key,
}
return self.call("CopyObject", **params)
|
MisterY/pydatum | pydatum/datum.py | Datum.add_days | python | def add_days(self, days: int) -> datetime:
self.value = self.value + relativedelta(days=days)
return self.value | Adds days | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L31-L34 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.add_months | python | def add_months(self, value: int) -> datetime:
self.value = self.value + relativedelta(months=value)
return self.value | Add a number of months to the given date | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L36-L39 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.from_date | python | def from_date(self, value: date) -> datetime:
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value | Initializes from the given date value | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L62-L68 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.from_iso_long_date | python | def from_iso_long_date(self, date_str: str) -> datetime:
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value | Parse ISO date string (YYYY-MM-DDTHH:mm:ss) | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L76-L82 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.from_iso_date_string | python | def from_iso_date_string(self, date_str: str) -> datetime:
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value | Parse ISO date string (YYYY-MM-DD) | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L84-L89 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.get_day_name | python | def get_day_name(self) -> str:
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday] | Returns the day name | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L95-L98 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.to_iso_string | python | def to_iso_string(self) -> str:
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value) | Returns full ISO string for the given date | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L110-L113 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.end_of_day | python | def end_of_day(self) -> datetime:
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value | End of day | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L123-L126 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.end_of_month | python | def end_of_month(self) -> datetime:
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value | Provides end of the month for the given date | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L128-L137 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.is_end_of_month | python | def is_end_of_month(self) -> bool:
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value | Checks if the date is at the end of the month | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L139-L144 | [
"def end_of_month(self) -> datetime:\n \"\"\" Provides end of the month for the given date \"\"\"\n # Increase month by 1,\n result = self.value + relativedelta(months=1)\n # take the 1st day of the (next) month,\n result = result.replace(day=1)\n # subtract one day\n result = result - relative... | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.set_day | python | def set_day(self, day: int) -> datetime:
self.value = self.value.replace(day=day)
return self.value | Sets the day value | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L146-L149 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.set_value | python | def set_value(self, value: datetime):
assert isinstance(value, datetime)
self.value = value | Sets the current value | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L151-L155 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.start_of_day | python | def start_of_day(self) -> datetime:
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value | Returns start of day | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L157-L160 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.subtract_days | python | def subtract_days(self, days: int) -> datetime:
self.value = self.value - relativedelta(days=days)
return self.value | Subtracts dates from the given value | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L162-L165 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.subtract_weeks | python | def subtract_weeks(self, weeks: int) -> datetime:
self.value = self.value - timedelta(weeks=weeks)
return self.value | Subtracts number of weeks from the current value | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L167-L170 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.subtract_months | python | def subtract_months(self, months: int) -> datetime:
self.value = self.value - relativedelta(months=months)
return self.value | Subtracts a number of months from the current value | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L172-L175 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.to_short_time_string | python | def to_short_time_string(self) -> str:
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}" | Return the iso time string only | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L177-L181 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.to_long_time_string | python | def to_long_time_string(self) -> str:
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}" | Return the iso time string only | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L183-L188 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.to_iso_time_string | python | def to_iso_time_string(self) -> str:
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}" | Return the iso time string only | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L190-L194 | [
"def to_short_time_string(self) -> str:\n \"\"\" Return the iso time string only \"\"\"\n hour = self.time.hour\n minute = self.time.minute\n return f\"{hour:02}:{minute:02}\"\n"
] | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.to_datetime_string | python | def to_datetime_string(self) -> str:
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}" | Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56 | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L196-L202 | [
"def to_iso_date_string(self):\n \"\"\" Gets the iso string representation of the given date \"\"\"\n return self.value.strftime(ISO_DATE_FORMAT)\n",
"def to_long_time_string(self) -> str:\n \"\"\" Return the iso time string only \"\"\"\n hour = self.time.hour\n minute = self.time.minute\n secon... | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.to_long_datetime_string | python | def to_long_datetime_string(self) -> str:
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}" | Returns the long date/time string
Example: 2018-12-06 12:34 | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L204-L210 | [
"def to_iso_date_string(self):\n \"\"\" Gets the iso string representation of the given date \"\"\"\n return self.value.strftime(ISO_DATE_FORMAT)\n",
"def to_short_time_string(self) -> str:\n \"\"\" Return the iso time string only \"\"\"\n hour = self.time.hour\n minute = self.time.minute\n retu... | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.today | python | def today(self) -> datetime:
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value | Returns today (date only) as datetime | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L213-L216 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def yesterday(self) -> datetime:
""" Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
MisterY/pydatum | pydatum/datum.py | Datum.yesterday | python | def yesterday(self) -> datetime:
self.value = datetime.today() - timedelta(days=1)
return self.value | Set the value to yesterday | train | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L218-L221 | null | class Datum:
""" Encapsulates datetime value and provides operations on top of it """
def __init__(self):
self.value: datetime = datetime.now()
@staticmethod
def parse(value: str):
""" Parse date string. Currently only ISO strings supported yyyy-mm-dd. """
result = Datum()
result.from_iso_date_string(value)
return result
def add_days(self, days: int) -> datetime:
""" Adds days """
self.value = self.value + relativedelta(days=days)
return self.value
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value
def clone(self):
""" Cretes a copy """
copy = Datum()
copy.from_datetime(self.value)
return copy
@property
def date(self) -> date:
""" Returns the date value """
return self.value.date()
@property
def time(self) -> time:
""" The time value """
return self.value.time()
@property
def datetime(self) -> datetime:
''' The datetime value. '''
return self.value
def from_date(self, value: date) -> datetime:
""" Initializes from the given date value """
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.value
def from_datetime(self, value: datetime) -> datetime:
assert isinstance(value, datetime)
self.value = value
return self.value
def from_iso_long_date(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DDTHH:mm:ss) """
assert isinstance(date_str, str)
assert len(date_str) == 19
self.value = datetime.strptime(date_str, ISO_LONG_FORMAT)
return self.value
def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value
def get_day(self) -> int:
""" Returns the day value """
return self.value.day
def get_day_name(self) -> str:
""" Returns the day name """
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
def get_iso_date_string(self):
return self.to_iso_date_string()
def to_iso_date_string(self):
""" Gets the iso string representation of the given date """
return self.value.strftime(ISO_DATE_FORMAT)
def get_iso_string(self) -> str:
return self.to_iso_string()
def to_iso_string(self) -> str:
""" Returns full ISO string for the given date """
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value)
def get_month(self) -> int:
""" Returns the year """
return self.value.month
def get_year(self) -> int:
""" Returns the year """
return self.value.year
def end_of_day(self) -> datetime:
""" End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value
def end_of_month(self) -> datetime:
""" Provides end of the month for the given date """
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value
def is_end_of_month(self) -> bool:
""" Checks if the date is at the end of the month """
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value
def set_day(self, day: int) -> datetime:
""" Sets the day value """
self.value = self.value.replace(day=day)
return self.value
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value
def start_of_day(self) -> datetime:
""" Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value
def subtract_days(self, days: int) -> datetime:
""" Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days)
return self.value
def subtract_weeks(self, weeks: int) -> datetime:
""" Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks)
return self.value
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}"
def to_long_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}"
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}"
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
def to_long_datetime_string(self) -> str:
""" Returns the long date/time string
Example: 2018-12-06 12:34
"""
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}"
def today(self) -> datetime:
""" Returns today (date only) as datetime """
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value
def __repr__(self):
""" string representation """
#iso_str = self.to_iso_string()
datetime_str = self.to_datetime_string()
return f"{datetime_str}"
|
bastikr/boolean.py | boolean/boolean.py | BooleanAlgebra.definition | python | def definition(self):
return self.TRUE, self.FALSE, self.NOT, self.AND, self.OR, self.Symbol | Return a tuple of this algebra defined elements and types as:
(TRUE, FALSE, NOT, AND, OR, Symbol) | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L161-L166 | null | class BooleanAlgebra(object):
"""
An algebra is defined by:
- the types of its operations and Symbol.
- the tokenizer used when parsing expressions from strings.
This class also serves as a base class for all boolean expressions,
including base elements, functions and variable symbols.
"""
def __init__(self, TRUE_class=None, FALSE_class=None, Symbol_class=None,
NOT_class=None, AND_class=None, OR_class=None):
"""
The types for TRUE, FALSE, NOT, AND, OR and Symbol define the boolean
algebra elements, operations and Symbol variable. They default to the
standard classes if not provided.
You can customize an algebra by providing alternative subclasses of the
standard types.
"""
# TRUE and FALSE base elements are algebra-level "singleton" instances
self.TRUE = TRUE_class or _TRUE
self.TRUE = self.TRUE()
self.FALSE = FALSE_class or _FALSE
self.FALSE = self.FALSE()
# they cross-reference each other
self.TRUE.dual = self.FALSE
self.FALSE.dual = self.TRUE
# boolean operation types, defaulting to the standard types
self.NOT = NOT_class or NOT
self.AND = AND_class or AND
self.OR = OR_class or OR
# class used for Symbols
self.Symbol = Symbol_class or Symbol
tf_nao = {
'TRUE': self.TRUE,
'FALSE': self.FALSE,
'NOT': self.NOT,
'AND': self.AND,
'OR': self.OR,
'Symbol': self.Symbol
}
# setup cross references such that all algebra types and
# objects hold a named attribute for every other types and
# objects, including themselves.
for obj in tf_nao.values():
for name, value in tf_nao.items():
setattr(obj, name, value)
def symbols(self, *args):
"""
Return a tuple of symbols building a new Symbol from each argument.
"""
return tuple(map(self.Symbol, args))
def parse(self, expr, simplify=False):
"""
Return a boolean expression parsed from `expr` either a unicode string
or tokens iterable.
Optionally simplify the expression if `simplify` is True.
Raise ParseError on errors.
If `expr` is a string, the standard `tokenizer` is used for tokenization
and the algebra configured Symbol type is used to create Symbol
instances from Symbol tokens.
If `expr` is an iterable, it should contain 3-tuples of: (token_type,
token_string, token_position). In this case, the `token_type` can be
a Symbol instance or one of the TOKEN_* constant types.
See the `tokenize()` method for detailed specification.
"""
precedence = {self.NOT: 5, self.AND: 10, self.OR: 15, TOKEN_LPAR: 20}
if isinstance(expr, basestring):
tokenized = self.tokenize(expr)
else:
tokenized = iter(expr)
if TRACE_PARSE:
tokenized = list(tokenized)
print('tokens:')
map(print, tokenized)
tokenized = iter(tokenized)
# the abstract syntax tree for this expression that will be build as we
# process tokens
# the first two items are None
# symbol items are appended to this structure
ast = [None, None]
def is_sym(_t):
return isinstance(_t, Symbol) or _t in (TOKEN_TRUE, TOKEN_FALSE, TOKEN_SYMBOL)
def is_operator(_t):
return _t in (TOKEN_AND, TOKEN_OR)
prev_token = None
for token_type, token_string, token_position in tokenized:
if TRACE_PARSE:
print('\nprocessing token_type:', repr(token_type), 'token_string:', repr(token_string), 'token_position:', repr(token_position))
if prev_token:
prev_token_type, _prev_token_string, _prev_token_position = prev_token
if TRACE_PARSE:
print(' prev_token:', repr(prev_token))
if is_sym(prev_token_type) and (is_sym(token_type)): # or token_type == TOKEN_LPAR) :
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_SYMBOL_SEQUENCE)
if is_operator(prev_token_type) and (is_operator(token_type) or token_type == TOKEN_RPAR):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
else:
if is_operator(token_type):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
if token_type == TOKEN_SYMBOL:
ast.append(self.Symbol(token_string))
if TRACE_PARSE:
print(' ast: token_type is TOKEN_SYMBOL: append new symbol', repr(ast))
elif isinstance(token_type, Symbol):
ast.append(token_type)
if TRACE_PARSE:
print(' ast: token_type is Symbol): append existing symbol', repr(ast))
elif token_type == TOKEN_TRUE:
ast.append(self.TRUE)
if TRACE_PARSE: print(' ast: token_type is TOKEN_TRUE:', repr(ast))
elif token_type == TOKEN_FALSE:
ast.append(self.FALSE)
if TRACE_PARSE: print(' ast: token_type is TOKEN_FALSE:', repr(ast))
elif token_type == TOKEN_NOT:
ast = [ast, self.NOT]
if TRACE_PARSE: print(' ast: token_type is TOKEN_NOT:', repr(ast))
elif token_type == TOKEN_AND:
# if not prev_token or not is_sym(prev_token_type):
# raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
ast = self._start_operation(ast, self.AND, precedence)
if TRACE_PARSE:
print(' ast:token_type is TOKEN_AND: start_operation', ast)
elif token_type == TOKEN_OR:
# if not prev_token or not is_sym(prev_token_type):
# raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
ast = self._start_operation(ast, self.OR, precedence)
if TRACE_PARSE:
print(' ast:token_type is TOKEN_OR: start_operation', ast)
elif token_type == TOKEN_LPAR:
if prev_token:
# Check that an opening parens is preceded by a function
# or an opening parens
if prev_token_type not in (TOKEN_NOT, TOKEN_AND, TOKEN_OR, TOKEN_LPAR):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_NESTING)
ast = [ast, TOKEN_LPAR]
elif token_type == TOKEN_RPAR:
while True:
if ast[0] is None:
raise ParseError(token_type, token_string, token_position, PARSE_UNBALANCED_CLOSING_PARENS)
if ast[1] is TOKEN_LPAR:
ast[0].append(ast[2])
if TRACE_PARSE: print('ast9:', repr(ast))
ast = ast[0]
if TRACE_PARSE: print('ast10:', repr(ast))
break
if isinstance(ast[1], int):
raise ParseError(token_type, token_string, token_position, PARSE_UNBALANCED_CLOSING_PARENS)
# the parens are properly nested
# the top ast node should be a function subclass
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_NESTING)
subex = ast[1](*ast[2:])
ast[0].append(subex)
if TRACE_PARSE: print('ast11:', repr(ast))
ast = ast[0]
if TRACE_PARSE: print('ast12:', repr(ast))
else:
raise ParseError(token_type, token_string, token_position, PARSE_UNKNOWN_TOKEN)
prev_token = (token_type, token_string, token_position)
try:
while True:
if ast[0] is None:
if TRACE_PARSE: print('ast[0] is None:', repr(ast))
if ast[1] is None:
if TRACE_PARSE: print(' ast[1] is None:', repr(ast))
if len(ast) != 3:
raise ParseError(error_code=PARSE_INVALID_EXPRESSION)
parsed = ast[2]
if TRACE_PARSE: print(' parsed = ast[2]:', repr(parsed))
else:
# call the function in ast[1] with the rest of the ast as args
parsed = ast[1](*ast[2:])
if TRACE_PARSE: print(' parsed = ast[1](*ast[2:]):', repr(parsed))
break
else:
if TRACE_PARSE: print('subex = ast[1](*ast[2:]):', repr(ast))
subex = ast[1](*ast[2:])
ast[0].append(subex)
if TRACE_PARSE: print(' ast[0].append(subex):', repr(ast))
ast = ast[0]
if TRACE_PARSE: print(' ast = ast[0]:', repr(ast))
except TypeError:
raise ParseError(error_code=PARSE_INVALID_EXPRESSION)
if simplify:
return parsed.simplify()
if TRACE_PARSE: print('final parsed:', repr(parsed))
return parsed
def _start_operation(self, ast, operation, precedence):
"""
Returns an AST where all operations of lower precedence are finalized.
"""
if TRACE_PARSE:
print(' start_operation:', repr(operation), 'AST:', ast)
op_prec = precedence[operation]
while True:
if ast[1] is None:
# [None, None, x]
if TRACE_PARSE: print(' start_op: ast[1] is None:', repr(ast))
ast[1] = operation
if TRACE_PARSE: print(' --> start_op: ast[1] is None:', repr(ast))
return ast
prec = precedence[ast[1]]
if prec > op_prec: # op=&, [ast, |, x, y] -> [[ast, |, x], &, y]
if TRACE_PARSE: print(' start_op: prec > op_prec:', repr(ast))
ast = [ast, operation, ast.pop(-1)]
if TRACE_PARSE: print(' --> start_op: prec > op_prec:', repr(ast))
return ast
if prec == op_prec: # op=&, [ast, &, x] -> [ast, &, x]
if TRACE_PARSE: print(' start_op: prec == op_prec:', repr(ast))
return ast
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
# the top ast node should be a function subclass at this stage
raise ParseError(error_code=PARSE_INVALID_NESTING)
if ast[0] is None: # op=|, [None, &, x, y] -> [None, |, x&y]
if TRACE_PARSE: print(' start_op: ast[0] is None:', repr(ast))
subexp = ast[1](*ast[2:])
new_ast = [ast[0], operation, subexp]
if TRACE_PARSE: print(' --> start_op: ast[0] is None:', repr(new_ast))
return new_ast
else: # op=|, [[ast, &, x], ~, y] -> [ast, &, x, ~y]
if TRACE_PARSE: print(' start_op: else:', repr(ast))
ast[0].append(ast[1](*ast[2:]))
ast = ast[0]
if TRACE_PARSE: print(' --> start_op: else:', repr(ast))
def tokenize(self, expr):
"""
Return an iterable of 3-tuple describing each token given an expression
unicode string.
This 3-tuple contains (token, token string, position):
- token: either a Symbol instance or one of TOKEN_* token types.
- token string: the original token unicode string.
- position: some simple object describing the starting position of the
original token string in the `expr` string. It can be an int for a
character offset, or a tuple of starting (row/line, column).
The token position is used only for error reporting and can be None or
empty.
Raise ParseError on errors. The ParseError.args is a tuple of:
(token_string, position, error message)
You can use this tokenizer as a base to create specialized tokenizers
for your custom algebra by subclassing BooleanAlgebra. See also the
tests for other examples of alternative tokenizers.
This tokenizer has these characteristics:
- The `expr` string can span multiple lines,
- Whitespace is not significant.
- The returned position is the starting character offset of a token.
- A TOKEN_SYMBOL is returned for valid identifiers which is a string
without spaces. These are valid identifiers:
- Python identifiers.
- a string even if starting with digits
- digits (except for 0 and 1).
- dotted names : foo.bar consist of one token.
- names with colons: foo:bar consist of one token.
These are not identifiers:
- quoted strings.
- any punctuation which is not an operation
- Recognized operators are (in any upper/lower case combinations):
- for and: '*', '&', 'and'
- for or: '+', '|', 'or'
- for not: '~', '!', 'not'
- Recognized special symbols are (in any upper/lower case combinations):
- True symbols: 1 and True
- False symbols: 0, False and None
"""
if not isinstance(expr, basestring):
raise TypeError('expr must be string but it is %s.' % type(expr))
# mapping of lowercase token strings to a token type id for the standard
# operators, parens and common true or false symbols, as used in the
# default tokenizer implementation.
TOKENS = {
'*': TOKEN_AND, '&': TOKEN_AND, 'and': TOKEN_AND,
'+': TOKEN_OR, '|': TOKEN_OR, 'or': TOKEN_OR,
'~': TOKEN_NOT, '!': TOKEN_NOT, 'not': TOKEN_NOT,
'(': TOKEN_LPAR, ')': TOKEN_RPAR,
'[': TOKEN_LPAR, ']': TOKEN_RPAR,
'true': TOKEN_TRUE, '1': TOKEN_TRUE,
'false': TOKEN_FALSE, '0': TOKEN_FALSE, 'none': TOKEN_FALSE
}
position = 0
length = len(expr)
while position < length:
tok = expr[position]
sym = tok.isalpha() or tok == '_'
if sym:
position += 1
while position < length:
char = expr[position]
if char.isalnum() or char in ('.', ':', '_'):
position += 1
tok += char
else:
break
position -= 1
try:
yield TOKENS[tok.lower()], tok, position
except KeyError:
if sym:
yield TOKEN_SYMBOL, tok, position
elif tok not in (' ', '\t', '\r', '\n'):
raise ParseError(token_string=tok, position=position,
error_code=PARSE_UNKNOWN_TOKEN)
position += 1
# TODO: explain what this means exactly
def _rdistributive(self, expr, op_example):
"""
Recursively flatten the `expr` expression for the `op_example`
AND or OR operation instance exmaple.
"""
if expr.isliteral:
return expr
expr_class = expr.__class__
args = (self._rdistributive(arg, op_example) for arg in expr.args)
args = tuple(arg.simplify() for arg in args)
if len(args) == 1:
return args[0]
expr = expr_class(*args)
dualoperation = op_example.dual
if isinstance(expr, dualoperation):
expr = expr.distributive()
return expr
def normalize(self, expr, operation):
"""
Return a normalized expression transformed to its normal form in the
given AND or OR operation.
The new expression arguments will satisfy these conditions:
- operation(*args) == expr (here mathematical equality is meant)
- the operation does not occur in any of its arg.
- NOT is only appearing in literals (aka. Negation normal form).
The operation must be an AND or OR operation or a subclass.
"""
# ensure that the operation is not NOT
assert operation in (self.AND, self.OR,)
# Move NOT inwards.
expr = expr.literalize()
# Simplify first otherwise _rdistributive() may take forever.
expr = expr.simplify()
operation_example = operation(self.TRUE, self.FALSE)
expr = self._rdistributive(expr, operation_example)
# Canonicalize
expr = expr.simplify()
return expr
def cnf(self, expr):
"""
Return a conjunctive normal form of the `expr` expression.
"""
return self.normalize(expr, self.AND)
def dnf(self, expr):
"""
Return a disjunctive normal form of the `expr` expression.
"""
return self.normalize(expr, self.OR)
|
bastikr/boolean.py | boolean/boolean.py | BooleanAlgebra.parse | python | def parse(self, expr, simplify=False):
precedence = {self.NOT: 5, self.AND: 10, self.OR: 15, TOKEN_LPAR: 20}
if isinstance(expr, basestring):
tokenized = self.tokenize(expr)
else:
tokenized = iter(expr)
if TRACE_PARSE:
tokenized = list(tokenized)
print('tokens:')
map(print, tokenized)
tokenized = iter(tokenized)
# the abstract syntax tree for this expression that will be build as we
# process tokens
# the first two items are None
# symbol items are appended to this structure
ast = [None, None]
def is_sym(_t):
return isinstance(_t, Symbol) or _t in (TOKEN_TRUE, TOKEN_FALSE, TOKEN_SYMBOL)
def is_operator(_t):
return _t in (TOKEN_AND, TOKEN_OR)
prev_token = None
for token_type, token_string, token_position in tokenized:
if TRACE_PARSE:
print('\nprocessing token_type:', repr(token_type), 'token_string:', repr(token_string), 'token_position:', repr(token_position))
if prev_token:
prev_token_type, _prev_token_string, _prev_token_position = prev_token
if TRACE_PARSE:
print(' prev_token:', repr(prev_token))
if is_sym(prev_token_type) and (is_sym(token_type)): # or token_type == TOKEN_LPAR) :
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_SYMBOL_SEQUENCE)
if is_operator(prev_token_type) and (is_operator(token_type) or token_type == TOKEN_RPAR):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
else:
if is_operator(token_type):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
if token_type == TOKEN_SYMBOL:
ast.append(self.Symbol(token_string))
if TRACE_PARSE:
print(' ast: token_type is TOKEN_SYMBOL: append new symbol', repr(ast))
elif isinstance(token_type, Symbol):
ast.append(token_type)
if TRACE_PARSE:
print(' ast: token_type is Symbol): append existing symbol', repr(ast))
elif token_type == TOKEN_TRUE:
ast.append(self.TRUE)
if TRACE_PARSE: print(' ast: token_type is TOKEN_TRUE:', repr(ast))
elif token_type == TOKEN_FALSE:
ast.append(self.FALSE)
if TRACE_PARSE: print(' ast: token_type is TOKEN_FALSE:', repr(ast))
elif token_type == TOKEN_NOT:
ast = [ast, self.NOT]
if TRACE_PARSE: print(' ast: token_type is TOKEN_NOT:', repr(ast))
elif token_type == TOKEN_AND:
# if not prev_token or not is_sym(prev_token_type):
# raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
ast = self._start_operation(ast, self.AND, precedence)
if TRACE_PARSE:
print(' ast:token_type is TOKEN_AND: start_operation', ast)
elif token_type == TOKEN_OR:
# if not prev_token or not is_sym(prev_token_type):
# raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
ast = self._start_operation(ast, self.OR, precedence)
if TRACE_PARSE:
print(' ast:token_type is TOKEN_OR: start_operation', ast)
elif token_type == TOKEN_LPAR:
if prev_token:
# Check that an opening parens is preceded by a function
# or an opening parens
if prev_token_type not in (TOKEN_NOT, TOKEN_AND, TOKEN_OR, TOKEN_LPAR):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_NESTING)
ast = [ast, TOKEN_LPAR]
elif token_type == TOKEN_RPAR:
while True:
if ast[0] is None:
raise ParseError(token_type, token_string, token_position, PARSE_UNBALANCED_CLOSING_PARENS)
if ast[1] is TOKEN_LPAR:
ast[0].append(ast[2])
if TRACE_PARSE: print('ast9:', repr(ast))
ast = ast[0]
if TRACE_PARSE: print('ast10:', repr(ast))
break
if isinstance(ast[1], int):
raise ParseError(token_type, token_string, token_position, PARSE_UNBALANCED_CLOSING_PARENS)
# the parens are properly nested
# the top ast node should be a function subclass
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_NESTING)
subex = ast[1](*ast[2:])
ast[0].append(subex)
if TRACE_PARSE: print('ast11:', repr(ast))
ast = ast[0]
if TRACE_PARSE: print('ast12:', repr(ast))
else:
raise ParseError(token_type, token_string, token_position, PARSE_UNKNOWN_TOKEN)
prev_token = (token_type, token_string, token_position)
try:
while True:
if ast[0] is None:
if TRACE_PARSE: print('ast[0] is None:', repr(ast))
if ast[1] is None:
if TRACE_PARSE: print(' ast[1] is None:', repr(ast))
if len(ast) != 3:
raise ParseError(error_code=PARSE_INVALID_EXPRESSION)
parsed = ast[2]
if TRACE_PARSE: print(' parsed = ast[2]:', repr(parsed))
else:
# call the function in ast[1] with the rest of the ast as args
parsed = ast[1](*ast[2:])
if TRACE_PARSE: print(' parsed = ast[1](*ast[2:]):', repr(parsed))
break
else:
if TRACE_PARSE: print('subex = ast[1](*ast[2:]):', repr(ast))
subex = ast[1](*ast[2:])
ast[0].append(subex)
if TRACE_PARSE: print(' ast[0].append(subex):', repr(ast))
ast = ast[0]
if TRACE_PARSE: print(' ast = ast[0]:', repr(ast))
except TypeError:
raise ParseError(error_code=PARSE_INVALID_EXPRESSION)
if simplify:
return parsed.simplify()
if TRACE_PARSE: print('final parsed:', repr(parsed))
return parsed | Return a boolean expression parsed from `expr` either a unicode string
or tokens iterable.
Optionally simplify the expression if `simplify` is True.
Raise ParseError on errors.
If `expr` is a string, the standard `tokenizer` is used for tokenization
and the algebra configured Symbol type is used to create Symbol
instances from Symbol tokens.
If `expr` is an iterable, it should contain 3-tuples of: (token_type,
token_string, token_position). In this case, the `token_type` can be
a Symbol instance or one of the TOKEN_* constant types.
See the `tokenize()` method for detailed specification. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L174-L344 | [
"def tokenize(self, expr):\n \"\"\"\n Return an iterable of 3-tuple describing each token given an expression\n unicode string.\n\n This 3-tuple contains (token, token string, position):\n - token: either a Symbol instance or one of TOKEN_* token types.\n - token string: the original token unicode... | class BooleanAlgebra(object):
"""
An algebra is defined by:
- the types of its operations and Symbol.
- the tokenizer used when parsing expressions from strings.
This class also serves as a base class for all boolean expressions,
including base elements, functions and variable symbols.
"""
def __init__(self, TRUE_class=None, FALSE_class=None, Symbol_class=None,
NOT_class=None, AND_class=None, OR_class=None):
"""
The types for TRUE, FALSE, NOT, AND, OR and Symbol define the boolean
algebra elements, operations and Symbol variable. They default to the
standard classes if not provided.
You can customize an algebra by providing alternative subclasses of the
standard types.
"""
# TRUE and FALSE base elements are algebra-level "singleton" instances
self.TRUE = TRUE_class or _TRUE
self.TRUE = self.TRUE()
self.FALSE = FALSE_class or _FALSE
self.FALSE = self.FALSE()
# they cross-reference each other
self.TRUE.dual = self.FALSE
self.FALSE.dual = self.TRUE
# boolean operation types, defaulting to the standard types
self.NOT = NOT_class or NOT
self.AND = AND_class or AND
self.OR = OR_class or OR
# class used for Symbols
self.Symbol = Symbol_class or Symbol
tf_nao = {
'TRUE': self.TRUE,
'FALSE': self.FALSE,
'NOT': self.NOT,
'AND': self.AND,
'OR': self.OR,
'Symbol': self.Symbol
}
# setup cross references such that all algebra types and
# objects hold a named attribute for every other types and
# objects, including themselves.
for obj in tf_nao.values():
for name, value in tf_nao.items():
setattr(obj, name, value)
def definition(self):
"""
Return a tuple of this algebra defined elements and types as:
(TRUE, FALSE, NOT, AND, OR, Symbol)
"""
return self.TRUE, self.FALSE, self.NOT, self.AND, self.OR, self.Symbol
def symbols(self, *args):
"""
Return a tuple of symbols building a new Symbol from each argument.
"""
return tuple(map(self.Symbol, args))
def _start_operation(self, ast, operation, precedence):
"""
Returns an AST where all operations of lower precedence are finalized.
"""
if TRACE_PARSE:
print(' start_operation:', repr(operation), 'AST:', ast)
op_prec = precedence[operation]
while True:
if ast[1] is None:
# [None, None, x]
if TRACE_PARSE: print(' start_op: ast[1] is None:', repr(ast))
ast[1] = operation
if TRACE_PARSE: print(' --> start_op: ast[1] is None:', repr(ast))
return ast
prec = precedence[ast[1]]
if prec > op_prec: # op=&, [ast, |, x, y] -> [[ast, |, x], &, y]
if TRACE_PARSE: print(' start_op: prec > op_prec:', repr(ast))
ast = [ast, operation, ast.pop(-1)]
if TRACE_PARSE: print(' --> start_op: prec > op_prec:', repr(ast))
return ast
if prec == op_prec: # op=&, [ast, &, x] -> [ast, &, x]
if TRACE_PARSE: print(' start_op: prec == op_prec:', repr(ast))
return ast
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
# the top ast node should be a function subclass at this stage
raise ParseError(error_code=PARSE_INVALID_NESTING)
if ast[0] is None: # op=|, [None, &, x, y] -> [None, |, x&y]
if TRACE_PARSE: print(' start_op: ast[0] is None:', repr(ast))
subexp = ast[1](*ast[2:])
new_ast = [ast[0], operation, subexp]
if TRACE_PARSE: print(' --> start_op: ast[0] is None:', repr(new_ast))
return new_ast
else: # op=|, [[ast, &, x], ~, y] -> [ast, &, x, ~y]
if TRACE_PARSE: print(' start_op: else:', repr(ast))
ast[0].append(ast[1](*ast[2:]))
ast = ast[0]
if TRACE_PARSE: print(' --> start_op: else:', repr(ast))
def tokenize(self, expr):
"""
Return an iterable of 3-tuple describing each token given an expression
unicode string.
This 3-tuple contains (token, token string, position):
- token: either a Symbol instance or one of TOKEN_* token types.
- token string: the original token unicode string.
- position: some simple object describing the starting position of the
original token string in the `expr` string. It can be an int for a
character offset, or a tuple of starting (row/line, column).
The token position is used only for error reporting and can be None or
empty.
Raise ParseError on errors. The ParseError.args is a tuple of:
(token_string, position, error message)
You can use this tokenizer as a base to create specialized tokenizers
for your custom algebra by subclassing BooleanAlgebra. See also the
tests for other examples of alternative tokenizers.
This tokenizer has these characteristics:
- The `expr` string can span multiple lines,
- Whitespace is not significant.
- The returned position is the starting character offset of a token.
- A TOKEN_SYMBOL is returned for valid identifiers which is a string
without spaces. These are valid identifiers:
- Python identifiers.
- a string even if starting with digits
- digits (except for 0 and 1).
- dotted names : foo.bar consist of one token.
- names with colons: foo:bar consist of one token.
These are not identifiers:
- quoted strings.
- any punctuation which is not an operation
- Recognized operators are (in any upper/lower case combinations):
- for and: '*', '&', 'and'
- for or: '+', '|', 'or'
- for not: '~', '!', 'not'
- Recognized special symbols are (in any upper/lower case combinations):
- True symbols: 1 and True
- False symbols: 0, False and None
"""
if not isinstance(expr, basestring):
raise TypeError('expr must be string but it is %s.' % type(expr))
# mapping of lowercase token strings to a token type id for the standard
# operators, parens and common true or false symbols, as used in the
# default tokenizer implementation.
TOKENS = {
'*': TOKEN_AND, '&': TOKEN_AND, 'and': TOKEN_AND,
'+': TOKEN_OR, '|': TOKEN_OR, 'or': TOKEN_OR,
'~': TOKEN_NOT, '!': TOKEN_NOT, 'not': TOKEN_NOT,
'(': TOKEN_LPAR, ')': TOKEN_RPAR,
'[': TOKEN_LPAR, ']': TOKEN_RPAR,
'true': TOKEN_TRUE, '1': TOKEN_TRUE,
'false': TOKEN_FALSE, '0': TOKEN_FALSE, 'none': TOKEN_FALSE
}
position = 0
length = len(expr)
while position < length:
tok = expr[position]
sym = tok.isalpha() or tok == '_'
if sym:
position += 1
while position < length:
char = expr[position]
if char.isalnum() or char in ('.', ':', '_'):
position += 1
tok += char
else:
break
position -= 1
try:
yield TOKENS[tok.lower()], tok, position
except KeyError:
if sym:
yield TOKEN_SYMBOL, tok, position
elif tok not in (' ', '\t', '\r', '\n'):
raise ParseError(token_string=tok, position=position,
error_code=PARSE_UNKNOWN_TOKEN)
position += 1
# TODO: explain what this means exactly
def _rdistributive(self, expr, op_example):
"""
Recursively flatten the `expr` expression for the `op_example`
AND or OR operation instance exmaple.
"""
if expr.isliteral:
return expr
expr_class = expr.__class__
args = (self._rdistributive(arg, op_example) for arg in expr.args)
args = tuple(arg.simplify() for arg in args)
if len(args) == 1:
return args[0]
expr = expr_class(*args)
dualoperation = op_example.dual
if isinstance(expr, dualoperation):
expr = expr.distributive()
return expr
def normalize(self, expr, operation):
"""
Return a normalized expression transformed to its normal form in the
given AND or OR operation.
The new expression arguments will satisfy these conditions:
- operation(*args) == expr (here mathematical equality is meant)
- the operation does not occur in any of its arg.
- NOT is only appearing in literals (aka. Negation normal form).
The operation must be an AND or OR operation or a subclass.
"""
# ensure that the operation is not NOT
assert operation in (self.AND, self.OR,)
# Move NOT inwards.
expr = expr.literalize()
# Simplify first otherwise _rdistributive() may take forever.
expr = expr.simplify()
operation_example = operation(self.TRUE, self.FALSE)
expr = self._rdistributive(expr, operation_example)
# Canonicalize
expr = expr.simplify()
return expr
def cnf(self, expr):
"""
Return a conjunctive normal form of the `expr` expression.
"""
return self.normalize(expr, self.AND)
def dnf(self, expr):
"""
Return a disjunctive normal form of the `expr` expression.
"""
return self.normalize(expr, self.OR)
|
bastikr/boolean.py | boolean/boolean.py | BooleanAlgebra._start_operation | python | def _start_operation(self, ast, operation, precedence):
if TRACE_PARSE:
print(' start_operation:', repr(operation), 'AST:', ast)
op_prec = precedence[operation]
while True:
if ast[1] is None:
# [None, None, x]
if TRACE_PARSE: print(' start_op: ast[1] is None:', repr(ast))
ast[1] = operation
if TRACE_PARSE: print(' --> start_op: ast[1] is None:', repr(ast))
return ast
prec = precedence[ast[1]]
if prec > op_prec: # op=&, [ast, |, x, y] -> [[ast, |, x], &, y]
if TRACE_PARSE: print(' start_op: prec > op_prec:', repr(ast))
ast = [ast, operation, ast.pop(-1)]
if TRACE_PARSE: print(' --> start_op: prec > op_prec:', repr(ast))
return ast
if prec == op_prec: # op=&, [ast, &, x] -> [ast, &, x]
if TRACE_PARSE: print(' start_op: prec == op_prec:', repr(ast))
return ast
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
# the top ast node should be a function subclass at this stage
raise ParseError(error_code=PARSE_INVALID_NESTING)
if ast[0] is None: # op=|, [None, &, x, y] -> [None, |, x&y]
if TRACE_PARSE: print(' start_op: ast[0] is None:', repr(ast))
subexp = ast[1](*ast[2:])
new_ast = [ast[0], operation, subexp]
if TRACE_PARSE: print(' --> start_op: ast[0] is None:', repr(new_ast))
return new_ast
else: # op=|, [[ast, &, x], ~, y] -> [ast, &, x, ~y]
if TRACE_PARSE: print(' start_op: else:', repr(ast))
ast[0].append(ast[1](*ast[2:]))
ast = ast[0]
if TRACE_PARSE: print(' --> start_op: else:', repr(ast)) | Returns an AST where all operations of lower precedence are finalized. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L346-L388 | null | class BooleanAlgebra(object):
"""
An algebra is defined by:
- the types of its operations and Symbol.
- the tokenizer used when parsing expressions from strings.
This class also serves as a base class for all boolean expressions,
including base elements, functions and variable symbols.
"""
def __init__(self, TRUE_class=None, FALSE_class=None, Symbol_class=None,
NOT_class=None, AND_class=None, OR_class=None):
"""
The types for TRUE, FALSE, NOT, AND, OR and Symbol define the boolean
algebra elements, operations and Symbol variable. They default to the
standard classes if not provided.
You can customize an algebra by providing alternative subclasses of the
standard types.
"""
# TRUE and FALSE base elements are algebra-level "singleton" instances
self.TRUE = TRUE_class or _TRUE
self.TRUE = self.TRUE()
self.FALSE = FALSE_class or _FALSE
self.FALSE = self.FALSE()
# they cross-reference each other
self.TRUE.dual = self.FALSE
self.FALSE.dual = self.TRUE
# boolean operation types, defaulting to the standard types
self.NOT = NOT_class or NOT
self.AND = AND_class or AND
self.OR = OR_class or OR
# class used for Symbols
self.Symbol = Symbol_class or Symbol
tf_nao = {
'TRUE': self.TRUE,
'FALSE': self.FALSE,
'NOT': self.NOT,
'AND': self.AND,
'OR': self.OR,
'Symbol': self.Symbol
}
# setup cross references such that all algebra types and
# objects hold a named attribute for every other types and
# objects, including themselves.
for obj in tf_nao.values():
for name, value in tf_nao.items():
setattr(obj, name, value)
def definition(self):
"""
Return a tuple of this algebra defined elements and types as:
(TRUE, FALSE, NOT, AND, OR, Symbol)
"""
return self.TRUE, self.FALSE, self.NOT, self.AND, self.OR, self.Symbol
def symbols(self, *args):
"""
Return a tuple of symbols building a new Symbol from each argument.
"""
return tuple(map(self.Symbol, args))
def parse(self, expr, simplify=False):
"""
Return a boolean expression parsed from `expr` either a unicode string
or tokens iterable.
Optionally simplify the expression if `simplify` is True.
Raise ParseError on errors.
If `expr` is a string, the standard `tokenizer` is used for tokenization
and the algebra configured Symbol type is used to create Symbol
instances from Symbol tokens.
If `expr` is an iterable, it should contain 3-tuples of: (token_type,
token_string, token_position). In this case, the `token_type` can be
a Symbol instance or one of the TOKEN_* constant types.
See the `tokenize()` method for detailed specification.
"""
precedence = {self.NOT: 5, self.AND: 10, self.OR: 15, TOKEN_LPAR: 20}
if isinstance(expr, basestring):
tokenized = self.tokenize(expr)
else:
tokenized = iter(expr)
if TRACE_PARSE:
tokenized = list(tokenized)
print('tokens:')
map(print, tokenized)
tokenized = iter(tokenized)
# the abstract syntax tree for this expression that will be build as we
# process tokens
# the first two items are None
# symbol items are appended to this structure
ast = [None, None]
def is_sym(_t):
return isinstance(_t, Symbol) or _t in (TOKEN_TRUE, TOKEN_FALSE, TOKEN_SYMBOL)
def is_operator(_t):
return _t in (TOKEN_AND, TOKEN_OR)
prev_token = None
for token_type, token_string, token_position in tokenized:
if TRACE_PARSE:
print('\nprocessing token_type:', repr(token_type), 'token_string:', repr(token_string), 'token_position:', repr(token_position))
if prev_token:
prev_token_type, _prev_token_string, _prev_token_position = prev_token
if TRACE_PARSE:
print(' prev_token:', repr(prev_token))
if is_sym(prev_token_type) and (is_sym(token_type)): # or token_type == TOKEN_LPAR) :
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_SYMBOL_SEQUENCE)
if is_operator(prev_token_type) and (is_operator(token_type) or token_type == TOKEN_RPAR):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
else:
if is_operator(token_type):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
if token_type == TOKEN_SYMBOL:
ast.append(self.Symbol(token_string))
if TRACE_PARSE:
print(' ast: token_type is TOKEN_SYMBOL: append new symbol', repr(ast))
elif isinstance(token_type, Symbol):
ast.append(token_type)
if TRACE_PARSE:
print(' ast: token_type is Symbol): append existing symbol', repr(ast))
elif token_type == TOKEN_TRUE:
ast.append(self.TRUE)
if TRACE_PARSE: print(' ast: token_type is TOKEN_TRUE:', repr(ast))
elif token_type == TOKEN_FALSE:
ast.append(self.FALSE)
if TRACE_PARSE: print(' ast: token_type is TOKEN_FALSE:', repr(ast))
elif token_type == TOKEN_NOT:
ast = [ast, self.NOT]
if TRACE_PARSE: print(' ast: token_type is TOKEN_NOT:', repr(ast))
elif token_type == TOKEN_AND:
# if not prev_token or not is_sym(prev_token_type):
# raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
ast = self._start_operation(ast, self.AND, precedence)
if TRACE_PARSE:
print(' ast:token_type is TOKEN_AND: start_operation', ast)
elif token_type == TOKEN_OR:
# if not prev_token or not is_sym(prev_token_type):
# raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
ast = self._start_operation(ast, self.OR, precedence)
if TRACE_PARSE:
print(' ast:token_type is TOKEN_OR: start_operation', ast)
elif token_type == TOKEN_LPAR:
if prev_token:
# Check that an opening parens is preceded by a function
# or an opening parens
if prev_token_type not in (TOKEN_NOT, TOKEN_AND, TOKEN_OR, TOKEN_LPAR):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_NESTING)
ast = [ast, TOKEN_LPAR]
elif token_type == TOKEN_RPAR:
while True:
if ast[0] is None:
raise ParseError(token_type, token_string, token_position, PARSE_UNBALANCED_CLOSING_PARENS)
if ast[1] is TOKEN_LPAR:
ast[0].append(ast[2])
if TRACE_PARSE: print('ast9:', repr(ast))
ast = ast[0]
if TRACE_PARSE: print('ast10:', repr(ast))
break
if isinstance(ast[1], int):
raise ParseError(token_type, token_string, token_position, PARSE_UNBALANCED_CLOSING_PARENS)
# the parens are properly nested
# the top ast node should be a function subclass
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_NESTING)
subex = ast[1](*ast[2:])
ast[0].append(subex)
if TRACE_PARSE: print('ast11:', repr(ast))
ast = ast[0]
if TRACE_PARSE: print('ast12:', repr(ast))
else:
raise ParseError(token_type, token_string, token_position, PARSE_UNKNOWN_TOKEN)
prev_token = (token_type, token_string, token_position)
try:
while True:
if ast[0] is None:
if TRACE_PARSE: print('ast[0] is None:', repr(ast))
if ast[1] is None:
if TRACE_PARSE: print(' ast[1] is None:', repr(ast))
if len(ast) != 3:
raise ParseError(error_code=PARSE_INVALID_EXPRESSION)
parsed = ast[2]
if TRACE_PARSE: print(' parsed = ast[2]:', repr(parsed))
else:
# call the function in ast[1] with the rest of the ast as args
parsed = ast[1](*ast[2:])
if TRACE_PARSE: print(' parsed = ast[1](*ast[2:]):', repr(parsed))
break
else:
if TRACE_PARSE: print('subex = ast[1](*ast[2:]):', repr(ast))
subex = ast[1](*ast[2:])
ast[0].append(subex)
if TRACE_PARSE: print(' ast[0].append(subex):', repr(ast))
ast = ast[0]
if TRACE_PARSE: print(' ast = ast[0]:', repr(ast))
except TypeError:
raise ParseError(error_code=PARSE_INVALID_EXPRESSION)
if simplify:
return parsed.simplify()
if TRACE_PARSE: print('final parsed:', repr(parsed))
return parsed
def tokenize(self, expr):
"""
Return an iterable of 3-tuple describing each token given an expression
unicode string.
This 3-tuple contains (token, token string, position):
- token: either a Symbol instance or one of TOKEN_* token types.
- token string: the original token unicode string.
- position: some simple object describing the starting position of the
original token string in the `expr` string. It can be an int for a
character offset, or a tuple of starting (row/line, column).
The token position is used only for error reporting and can be None or
empty.
Raise ParseError on errors. The ParseError.args is a tuple of:
(token_string, position, error message)
You can use this tokenizer as a base to create specialized tokenizers
for your custom algebra by subclassing BooleanAlgebra. See also the
tests for other examples of alternative tokenizers.
This tokenizer has these characteristics:
- The `expr` string can span multiple lines,
- Whitespace is not significant.
- The returned position is the starting character offset of a token.
- A TOKEN_SYMBOL is returned for valid identifiers which is a string
without spaces. These are valid identifiers:
- Python identifiers.
- a string even if starting with digits
- digits (except for 0 and 1).
- dotted names : foo.bar consist of one token.
- names with colons: foo:bar consist of one token.
These are not identifiers:
- quoted strings.
- any punctuation which is not an operation
- Recognized operators are (in any upper/lower case combinations):
- for and: '*', '&', 'and'
- for or: '+', '|', 'or'
- for not: '~', '!', 'not'
- Recognized special symbols are (in any upper/lower case combinations):
- True symbols: 1 and True
- False symbols: 0, False and None
"""
if not isinstance(expr, basestring):
raise TypeError('expr must be string but it is %s.' % type(expr))
# mapping of lowercase token strings to a token type id for the standard
# operators, parens and common true or false symbols, as used in the
# default tokenizer implementation.
TOKENS = {
'*': TOKEN_AND, '&': TOKEN_AND, 'and': TOKEN_AND,
'+': TOKEN_OR, '|': TOKEN_OR, 'or': TOKEN_OR,
'~': TOKEN_NOT, '!': TOKEN_NOT, 'not': TOKEN_NOT,
'(': TOKEN_LPAR, ')': TOKEN_RPAR,
'[': TOKEN_LPAR, ']': TOKEN_RPAR,
'true': TOKEN_TRUE, '1': TOKEN_TRUE,
'false': TOKEN_FALSE, '0': TOKEN_FALSE, 'none': TOKEN_FALSE
}
position = 0
length = len(expr)
while position < length:
tok = expr[position]
sym = tok.isalpha() or tok == '_'
if sym:
position += 1
while position < length:
char = expr[position]
if char.isalnum() or char in ('.', ':', '_'):
position += 1
tok += char
else:
break
position -= 1
try:
yield TOKENS[tok.lower()], tok, position
except KeyError:
if sym:
yield TOKEN_SYMBOL, tok, position
elif tok not in (' ', '\t', '\r', '\n'):
raise ParseError(token_string=tok, position=position,
error_code=PARSE_UNKNOWN_TOKEN)
position += 1
# TODO: explain what this means exactly
def _rdistributive(self, expr, op_example):
"""
Recursively flatten the `expr` expression for the `op_example`
AND or OR operation instance exmaple.
"""
if expr.isliteral:
return expr
expr_class = expr.__class__
args = (self._rdistributive(arg, op_example) for arg in expr.args)
args = tuple(arg.simplify() for arg in args)
if len(args) == 1:
return args[0]
expr = expr_class(*args)
dualoperation = op_example.dual
if isinstance(expr, dualoperation):
expr = expr.distributive()
return expr
def normalize(self, expr, operation):
"""
Return a normalized expression transformed to its normal form in the
given AND or OR operation.
The new expression arguments will satisfy these conditions:
- operation(*args) == expr (here mathematical equality is meant)
- the operation does not occur in any of its arg.
- NOT is only appearing in literals (aka. Negation normal form).
The operation must be an AND or OR operation or a subclass.
"""
# ensure that the operation is not NOT
assert operation in (self.AND, self.OR,)
# Move NOT inwards.
expr = expr.literalize()
# Simplify first otherwise _rdistributive() may take forever.
expr = expr.simplify()
operation_example = operation(self.TRUE, self.FALSE)
expr = self._rdistributive(expr, operation_example)
# Canonicalize
expr = expr.simplify()
return expr
def cnf(self, expr):
"""
Return a conjunctive normal form of the `expr` expression.
"""
return self.normalize(expr, self.AND)
def dnf(self, expr):
"""
Return a disjunctive normal form of the `expr` expression.
"""
return self.normalize(expr, self.OR)
|
bastikr/boolean.py | boolean/boolean.py | BooleanAlgebra.tokenize | python | def tokenize(self, expr):
if not isinstance(expr, basestring):
raise TypeError('expr must be string but it is %s.' % type(expr))
# mapping of lowercase token strings to a token type id for the standard
# operators, parens and common true or false symbols, as used in the
# default tokenizer implementation.
TOKENS = {
'*': TOKEN_AND, '&': TOKEN_AND, 'and': TOKEN_AND,
'+': TOKEN_OR, '|': TOKEN_OR, 'or': TOKEN_OR,
'~': TOKEN_NOT, '!': TOKEN_NOT, 'not': TOKEN_NOT,
'(': TOKEN_LPAR, ')': TOKEN_RPAR,
'[': TOKEN_LPAR, ']': TOKEN_RPAR,
'true': TOKEN_TRUE, '1': TOKEN_TRUE,
'false': TOKEN_FALSE, '0': TOKEN_FALSE, 'none': TOKEN_FALSE
}
position = 0
length = len(expr)
while position < length:
tok = expr[position]
sym = tok.isalpha() or tok == '_'
if sym:
position += 1
while position < length:
char = expr[position]
if char.isalnum() or char in ('.', ':', '_'):
position += 1
tok += char
else:
break
position -= 1
try:
yield TOKENS[tok.lower()], tok, position
except KeyError:
if sym:
yield TOKEN_SYMBOL, tok, position
elif tok not in (' ', '\t', '\r', '\n'):
raise ParseError(token_string=tok, position=position,
error_code=PARSE_UNKNOWN_TOKEN)
position += 1 | Return an iterable of 3-tuple describing each token given an expression
unicode string.
This 3-tuple contains (token, token string, position):
- token: either a Symbol instance or one of TOKEN_* token types.
- token string: the original token unicode string.
- position: some simple object describing the starting position of the
original token string in the `expr` string. It can be an int for a
character offset, or a tuple of starting (row/line, column).
The token position is used only for error reporting and can be None or
empty.
Raise ParseError on errors. The ParseError.args is a tuple of:
(token_string, position, error message)
You can use this tokenizer as a base to create specialized tokenizers
for your custom algebra by subclassing BooleanAlgebra. See also the
tests for other examples of alternative tokenizers.
This tokenizer has these characteristics:
- The `expr` string can span multiple lines,
- Whitespace is not significant.
- The returned position is the starting character offset of a token.
- A TOKEN_SYMBOL is returned for valid identifiers which is a string
without spaces. These are valid identifiers:
- Python identifiers.
- a string even if starting with digits
- digits (except for 0 and 1).
- dotted names : foo.bar consist of one token.
- names with colons: foo:bar consist of one token.
These are not identifiers:
- quoted strings.
- any punctuation which is not an operation
- Recognized operators are (in any upper/lower case combinations):
- for and: '*', '&', 'and'
- for or: '+', '|', 'or'
- for not: '~', '!', 'not'
- Recognized special symbols are (in any upper/lower case combinations):
- True symbols: 1 and True
- False symbols: 0, False and None | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L390-L480 | null | class BooleanAlgebra(object):
"""
An algebra is defined by:
- the types of its operations and Symbol.
- the tokenizer used when parsing expressions from strings.
This class also serves as a base class for all boolean expressions,
including base elements, functions and variable symbols.
"""
def __init__(self, TRUE_class=None, FALSE_class=None, Symbol_class=None,
NOT_class=None, AND_class=None, OR_class=None):
"""
The types for TRUE, FALSE, NOT, AND, OR and Symbol define the boolean
algebra elements, operations and Symbol variable. They default to the
standard classes if not provided.
You can customize an algebra by providing alternative subclasses of the
standard types.
"""
# TRUE and FALSE base elements are algebra-level "singleton" instances
self.TRUE = TRUE_class or _TRUE
self.TRUE = self.TRUE()
self.FALSE = FALSE_class or _FALSE
self.FALSE = self.FALSE()
# they cross-reference each other
self.TRUE.dual = self.FALSE
self.FALSE.dual = self.TRUE
# boolean operation types, defaulting to the standard types
self.NOT = NOT_class or NOT
self.AND = AND_class or AND
self.OR = OR_class or OR
# class used for Symbols
self.Symbol = Symbol_class or Symbol
tf_nao = {
'TRUE': self.TRUE,
'FALSE': self.FALSE,
'NOT': self.NOT,
'AND': self.AND,
'OR': self.OR,
'Symbol': self.Symbol
}
# setup cross references such that all algebra types and
# objects hold a named attribute for every other types and
# objects, including themselves.
for obj in tf_nao.values():
for name, value in tf_nao.items():
setattr(obj, name, value)
def definition(self):
"""
Return a tuple of this algebra defined elements and types as:
(TRUE, FALSE, NOT, AND, OR, Symbol)
"""
return self.TRUE, self.FALSE, self.NOT, self.AND, self.OR, self.Symbol
def symbols(self, *args):
"""
Return a tuple of symbols building a new Symbol from each argument.
"""
return tuple(map(self.Symbol, args))
def parse(self, expr, simplify=False):
"""
Return a boolean expression parsed from `expr` either a unicode string
or tokens iterable.
Optionally simplify the expression if `simplify` is True.
Raise ParseError on errors.
If `expr` is a string, the standard `tokenizer` is used for tokenization
and the algebra configured Symbol type is used to create Symbol
instances from Symbol tokens.
If `expr` is an iterable, it should contain 3-tuples of: (token_type,
token_string, token_position). In this case, the `token_type` can be
a Symbol instance or one of the TOKEN_* constant types.
See the `tokenize()` method for detailed specification.
"""
precedence = {self.NOT: 5, self.AND: 10, self.OR: 15, TOKEN_LPAR: 20}
if isinstance(expr, basestring):
tokenized = self.tokenize(expr)
else:
tokenized = iter(expr)
if TRACE_PARSE:
tokenized = list(tokenized)
print('tokens:')
map(print, tokenized)
tokenized = iter(tokenized)
# the abstract syntax tree for this expression that will be build as we
# process tokens
# the first two items are None
# symbol items are appended to this structure
ast = [None, None]
def is_sym(_t):
return isinstance(_t, Symbol) or _t in (TOKEN_TRUE, TOKEN_FALSE, TOKEN_SYMBOL)
def is_operator(_t):
return _t in (TOKEN_AND, TOKEN_OR)
prev_token = None
for token_type, token_string, token_position in tokenized:
if TRACE_PARSE:
print('\nprocessing token_type:', repr(token_type), 'token_string:', repr(token_string), 'token_position:', repr(token_position))
if prev_token:
prev_token_type, _prev_token_string, _prev_token_position = prev_token
if TRACE_PARSE:
print(' prev_token:', repr(prev_token))
if is_sym(prev_token_type) and (is_sym(token_type)): # or token_type == TOKEN_LPAR) :
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_SYMBOL_SEQUENCE)
if is_operator(prev_token_type) and (is_operator(token_type) or token_type == TOKEN_RPAR):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
else:
if is_operator(token_type):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
if token_type == TOKEN_SYMBOL:
ast.append(self.Symbol(token_string))
if TRACE_PARSE:
print(' ast: token_type is TOKEN_SYMBOL: append new symbol', repr(ast))
elif isinstance(token_type, Symbol):
ast.append(token_type)
if TRACE_PARSE:
print(' ast: token_type is Symbol): append existing symbol', repr(ast))
elif token_type == TOKEN_TRUE:
ast.append(self.TRUE)
if TRACE_PARSE: print(' ast: token_type is TOKEN_TRUE:', repr(ast))
elif token_type == TOKEN_FALSE:
ast.append(self.FALSE)
if TRACE_PARSE: print(' ast: token_type is TOKEN_FALSE:', repr(ast))
elif token_type == TOKEN_NOT:
ast = [ast, self.NOT]
if TRACE_PARSE: print(' ast: token_type is TOKEN_NOT:', repr(ast))
elif token_type == TOKEN_AND:
# if not prev_token or not is_sym(prev_token_type):
# raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
ast = self._start_operation(ast, self.AND, precedence)
if TRACE_PARSE:
print(' ast:token_type is TOKEN_AND: start_operation', ast)
elif token_type == TOKEN_OR:
# if not prev_token or not is_sym(prev_token_type):
# raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
ast = self._start_operation(ast, self.OR, precedence)
if TRACE_PARSE:
print(' ast:token_type is TOKEN_OR: start_operation', ast)
elif token_type == TOKEN_LPAR:
if prev_token:
# Check that an opening parens is preceded by a function
# or an opening parens
if prev_token_type not in (TOKEN_NOT, TOKEN_AND, TOKEN_OR, TOKEN_LPAR):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_NESTING)
ast = [ast, TOKEN_LPAR]
elif token_type == TOKEN_RPAR:
while True:
if ast[0] is None:
raise ParseError(token_type, token_string, token_position, PARSE_UNBALANCED_CLOSING_PARENS)
if ast[1] is TOKEN_LPAR:
ast[0].append(ast[2])
if TRACE_PARSE: print('ast9:', repr(ast))
ast = ast[0]
if TRACE_PARSE: print('ast10:', repr(ast))
break
if isinstance(ast[1], int):
raise ParseError(token_type, token_string, token_position, PARSE_UNBALANCED_CLOSING_PARENS)
# the parens are properly nested
# the top ast node should be a function subclass
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_NESTING)
subex = ast[1](*ast[2:])
ast[0].append(subex)
if TRACE_PARSE: print('ast11:', repr(ast))
ast = ast[0]
if TRACE_PARSE: print('ast12:', repr(ast))
else:
raise ParseError(token_type, token_string, token_position, PARSE_UNKNOWN_TOKEN)
prev_token = (token_type, token_string, token_position)
try:
while True:
if ast[0] is None:
if TRACE_PARSE: print('ast[0] is None:', repr(ast))
if ast[1] is None:
if TRACE_PARSE: print(' ast[1] is None:', repr(ast))
if len(ast) != 3:
raise ParseError(error_code=PARSE_INVALID_EXPRESSION)
parsed = ast[2]
if TRACE_PARSE: print(' parsed = ast[2]:', repr(parsed))
else:
# call the function in ast[1] with the rest of the ast as args
parsed = ast[1](*ast[2:])
if TRACE_PARSE: print(' parsed = ast[1](*ast[2:]):', repr(parsed))
break
else:
if TRACE_PARSE: print('subex = ast[1](*ast[2:]):', repr(ast))
subex = ast[1](*ast[2:])
ast[0].append(subex)
if TRACE_PARSE: print(' ast[0].append(subex):', repr(ast))
ast = ast[0]
if TRACE_PARSE: print(' ast = ast[0]:', repr(ast))
except TypeError:
raise ParseError(error_code=PARSE_INVALID_EXPRESSION)
if simplify:
return parsed.simplify()
if TRACE_PARSE: print('final parsed:', repr(parsed))
return parsed
def _start_operation(self, ast, operation, precedence):
"""
Returns an AST where all operations of lower precedence are finalized.
"""
if TRACE_PARSE:
print(' start_operation:', repr(operation), 'AST:', ast)
op_prec = precedence[operation]
while True:
if ast[1] is None:
# [None, None, x]
if TRACE_PARSE: print(' start_op: ast[1] is None:', repr(ast))
ast[1] = operation
if TRACE_PARSE: print(' --> start_op: ast[1] is None:', repr(ast))
return ast
prec = precedence[ast[1]]
if prec > op_prec: # op=&, [ast, |, x, y] -> [[ast, |, x], &, y]
if TRACE_PARSE: print(' start_op: prec > op_prec:', repr(ast))
ast = [ast, operation, ast.pop(-1)]
if TRACE_PARSE: print(' --> start_op: prec > op_prec:', repr(ast))
return ast
if prec == op_prec: # op=&, [ast, &, x] -> [ast, &, x]
if TRACE_PARSE: print(' start_op: prec == op_prec:', repr(ast))
return ast
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
# the top ast node should be a function subclass at this stage
raise ParseError(error_code=PARSE_INVALID_NESTING)
if ast[0] is None: # op=|, [None, &, x, y] -> [None, |, x&y]
if TRACE_PARSE: print(' start_op: ast[0] is None:', repr(ast))
subexp = ast[1](*ast[2:])
new_ast = [ast[0], operation, subexp]
if TRACE_PARSE: print(' --> start_op: ast[0] is None:', repr(new_ast))
return new_ast
else: # op=|, [[ast, &, x], ~, y] -> [ast, &, x, ~y]
if TRACE_PARSE: print(' start_op: else:', repr(ast))
ast[0].append(ast[1](*ast[2:]))
ast = ast[0]
if TRACE_PARSE: print(' --> start_op: else:', repr(ast))
# TODO: explain what this means exactly
def _rdistributive(self, expr, op_example):
"""
Recursively flatten the `expr` expression for the `op_example`
AND or OR operation instance exmaple.
"""
if expr.isliteral:
return expr
expr_class = expr.__class__
args = (self._rdistributive(arg, op_example) for arg in expr.args)
args = tuple(arg.simplify() for arg in args)
if len(args) == 1:
return args[0]
expr = expr_class(*args)
dualoperation = op_example.dual
if isinstance(expr, dualoperation):
expr = expr.distributive()
return expr
def normalize(self, expr, operation):
"""
Return a normalized expression transformed to its normal form in the
given AND or OR operation.
The new expression arguments will satisfy these conditions:
- operation(*args) == expr (here mathematical equality is meant)
- the operation does not occur in any of its arg.
- NOT is only appearing in literals (aka. Negation normal form).
The operation must be an AND or OR operation or a subclass.
"""
# ensure that the operation is not NOT
assert operation in (self.AND, self.OR,)
# Move NOT inwards.
expr = expr.literalize()
# Simplify first otherwise _rdistributive() may take forever.
expr = expr.simplify()
operation_example = operation(self.TRUE, self.FALSE)
expr = self._rdistributive(expr, operation_example)
# Canonicalize
expr = expr.simplify()
return expr
def cnf(self, expr):
"""
Return a conjunctive normal form of the `expr` expression.
"""
return self.normalize(expr, self.AND)
def dnf(self, expr):
"""
Return a disjunctive normal form of the `expr` expression.
"""
return self.normalize(expr, self.OR)
|
bastikr/boolean.py | boolean/boolean.py | BooleanAlgebra._rdistributive | python | def _rdistributive(self, expr, op_example):
if expr.isliteral:
return expr
expr_class = expr.__class__
args = (self._rdistributive(arg, op_example) for arg in expr.args)
args = tuple(arg.simplify() for arg in args)
if len(args) == 1:
return args[0]
expr = expr_class(*args)
dualoperation = op_example.dual
if isinstance(expr, dualoperation):
expr = expr.distributive()
return expr | Recursively flatten the `expr` expression for the `op_example`
AND or OR operation instance exmaple. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L483-L503 | null | class BooleanAlgebra(object):
"""
An algebra is defined by:
- the types of its operations and Symbol.
- the tokenizer used when parsing expressions from strings.
This class also serves as a base class for all boolean expressions,
including base elements, functions and variable symbols.
"""
def __init__(self, TRUE_class=None, FALSE_class=None, Symbol_class=None,
NOT_class=None, AND_class=None, OR_class=None):
"""
The types for TRUE, FALSE, NOT, AND, OR and Symbol define the boolean
algebra elements, operations and Symbol variable. They default to the
standard classes if not provided.
You can customize an algebra by providing alternative subclasses of the
standard types.
"""
# TRUE and FALSE base elements are algebra-level "singleton" instances
self.TRUE = TRUE_class or _TRUE
self.TRUE = self.TRUE()
self.FALSE = FALSE_class or _FALSE
self.FALSE = self.FALSE()
# they cross-reference each other
self.TRUE.dual = self.FALSE
self.FALSE.dual = self.TRUE
# boolean operation types, defaulting to the standard types
self.NOT = NOT_class or NOT
self.AND = AND_class or AND
self.OR = OR_class or OR
# class used for Symbols
self.Symbol = Symbol_class or Symbol
tf_nao = {
'TRUE': self.TRUE,
'FALSE': self.FALSE,
'NOT': self.NOT,
'AND': self.AND,
'OR': self.OR,
'Symbol': self.Symbol
}
# setup cross references such that all algebra types and
# objects hold a named attribute for every other types and
# objects, including themselves.
for obj in tf_nao.values():
for name, value in tf_nao.items():
setattr(obj, name, value)
def definition(self):
"""
Return a tuple of this algebra defined elements and types as:
(TRUE, FALSE, NOT, AND, OR, Symbol)
"""
return self.TRUE, self.FALSE, self.NOT, self.AND, self.OR, self.Symbol
def symbols(self, *args):
"""
Return a tuple of symbols building a new Symbol from each argument.
"""
return tuple(map(self.Symbol, args))
def parse(self, expr, simplify=False):
"""
Return a boolean expression parsed from `expr` either a unicode string
or tokens iterable.
Optionally simplify the expression if `simplify` is True.
Raise ParseError on errors.
If `expr` is a string, the standard `tokenizer` is used for tokenization
and the algebra configured Symbol type is used to create Symbol
instances from Symbol tokens.
If `expr` is an iterable, it should contain 3-tuples of: (token_type,
token_string, token_position). In this case, the `token_type` can be
a Symbol instance or one of the TOKEN_* constant types.
See the `tokenize()` method for detailed specification.
"""
precedence = {self.NOT: 5, self.AND: 10, self.OR: 15, TOKEN_LPAR: 20}
if isinstance(expr, basestring):
tokenized = self.tokenize(expr)
else:
tokenized = iter(expr)
if TRACE_PARSE:
tokenized = list(tokenized)
print('tokens:')
map(print, tokenized)
tokenized = iter(tokenized)
# the abstract syntax tree for this expression that will be build as we
# process tokens
# the first two items are None
# symbol items are appended to this structure
ast = [None, None]
def is_sym(_t):
return isinstance(_t, Symbol) or _t in (TOKEN_TRUE, TOKEN_FALSE, TOKEN_SYMBOL)
def is_operator(_t):
return _t in (TOKEN_AND, TOKEN_OR)
prev_token = None
for token_type, token_string, token_position in tokenized:
if TRACE_PARSE:
print('\nprocessing token_type:', repr(token_type), 'token_string:', repr(token_string), 'token_position:', repr(token_position))
if prev_token:
prev_token_type, _prev_token_string, _prev_token_position = prev_token
if TRACE_PARSE:
print(' prev_token:', repr(prev_token))
if is_sym(prev_token_type) and (is_sym(token_type)): # or token_type == TOKEN_LPAR) :
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_SYMBOL_SEQUENCE)
if is_operator(prev_token_type) and (is_operator(token_type) or token_type == TOKEN_RPAR):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
else:
if is_operator(token_type):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
if token_type == TOKEN_SYMBOL:
ast.append(self.Symbol(token_string))
if TRACE_PARSE:
print(' ast: token_type is TOKEN_SYMBOL: append new symbol', repr(ast))
elif isinstance(token_type, Symbol):
ast.append(token_type)
if TRACE_PARSE:
print(' ast: token_type is Symbol): append existing symbol', repr(ast))
elif token_type == TOKEN_TRUE:
ast.append(self.TRUE)
if TRACE_PARSE: print(' ast: token_type is TOKEN_TRUE:', repr(ast))
elif token_type == TOKEN_FALSE:
ast.append(self.FALSE)
if TRACE_PARSE: print(' ast: token_type is TOKEN_FALSE:', repr(ast))
elif token_type == TOKEN_NOT:
ast = [ast, self.NOT]
if TRACE_PARSE: print(' ast: token_type is TOKEN_NOT:', repr(ast))
elif token_type == TOKEN_AND:
# if not prev_token or not is_sym(prev_token_type):
# raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
ast = self._start_operation(ast, self.AND, precedence)
if TRACE_PARSE:
print(' ast:token_type is TOKEN_AND: start_operation', ast)
elif token_type == TOKEN_OR:
# if not prev_token or not is_sym(prev_token_type):
# raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
ast = self._start_operation(ast, self.OR, precedence)
if TRACE_PARSE:
print(' ast:token_type is TOKEN_OR: start_operation', ast)
elif token_type == TOKEN_LPAR:
if prev_token:
# Check that an opening parens is preceded by a function
# or an opening parens
if prev_token_type not in (TOKEN_NOT, TOKEN_AND, TOKEN_OR, TOKEN_LPAR):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_NESTING)
ast = [ast, TOKEN_LPAR]
elif token_type == TOKEN_RPAR:
while True:
if ast[0] is None:
raise ParseError(token_type, token_string, token_position, PARSE_UNBALANCED_CLOSING_PARENS)
if ast[1] is TOKEN_LPAR:
ast[0].append(ast[2])
if TRACE_PARSE: print('ast9:', repr(ast))
ast = ast[0]
if TRACE_PARSE: print('ast10:', repr(ast))
break
if isinstance(ast[1], int):
raise ParseError(token_type, token_string, token_position, PARSE_UNBALANCED_CLOSING_PARENS)
# the parens are properly nested
# the top ast node should be a function subclass
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_NESTING)
subex = ast[1](*ast[2:])
ast[0].append(subex)
if TRACE_PARSE: print('ast11:', repr(ast))
ast = ast[0]
if TRACE_PARSE: print('ast12:', repr(ast))
else:
raise ParseError(token_type, token_string, token_position, PARSE_UNKNOWN_TOKEN)
prev_token = (token_type, token_string, token_position)
try:
while True:
if ast[0] is None:
if TRACE_PARSE: print('ast[0] is None:', repr(ast))
if ast[1] is None:
if TRACE_PARSE: print(' ast[1] is None:', repr(ast))
if len(ast) != 3:
raise ParseError(error_code=PARSE_INVALID_EXPRESSION)
parsed = ast[2]
if TRACE_PARSE: print(' parsed = ast[2]:', repr(parsed))
else:
# call the function in ast[1] with the rest of the ast as args
parsed = ast[1](*ast[2:])
if TRACE_PARSE: print(' parsed = ast[1](*ast[2:]):', repr(parsed))
break
else:
if TRACE_PARSE: print('subex = ast[1](*ast[2:]):', repr(ast))
subex = ast[1](*ast[2:])
ast[0].append(subex)
if TRACE_PARSE: print(' ast[0].append(subex):', repr(ast))
ast = ast[0]
if TRACE_PARSE: print(' ast = ast[0]:', repr(ast))
except TypeError:
raise ParseError(error_code=PARSE_INVALID_EXPRESSION)
if simplify:
return parsed.simplify()
if TRACE_PARSE: print('final parsed:', repr(parsed))
return parsed
def _start_operation(self, ast, operation, precedence):
"""
Returns an AST where all operations of lower precedence are finalized.
"""
if TRACE_PARSE:
print(' start_operation:', repr(operation), 'AST:', ast)
op_prec = precedence[operation]
while True:
if ast[1] is None:
# [None, None, x]
if TRACE_PARSE: print(' start_op: ast[1] is None:', repr(ast))
ast[1] = operation
if TRACE_PARSE: print(' --> start_op: ast[1] is None:', repr(ast))
return ast
prec = precedence[ast[1]]
if prec > op_prec: # op=&, [ast, |, x, y] -> [[ast, |, x], &, y]
if TRACE_PARSE: print(' start_op: prec > op_prec:', repr(ast))
ast = [ast, operation, ast.pop(-1)]
if TRACE_PARSE: print(' --> start_op: prec > op_prec:', repr(ast))
return ast
if prec == op_prec: # op=&, [ast, &, x] -> [ast, &, x]
if TRACE_PARSE: print(' start_op: prec == op_prec:', repr(ast))
return ast
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
# the top ast node should be a function subclass at this stage
raise ParseError(error_code=PARSE_INVALID_NESTING)
if ast[0] is None: # op=|, [None, &, x, y] -> [None, |, x&y]
if TRACE_PARSE: print(' start_op: ast[0] is None:', repr(ast))
subexp = ast[1](*ast[2:])
new_ast = [ast[0], operation, subexp]
if TRACE_PARSE: print(' --> start_op: ast[0] is None:', repr(new_ast))
return new_ast
else: # op=|, [[ast, &, x], ~, y] -> [ast, &, x, ~y]
if TRACE_PARSE: print(' start_op: else:', repr(ast))
ast[0].append(ast[1](*ast[2:]))
ast = ast[0]
if TRACE_PARSE: print(' --> start_op: else:', repr(ast))
def tokenize(self, expr):
"""
Return an iterable of 3-tuple describing each token given an expression
unicode string.
This 3-tuple contains (token, token string, position):
- token: either a Symbol instance or one of TOKEN_* token types.
- token string: the original token unicode string.
- position: some simple object describing the starting position of the
original token string in the `expr` string. It can be an int for a
character offset, or a tuple of starting (row/line, column).
The token position is used only for error reporting and can be None or
empty.
Raise ParseError on errors. The ParseError.args is a tuple of:
(token_string, position, error message)
You can use this tokenizer as a base to create specialized tokenizers
for your custom algebra by subclassing BooleanAlgebra. See also the
tests for other examples of alternative tokenizers.
This tokenizer has these characteristics:
- The `expr` string can span multiple lines,
- Whitespace is not significant.
- The returned position is the starting character offset of a token.
- A TOKEN_SYMBOL is returned for valid identifiers which is a string
without spaces. These are valid identifiers:
- Python identifiers.
- a string even if starting with digits
- digits (except for 0 and 1).
- dotted names : foo.bar consist of one token.
- names with colons: foo:bar consist of one token.
These are not identifiers:
- quoted strings.
- any punctuation which is not an operation
- Recognized operators are (in any upper/lower case combinations):
- for and: '*', '&', 'and'
- for or: '+', '|', 'or'
- for not: '~', '!', 'not'
- Recognized special symbols are (in any upper/lower case combinations):
- True symbols: 1 and True
- False symbols: 0, False and None
"""
if not isinstance(expr, basestring):
raise TypeError('expr must be string but it is %s.' % type(expr))
# mapping of lowercase token strings to a token type id for the standard
# operators, parens and common true or false symbols, as used in the
# default tokenizer implementation.
TOKENS = {
'*': TOKEN_AND, '&': TOKEN_AND, 'and': TOKEN_AND,
'+': TOKEN_OR, '|': TOKEN_OR, 'or': TOKEN_OR,
'~': TOKEN_NOT, '!': TOKEN_NOT, 'not': TOKEN_NOT,
'(': TOKEN_LPAR, ')': TOKEN_RPAR,
'[': TOKEN_LPAR, ']': TOKEN_RPAR,
'true': TOKEN_TRUE, '1': TOKEN_TRUE,
'false': TOKEN_FALSE, '0': TOKEN_FALSE, 'none': TOKEN_FALSE
}
position = 0
length = len(expr)
while position < length:
tok = expr[position]
sym = tok.isalpha() or tok == '_'
if sym:
position += 1
while position < length:
char = expr[position]
if char.isalnum() or char in ('.', ':', '_'):
position += 1
tok += char
else:
break
position -= 1
try:
yield TOKENS[tok.lower()], tok, position
except KeyError:
if sym:
yield TOKEN_SYMBOL, tok, position
elif tok not in (' ', '\t', '\r', '\n'):
raise ParseError(token_string=tok, position=position,
error_code=PARSE_UNKNOWN_TOKEN)
position += 1
# TODO: explain what this means exactly
def normalize(self, expr, operation):
"""
Return a normalized expression transformed to its normal form in the
given AND or OR operation.
The new expression arguments will satisfy these conditions:
- operation(*args) == expr (here mathematical equality is meant)
- the operation does not occur in any of its arg.
- NOT is only appearing in literals (aka. Negation normal form).
The operation must be an AND or OR operation or a subclass.
"""
# ensure that the operation is not NOT
assert operation in (self.AND, self.OR,)
# Move NOT inwards.
expr = expr.literalize()
# Simplify first otherwise _rdistributive() may take forever.
expr = expr.simplify()
operation_example = operation(self.TRUE, self.FALSE)
expr = self._rdistributive(expr, operation_example)
# Canonicalize
expr = expr.simplify()
return expr
def cnf(self, expr):
"""
Return a conjunctive normal form of the `expr` expression.
"""
return self.normalize(expr, self.AND)
def dnf(self, expr):
"""
Return a disjunctive normal form of the `expr` expression.
"""
return self.normalize(expr, self.OR)
|
bastikr/boolean.py | boolean/boolean.py | BooleanAlgebra.normalize | python | def normalize(self, expr, operation):
# ensure that the operation is not NOT
assert operation in (self.AND, self.OR,)
# Move NOT inwards.
expr = expr.literalize()
# Simplify first otherwise _rdistributive() may take forever.
expr = expr.simplify()
operation_example = operation(self.TRUE, self.FALSE)
expr = self._rdistributive(expr, operation_example)
# Canonicalize
expr = expr.simplify()
return expr | Return a normalized expression transformed to its normal form in the
given AND or OR operation.
The new expression arguments will satisfy these conditions:
- operation(*args) == expr (here mathematical equality is meant)
- the operation does not occur in any of its arg.
- NOT is only appearing in literals (aka. Negation normal form).
The operation must be an AND or OR operation or a subclass. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L505-L527 | null | class BooleanAlgebra(object):
"""
An algebra is defined by:
- the types of its operations and Symbol.
- the tokenizer used when parsing expressions from strings.
This class also serves as a base class for all boolean expressions,
including base elements, functions and variable symbols.
"""
def __init__(self, TRUE_class=None, FALSE_class=None, Symbol_class=None,
NOT_class=None, AND_class=None, OR_class=None):
"""
The types for TRUE, FALSE, NOT, AND, OR and Symbol define the boolean
algebra elements, operations and Symbol variable. They default to the
standard classes if not provided.
You can customize an algebra by providing alternative subclasses of the
standard types.
"""
# TRUE and FALSE base elements are algebra-level "singleton" instances
self.TRUE = TRUE_class or _TRUE
self.TRUE = self.TRUE()
self.FALSE = FALSE_class or _FALSE
self.FALSE = self.FALSE()
# they cross-reference each other
self.TRUE.dual = self.FALSE
self.FALSE.dual = self.TRUE
# boolean operation types, defaulting to the standard types
self.NOT = NOT_class or NOT
self.AND = AND_class or AND
self.OR = OR_class or OR
# class used for Symbols
self.Symbol = Symbol_class or Symbol
tf_nao = {
'TRUE': self.TRUE,
'FALSE': self.FALSE,
'NOT': self.NOT,
'AND': self.AND,
'OR': self.OR,
'Symbol': self.Symbol
}
# setup cross references such that all algebra types and
# objects hold a named attribute for every other types and
# objects, including themselves.
for obj in tf_nao.values():
for name, value in tf_nao.items():
setattr(obj, name, value)
def definition(self):
"""
Return a tuple of this algebra defined elements and types as:
(TRUE, FALSE, NOT, AND, OR, Symbol)
"""
return self.TRUE, self.FALSE, self.NOT, self.AND, self.OR, self.Symbol
def symbols(self, *args):
"""
Return a tuple of symbols building a new Symbol from each argument.
"""
return tuple(map(self.Symbol, args))
def parse(self, expr, simplify=False):
"""
Return a boolean expression parsed from `expr` either a unicode string
or tokens iterable.
Optionally simplify the expression if `simplify` is True.
Raise ParseError on errors.
If `expr` is a string, the standard `tokenizer` is used for tokenization
and the algebra configured Symbol type is used to create Symbol
instances from Symbol tokens.
If `expr` is an iterable, it should contain 3-tuples of: (token_type,
token_string, token_position). In this case, the `token_type` can be
a Symbol instance or one of the TOKEN_* constant types.
See the `tokenize()` method for detailed specification.
"""
precedence = {self.NOT: 5, self.AND: 10, self.OR: 15, TOKEN_LPAR: 20}
if isinstance(expr, basestring):
tokenized = self.tokenize(expr)
else:
tokenized = iter(expr)
if TRACE_PARSE:
tokenized = list(tokenized)
print('tokens:')
map(print, tokenized)
tokenized = iter(tokenized)
# the abstract syntax tree for this expression that will be build as we
# process tokens
# the first two items are None
# symbol items are appended to this structure
ast = [None, None]
def is_sym(_t):
return isinstance(_t, Symbol) or _t in (TOKEN_TRUE, TOKEN_FALSE, TOKEN_SYMBOL)
def is_operator(_t):
return _t in (TOKEN_AND, TOKEN_OR)
prev_token = None
for token_type, token_string, token_position in tokenized:
if TRACE_PARSE:
print('\nprocessing token_type:', repr(token_type), 'token_string:', repr(token_string), 'token_position:', repr(token_position))
if prev_token:
prev_token_type, _prev_token_string, _prev_token_position = prev_token
if TRACE_PARSE:
print(' prev_token:', repr(prev_token))
if is_sym(prev_token_type) and (is_sym(token_type)): # or token_type == TOKEN_LPAR) :
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_SYMBOL_SEQUENCE)
if is_operator(prev_token_type) and (is_operator(token_type) or token_type == TOKEN_RPAR):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
else:
if is_operator(token_type):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
if token_type == TOKEN_SYMBOL:
ast.append(self.Symbol(token_string))
if TRACE_PARSE:
print(' ast: token_type is TOKEN_SYMBOL: append new symbol', repr(ast))
elif isinstance(token_type, Symbol):
ast.append(token_type)
if TRACE_PARSE:
print(' ast: token_type is Symbol): append existing symbol', repr(ast))
elif token_type == TOKEN_TRUE:
ast.append(self.TRUE)
if TRACE_PARSE: print(' ast: token_type is TOKEN_TRUE:', repr(ast))
elif token_type == TOKEN_FALSE:
ast.append(self.FALSE)
if TRACE_PARSE: print(' ast: token_type is TOKEN_FALSE:', repr(ast))
elif token_type == TOKEN_NOT:
ast = [ast, self.NOT]
if TRACE_PARSE: print(' ast: token_type is TOKEN_NOT:', repr(ast))
elif token_type == TOKEN_AND:
# if not prev_token or not is_sym(prev_token_type):
# raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
ast = self._start_operation(ast, self.AND, precedence)
if TRACE_PARSE:
print(' ast:token_type is TOKEN_AND: start_operation', ast)
elif token_type == TOKEN_OR:
# if not prev_token or not is_sym(prev_token_type):
# raise ParseError(token_type, token_string, token_position, PARSE_INVALID_OPERATOR_SEQUENCE)
ast = self._start_operation(ast, self.OR, precedence)
if TRACE_PARSE:
print(' ast:token_type is TOKEN_OR: start_operation', ast)
elif token_type == TOKEN_LPAR:
if prev_token:
# Check that an opening parens is preceded by a function
# or an opening parens
if prev_token_type not in (TOKEN_NOT, TOKEN_AND, TOKEN_OR, TOKEN_LPAR):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_NESTING)
ast = [ast, TOKEN_LPAR]
elif token_type == TOKEN_RPAR:
while True:
if ast[0] is None:
raise ParseError(token_type, token_string, token_position, PARSE_UNBALANCED_CLOSING_PARENS)
if ast[1] is TOKEN_LPAR:
ast[0].append(ast[2])
if TRACE_PARSE: print('ast9:', repr(ast))
ast = ast[0]
if TRACE_PARSE: print('ast10:', repr(ast))
break
if isinstance(ast[1], int):
raise ParseError(token_type, token_string, token_position, PARSE_UNBALANCED_CLOSING_PARENS)
# the parens are properly nested
# the top ast node should be a function subclass
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
raise ParseError(token_type, token_string, token_position, PARSE_INVALID_NESTING)
subex = ast[1](*ast[2:])
ast[0].append(subex)
if TRACE_PARSE: print('ast11:', repr(ast))
ast = ast[0]
if TRACE_PARSE: print('ast12:', repr(ast))
else:
raise ParseError(token_type, token_string, token_position, PARSE_UNKNOWN_TOKEN)
prev_token = (token_type, token_string, token_position)
try:
while True:
if ast[0] is None:
if TRACE_PARSE: print('ast[0] is None:', repr(ast))
if ast[1] is None:
if TRACE_PARSE: print(' ast[1] is None:', repr(ast))
if len(ast) != 3:
raise ParseError(error_code=PARSE_INVALID_EXPRESSION)
parsed = ast[2]
if TRACE_PARSE: print(' parsed = ast[2]:', repr(parsed))
else:
# call the function in ast[1] with the rest of the ast as args
parsed = ast[1](*ast[2:])
if TRACE_PARSE: print(' parsed = ast[1](*ast[2:]):', repr(parsed))
break
else:
if TRACE_PARSE: print('subex = ast[1](*ast[2:]):', repr(ast))
subex = ast[1](*ast[2:])
ast[0].append(subex)
if TRACE_PARSE: print(' ast[0].append(subex):', repr(ast))
ast = ast[0]
if TRACE_PARSE: print(' ast = ast[0]:', repr(ast))
except TypeError:
raise ParseError(error_code=PARSE_INVALID_EXPRESSION)
if simplify:
return parsed.simplify()
if TRACE_PARSE: print('final parsed:', repr(parsed))
return parsed
def _start_operation(self, ast, operation, precedence):
"""
Returns an AST where all operations of lower precedence are finalized.
"""
if TRACE_PARSE:
print(' start_operation:', repr(operation), 'AST:', ast)
op_prec = precedence[operation]
while True:
if ast[1] is None:
# [None, None, x]
if TRACE_PARSE: print(' start_op: ast[1] is None:', repr(ast))
ast[1] = operation
if TRACE_PARSE: print(' --> start_op: ast[1] is None:', repr(ast))
return ast
prec = precedence[ast[1]]
if prec > op_prec: # op=&, [ast, |, x, y] -> [[ast, |, x], &, y]
if TRACE_PARSE: print(' start_op: prec > op_prec:', repr(ast))
ast = [ast, operation, ast.pop(-1)]
if TRACE_PARSE: print(' --> start_op: prec > op_prec:', repr(ast))
return ast
if prec == op_prec: # op=&, [ast, &, x] -> [ast, &, x]
if TRACE_PARSE: print(' start_op: prec == op_prec:', repr(ast))
return ast
if not (inspect.isclass(ast[1]) and issubclass(ast[1], Function)):
# the top ast node should be a function subclass at this stage
raise ParseError(error_code=PARSE_INVALID_NESTING)
if ast[0] is None: # op=|, [None, &, x, y] -> [None, |, x&y]
if TRACE_PARSE: print(' start_op: ast[0] is None:', repr(ast))
subexp = ast[1](*ast[2:])
new_ast = [ast[0], operation, subexp]
if TRACE_PARSE: print(' --> start_op: ast[0] is None:', repr(new_ast))
return new_ast
else: # op=|, [[ast, &, x], ~, y] -> [ast, &, x, ~y]
if TRACE_PARSE: print(' start_op: else:', repr(ast))
ast[0].append(ast[1](*ast[2:]))
ast = ast[0]
if TRACE_PARSE: print(' --> start_op: else:', repr(ast))
def tokenize(self, expr):
"""
Return an iterable of 3-tuple describing each token given an expression
unicode string.
This 3-tuple contains (token, token string, position):
- token: either a Symbol instance or one of TOKEN_* token types.
- token string: the original token unicode string.
- position: some simple object describing the starting position of the
original token string in the `expr` string. It can be an int for a
character offset, or a tuple of starting (row/line, column).
The token position is used only for error reporting and can be None or
empty.
Raise ParseError on errors. The ParseError.args is a tuple of:
(token_string, position, error message)
You can use this tokenizer as a base to create specialized tokenizers
for your custom algebra by subclassing BooleanAlgebra. See also the
tests for other examples of alternative tokenizers.
This tokenizer has these characteristics:
- The `expr` string can span multiple lines,
- Whitespace is not significant.
- The returned position is the starting character offset of a token.
- A TOKEN_SYMBOL is returned for valid identifiers which is a string
without spaces. These are valid identifiers:
- Python identifiers.
- a string even if starting with digits
- digits (except for 0 and 1).
- dotted names : foo.bar consist of one token.
- names with colons: foo:bar consist of one token.
These are not identifiers:
- quoted strings.
- any punctuation which is not an operation
- Recognized operators are (in any upper/lower case combinations):
- for and: '*', '&', 'and'
- for or: '+', '|', 'or'
- for not: '~', '!', 'not'
- Recognized special symbols are (in any upper/lower case combinations):
- True symbols: 1 and True
- False symbols: 0, False and None
"""
if not isinstance(expr, basestring):
raise TypeError('expr must be string but it is %s.' % type(expr))
# mapping of lowercase token strings to a token type id for the standard
# operators, parens and common true or false symbols, as used in the
# default tokenizer implementation.
TOKENS = {
'*': TOKEN_AND, '&': TOKEN_AND, 'and': TOKEN_AND,
'+': TOKEN_OR, '|': TOKEN_OR, 'or': TOKEN_OR,
'~': TOKEN_NOT, '!': TOKEN_NOT, 'not': TOKEN_NOT,
'(': TOKEN_LPAR, ')': TOKEN_RPAR,
'[': TOKEN_LPAR, ']': TOKEN_RPAR,
'true': TOKEN_TRUE, '1': TOKEN_TRUE,
'false': TOKEN_FALSE, '0': TOKEN_FALSE, 'none': TOKEN_FALSE
}
position = 0
length = len(expr)
while position < length:
tok = expr[position]
sym = tok.isalpha() or tok == '_'
if sym:
position += 1
while position < length:
char = expr[position]
if char.isalnum() or char in ('.', ':', '_'):
position += 1
tok += char
else:
break
position -= 1
try:
yield TOKENS[tok.lower()], tok, position
except KeyError:
if sym:
yield TOKEN_SYMBOL, tok, position
elif tok not in (' ', '\t', '\r', '\n'):
raise ParseError(token_string=tok, position=position,
error_code=PARSE_UNKNOWN_TOKEN)
position += 1
# TODO: explain what this means exactly
def _rdistributive(self, expr, op_example):
"""
Recursively flatten the `expr` expression for the `op_example`
AND or OR operation instance exmaple.
"""
if expr.isliteral:
return expr
expr_class = expr.__class__
args = (self._rdistributive(arg, op_example) for arg in expr.args)
args = tuple(arg.simplify() for arg in args)
if len(args) == 1:
return args[0]
expr = expr_class(*args)
dualoperation = op_example.dual
if isinstance(expr, dualoperation):
expr = expr.distributive()
return expr
def cnf(self, expr):
"""
Return a conjunctive normal form of the `expr` expression.
"""
return self.normalize(expr, self.AND)
def dnf(self, expr):
"""
Return a disjunctive normal form of the `expr` expression.
"""
return self.normalize(expr, self.OR)
|
bastikr/boolean.py | boolean/boolean.py | Expression.get_literals | python | def get_literals(self):
if self.isliteral:
return [self]
if not self.args:
return []
return list(itertools.chain.from_iterable(arg.get_literals() for arg in self.args)) | Return a list of all the literals contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L576-L586 | null | class Expression(object):
"""
Abstract base class for all boolean expressions, including functions and
variable symbols.
"""
# Defines sort and comparison order between expressions arguments
sort_order = None
# Store arguments aka. subterms of this expressions.
# subterms are either literals or expressions.
args = tuple()
# True is this is a literal expression such as a Symbol, TRUE or FALSE
isliteral = False
# True if this expression has been simplified to in canonical form.
iscanonical = False
# these class attributes are configured when a new BooleanAlgebra is created
TRUE = None
FALSE = None
NOT = None
AND = None
OR = None
Symbol = None
@property
def objects(self):
"""
Return a set of all associated objects with this expression symbols.
Include recursively subexpressions objects.
"""
return set(s.obj for s in self.symbols)
@property
def literals(self):
"""
Return a set of all literals contained in this expression.
Include recursively subexpressions literals.
"""
return set(self.get_literals())
def literalize(self):
"""
Return an expression where NOTs are only occurring as literals.
Applied recursively to subexpressions.
"""
if self.isliteral:
return self
args = tuple(arg.literalize() for arg in self.args)
if all(arg is self.args[i] for i, arg in enumerate(args)):
return self
return self.__class__(*args)
def get_symbols(self):
"""
Return a list of all the symbols contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
"""
return [s if isinstance(s, Symbol) else s.args[0] for s in self.get_literals()]
@property
def symbols(self,):
"""
Return a list of all the symbols contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
"""
return set(self.get_symbols())
def subs(self, substitutions, default=None, simplify=False):
"""
Return an expression where the expression or all subterms equal to a key
expression are substituted with the corresponding value expression using
a mapping of: {expr->expr to substitute.}
Return this expression unmodified if nothing could be substituted.
Note that this can be used to tested for expression containment.
"""
# shortcut: check if we have our whole expression as a possible
# subsitution source
for expr, substitution in substitutions.items():
if expr == self:
return substitution
# otherwise, do a proper substitution of sub expressions
expr = self._subs(substitutions, default, simplify)
return self if expr is None else expr
def _subs(self, substitutions, default, simplify):
"""
Return an expression where all subterms equal to a key expression are
substituted by the corresponding value expression using a mapping of:
{expr->expr to substitute.}
"""
# track the new list of unchanged args or replaced args through
# a substitution
new_arguments = []
changed_something = False
# shortcut for basic logic True or False
if self is self.TRUE or self is self.FALSE:
return self
# if the expression has no elements, e.g. is empty, do not apply
# substitions
if not self.args:
return default
# iterate the subexpressions: either plain symbols or a subexpressions
for arg in self.args:
# collect substitutions for exact matches
# break as soon as we have a match
for expr, substitution in substitutions.items():
if arg == expr:
new_arguments.append(substitution)
changed_something = True
break
# this will execute only if we did not break out of the
# loop, e.g. if we did not change anything and did not
# collect any substitutions
else:
# recursively call _subs on each arg to see if we get a
# substituted arg
new_arg = arg._subs(substitutions, default, simplify)
if new_arg is None:
# if we did not collect a substitution for this arg,
# keep the arg as-is, it is not replaced by anything
new_arguments.append(arg)
else:
# otherwise, we add the substitution for this arg instead
new_arguments.append(new_arg)
changed_something = True
if not changed_something:
return
# here we did some substitution: we return a new expression
# built from the new_arguments
newexpr = self.__class__(*new_arguments)
return newexpr.simplify() if simplify else newexpr
def simplify(self):
"""
Return a new simplified expression in canonical form built from this
expression. The simplified expression may be exactly the same as this
expression.
Subclasses override this method to compute actual simplification.
"""
return self
def __hash__(self):
"""
Expressions are immutable and hashable. The hash of Functions is
computed by respecting the structure of the whole expression by mixing
the class name hash and the recursive hash of a frozenset of arguments.
Hash of elements is based on their boolean equivalent. Hash of symbols
is based on their object.
"""
if not self.args:
arghash = id(self)
else:
arghash = hash(frozenset(map(hash, self.args)))
return hash(self.__class__.__name__) ^ arghash
def __eq__(self, other):
"""
Test if other element is structurally the same as itself.
This method does not make any simplification or transformation, so it
will return False although the expression terms may be mathematically
equal. Use simplify() before testing equality.
For literals, plain equality is used.
For functions, it uses the facts that operations are:
- commutative and considers different ordering as equal.
- idempotent, so args can appear more often in one term than in the other.
"""
if self is other:
return True
if isinstance(other, self.__class__):
return frozenset(self.args) == frozenset(other.args)
return NotImplemented
def __ne__(self, other):
return not self == other
def __lt__(self, other):
if self.sort_order is not None and other.sort_order is not None:
if self.sort_order == other.sort_order:
return NotImplemented
return self.sort_order < other.sort_order
return NotImplemented
def __gt__(self, other):
lt = other.__lt__(self)
if lt is NotImplemented:
return not self.__lt__(other)
return lt
def __and__(self, other):
return self.AND(self, other)
__mul__ = __and__
def __invert__(self):
return self.NOT(self)
def __or__(self, other):
return self.OR(self, other)
__add__ = __or__
def __bool__(self):
raise TypeError('Cannot evaluate expression as a Python Boolean.')
__nonzero__ = __bool__
|
bastikr/boolean.py | boolean/boolean.py | Expression.literalize | python | def literalize(self):
if self.isliteral:
return self
args = tuple(arg.literalize() for arg in self.args)
if all(arg is self.args[i] for i, arg in enumerate(args)):
return self
return self.__class__(*args) | Return an expression where NOTs are only occurring as literals.
Applied recursively to subexpressions. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L596-L607 | null | class Expression(object):
"""
Abstract base class for all boolean expressions, including functions and
variable symbols.
"""
# Defines sort and comparison order between expressions arguments
sort_order = None
# Store arguments aka. subterms of this expressions.
# subterms are either literals or expressions.
args = tuple()
# True is this is a literal expression such as a Symbol, TRUE or FALSE
isliteral = False
# True if this expression has been simplified to in canonical form.
iscanonical = False
# these class attributes are configured when a new BooleanAlgebra is created
TRUE = None
FALSE = None
NOT = None
AND = None
OR = None
Symbol = None
@property
def objects(self):
"""
Return a set of all associated objects with this expression symbols.
Include recursively subexpressions objects.
"""
return set(s.obj for s in self.symbols)
def get_literals(self):
"""
Return a list of all the literals contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
"""
if self.isliteral:
return [self]
if not self.args:
return []
return list(itertools.chain.from_iterable(arg.get_literals() for arg in self.args))
@property
def literals(self):
"""
Return a set of all literals contained in this expression.
Include recursively subexpressions literals.
"""
return set(self.get_literals())
def get_symbols(self):
"""
Return a list of all the symbols contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
"""
return [s if isinstance(s, Symbol) else s.args[0] for s in self.get_literals()]
@property
def symbols(self,):
"""
Return a list of all the symbols contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
"""
return set(self.get_symbols())
def subs(self, substitutions, default=None, simplify=False):
"""
Return an expression where the expression or all subterms equal to a key
expression are substituted with the corresponding value expression using
a mapping of: {expr->expr to substitute.}
Return this expression unmodified if nothing could be substituted.
Note that this can be used to tested for expression containment.
"""
# shortcut: check if we have our whole expression as a possible
# subsitution source
for expr, substitution in substitutions.items():
if expr == self:
return substitution
# otherwise, do a proper substitution of sub expressions
expr = self._subs(substitutions, default, simplify)
return self if expr is None else expr
def _subs(self, substitutions, default, simplify):
"""
Return an expression where all subterms equal to a key expression are
substituted by the corresponding value expression using a mapping of:
{expr->expr to substitute.}
"""
# track the new list of unchanged args or replaced args through
# a substitution
new_arguments = []
changed_something = False
# shortcut for basic logic True or False
if self is self.TRUE or self is self.FALSE:
return self
# if the expression has no elements, e.g. is empty, do not apply
# substitions
if not self.args:
return default
# iterate the subexpressions: either plain symbols or a subexpressions
for arg in self.args:
# collect substitutions for exact matches
# break as soon as we have a match
for expr, substitution in substitutions.items():
if arg == expr:
new_arguments.append(substitution)
changed_something = True
break
# this will execute only if we did not break out of the
# loop, e.g. if we did not change anything and did not
# collect any substitutions
else:
# recursively call _subs on each arg to see if we get a
# substituted arg
new_arg = arg._subs(substitutions, default, simplify)
if new_arg is None:
# if we did not collect a substitution for this arg,
# keep the arg as-is, it is not replaced by anything
new_arguments.append(arg)
else:
# otherwise, we add the substitution for this arg instead
new_arguments.append(new_arg)
changed_something = True
if not changed_something:
return
# here we did some substitution: we return a new expression
# built from the new_arguments
newexpr = self.__class__(*new_arguments)
return newexpr.simplify() if simplify else newexpr
def simplify(self):
"""
Return a new simplified expression in canonical form built from this
expression. The simplified expression may be exactly the same as this
expression.
Subclasses override this method to compute actual simplification.
"""
return self
def __hash__(self):
"""
Expressions are immutable and hashable. The hash of Functions is
computed by respecting the structure of the whole expression by mixing
the class name hash and the recursive hash of a frozenset of arguments.
Hash of elements is based on their boolean equivalent. Hash of symbols
is based on their object.
"""
if not self.args:
arghash = id(self)
else:
arghash = hash(frozenset(map(hash, self.args)))
return hash(self.__class__.__name__) ^ arghash
def __eq__(self, other):
"""
Test if other element is structurally the same as itself.
This method does not make any simplification or transformation, so it
will return False although the expression terms may be mathematically
equal. Use simplify() before testing equality.
For literals, plain equality is used.
For functions, it uses the facts that operations are:
- commutative and considers different ordering as equal.
- idempotent, so args can appear more often in one term than in the other.
"""
if self is other:
return True
if isinstance(other, self.__class__):
return frozenset(self.args) == frozenset(other.args)
return NotImplemented
def __ne__(self, other):
return not self == other
def __lt__(self, other):
if self.sort_order is not None and other.sort_order is not None:
if self.sort_order == other.sort_order:
return NotImplemented
return self.sort_order < other.sort_order
return NotImplemented
def __gt__(self, other):
lt = other.__lt__(self)
if lt is NotImplemented:
return not self.__lt__(other)
return lt
def __and__(self, other):
return self.AND(self, other)
__mul__ = __and__
def __invert__(self):
return self.NOT(self)
def __or__(self, other):
return self.OR(self, other)
__add__ = __or__
def __bool__(self):
raise TypeError('Cannot evaluate expression as a Python Boolean.')
__nonzero__ = __bool__
|
bastikr/boolean.py | boolean/boolean.py | Expression.get_symbols | python | def get_symbols(self):
return [s if isinstance(s, Symbol) else s.args[0] for s in self.get_literals()] | Return a list of all the symbols contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L609-L615 | [
"def get_literals(self):\n \"\"\"\n Return a list of all the literals contained in this expression.\n Include recursively subexpressions symbols.\n This includes duplicates.\n \"\"\"\n if self.isliteral:\n return [self]\n if not self.args:\n return []\n return list(itertools.ch... | class Expression(object):
"""
Abstract base class for all boolean expressions, including functions and
variable symbols.
"""
# Defines sort and comparison order between expressions arguments
sort_order = None
# Store arguments aka. subterms of this expressions.
# subterms are either literals or expressions.
args = tuple()
# True is this is a literal expression such as a Symbol, TRUE or FALSE
isliteral = False
# True if this expression has been simplified to in canonical form.
iscanonical = False
# these class attributes are configured when a new BooleanAlgebra is created
TRUE = None
FALSE = None
NOT = None
AND = None
OR = None
Symbol = None
@property
def objects(self):
"""
Return a set of all associated objects with this expression symbols.
Include recursively subexpressions objects.
"""
return set(s.obj for s in self.symbols)
def get_literals(self):
"""
Return a list of all the literals contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
"""
if self.isliteral:
return [self]
if not self.args:
return []
return list(itertools.chain.from_iterable(arg.get_literals() for arg in self.args))
@property
def literals(self):
"""
Return a set of all literals contained in this expression.
Include recursively subexpressions literals.
"""
return set(self.get_literals())
def literalize(self):
"""
Return an expression where NOTs are only occurring as literals.
Applied recursively to subexpressions.
"""
if self.isliteral:
return self
args = tuple(arg.literalize() for arg in self.args)
if all(arg is self.args[i] for i, arg in enumerate(args)):
return self
return self.__class__(*args)
@property
def symbols(self,):
"""
Return a list of all the symbols contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
"""
return set(self.get_symbols())
def subs(self, substitutions, default=None, simplify=False):
"""
Return an expression where the expression or all subterms equal to a key
expression are substituted with the corresponding value expression using
a mapping of: {expr->expr to substitute.}
Return this expression unmodified if nothing could be substituted.
Note that this can be used to tested for expression containment.
"""
# shortcut: check if we have our whole expression as a possible
# subsitution source
for expr, substitution in substitutions.items():
if expr == self:
return substitution
# otherwise, do a proper substitution of sub expressions
expr = self._subs(substitutions, default, simplify)
return self if expr is None else expr
def _subs(self, substitutions, default, simplify):
"""
Return an expression where all subterms equal to a key expression are
substituted by the corresponding value expression using a mapping of:
{expr->expr to substitute.}
"""
# track the new list of unchanged args or replaced args through
# a substitution
new_arguments = []
changed_something = False
# shortcut for basic logic True or False
if self is self.TRUE or self is self.FALSE:
return self
# if the expression has no elements, e.g. is empty, do not apply
# substitions
if not self.args:
return default
# iterate the subexpressions: either plain symbols or a subexpressions
for arg in self.args:
# collect substitutions for exact matches
# break as soon as we have a match
for expr, substitution in substitutions.items():
if arg == expr:
new_arguments.append(substitution)
changed_something = True
break
# this will execute only if we did not break out of the
# loop, e.g. if we did not change anything and did not
# collect any substitutions
else:
# recursively call _subs on each arg to see if we get a
# substituted arg
new_arg = arg._subs(substitutions, default, simplify)
if new_arg is None:
# if we did not collect a substitution for this arg,
# keep the arg as-is, it is not replaced by anything
new_arguments.append(arg)
else:
# otherwise, we add the substitution for this arg instead
new_arguments.append(new_arg)
changed_something = True
if not changed_something:
return
# here we did some substitution: we return a new expression
# built from the new_arguments
newexpr = self.__class__(*new_arguments)
return newexpr.simplify() if simplify else newexpr
def simplify(self):
"""
Return a new simplified expression in canonical form built from this
expression. The simplified expression may be exactly the same as this
expression.
Subclasses override this method to compute actual simplification.
"""
return self
def __hash__(self):
"""
Expressions are immutable and hashable. The hash of Functions is
computed by respecting the structure of the whole expression by mixing
the class name hash and the recursive hash of a frozenset of arguments.
Hash of elements is based on their boolean equivalent. Hash of symbols
is based on their object.
"""
if not self.args:
arghash = id(self)
else:
arghash = hash(frozenset(map(hash, self.args)))
return hash(self.__class__.__name__) ^ arghash
def __eq__(self, other):
"""
Test if other element is structurally the same as itself.
This method does not make any simplification or transformation, so it
will return False although the expression terms may be mathematically
equal. Use simplify() before testing equality.
For literals, plain equality is used.
For functions, it uses the facts that operations are:
- commutative and considers different ordering as equal.
- idempotent, so args can appear more often in one term than in the other.
"""
if self is other:
return True
if isinstance(other, self.__class__):
return frozenset(self.args) == frozenset(other.args)
return NotImplemented
def __ne__(self, other):
return not self == other
def __lt__(self, other):
if self.sort_order is not None and other.sort_order is not None:
if self.sort_order == other.sort_order:
return NotImplemented
return self.sort_order < other.sort_order
return NotImplemented
def __gt__(self, other):
lt = other.__lt__(self)
if lt is NotImplemented:
return not self.__lt__(other)
return lt
def __and__(self, other):
return self.AND(self, other)
__mul__ = __and__
def __invert__(self):
return self.NOT(self)
def __or__(self, other):
return self.OR(self, other)
__add__ = __or__
def __bool__(self):
raise TypeError('Cannot evaluate expression as a Python Boolean.')
__nonzero__ = __bool__
|
bastikr/boolean.py | boolean/boolean.py | Expression.subs | python | def subs(self, substitutions, default=None, simplify=False):
# shortcut: check if we have our whole expression as a possible
# subsitution source
for expr, substitution in substitutions.items():
if expr == self:
return substitution
# otherwise, do a proper substitution of sub expressions
expr = self._subs(substitutions, default, simplify)
return self if expr is None else expr | Return an expression where the expression or all subterms equal to a key
expression are substituted with the corresponding value expression using
a mapping of: {expr->expr to substitute.}
Return this expression unmodified if nothing could be substituted.
Note that this can be used to tested for expression containment. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L626-L644 | [
"def _subs(self, substitutions, default, simplify):\n \"\"\"\n Return an expression where all subterms equal to a key expression are\n substituted by the corresponding value expression using a mapping of:\n {expr->expr to substitute.}\n \"\"\"\n # track the new list of unchanged args or replaced a... | class Expression(object):
"""
Abstract base class for all boolean expressions, including functions and
variable symbols.
"""
# Defines sort and comparison order between expressions arguments
sort_order = None
# Store arguments aka. subterms of this expressions.
# subterms are either literals or expressions.
args = tuple()
# True is this is a literal expression such as a Symbol, TRUE or FALSE
isliteral = False
# True if this expression has been simplified to in canonical form.
iscanonical = False
# these class attributes are configured when a new BooleanAlgebra is created
TRUE = None
FALSE = None
NOT = None
AND = None
OR = None
Symbol = None
@property
def objects(self):
"""
Return a set of all associated objects with this expression symbols.
Include recursively subexpressions objects.
"""
return set(s.obj for s in self.symbols)
def get_literals(self):
"""
Return a list of all the literals contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
"""
if self.isliteral:
return [self]
if not self.args:
return []
return list(itertools.chain.from_iterable(arg.get_literals() for arg in self.args))
@property
def literals(self):
"""
Return a set of all literals contained in this expression.
Include recursively subexpressions literals.
"""
return set(self.get_literals())
def literalize(self):
"""
Return an expression where NOTs are only occurring as literals.
Applied recursively to subexpressions.
"""
if self.isliteral:
return self
args = tuple(arg.literalize() for arg in self.args)
if all(arg is self.args[i] for i, arg in enumerate(args)):
return self
return self.__class__(*args)
def get_symbols(self):
"""
Return a list of all the symbols contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
"""
return [s if isinstance(s, Symbol) else s.args[0] for s in self.get_literals()]
@property
def symbols(self,):
"""
Return a list of all the symbols contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
"""
return set(self.get_symbols())
def _subs(self, substitutions, default, simplify):
"""
Return an expression where all subterms equal to a key expression are
substituted by the corresponding value expression using a mapping of:
{expr->expr to substitute.}
"""
# track the new list of unchanged args or replaced args through
# a substitution
new_arguments = []
changed_something = False
# shortcut for basic logic True or False
if self is self.TRUE or self is self.FALSE:
return self
# if the expression has no elements, e.g. is empty, do not apply
# substitions
if not self.args:
return default
# iterate the subexpressions: either plain symbols or a subexpressions
for arg in self.args:
# collect substitutions for exact matches
# break as soon as we have a match
for expr, substitution in substitutions.items():
if arg == expr:
new_arguments.append(substitution)
changed_something = True
break
# this will execute only if we did not break out of the
# loop, e.g. if we did not change anything and did not
# collect any substitutions
else:
# recursively call _subs on each arg to see if we get a
# substituted arg
new_arg = arg._subs(substitutions, default, simplify)
if new_arg is None:
# if we did not collect a substitution for this arg,
# keep the arg as-is, it is not replaced by anything
new_arguments.append(arg)
else:
# otherwise, we add the substitution for this arg instead
new_arguments.append(new_arg)
changed_something = True
if not changed_something:
return
# here we did some substitution: we return a new expression
# built from the new_arguments
newexpr = self.__class__(*new_arguments)
return newexpr.simplify() if simplify else newexpr
def simplify(self):
"""
Return a new simplified expression in canonical form built from this
expression. The simplified expression may be exactly the same as this
expression.
Subclasses override this method to compute actual simplification.
"""
return self
def __hash__(self):
"""
Expressions are immutable and hashable. The hash of Functions is
computed by respecting the structure of the whole expression by mixing
the class name hash and the recursive hash of a frozenset of arguments.
Hash of elements is based on their boolean equivalent. Hash of symbols
is based on their object.
"""
if not self.args:
arghash = id(self)
else:
arghash = hash(frozenset(map(hash, self.args)))
return hash(self.__class__.__name__) ^ arghash
def __eq__(self, other):
"""
Test if other element is structurally the same as itself.
This method does not make any simplification or transformation, so it
will return False although the expression terms may be mathematically
equal. Use simplify() before testing equality.
For literals, plain equality is used.
For functions, it uses the facts that operations are:
- commutative and considers different ordering as equal.
- idempotent, so args can appear more often in one term than in the other.
"""
if self is other:
return True
if isinstance(other, self.__class__):
return frozenset(self.args) == frozenset(other.args)
return NotImplemented
def __ne__(self, other):
return not self == other
def __lt__(self, other):
if self.sort_order is not None and other.sort_order is not None:
if self.sort_order == other.sort_order:
return NotImplemented
return self.sort_order < other.sort_order
return NotImplemented
def __gt__(self, other):
lt = other.__lt__(self)
if lt is NotImplemented:
return not self.__lt__(other)
return lt
def __and__(self, other):
return self.AND(self, other)
__mul__ = __and__
def __invert__(self):
return self.NOT(self)
def __or__(self, other):
return self.OR(self, other)
__add__ = __or__
def __bool__(self):
raise TypeError('Cannot evaluate expression as a Python Boolean.')
__nonzero__ = __bool__
|
bastikr/boolean.py | boolean/boolean.py | Expression._subs | python | def _subs(self, substitutions, default, simplify):
# track the new list of unchanged args or replaced args through
# a substitution
new_arguments = []
changed_something = False
# shortcut for basic logic True or False
if self is self.TRUE or self is self.FALSE:
return self
# if the expression has no elements, e.g. is empty, do not apply
# substitions
if not self.args:
return default
# iterate the subexpressions: either plain symbols or a subexpressions
for arg in self.args:
# collect substitutions for exact matches
# break as soon as we have a match
for expr, substitution in substitutions.items():
if arg == expr:
new_arguments.append(substitution)
changed_something = True
break
# this will execute only if we did not break out of the
# loop, e.g. if we did not change anything and did not
# collect any substitutions
else:
# recursively call _subs on each arg to see if we get a
# substituted arg
new_arg = arg._subs(substitutions, default, simplify)
if new_arg is None:
# if we did not collect a substitution for this arg,
# keep the arg as-is, it is not replaced by anything
new_arguments.append(arg)
else:
# otherwise, we add the substitution for this arg instead
new_arguments.append(new_arg)
changed_something = True
if not changed_something:
return
# here we did some substitution: we return a new expression
# built from the new_arguments
newexpr = self.__class__(*new_arguments)
return newexpr.simplify() if simplify else newexpr | Return an expression where all subterms equal to a key expression are
substituted by the corresponding value expression using a mapping of:
{expr->expr to substitute.} | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L646-L698 | null | class Expression(object):
"""
Abstract base class for all boolean expressions, including functions and
variable symbols.
"""
# Defines sort and comparison order between expressions arguments
sort_order = None
# Store arguments aka. subterms of this expressions.
# subterms are either literals or expressions.
args = tuple()
# True is this is a literal expression such as a Symbol, TRUE or FALSE
isliteral = False
# True if this expression has been simplified to in canonical form.
iscanonical = False
# these class attributes are configured when a new BooleanAlgebra is created
TRUE = None
FALSE = None
NOT = None
AND = None
OR = None
Symbol = None
@property
def objects(self):
"""
Return a set of all associated objects with this expression symbols.
Include recursively subexpressions objects.
"""
return set(s.obj for s in self.symbols)
def get_literals(self):
"""
Return a list of all the literals contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
"""
if self.isliteral:
return [self]
if not self.args:
return []
return list(itertools.chain.from_iterable(arg.get_literals() for arg in self.args))
@property
def literals(self):
"""
Return a set of all literals contained in this expression.
Include recursively subexpressions literals.
"""
return set(self.get_literals())
def literalize(self):
"""
Return an expression where NOTs are only occurring as literals.
Applied recursively to subexpressions.
"""
if self.isliteral:
return self
args = tuple(arg.literalize() for arg in self.args)
if all(arg is self.args[i] for i, arg in enumerate(args)):
return self
return self.__class__(*args)
def get_symbols(self):
"""
Return a list of all the symbols contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
"""
return [s if isinstance(s, Symbol) else s.args[0] for s in self.get_literals()]
@property
def symbols(self,):
"""
Return a list of all the symbols contained in this expression.
Include recursively subexpressions symbols.
This includes duplicates.
"""
return set(self.get_symbols())
def subs(self, substitutions, default=None, simplify=False):
"""
Return an expression where the expression or all subterms equal to a key
expression are substituted with the corresponding value expression using
a mapping of: {expr->expr to substitute.}
Return this expression unmodified if nothing could be substituted.
Note that this can be used to tested for expression containment.
"""
# shortcut: check if we have our whole expression as a possible
# subsitution source
for expr, substitution in substitutions.items():
if expr == self:
return substitution
# otherwise, do a proper substitution of sub expressions
expr = self._subs(substitutions, default, simplify)
return self if expr is None else expr
def simplify(self):
"""
Return a new simplified expression in canonical form built from this
expression. The simplified expression may be exactly the same as this
expression.
Subclasses override this method to compute actual simplification.
"""
return self
def __hash__(self):
"""
Expressions are immutable and hashable. The hash of Functions is
computed by respecting the structure of the whole expression by mixing
the class name hash and the recursive hash of a frozenset of arguments.
Hash of elements is based on their boolean equivalent. Hash of symbols
is based on their object.
"""
if not self.args:
arghash = id(self)
else:
arghash = hash(frozenset(map(hash, self.args)))
return hash(self.__class__.__name__) ^ arghash
def __eq__(self, other):
"""
Test if other element is structurally the same as itself.
This method does not make any simplification or transformation, so it
will return False although the expression terms may be mathematically
equal. Use simplify() before testing equality.
For literals, plain equality is used.
For functions, it uses the facts that operations are:
- commutative and considers different ordering as equal.
- idempotent, so args can appear more often in one term than in the other.
"""
if self is other:
return True
if isinstance(other, self.__class__):
return frozenset(self.args) == frozenset(other.args)
return NotImplemented
def __ne__(self, other):
return not self == other
def __lt__(self, other):
if self.sort_order is not None and other.sort_order is not None:
if self.sort_order == other.sort_order:
return NotImplemented
return self.sort_order < other.sort_order
return NotImplemented
def __gt__(self, other):
lt = other.__lt__(self)
if lt is NotImplemented:
return not self.__lt__(other)
return lt
def __and__(self, other):
return self.AND(self, other)
__mul__ = __and__
def __invert__(self):
return self.NOT(self)
def __or__(self, other):
return self.OR(self, other)
__add__ = __or__
def __bool__(self):
raise TypeError('Cannot evaluate expression as a Python Boolean.')
__nonzero__ = __bool__
|
bastikr/boolean.py | boolean/boolean.py | Symbol.pretty | python | def pretty(self, indent=0, debug=False):
debug_details = ''
if debug:
debug_details += '<isliteral=%r, iscanonical=%r>' % (self.isliteral, self.iscanonical)
obj = "'%s'" % self.obj if isinstance(self.obj, basestring) else repr(self.obj)
return (' ' * indent) + ('%s(%s%s)' % (self.__class__.__name__, debug_details, obj)) | Return a pretty formatted representation of self. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L910-L919 | null | class Symbol(Expression):
"""
Boolean variable.
A Symbol can hold an object used to determine equality between symbols.
"""
# FIXME: the statement below in the original docstring is weird: Symbols do
# not have a value assigned, so how could they ever be FALSE
"""
Symbols (also called boolean variables) can only take on the values TRUE or
FALSE.
"""
sort_order = 5
def __init__(self, obj):
super(Symbol, self).__init__()
# Store an associated object. This object determines equality
self.obj = obj
self.iscanonical = True
self.isliteral = True
def __hash__(self):
if self.obj is None: # Anonymous Symbol.
return id(self)
return hash(self.obj)
def __eq__(self, other):
if self is other:
return True
if isinstance(other, self.__class__):
return self.obj == other.obj
return NotImplemented
def __lt__(self, other):
comparator = Expression.__lt__(self, other)
if comparator is not NotImplemented:
return comparator
if isinstance(other, Symbol):
return self.obj < other.obj
return NotImplemented
def __str__(self):
return str(self.obj)
def __repr__(self):
obj = "'%s'" % self.obj if isinstance(self.obj, basestring) else repr(self.obj)
return '%s(%s)' % (self.__class__.__name__, obj)
|
bastikr/boolean.py | boolean/boolean.py | Function.pretty | python | def pretty(self, indent=0, debug=False):
debug_details = ''
if debug:
debug_details += '<isliteral=%r, iscanonical=%r' % (self.isliteral, self.iscanonical)
identity = getattr(self, 'identity', None)
if identity is not None:
debug_details += ', identity=%r' % (identity)
annihilator = getattr(self, 'annihilator', None)
if annihilator is not None:
debug_details += ', annihilator=%r' % (annihilator)
dual = getattr(self, 'dual', None)
if dual is not None:
debug_details += ', dual=%r' % (dual)
debug_details += '>'
cls = self.__class__.__name__
args = [a.pretty(indent=indent + 2, debug=debug) for a in self.args]
pfargs = ',\n'.join(args)
cur_indent = ' ' * indent
new_line = '' if self.isliteral else '\n'
return '{cur_indent}{cls}({debug_details}{new_line}{pfargs}\n{cur_indent})'.format(**locals()) | Return a pretty formatted representation of self as an indented tree.
If debug is True, also prints debug information for each expression arg.
For example:
>>> print Expression().parse(u'not a and not b and not (a and ba and c) and c or c').pretty()
OR(
AND(
NOT(Symbol('a')),
NOT(Symbol('b')),
NOT(
AND(
Symbol('a'),
Symbol('ba'),
Symbol('c')
)
),
Symbol('c')
),
Symbol('c')
) | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L960-L1004 | null | class Function(Expression):
"""
Boolean function.
A boolean function takes n (one or more) boolean expressions as arguments
where n is called the order of the function and maps them to one of the base
elements TRUE or FALSE. Implemented functions are AND, OR and NOT.
"""
def __init__(self, *args):
super(Function, self).__init__()
# Specifies an infix notation of an operator for printing such as | or &.
self.operator = None
assert all(isinstance(arg, Expression) for arg in args), \
'Bad arguments: all arguments must be an Expression: %r' % (args,)
self.args = tuple(args)
def __str__(self):
args = self.args
if len(args) == 1:
if self.isliteral:
return '%s%s' % (self.operator, args[0])
return '%s(%s)' % (self.operator, args[0])
args_str = []
for arg in args:
if arg.isliteral:
args_str.append(str(arg))
else:
args_str.append('(%s)' % arg)
return self.operator.join(args_str)
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, ', '.join(map(repr, self.args)))
|
bastikr/boolean.py | boolean/boolean.py | NOT.literalize | python | def literalize(self):
expr = self.demorgan()
if isinstance(expr, self.__class__):
return expr
return expr.literalize() | Return an expression where NOTs are only occurring as literals. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L1031-L1038 | [
"def demorgan(self):\n \"\"\"\n Return a expr where the NOT function is moved inward.\n This is achieved by canceling double NOTs and using De Morgan laws.\n \"\"\"\n expr = self.cancel()\n if expr.isliteral or not isinstance(expr, self.NOT):\n return expr\n op = expr.args[0]\n return... | class NOT(Function):
"""
Boolean NOT operation.
The NOT operation takes exactly one argument. If this argument is a Symbol
the resulting expression is also called a literal.
The operator "~" can be used as abbreviation for NOT, e.g. instead of NOT(x)
one can write ~x (where x is some boolean expression). Also for printing "~"
is used for better readability.
You can subclass to define alternative string representation.
For example::
>>> class NOT2(NOT):
def __init__(self, *args):
super(NOT2, self).__init__(*args)
self.operator = '!'
"""
def __init__(self, arg1):
super(NOT, self).__init__(arg1)
self.isliteral = isinstance(self.args[0], Symbol)
self.operator = '~'
def simplify(self):
"""
Return a simplified expr in canonical form.
This means double negations are canceled out and all contained boolean
objects are in their canonical form.
"""
if self.iscanonical:
return self
expr = self.cancel()
if not isinstance(expr, self.__class__):
return expr.simplify()
if expr.args[0] in (self.TRUE, self.FALSE,):
return expr.args[0].dual
expr = self.__class__(expr.args[0].simplify())
expr.iscanonical = True
return expr
def cancel(self):
"""
Cancel itself and following NOTs as far as possible.
Returns the simplified expression.
"""
expr = self
while True:
arg = expr.args[0]
if not isinstance(arg, self.__class__):
return expr
expr = arg.args[0]
if not isinstance(expr, self.__class__):
return expr
def demorgan(self):
"""
Return a expr where the NOT function is moved inward.
This is achieved by canceling double NOTs and using De Morgan laws.
"""
expr = self.cancel()
if expr.isliteral or not isinstance(expr, self.NOT):
return expr
op = expr.args[0]
return op.dual(*(self.__class__(arg).cancel() for arg in op.args))
def __lt__(self, other):
return self.args[0] < other
def pretty(self, indent=1, debug=False):
"""
Return a pretty formatted representation of self.
Include additional debug details if `debug` is True.
"""
debug_details = ''
if debug:
debug_details += '<isliteral=%r, iscanonical=%r>' % (self.isliteral, self.iscanonical)
if self.isliteral:
pretty_literal = self.args[0].pretty(indent=0, debug=debug)
return (' ' * indent) + '%s(%s%s)' % (self.__class__.__name__, debug_details, pretty_literal)
else:
return super(NOT, self).pretty(indent=indent, debug=debug)
|
bastikr/boolean.py | boolean/boolean.py | NOT.simplify | python | def simplify(self):
if self.iscanonical:
return self
expr = self.cancel()
if not isinstance(expr, self.__class__):
return expr.simplify()
if expr.args[0] in (self.TRUE, self.FALSE,):
return expr.args[0].dual
expr = self.__class__(expr.args[0].simplify())
expr.iscanonical = True
return expr | Return a simplified expr in canonical form.
This means double negations are canceled out and all contained boolean
objects are in their canonical form. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L1040-L1059 | [
"def simplify(self):\n \"\"\"\n Return a simplified expr in canonical form.\n\n This means double negations are canceled out and all contained boolean\n objects are in their canonical form.\n \"\"\"\n if self.iscanonical:\n return self\n\n expr = self.cancel()\n if not isinstance(expr... | class NOT(Function):
"""
Boolean NOT operation.
The NOT operation takes exactly one argument. If this argument is a Symbol
the resulting expression is also called a literal.
The operator "~" can be used as abbreviation for NOT, e.g. instead of NOT(x)
one can write ~x (where x is some boolean expression). Also for printing "~"
is used for better readability.
You can subclass to define alternative string representation.
For example::
>>> class NOT2(NOT):
def __init__(self, *args):
super(NOT2, self).__init__(*args)
self.operator = '!'
"""
def __init__(self, arg1):
super(NOT, self).__init__(arg1)
self.isliteral = isinstance(self.args[0], Symbol)
self.operator = '~'
def literalize(self):
"""
Return an expression where NOTs are only occurring as literals.
"""
expr = self.demorgan()
if isinstance(expr, self.__class__):
return expr
return expr.literalize()
def cancel(self):
"""
Cancel itself and following NOTs as far as possible.
Returns the simplified expression.
"""
expr = self
while True:
arg = expr.args[0]
if not isinstance(arg, self.__class__):
return expr
expr = arg.args[0]
if not isinstance(expr, self.__class__):
return expr
def demorgan(self):
"""
Return a expr where the NOT function is moved inward.
This is achieved by canceling double NOTs and using De Morgan laws.
"""
expr = self.cancel()
if expr.isliteral or not isinstance(expr, self.NOT):
return expr
op = expr.args[0]
return op.dual(*(self.__class__(arg).cancel() for arg in op.args))
def __lt__(self, other):
return self.args[0] < other
def pretty(self, indent=1, debug=False):
"""
Return a pretty formatted representation of self.
Include additional debug details if `debug` is True.
"""
debug_details = ''
if debug:
debug_details += '<isliteral=%r, iscanonical=%r>' % (self.isliteral, self.iscanonical)
if self.isliteral:
pretty_literal = self.args[0].pretty(indent=0, debug=debug)
return (' ' * indent) + '%s(%s%s)' % (self.__class__.__name__, debug_details, pretty_literal)
else:
return super(NOT, self).pretty(indent=indent, debug=debug)
|
bastikr/boolean.py | boolean/boolean.py | NOT.cancel | python | def cancel(self):
expr = self
while True:
arg = expr.args[0]
if not isinstance(arg, self.__class__):
return expr
expr = arg.args[0]
if not isinstance(expr, self.__class__):
return expr | Cancel itself and following NOTs as far as possible.
Returns the simplified expression. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L1061-L1073 | null | class NOT(Function):
"""
Boolean NOT operation.
The NOT operation takes exactly one argument. If this argument is a Symbol
the resulting expression is also called a literal.
The operator "~" can be used as abbreviation for NOT, e.g. instead of NOT(x)
one can write ~x (where x is some boolean expression). Also for printing "~"
is used for better readability.
You can subclass to define alternative string representation.
For example::
>>> class NOT2(NOT):
def __init__(self, *args):
super(NOT2, self).__init__(*args)
self.operator = '!'
"""
def __init__(self, arg1):
super(NOT, self).__init__(arg1)
self.isliteral = isinstance(self.args[0], Symbol)
self.operator = '~'
def literalize(self):
"""
Return an expression where NOTs are only occurring as literals.
"""
expr = self.demorgan()
if isinstance(expr, self.__class__):
return expr
return expr.literalize()
def simplify(self):
"""
Return a simplified expr in canonical form.
This means double negations are canceled out and all contained boolean
objects are in their canonical form.
"""
if self.iscanonical:
return self
expr = self.cancel()
if not isinstance(expr, self.__class__):
return expr.simplify()
if expr.args[0] in (self.TRUE, self.FALSE,):
return expr.args[0].dual
expr = self.__class__(expr.args[0].simplify())
expr.iscanonical = True
return expr
def demorgan(self):
"""
Return a expr where the NOT function is moved inward.
This is achieved by canceling double NOTs and using De Morgan laws.
"""
expr = self.cancel()
if expr.isliteral or not isinstance(expr, self.NOT):
return expr
op = expr.args[0]
return op.dual(*(self.__class__(arg).cancel() for arg in op.args))
def __lt__(self, other):
return self.args[0] < other
def pretty(self, indent=1, debug=False):
"""
Return a pretty formatted representation of self.
Include additional debug details if `debug` is True.
"""
debug_details = ''
if debug:
debug_details += '<isliteral=%r, iscanonical=%r>' % (self.isliteral, self.iscanonical)
if self.isliteral:
pretty_literal = self.args[0].pretty(indent=0, debug=debug)
return (' ' * indent) + '%s(%s%s)' % (self.__class__.__name__, debug_details, pretty_literal)
else:
return super(NOT, self).pretty(indent=indent, debug=debug)
|
bastikr/boolean.py | boolean/boolean.py | NOT.demorgan | python | def demorgan(self):
expr = self.cancel()
if expr.isliteral or not isinstance(expr, self.NOT):
return expr
op = expr.args[0]
return op.dual(*(self.__class__(arg).cancel() for arg in op.args)) | Return a expr where the NOT function is moved inward.
This is achieved by canceling double NOTs and using De Morgan laws. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L1075-L1084 | [
"def cancel(self):\n \"\"\"\n Cancel itself and following NOTs as far as possible.\n Returns the simplified expression.\n \"\"\"\n expr = self\n while True:\n arg = expr.args[0]\n if not isinstance(arg, self.__class__):\n return expr\n expr = arg.args[0]\n if... | class NOT(Function):
"""
Boolean NOT operation.
The NOT operation takes exactly one argument. If this argument is a Symbol
the resulting expression is also called a literal.
The operator "~" can be used as abbreviation for NOT, e.g. instead of NOT(x)
one can write ~x (where x is some boolean expression). Also for printing "~"
is used for better readability.
You can subclass to define alternative string representation.
For example::
>>> class NOT2(NOT):
def __init__(self, *args):
super(NOT2, self).__init__(*args)
self.operator = '!'
"""
def __init__(self, arg1):
super(NOT, self).__init__(arg1)
self.isliteral = isinstance(self.args[0], Symbol)
self.operator = '~'
def literalize(self):
"""
Return an expression where NOTs are only occurring as literals.
"""
expr = self.demorgan()
if isinstance(expr, self.__class__):
return expr
return expr.literalize()
def simplify(self):
"""
Return a simplified expr in canonical form.
This means double negations are canceled out and all contained boolean
objects are in their canonical form.
"""
if self.iscanonical:
return self
expr = self.cancel()
if not isinstance(expr, self.__class__):
return expr.simplify()
if expr.args[0] in (self.TRUE, self.FALSE,):
return expr.args[0].dual
expr = self.__class__(expr.args[0].simplify())
expr.iscanonical = True
return expr
def cancel(self):
"""
Cancel itself and following NOTs as far as possible.
Returns the simplified expression.
"""
expr = self
while True:
arg = expr.args[0]
if not isinstance(arg, self.__class__):
return expr
expr = arg.args[0]
if not isinstance(expr, self.__class__):
return expr
def __lt__(self, other):
return self.args[0] < other
def pretty(self, indent=1, debug=False):
"""
Return a pretty formatted representation of self.
Include additional debug details if `debug` is True.
"""
debug_details = ''
if debug:
debug_details += '<isliteral=%r, iscanonical=%r>' % (self.isliteral, self.iscanonical)
if self.isliteral:
pretty_literal = self.args[0].pretty(indent=0, debug=debug)
return (' ' * indent) + '%s(%s%s)' % (self.__class__.__name__, debug_details, pretty_literal)
else:
return super(NOT, self).pretty(indent=indent, debug=debug)
|
bastikr/boolean.py | boolean/boolean.py | NOT.pretty | python | def pretty(self, indent=1, debug=False):
debug_details = ''
if debug:
debug_details += '<isliteral=%r, iscanonical=%r>' % (self.isliteral, self.iscanonical)
if self.isliteral:
pretty_literal = self.args[0].pretty(indent=0, debug=debug)
return (' ' * indent) + '%s(%s%s)' % (self.__class__.__name__, debug_details, pretty_literal)
else:
return super(NOT, self).pretty(indent=indent, debug=debug) | Return a pretty formatted representation of self.
Include additional debug details if `debug` is True. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L1089-L1101 | [
"def pretty(self, indent=0, debug=False):\n \"\"\"\n Return a pretty formatted representation of self as an indented tree.\n\n If debug is True, also prints debug information for each expression arg.\n\n For example:\n >>> print Expression().parse(u'not a and not b and not (a and ba and c) and c or c... | class NOT(Function):
"""
Boolean NOT operation.
The NOT operation takes exactly one argument. If this argument is a Symbol
the resulting expression is also called a literal.
The operator "~" can be used as abbreviation for NOT, e.g. instead of NOT(x)
one can write ~x (where x is some boolean expression). Also for printing "~"
is used for better readability.
You can subclass to define alternative string representation.
For example::
>>> class NOT2(NOT):
def __init__(self, *args):
super(NOT2, self).__init__(*args)
self.operator = '!'
"""
def __init__(self, arg1):
super(NOT, self).__init__(arg1)
self.isliteral = isinstance(self.args[0], Symbol)
self.operator = '~'
def literalize(self):
"""
Return an expression where NOTs are only occurring as literals.
"""
expr = self.demorgan()
if isinstance(expr, self.__class__):
return expr
return expr.literalize()
def simplify(self):
"""
Return a simplified expr in canonical form.
This means double negations are canceled out and all contained boolean
objects are in their canonical form.
"""
if self.iscanonical:
return self
expr = self.cancel()
if not isinstance(expr, self.__class__):
return expr.simplify()
if expr.args[0] in (self.TRUE, self.FALSE,):
return expr.args[0].dual
expr = self.__class__(expr.args[0].simplify())
expr.iscanonical = True
return expr
def cancel(self):
"""
Cancel itself and following NOTs as far as possible.
Returns the simplified expression.
"""
expr = self
while True:
arg = expr.args[0]
if not isinstance(arg, self.__class__):
return expr
expr = arg.args[0]
if not isinstance(expr, self.__class__):
return expr
def demorgan(self):
"""
Return a expr where the NOT function is moved inward.
This is achieved by canceling double NOTs and using De Morgan laws.
"""
expr = self.cancel()
if expr.isliteral or not isinstance(expr, self.NOT):
return expr
op = expr.args[0]
return op.dual(*(self.__class__(arg).cancel() for arg in op.args))
def __lt__(self, other):
return self.args[0] < other
|
bastikr/boolean.py | boolean/boolean.py | DualBase.simplify | python | def simplify(self):
# TODO: Refactor DualBase.simplify into different "sub-evals".
# If self is already canonical do nothing.
if self.iscanonical:
return self
# Otherwise bring arguments into canonical form.
args = [arg.simplify() for arg in self.args]
# Create new instance of own class with canonical args.
# TODO: Only create new class if some args changed.
expr = self.__class__(*args)
# Literalize before doing anything, this also applies De Morgan's Law
expr = expr.literalize()
# Associativity:
# (A & B) & C = A & (B & C) = A & B & C
# (A | B) | C = A | (B | C) = A | B | C
expr = expr.flatten()
# Annihilation: A & 0 = 0, A | 1 = 1
if self.annihilator in expr.args:
return self.annihilator
# Idempotence: A & A = A, A | A = A
# this boils down to removing duplicates
args = []
for arg in expr.args:
if arg not in args:
args.append(arg)
if len(args) == 1:
return args[0]
# Identity: A & 1 = A, A | 0 = A
if self.identity in args:
args.remove(self.identity)
if len(args) == 1:
return args[0]
# Complementation: A & ~A = 0, A | ~A = 1
for arg in args:
if self.NOT(arg) in args:
return self.annihilator
# Elimination: (A & B) | (A & ~B) = A, (A | B) & (A | ~B) = A
i = 0
while i < len(args) - 1:
j = i + 1
ai = args[i]
if not isinstance(ai, self.dual):
i += 1
continue
while j < len(args):
aj = args[j]
if not isinstance(aj, self.dual) or len(ai.args) != len(aj.args):
j += 1
continue
# Find terms where only one arg is different.
negated = None
for arg in ai.args:
# FIXME: what does this pass Do?
if arg in aj.args:
pass
elif self.NOT(arg).cancel() in aj.args:
if negated is None:
negated = arg
else:
negated = None
break
else:
negated = None
break
# If the different arg is a negation simplify the expr.
if negated is not None:
# Cancel out one of the two terms.
del args[j]
aiargs = list(ai.args)
aiargs.remove(negated)
if len(aiargs) == 1:
args[i] = aiargs[0]
else:
args[i] = self.dual(*aiargs)
if len(args) == 1:
return args[0]
else:
# Now the other simplifications have to be redone.
return self.__class__(*args).simplify()
j += 1
i += 1
# Absorption: A & (A | B) = A, A | (A & B) = A
# Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B
args = self.absorb(args)
if len(args) == 1:
return args[0]
# Commutativity: A & B = B & A, A | B = B | A
args.sort()
# Create new (now canonical) expression.
expr = self.__class__(*args)
expr.iscanonical = True
return expr | Return a new simplified expression in canonical form from this
expression.
For simplification of AND and OR fthe ollowing rules are used
recursively bottom up:
- Associativity (output does not contain same operations nested)
- Annihilation
- Idempotence
- Identity
- Complementation
- Elimination
- Absorption
- Commutativity (output is always sorted)
Other boolean objects are also in their canonical form. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L1138-L1262 | [
"def absorb(self, args):\n \"\"\"\n Given an `args` sequence of expressions, return a new list of expression\n applying absorption and negative absorption.\n\n See https://en.wikipedia.org/wiki/Absorption_law\n\n Absorption: A & (A | B) = A, A | (A & B) = A\n Negative absorption: A & (~A | B) = A ... | class DualBase(Function):
"""
Base class for AND and OR function.
This class uses the duality principle to combine similar methods of AND
and OR. Both operations take 2 or more arguments and can be created using
"|" for OR and "&" for AND.
"""
def __init__(self, arg1, arg2, *args):
super(DualBase, self).__init__(arg1, arg2, *args)
# identity element for the specific operation.
# This will be TRUE for the AND operation and FALSE for the OR operation.
self.identity = None
# annihilator element for this function.
# This will be FALSE for the AND operation and TRUE for the OR operation.
self.annihilator = None
# dual class of this function.
# This means OR.dual returns AND and AND.dual returns OR.
self.dual = None
def __contains__(self, expr):
"""
Test if expr is a subterm of this expression.
"""
if expr in self.args:
return True
if isinstance(expr, self.__class__):
return all(arg in self.args for arg in expr.args)
def flatten(self):
"""
Return a new expression where nested terms of this expression are
flattened as far as possible.
E.g. A & (B & C) becomes A & B & C.
"""
args = list(self.args)
i = 0
for arg in self.args:
if isinstance(arg, self.__class__):
args[i:i + 1] = arg.args
i += len(arg.args)
else:
i += 1
return self.__class__(*args)
def absorb(self, args):
"""
Given an `args` sequence of expressions, return a new list of expression
applying absorption and negative absorption.
See https://en.wikipedia.org/wiki/Absorption_law
Absorption: A & (A | B) = A, A | (A & B) = A
Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B
"""
args = list(args)
if not args:
args = list(self.args)
i = 0
while i < len(args):
absorber = args[i]
j = 0
while j < len(args):
if j == i:
j += 1
continue
target = args[j]
if not isinstance(target, self.dual):
j += 1
continue
# Absorption
if absorber in target:
del args[j]
if j < i:
i -= 1
continue
# Negative absorption
neg_absorber = self.NOT(absorber).cancel()
if neg_absorber in target:
b = target.subtract(neg_absorber, simplify=False)
if b is None:
del args[j]
if j < i:
i -= 1
continue
else:
args[j] = b
j += 1
continue
if isinstance(absorber, self.dual):
remove = None
for arg in absorber.args:
narg = self.NOT(arg).cancel()
if arg in target.args:
pass
elif narg in target.args:
if remove is None:
remove = narg
else:
remove = None
break
else:
remove = None
break
if remove is not None:
args[j] = target.subtract(remove, simplify=True)
j += 1
i += 1
return args
def subtract(self, expr, simplify):
"""
Return a new expression where the `expr` expression has been removed
from this expression if it exists.
"""
args = self.args
if expr in self.args:
args = list(self.args)
args.remove(expr)
elif isinstance(expr, self.__class__):
if all(arg in self.args for arg in expr.args):
args = tuple(arg for arg in self.args if arg not in expr)
if len(args) == 0:
return None
if len(args) == 1:
return args[0]
newexpr = self.__class__(*args)
if simplify:
newexpr = newexpr.simplify()
return newexpr
def distributive(self):
"""
Return a term where the leading AND or OR terms are switched.
This is done by applying the distributive laws:
A & (B|C) = (A&B) | (A&C)
A | (B&C) = (A|B) & (A|C)
"""
dual = self.dual
args = list(self.args)
for i, arg in enumerate(args):
if isinstance(arg, dual):
args[i] = arg.args
else:
args[i] = (arg,)
prod = itertools.product(*args)
args = tuple(self.__class__(*arg).simplify() for arg in prod)
if len(args) == 1:
return args[0]
else:
return dual(*args)
def __lt__(self, other):
comparator = Expression.__lt__(self, other)
if comparator is not NotImplemented:
return comparator
if isinstance(other, self.__class__):
lenself = len(self.args)
lenother = len(other.args)
for i in range(min(lenself, lenother)):
if self.args[i] == other.args[i]:
continue
comparator = self.args[i] < other.args[i]
if comparator is not NotImplemented:
return comparator
if lenself != lenother:
return lenself < lenother
return NotImplemented
|
bastikr/boolean.py | boolean/boolean.py | DualBase.flatten | python | def flatten(self):
args = list(self.args)
i = 0
for arg in self.args:
if isinstance(arg, self.__class__):
args[i:i + 1] = arg.args
i += len(arg.args)
else:
i += 1
return self.__class__(*args) | Return a new expression where nested terms of this expression are
flattened as far as possible.
E.g. A & (B & C) becomes A & B & C. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L1264-L1280 | null | class DualBase(Function):
"""
Base class for AND and OR function.
This class uses the duality principle to combine similar methods of AND
and OR. Both operations take 2 or more arguments and can be created using
"|" for OR and "&" for AND.
"""
def __init__(self, arg1, arg2, *args):
super(DualBase, self).__init__(arg1, arg2, *args)
# identity element for the specific operation.
# This will be TRUE for the AND operation and FALSE for the OR operation.
self.identity = None
# annihilator element for this function.
# This will be FALSE for the AND operation and TRUE for the OR operation.
self.annihilator = None
# dual class of this function.
# This means OR.dual returns AND and AND.dual returns OR.
self.dual = None
def __contains__(self, expr):
"""
Test if expr is a subterm of this expression.
"""
if expr in self.args:
return True
if isinstance(expr, self.__class__):
return all(arg in self.args for arg in expr.args)
def simplify(self):
"""
Return a new simplified expression in canonical form from this
expression.
For simplification of AND and OR fthe ollowing rules are used
recursively bottom up:
- Associativity (output does not contain same operations nested)
- Annihilation
- Idempotence
- Identity
- Complementation
- Elimination
- Absorption
- Commutativity (output is always sorted)
Other boolean objects are also in their canonical form.
"""
# TODO: Refactor DualBase.simplify into different "sub-evals".
# If self is already canonical do nothing.
if self.iscanonical:
return self
# Otherwise bring arguments into canonical form.
args = [arg.simplify() for arg in self.args]
# Create new instance of own class with canonical args.
# TODO: Only create new class if some args changed.
expr = self.__class__(*args)
# Literalize before doing anything, this also applies De Morgan's Law
expr = expr.literalize()
# Associativity:
# (A & B) & C = A & (B & C) = A & B & C
# (A | B) | C = A | (B | C) = A | B | C
expr = expr.flatten()
# Annihilation: A & 0 = 0, A | 1 = 1
if self.annihilator in expr.args:
return self.annihilator
# Idempotence: A & A = A, A | A = A
# this boils down to removing duplicates
args = []
for arg in expr.args:
if arg not in args:
args.append(arg)
if len(args) == 1:
return args[0]
# Identity: A & 1 = A, A | 0 = A
if self.identity in args:
args.remove(self.identity)
if len(args) == 1:
return args[0]
# Complementation: A & ~A = 0, A | ~A = 1
for arg in args:
if self.NOT(arg) in args:
return self.annihilator
# Elimination: (A & B) | (A & ~B) = A, (A | B) & (A | ~B) = A
i = 0
while i < len(args) - 1:
j = i + 1
ai = args[i]
if not isinstance(ai, self.dual):
i += 1
continue
while j < len(args):
aj = args[j]
if not isinstance(aj, self.dual) or len(ai.args) != len(aj.args):
j += 1
continue
# Find terms where only one arg is different.
negated = None
for arg in ai.args:
# FIXME: what does this pass Do?
if arg in aj.args:
pass
elif self.NOT(arg).cancel() in aj.args:
if negated is None:
negated = arg
else:
negated = None
break
else:
negated = None
break
# If the different arg is a negation simplify the expr.
if negated is not None:
# Cancel out one of the two terms.
del args[j]
aiargs = list(ai.args)
aiargs.remove(negated)
if len(aiargs) == 1:
args[i] = aiargs[0]
else:
args[i] = self.dual(*aiargs)
if len(args) == 1:
return args[0]
else:
# Now the other simplifications have to be redone.
return self.__class__(*args).simplify()
j += 1
i += 1
# Absorption: A & (A | B) = A, A | (A & B) = A
# Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B
args = self.absorb(args)
if len(args) == 1:
return args[0]
# Commutativity: A & B = B & A, A | B = B | A
args.sort()
# Create new (now canonical) expression.
expr = self.__class__(*args)
expr.iscanonical = True
return expr
def absorb(self, args):
"""
Given an `args` sequence of expressions, return a new list of expression
applying absorption and negative absorption.
See https://en.wikipedia.org/wiki/Absorption_law
Absorption: A & (A | B) = A, A | (A & B) = A
Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B
"""
args = list(args)
if not args:
args = list(self.args)
i = 0
while i < len(args):
absorber = args[i]
j = 0
while j < len(args):
if j == i:
j += 1
continue
target = args[j]
if not isinstance(target, self.dual):
j += 1
continue
# Absorption
if absorber in target:
del args[j]
if j < i:
i -= 1
continue
# Negative absorption
neg_absorber = self.NOT(absorber).cancel()
if neg_absorber in target:
b = target.subtract(neg_absorber, simplify=False)
if b is None:
del args[j]
if j < i:
i -= 1
continue
else:
args[j] = b
j += 1
continue
if isinstance(absorber, self.dual):
remove = None
for arg in absorber.args:
narg = self.NOT(arg).cancel()
if arg in target.args:
pass
elif narg in target.args:
if remove is None:
remove = narg
else:
remove = None
break
else:
remove = None
break
if remove is not None:
args[j] = target.subtract(remove, simplify=True)
j += 1
i += 1
return args
def subtract(self, expr, simplify):
"""
Return a new expression where the `expr` expression has been removed
from this expression if it exists.
"""
args = self.args
if expr in self.args:
args = list(self.args)
args.remove(expr)
elif isinstance(expr, self.__class__):
if all(arg in self.args for arg in expr.args):
args = tuple(arg for arg in self.args if arg not in expr)
if len(args) == 0:
return None
if len(args) == 1:
return args[0]
newexpr = self.__class__(*args)
if simplify:
newexpr = newexpr.simplify()
return newexpr
def distributive(self):
"""
Return a term where the leading AND or OR terms are switched.
This is done by applying the distributive laws:
A & (B|C) = (A&B) | (A&C)
A | (B&C) = (A|B) & (A|C)
"""
dual = self.dual
args = list(self.args)
for i, arg in enumerate(args):
if isinstance(arg, dual):
args[i] = arg.args
else:
args[i] = (arg,)
prod = itertools.product(*args)
args = tuple(self.__class__(*arg).simplify() for arg in prod)
if len(args) == 1:
return args[0]
else:
return dual(*args)
def __lt__(self, other):
comparator = Expression.__lt__(self, other)
if comparator is not NotImplemented:
return comparator
if isinstance(other, self.__class__):
lenself = len(self.args)
lenother = len(other.args)
for i in range(min(lenself, lenother)):
if self.args[i] == other.args[i]:
continue
comparator = self.args[i] < other.args[i]
if comparator is not NotImplemented:
return comparator
if lenself != lenother:
return lenself < lenother
return NotImplemented
|
bastikr/boolean.py | boolean/boolean.py | DualBase.absorb | python | def absorb(self, args):
args = list(args)
if not args:
args = list(self.args)
i = 0
while i < len(args):
absorber = args[i]
j = 0
while j < len(args):
if j == i:
j += 1
continue
target = args[j]
if not isinstance(target, self.dual):
j += 1
continue
# Absorption
if absorber in target:
del args[j]
if j < i:
i -= 1
continue
# Negative absorption
neg_absorber = self.NOT(absorber).cancel()
if neg_absorber in target:
b = target.subtract(neg_absorber, simplify=False)
if b is None:
del args[j]
if j < i:
i -= 1
continue
else:
args[j] = b
j += 1
continue
if isinstance(absorber, self.dual):
remove = None
for arg in absorber.args:
narg = self.NOT(arg).cancel()
if arg in target.args:
pass
elif narg in target.args:
if remove is None:
remove = narg
else:
remove = None
break
else:
remove = None
break
if remove is not None:
args[j] = target.subtract(remove, simplify=True)
j += 1
i += 1
return args | Given an `args` sequence of expressions, return a new list of expression
applying absorption and negative absorption.
See https://en.wikipedia.org/wiki/Absorption_law
Absorption: A & (A | B) = A, A | (A & B) = A
Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L1282-L1349 | null | class DualBase(Function):
"""
Base class for AND and OR function.
This class uses the duality principle to combine similar methods of AND
and OR. Both operations take 2 or more arguments and can be created using
"|" for OR and "&" for AND.
"""
def __init__(self, arg1, arg2, *args):
super(DualBase, self).__init__(arg1, arg2, *args)
# identity element for the specific operation.
# This will be TRUE for the AND operation and FALSE for the OR operation.
self.identity = None
# annihilator element for this function.
# This will be FALSE for the AND operation and TRUE for the OR operation.
self.annihilator = None
# dual class of this function.
# This means OR.dual returns AND and AND.dual returns OR.
self.dual = None
def __contains__(self, expr):
"""
Test if expr is a subterm of this expression.
"""
if expr in self.args:
return True
if isinstance(expr, self.__class__):
return all(arg in self.args for arg in expr.args)
def simplify(self):
"""
Return a new simplified expression in canonical form from this
expression.
For simplification of AND and OR fthe ollowing rules are used
recursively bottom up:
- Associativity (output does not contain same operations nested)
- Annihilation
- Idempotence
- Identity
- Complementation
- Elimination
- Absorption
- Commutativity (output is always sorted)
Other boolean objects are also in their canonical form.
"""
# TODO: Refactor DualBase.simplify into different "sub-evals".
# If self is already canonical do nothing.
if self.iscanonical:
return self
# Otherwise bring arguments into canonical form.
args = [arg.simplify() for arg in self.args]
# Create new instance of own class with canonical args.
# TODO: Only create new class if some args changed.
expr = self.__class__(*args)
# Literalize before doing anything, this also applies De Morgan's Law
expr = expr.literalize()
# Associativity:
# (A & B) & C = A & (B & C) = A & B & C
# (A | B) | C = A | (B | C) = A | B | C
expr = expr.flatten()
# Annihilation: A & 0 = 0, A | 1 = 1
if self.annihilator in expr.args:
return self.annihilator
# Idempotence: A & A = A, A | A = A
# this boils down to removing duplicates
args = []
for arg in expr.args:
if arg not in args:
args.append(arg)
if len(args) == 1:
return args[0]
# Identity: A & 1 = A, A | 0 = A
if self.identity in args:
args.remove(self.identity)
if len(args) == 1:
return args[0]
# Complementation: A & ~A = 0, A | ~A = 1
for arg in args:
if self.NOT(arg) in args:
return self.annihilator
# Elimination: (A & B) | (A & ~B) = A, (A | B) & (A | ~B) = A
i = 0
while i < len(args) - 1:
j = i + 1
ai = args[i]
if not isinstance(ai, self.dual):
i += 1
continue
while j < len(args):
aj = args[j]
if not isinstance(aj, self.dual) or len(ai.args) != len(aj.args):
j += 1
continue
# Find terms where only one arg is different.
negated = None
for arg in ai.args:
# FIXME: what does this pass Do?
if arg in aj.args:
pass
elif self.NOT(arg).cancel() in aj.args:
if negated is None:
negated = arg
else:
negated = None
break
else:
negated = None
break
# If the different arg is a negation simplify the expr.
if negated is not None:
# Cancel out one of the two terms.
del args[j]
aiargs = list(ai.args)
aiargs.remove(negated)
if len(aiargs) == 1:
args[i] = aiargs[0]
else:
args[i] = self.dual(*aiargs)
if len(args) == 1:
return args[0]
else:
# Now the other simplifications have to be redone.
return self.__class__(*args).simplify()
j += 1
i += 1
# Absorption: A & (A | B) = A, A | (A & B) = A
# Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B
args = self.absorb(args)
if len(args) == 1:
return args[0]
# Commutativity: A & B = B & A, A | B = B | A
args.sort()
# Create new (now canonical) expression.
expr = self.__class__(*args)
expr.iscanonical = True
return expr
def flatten(self):
"""
Return a new expression where nested terms of this expression are
flattened as far as possible.
E.g. A & (B & C) becomes A & B & C.
"""
args = list(self.args)
i = 0
for arg in self.args:
if isinstance(arg, self.__class__):
args[i:i + 1] = arg.args
i += len(arg.args)
else:
i += 1
return self.__class__(*args)
def subtract(self, expr, simplify):
"""
Return a new expression where the `expr` expression has been removed
from this expression if it exists.
"""
args = self.args
if expr in self.args:
args = list(self.args)
args.remove(expr)
elif isinstance(expr, self.__class__):
if all(arg in self.args for arg in expr.args):
args = tuple(arg for arg in self.args if arg not in expr)
if len(args) == 0:
return None
if len(args) == 1:
return args[0]
newexpr = self.__class__(*args)
if simplify:
newexpr = newexpr.simplify()
return newexpr
def distributive(self):
"""
Return a term where the leading AND or OR terms are switched.
This is done by applying the distributive laws:
A & (B|C) = (A&B) | (A&C)
A | (B&C) = (A|B) & (A|C)
"""
dual = self.dual
args = list(self.args)
for i, arg in enumerate(args):
if isinstance(arg, dual):
args[i] = arg.args
else:
args[i] = (arg,)
prod = itertools.product(*args)
args = tuple(self.__class__(*arg).simplify() for arg in prod)
if len(args) == 1:
return args[0]
else:
return dual(*args)
def __lt__(self, other):
comparator = Expression.__lt__(self, other)
if comparator is not NotImplemented:
return comparator
if isinstance(other, self.__class__):
lenself = len(self.args)
lenother = len(other.args)
for i in range(min(lenself, lenother)):
if self.args[i] == other.args[i]:
continue
comparator = self.args[i] < other.args[i]
if comparator is not NotImplemented:
return comparator
if lenself != lenother:
return lenself < lenother
return NotImplemented
|
bastikr/boolean.py | boolean/boolean.py | DualBase.subtract | python | def subtract(self, expr, simplify):
args = self.args
if expr in self.args:
args = list(self.args)
args.remove(expr)
elif isinstance(expr, self.__class__):
if all(arg in self.args for arg in expr.args):
args = tuple(arg for arg in self.args if arg not in expr)
if len(args) == 0:
return None
if len(args) == 1:
return args[0]
newexpr = self.__class__(*args)
if simplify:
newexpr = newexpr.simplify()
return newexpr | Return a new expression where the `expr` expression has been removed
from this expression if it exists. | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L1351-L1371 | null | class DualBase(Function):
"""
Base class for AND and OR function.
This class uses the duality principle to combine similar methods of AND
and OR. Both operations take 2 or more arguments and can be created using
"|" for OR and "&" for AND.
"""
def __init__(self, arg1, arg2, *args):
super(DualBase, self).__init__(arg1, arg2, *args)
# identity element for the specific operation.
# This will be TRUE for the AND operation and FALSE for the OR operation.
self.identity = None
# annihilator element for this function.
# This will be FALSE for the AND operation and TRUE for the OR operation.
self.annihilator = None
# dual class of this function.
# This means OR.dual returns AND and AND.dual returns OR.
self.dual = None
def __contains__(self, expr):
"""
Test if expr is a subterm of this expression.
"""
if expr in self.args:
return True
if isinstance(expr, self.__class__):
return all(arg in self.args for arg in expr.args)
def simplify(self):
"""
Return a new simplified expression in canonical form from this
expression.
For simplification of AND and OR fthe ollowing rules are used
recursively bottom up:
- Associativity (output does not contain same operations nested)
- Annihilation
- Idempotence
- Identity
- Complementation
- Elimination
- Absorption
- Commutativity (output is always sorted)
Other boolean objects are also in their canonical form.
"""
# TODO: Refactor DualBase.simplify into different "sub-evals".
# If self is already canonical do nothing.
if self.iscanonical:
return self
# Otherwise bring arguments into canonical form.
args = [arg.simplify() for arg in self.args]
# Create new instance of own class with canonical args.
# TODO: Only create new class if some args changed.
expr = self.__class__(*args)
# Literalize before doing anything, this also applies De Morgan's Law
expr = expr.literalize()
# Associativity:
# (A & B) & C = A & (B & C) = A & B & C
# (A | B) | C = A | (B | C) = A | B | C
expr = expr.flatten()
# Annihilation: A & 0 = 0, A | 1 = 1
if self.annihilator in expr.args:
return self.annihilator
# Idempotence: A & A = A, A | A = A
# this boils down to removing duplicates
args = []
for arg in expr.args:
if arg not in args:
args.append(arg)
if len(args) == 1:
return args[0]
# Identity: A & 1 = A, A | 0 = A
if self.identity in args:
args.remove(self.identity)
if len(args) == 1:
return args[0]
# Complementation: A & ~A = 0, A | ~A = 1
for arg in args:
if self.NOT(arg) in args:
return self.annihilator
# Elimination: (A & B) | (A & ~B) = A, (A | B) & (A | ~B) = A
i = 0
while i < len(args) - 1:
j = i + 1
ai = args[i]
if not isinstance(ai, self.dual):
i += 1
continue
while j < len(args):
aj = args[j]
if not isinstance(aj, self.dual) or len(ai.args) != len(aj.args):
j += 1
continue
# Find terms where only one arg is different.
negated = None
for arg in ai.args:
# FIXME: what does this pass Do?
if arg in aj.args:
pass
elif self.NOT(arg).cancel() in aj.args:
if negated is None:
negated = arg
else:
negated = None
break
else:
negated = None
break
# If the different arg is a negation simplify the expr.
if negated is not None:
# Cancel out one of the two terms.
del args[j]
aiargs = list(ai.args)
aiargs.remove(negated)
if len(aiargs) == 1:
args[i] = aiargs[0]
else:
args[i] = self.dual(*aiargs)
if len(args) == 1:
return args[0]
else:
# Now the other simplifications have to be redone.
return self.__class__(*args).simplify()
j += 1
i += 1
# Absorption: A & (A | B) = A, A | (A & B) = A
# Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B
args = self.absorb(args)
if len(args) == 1:
return args[0]
# Commutativity: A & B = B & A, A | B = B | A
args.sort()
# Create new (now canonical) expression.
expr = self.__class__(*args)
expr.iscanonical = True
return expr
def flatten(self):
"""
Return a new expression where nested terms of this expression are
flattened as far as possible.
E.g. A & (B & C) becomes A & B & C.
"""
args = list(self.args)
i = 0
for arg in self.args:
if isinstance(arg, self.__class__):
args[i:i + 1] = arg.args
i += len(arg.args)
else:
i += 1
return self.__class__(*args)
def absorb(self, args):
"""
Given an `args` sequence of expressions, return a new list of expression
applying absorption and negative absorption.
See https://en.wikipedia.org/wiki/Absorption_law
Absorption: A & (A | B) = A, A | (A & B) = A
Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B
"""
args = list(args)
if not args:
args = list(self.args)
i = 0
while i < len(args):
absorber = args[i]
j = 0
while j < len(args):
if j == i:
j += 1
continue
target = args[j]
if not isinstance(target, self.dual):
j += 1
continue
# Absorption
if absorber in target:
del args[j]
if j < i:
i -= 1
continue
# Negative absorption
neg_absorber = self.NOT(absorber).cancel()
if neg_absorber in target:
b = target.subtract(neg_absorber, simplify=False)
if b is None:
del args[j]
if j < i:
i -= 1
continue
else:
args[j] = b
j += 1
continue
if isinstance(absorber, self.dual):
remove = None
for arg in absorber.args:
narg = self.NOT(arg).cancel()
if arg in target.args:
pass
elif narg in target.args:
if remove is None:
remove = narg
else:
remove = None
break
else:
remove = None
break
if remove is not None:
args[j] = target.subtract(remove, simplify=True)
j += 1
i += 1
return args
def distributive(self):
"""
Return a term where the leading AND or OR terms are switched.
This is done by applying the distributive laws:
A & (B|C) = (A&B) | (A&C)
A | (B&C) = (A|B) & (A|C)
"""
dual = self.dual
args = list(self.args)
for i, arg in enumerate(args):
if isinstance(arg, dual):
args[i] = arg.args
else:
args[i] = (arg,)
prod = itertools.product(*args)
args = tuple(self.__class__(*arg).simplify() for arg in prod)
if len(args) == 1:
return args[0]
else:
return dual(*args)
def __lt__(self, other):
comparator = Expression.__lt__(self, other)
if comparator is not NotImplemented:
return comparator
if isinstance(other, self.__class__):
lenself = len(self.args)
lenother = len(other.args)
for i in range(min(lenself, lenother)):
if self.args[i] == other.args[i]:
continue
comparator = self.args[i] < other.args[i]
if comparator is not NotImplemented:
return comparator
if lenself != lenother:
return lenself < lenother
return NotImplemented
|
bastikr/boolean.py | boolean/boolean.py | DualBase.distributive | python | def distributive(self):
dual = self.dual
args = list(self.args)
for i, arg in enumerate(args):
if isinstance(arg, dual):
args[i] = arg.args
else:
args[i] = (arg,)
prod = itertools.product(*args)
args = tuple(self.__class__(*arg).simplify() for arg in prod)
if len(args) == 1:
return args[0]
else:
return dual(*args) | Return a term where the leading AND or OR terms are switched.
This is done by applying the distributive laws:
A & (B|C) = (A&B) | (A&C)
A | (B&C) = (A|B) & (A|C) | train | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L1373-L1395 | null | class DualBase(Function):
"""
Base class for AND and OR function.
This class uses the duality principle to combine similar methods of AND
and OR. Both operations take 2 or more arguments and can be created using
"|" for OR and "&" for AND.
"""
def __init__(self, arg1, arg2, *args):
super(DualBase, self).__init__(arg1, arg2, *args)
# identity element for the specific operation.
# This will be TRUE for the AND operation and FALSE for the OR operation.
self.identity = None
# annihilator element for this function.
# This will be FALSE for the AND operation and TRUE for the OR operation.
self.annihilator = None
# dual class of this function.
# This means OR.dual returns AND and AND.dual returns OR.
self.dual = None
def __contains__(self, expr):
"""
Test if expr is a subterm of this expression.
"""
if expr in self.args:
return True
if isinstance(expr, self.__class__):
return all(arg in self.args for arg in expr.args)
def simplify(self):
"""
Return a new simplified expression in canonical form from this
expression.
For simplification of AND and OR fthe ollowing rules are used
recursively bottom up:
- Associativity (output does not contain same operations nested)
- Annihilation
- Idempotence
- Identity
- Complementation
- Elimination
- Absorption
- Commutativity (output is always sorted)
Other boolean objects are also in their canonical form.
"""
# TODO: Refactor DualBase.simplify into different "sub-evals".
# If self is already canonical do nothing.
if self.iscanonical:
return self
# Otherwise bring arguments into canonical form.
args = [arg.simplify() for arg in self.args]
# Create new instance of own class with canonical args.
# TODO: Only create new class if some args changed.
expr = self.__class__(*args)
# Literalize before doing anything, this also applies De Morgan's Law
expr = expr.literalize()
# Associativity:
# (A & B) & C = A & (B & C) = A & B & C
# (A | B) | C = A | (B | C) = A | B | C
expr = expr.flatten()
# Annihilation: A & 0 = 0, A | 1 = 1
if self.annihilator in expr.args:
return self.annihilator
# Idempotence: A & A = A, A | A = A
# this boils down to removing duplicates
args = []
for arg in expr.args:
if arg not in args:
args.append(arg)
if len(args) == 1:
return args[0]
# Identity: A & 1 = A, A | 0 = A
if self.identity in args:
args.remove(self.identity)
if len(args) == 1:
return args[0]
# Complementation: A & ~A = 0, A | ~A = 1
for arg in args:
if self.NOT(arg) in args:
return self.annihilator
# Elimination: (A & B) | (A & ~B) = A, (A | B) & (A | ~B) = A
i = 0
while i < len(args) - 1:
j = i + 1
ai = args[i]
if not isinstance(ai, self.dual):
i += 1
continue
while j < len(args):
aj = args[j]
if not isinstance(aj, self.dual) or len(ai.args) != len(aj.args):
j += 1
continue
# Find terms where only one arg is different.
negated = None
for arg in ai.args:
# FIXME: what does this pass Do?
if arg in aj.args:
pass
elif self.NOT(arg).cancel() in aj.args:
if negated is None:
negated = arg
else:
negated = None
break
else:
negated = None
break
# If the different arg is a negation simplify the expr.
if negated is not None:
# Cancel out one of the two terms.
del args[j]
aiargs = list(ai.args)
aiargs.remove(negated)
if len(aiargs) == 1:
args[i] = aiargs[0]
else:
args[i] = self.dual(*aiargs)
if len(args) == 1:
return args[0]
else:
# Now the other simplifications have to be redone.
return self.__class__(*args).simplify()
j += 1
i += 1
# Absorption: A & (A | B) = A, A | (A & B) = A
# Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B
args = self.absorb(args)
if len(args) == 1:
return args[0]
# Commutativity: A & B = B & A, A | B = B | A
args.sort()
# Create new (now canonical) expression.
expr = self.__class__(*args)
expr.iscanonical = True
return expr
def flatten(self):
"""
Return a new expression where nested terms of this expression are
flattened as far as possible.
E.g. A & (B & C) becomes A & B & C.
"""
args = list(self.args)
i = 0
for arg in self.args:
if isinstance(arg, self.__class__):
args[i:i + 1] = arg.args
i += len(arg.args)
else:
i += 1
return self.__class__(*args)
def absorb(self, args):
"""
Given an `args` sequence of expressions, return a new list of expression
applying absorption and negative absorption.
See https://en.wikipedia.org/wiki/Absorption_law
Absorption: A & (A | B) = A, A | (A & B) = A
Negative absorption: A & (~A | B) = A & B, A | (~A & B) = A | B
"""
args = list(args)
if not args:
args = list(self.args)
i = 0
while i < len(args):
absorber = args[i]
j = 0
while j < len(args):
if j == i:
j += 1
continue
target = args[j]
if not isinstance(target, self.dual):
j += 1
continue
# Absorption
if absorber in target:
del args[j]
if j < i:
i -= 1
continue
# Negative absorption
neg_absorber = self.NOT(absorber).cancel()
if neg_absorber in target:
b = target.subtract(neg_absorber, simplify=False)
if b is None:
del args[j]
if j < i:
i -= 1
continue
else:
args[j] = b
j += 1
continue
if isinstance(absorber, self.dual):
remove = None
for arg in absorber.args:
narg = self.NOT(arg).cancel()
if arg in target.args:
pass
elif narg in target.args:
if remove is None:
remove = narg
else:
remove = None
break
else:
remove = None
break
if remove is not None:
args[j] = target.subtract(remove, simplify=True)
j += 1
i += 1
return args
def subtract(self, expr, simplify):
"""
Return a new expression where the `expr` expression has been removed
from this expression if it exists.
"""
args = self.args
if expr in self.args:
args = list(self.args)
args.remove(expr)
elif isinstance(expr, self.__class__):
if all(arg in self.args for arg in expr.args):
args = tuple(arg for arg in self.args if arg not in expr)
if len(args) == 0:
return None
if len(args) == 1:
return args[0]
newexpr = self.__class__(*args)
if simplify:
newexpr = newexpr.simplify()
return newexpr
def __lt__(self, other):
comparator = Expression.__lt__(self, other)
if comparator is not NotImplemented:
return comparator
if isinstance(other, self.__class__):
lenself = len(self.args)
lenother = len(other.args)
for i in range(min(lenself, lenother)):
if self.args[i] == other.args[i]:
continue
comparator = self.args[i] < other.args[i]
if comparator is not NotImplemented:
return comparator
if lenself != lenother:
return lenself < lenother
return NotImplemented
|
liamw9534/bt-manager | bt_manager/interface.py | translate_to_dbus_type | python | def translate_to_dbus_type(typeof, value):
if ((isinstance(value, types.UnicodeType) or
isinstance(value, str)) and typeof is not dbus.String):
# FIXME: This is potentially dangerous since it evaluates
# a string in-situ
return typeof(eval(value))
else:
return typeof(value) | Helper function to map values from their native Python types
to Dbus types.
:param type typeof: Target for type conversion e.g., 'dbus.Dictionary'
:param value: Value to assign using type 'typeof'
:return: 'value' converted to type 'typeof'
:rtype: typeof | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/interface.py#L10-L26 | null | from __future__ import unicode_literals
import dbus
import types
import pprint
from exceptions import BTSignalNameNotRecognisedException
class Signal():
"""
Encapsulation of user callback wrapper for signals
fired by dbus. This allows us to prepend the signal
name and the user callback argument.
:param str signal: Signal name
:param func user_callback: User-defined callback function to
call when the signal triggers
:param user_arg: User-defined callback argument to be passed
as callback function
"""
def __init__(self, signal, user_callback, user_arg):
self.signal = signal
self.user_callback = user_callback
self.user_arg = user_arg
def signal_handler(self, *args):
"""
Method to call in order to invoke the user callback.
:param args: list of signal-dependent arguments
:return:
"""
self.user_callback(self.signal, self.user_arg, *args)
class BTSimpleInterface:
"""
Wrapper around dbus to encapsulated a BT simple interface
entry point (i.e., has no signals or properties).
:param str path: Object path pertaining to the interface to open
e.g., '/org/bluez/985/hci0'
:param str addr: dbus address of the interface instance to open
e.g., 'org.bluez.Adapter'
.. note:: This class should always be sub-classed with a concrete
implementation of a bluez interface which has no signals or
properties.
"""
def __init__(self, path, addr):
self._dbus_addr = addr
self._bus = dbus.SystemBus()
self._object = self._bus.get_object('org.bluez', path)
self._interface = dbus.Interface(self._object, addr)
self._path = path
# This class is not intended to be instantiated directly and should be
# sub-classed with a concrete implementation for an interface
class BTInterface(BTSimpleInterface):
"""
Wrapper around DBus to encapsulated a BT interface
entry point e.g., an adapter, a device, etc.
:param str path: Object path pertaining to the interface to open
e.g., '/org/bluez/985/hci0'
:param str addr: dbus address of the interface instance to open
e.g., 'org.bluez.Adapter'
.. note:: This class should always be sub-classed with a concrete
implementation of a bluez interface which has both signals
and properties.
"""
SIGNAL_PROPERTY_CHANGED = 'PropertyChanged'
"""
:signal PropertyChanged(sig_name, user_arg, prop_name, prop_value):
Signal notifying when a property has changed.
"""
def __init__(self, path, addr):
BTSimpleInterface.__init__(self, path, addr)
self._signals = {}
self._signal_names = []
self._properties = self._interface.GetProperties().keys()
self._register_signal_name(BTInterface.SIGNAL_PROPERTY_CHANGED)
def _register_signal_name(self, name):
"""
Helper function to register allowed signals on this
instance. Need only be called once per signal name and must be done
for each signal that may be used via :py:meth:`add_signal_receiver`
:param str name: Signal name to register e.g.,
:py:attr:`SIGNAL_PROPERTY_CHANGED`
:return:
"""
self._signal_names.append(name)
def add_signal_receiver(self, callback_fn, signal, user_arg):
"""
Add a signal receiver callback with user argument
See also :py:meth:`remove_signal_receiver`,
:py:exc:`.BTSignalNameNotRecognisedException`
:param func callback_fn: User-defined callback function to call when
signal triggers
:param str signal: Signal name e.g.,
:py:attr:`.BTInterface.SIGNAL_PROPERTY_CHANGED`
:param user_arg: User-defined callback argument to be passed with
callback function
:return:
:raises BTSignalNameNotRecognisedException: if the signal name is
not registered
"""
if (signal in self._signal_names):
s = Signal(signal, callback_fn, user_arg)
self._signals[signal] = s
self._bus.add_signal_receiver(s.signal_handler,
signal,
dbus_interface=self._dbus_addr,
path=self._path)
else:
raise BTSignalNameNotRecognisedException
def remove_signal_receiver(self, signal):
"""
Remove an installed signal receiver by signal name.
See also :py:meth:`add_signal_receiver`
:py:exc:`exceptions.BTSignalNameNotRecognisedException`
:param str signal: Signal name to uninstall
e.g., :py:attr:`SIGNAL_PROPERTY_CHANGED`
:return:
:raises BTSignalNameNotRecognisedException: if the signal name is
not registered
"""
if (signal in self._signal_names):
s = self._signals.get(signal)
if (s):
self._bus.remove_signal_receiver(s.signal_handler,
signal,
dbus_interface=self._dbus_addr) # noqa
self._signals.pop(signal)
else:
raise BTSignalNameNotRecognisedException
def get_property(self, name=None):
"""
Helper to get a property value by name or all
properties as a dictionary.
See also :py:meth:`set_property`
:param str name: defaults to None which means all properties
in the object's dictionary are returned as a dict.
Otherwise, the property name key is used and its value
is returned.
:return: Property value by property key, or a dictionary of
all properties
:raises KeyError: if the property key is not found in the
object's dictionary
:raises dbus.Exception: org.bluez.Error.DoesNotExist
:raises dbus.Exception: org.bluez.Error.InvalidArguments
"""
if (name):
return self._interface.GetProperties()[name]
else:
return self._interface.GetProperties()
def set_property(self, name, value):
"""
Helper to set a property value by name, translating to correct
dbus type
See also :py:meth:`get_property`
:param str name: The property name in the object's dictionary
whose value shall be set.
:param value: Properties new value to be assigned.
:return:
:raises KeyError: if the property key is not found in the
object's dictionary
:raises dbus.Exception: org.bluez.Error.DoesNotExist
:raises dbus.Exception: org.bluez.Error.InvalidArguments
"""
typeof = type(self.get_property(name))
self._interface.SetProperty(name,
translate_to_dbus_type(typeof, value))
def __getattr__(self, name):
"""Override default getattr behaviours to allow DBus object
properties to be exposed in the class for getting"""
if name in self.__dict__:
return self.__dict__[name]
elif '_properties' in self.__dict__ and name in self._properties:
return self.get_property(name)
def __setattr__(self, name, value):
"""Override default setattr behaviours to allow DBus object
properties to be exposed in the class for setting"""
if '_properties' in self.__dict__ and name not in self.__dict__:
self.set_property(name, value)
else:
self.__dict__[name] = value
def __repr__(self):
"""Stringify the Dbus interface properties as raw"""
return self.__str__()
def __str__(self):
"""Stringify the Dbus interface properties in a nice format"""
return pprint.pformat(self._interface.GetProperties())
|
liamw9534/bt-manager | bt_manager/interface.py | Signal.signal_handler | python | def signal_handler(self, *args):
self.user_callback(self.signal, self.user_arg, *args) | Method to call in order to invoke the user callback.
:param args: list of signal-dependent arguments
:return: | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/interface.py#L46-L53 | null | class Signal():
"""
Encapsulation of user callback wrapper for signals
fired by dbus. This allows us to prepend the signal
name and the user callback argument.
:param str signal: Signal name
:param func user_callback: User-defined callback function to
call when the signal triggers
:param user_arg: User-defined callback argument to be passed
as callback function
"""
def __init__(self, signal, user_callback, user_arg):
self.signal = signal
self.user_callback = user_callback
self.user_arg = user_arg
|
liamw9534/bt-manager | bt_manager/interface.py | BTInterface.add_signal_receiver | python | def add_signal_receiver(self, callback_fn, signal, user_arg):
if (signal in self._signal_names):
s = Signal(signal, callback_fn, user_arg)
self._signals[signal] = s
self._bus.add_signal_receiver(s.signal_handler,
signal,
dbus_interface=self._dbus_addr,
path=self._path)
else:
raise BTSignalNameNotRecognisedException | Add a signal receiver callback with user argument
See also :py:meth:`remove_signal_receiver`,
:py:exc:`.BTSignalNameNotRecognisedException`
:param func callback_fn: User-defined callback function to call when
signal triggers
:param str signal: Signal name e.g.,
:py:attr:`.BTInterface.SIGNAL_PROPERTY_CHANGED`
:param user_arg: User-defined callback argument to be passed with
callback function
:return:
:raises BTSignalNameNotRecognisedException: if the signal name is
not registered | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/interface.py#L120-L145 | null | class BTInterface(BTSimpleInterface):
"""
Wrapper around DBus to encapsulated a BT interface
entry point e.g., an adapter, a device, etc.
:param str path: Object path pertaining to the interface to open
e.g., '/org/bluez/985/hci0'
:param str addr: dbus address of the interface instance to open
e.g., 'org.bluez.Adapter'
.. note:: This class should always be sub-classed with a concrete
implementation of a bluez interface which has both signals
and properties.
"""
SIGNAL_PROPERTY_CHANGED = 'PropertyChanged'
"""
:signal PropertyChanged(sig_name, user_arg, prop_name, prop_value):
Signal notifying when a property has changed.
"""
def __init__(self, path, addr):
BTSimpleInterface.__init__(self, path, addr)
self._signals = {}
self._signal_names = []
self._properties = self._interface.GetProperties().keys()
self._register_signal_name(BTInterface.SIGNAL_PROPERTY_CHANGED)
def _register_signal_name(self, name):
"""
Helper function to register allowed signals on this
instance. Need only be called once per signal name and must be done
for each signal that may be used via :py:meth:`add_signal_receiver`
:param str name: Signal name to register e.g.,
:py:attr:`SIGNAL_PROPERTY_CHANGED`
:return:
"""
self._signal_names.append(name)
def remove_signal_receiver(self, signal):
"""
Remove an installed signal receiver by signal name.
See also :py:meth:`add_signal_receiver`
:py:exc:`exceptions.BTSignalNameNotRecognisedException`
:param str signal: Signal name to uninstall
e.g., :py:attr:`SIGNAL_PROPERTY_CHANGED`
:return:
:raises BTSignalNameNotRecognisedException: if the signal name is
not registered
"""
if (signal in self._signal_names):
s = self._signals.get(signal)
if (s):
self._bus.remove_signal_receiver(s.signal_handler,
signal,
dbus_interface=self._dbus_addr) # noqa
self._signals.pop(signal)
else:
raise BTSignalNameNotRecognisedException
def get_property(self, name=None):
"""
Helper to get a property value by name or all
properties as a dictionary.
See also :py:meth:`set_property`
:param str name: defaults to None which means all properties
in the object's dictionary are returned as a dict.
Otherwise, the property name key is used and its value
is returned.
:return: Property value by property key, or a dictionary of
all properties
:raises KeyError: if the property key is not found in the
object's dictionary
:raises dbus.Exception: org.bluez.Error.DoesNotExist
:raises dbus.Exception: org.bluez.Error.InvalidArguments
"""
if (name):
return self._interface.GetProperties()[name]
else:
return self._interface.GetProperties()
def set_property(self, name, value):
"""
Helper to set a property value by name, translating to correct
dbus type
See also :py:meth:`get_property`
:param str name: The property name in the object's dictionary
whose value shall be set.
:param value: Properties new value to be assigned.
:return:
:raises KeyError: if the property key is not found in the
object's dictionary
:raises dbus.Exception: org.bluez.Error.DoesNotExist
:raises dbus.Exception: org.bluez.Error.InvalidArguments
"""
typeof = type(self.get_property(name))
self._interface.SetProperty(name,
translate_to_dbus_type(typeof, value))
def __getattr__(self, name):
"""Override default getattr behaviours to allow DBus object
properties to be exposed in the class for getting"""
if name in self.__dict__:
return self.__dict__[name]
elif '_properties' in self.__dict__ and name in self._properties:
return self.get_property(name)
def __setattr__(self, name, value):
"""Override default setattr behaviours to allow DBus object
properties to be exposed in the class for setting"""
if '_properties' in self.__dict__ and name not in self.__dict__:
self.set_property(name, value)
else:
self.__dict__[name] = value
def __repr__(self):
"""Stringify the Dbus interface properties as raw"""
return self.__str__()
def __str__(self):
"""Stringify the Dbus interface properties in a nice format"""
return pprint.pformat(self._interface.GetProperties())
|
liamw9534/bt-manager | bt_manager/interface.py | BTInterface.get_property | python | def get_property(self, name=None):
if (name):
return self._interface.GetProperties()[name]
else:
return self._interface.GetProperties() | Helper to get a property value by name or all
properties as a dictionary.
See also :py:meth:`set_property`
:param str name: defaults to None which means all properties
in the object's dictionary are returned as a dict.
Otherwise, the property name key is used and its value
is returned.
:return: Property value by property key, or a dictionary of
all properties
:raises KeyError: if the property key is not found in the
object's dictionary
:raises dbus.Exception: org.bluez.Error.DoesNotExist
:raises dbus.Exception: org.bluez.Error.InvalidArguments | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/interface.py#L170-L191 | null | class BTInterface(BTSimpleInterface):
"""
Wrapper around DBus to encapsulated a BT interface
entry point e.g., an adapter, a device, etc.
:param str path: Object path pertaining to the interface to open
e.g., '/org/bluez/985/hci0'
:param str addr: dbus address of the interface instance to open
e.g., 'org.bluez.Adapter'
.. note:: This class should always be sub-classed with a concrete
implementation of a bluez interface which has both signals
and properties.
"""
SIGNAL_PROPERTY_CHANGED = 'PropertyChanged'
"""
:signal PropertyChanged(sig_name, user_arg, prop_name, prop_value):
Signal notifying when a property has changed.
"""
def __init__(self, path, addr):
BTSimpleInterface.__init__(self, path, addr)
self._signals = {}
self._signal_names = []
self._properties = self._interface.GetProperties().keys()
self._register_signal_name(BTInterface.SIGNAL_PROPERTY_CHANGED)
def _register_signal_name(self, name):
"""
Helper function to register allowed signals on this
instance. Need only be called once per signal name and must be done
for each signal that may be used via :py:meth:`add_signal_receiver`
:param str name: Signal name to register e.g.,
:py:attr:`SIGNAL_PROPERTY_CHANGED`
:return:
"""
self._signal_names.append(name)
def add_signal_receiver(self, callback_fn, signal, user_arg):
"""
Add a signal receiver callback with user argument
See also :py:meth:`remove_signal_receiver`,
:py:exc:`.BTSignalNameNotRecognisedException`
:param func callback_fn: User-defined callback function to call when
signal triggers
:param str signal: Signal name e.g.,
:py:attr:`.BTInterface.SIGNAL_PROPERTY_CHANGED`
:param user_arg: User-defined callback argument to be passed with
callback function
:return:
:raises BTSignalNameNotRecognisedException: if the signal name is
not registered
"""
if (signal in self._signal_names):
s = Signal(signal, callback_fn, user_arg)
self._signals[signal] = s
self._bus.add_signal_receiver(s.signal_handler,
signal,
dbus_interface=self._dbus_addr,
path=self._path)
else:
raise BTSignalNameNotRecognisedException
def remove_signal_receiver(self, signal):
"""
Remove an installed signal receiver by signal name.
See also :py:meth:`add_signal_receiver`
:py:exc:`exceptions.BTSignalNameNotRecognisedException`
:param str signal: Signal name to uninstall
e.g., :py:attr:`SIGNAL_PROPERTY_CHANGED`
:return:
:raises BTSignalNameNotRecognisedException: if the signal name is
not registered
"""
if (signal in self._signal_names):
s = self._signals.get(signal)
if (s):
self._bus.remove_signal_receiver(s.signal_handler,
signal,
dbus_interface=self._dbus_addr) # noqa
self._signals.pop(signal)
else:
raise BTSignalNameNotRecognisedException
def set_property(self, name, value):
"""
Helper to set a property value by name, translating to correct
dbus type
See also :py:meth:`get_property`
:param str name: The property name in the object's dictionary
whose value shall be set.
:param value: Properties new value to be assigned.
:return:
:raises KeyError: if the property key is not found in the
object's dictionary
:raises dbus.Exception: org.bluez.Error.DoesNotExist
:raises dbus.Exception: org.bluez.Error.InvalidArguments
"""
typeof = type(self.get_property(name))
self._interface.SetProperty(name,
translate_to_dbus_type(typeof, value))
def __getattr__(self, name):
"""Override default getattr behaviours to allow DBus object
properties to be exposed in the class for getting"""
if name in self.__dict__:
return self.__dict__[name]
elif '_properties' in self.__dict__ and name in self._properties:
return self.get_property(name)
def __setattr__(self, name, value):
"""Override default setattr behaviours to allow DBus object
properties to be exposed in the class for setting"""
if '_properties' in self.__dict__ and name not in self.__dict__:
self.set_property(name, value)
else:
self.__dict__[name] = value
def __repr__(self):
"""Stringify the Dbus interface properties as raw"""
return self.__str__()
def __str__(self):
"""Stringify the Dbus interface properties in a nice format"""
return pprint.pformat(self._interface.GetProperties())
|
liamw9534/bt-manager | bt_manager/interface.py | BTInterface.set_property | python | def set_property(self, name, value):
typeof = type(self.get_property(name))
self._interface.SetProperty(name,
translate_to_dbus_type(typeof, value)) | Helper to set a property value by name, translating to correct
dbus type
See also :py:meth:`get_property`
:param str name: The property name in the object's dictionary
whose value shall be set.
:param value: Properties new value to be assigned.
:return:
:raises KeyError: if the property key is not found in the
object's dictionary
:raises dbus.Exception: org.bluez.Error.DoesNotExist
:raises dbus.Exception: org.bluez.Error.InvalidArguments | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/interface.py#L193-L211 | [
"def translate_to_dbus_type(typeof, value):\n \"\"\"\n Helper function to map values from their native Python types\n to Dbus types.\n\n :param type typeof: Target for type conversion e.g., 'dbus.Dictionary'\n :param value: Value to assign using type 'typeof'\n :return: 'value' converted to type '... | class BTInterface(BTSimpleInterface):
"""
Wrapper around DBus to encapsulated a BT interface
entry point e.g., an adapter, a device, etc.
:param str path: Object path pertaining to the interface to open
e.g., '/org/bluez/985/hci0'
:param str addr: dbus address of the interface instance to open
e.g., 'org.bluez.Adapter'
.. note:: This class should always be sub-classed with a concrete
implementation of a bluez interface which has both signals
and properties.
"""
SIGNAL_PROPERTY_CHANGED = 'PropertyChanged'
"""
:signal PropertyChanged(sig_name, user_arg, prop_name, prop_value):
Signal notifying when a property has changed.
"""
def __init__(self, path, addr):
BTSimpleInterface.__init__(self, path, addr)
self._signals = {}
self._signal_names = []
self._properties = self._interface.GetProperties().keys()
self._register_signal_name(BTInterface.SIGNAL_PROPERTY_CHANGED)
def _register_signal_name(self, name):
"""
Helper function to register allowed signals on this
instance. Need only be called once per signal name and must be done
for each signal that may be used via :py:meth:`add_signal_receiver`
:param str name: Signal name to register e.g.,
:py:attr:`SIGNAL_PROPERTY_CHANGED`
:return:
"""
self._signal_names.append(name)
def add_signal_receiver(self, callback_fn, signal, user_arg):
"""
Add a signal receiver callback with user argument
See also :py:meth:`remove_signal_receiver`,
:py:exc:`.BTSignalNameNotRecognisedException`
:param func callback_fn: User-defined callback function to call when
signal triggers
:param str signal: Signal name e.g.,
:py:attr:`.BTInterface.SIGNAL_PROPERTY_CHANGED`
:param user_arg: User-defined callback argument to be passed with
callback function
:return:
:raises BTSignalNameNotRecognisedException: if the signal name is
not registered
"""
if (signal in self._signal_names):
s = Signal(signal, callback_fn, user_arg)
self._signals[signal] = s
self._bus.add_signal_receiver(s.signal_handler,
signal,
dbus_interface=self._dbus_addr,
path=self._path)
else:
raise BTSignalNameNotRecognisedException
def remove_signal_receiver(self, signal):
"""
Remove an installed signal receiver by signal name.
See also :py:meth:`add_signal_receiver`
:py:exc:`exceptions.BTSignalNameNotRecognisedException`
:param str signal: Signal name to uninstall
e.g., :py:attr:`SIGNAL_PROPERTY_CHANGED`
:return:
:raises BTSignalNameNotRecognisedException: if the signal name is
not registered
"""
if (signal in self._signal_names):
s = self._signals.get(signal)
if (s):
self._bus.remove_signal_receiver(s.signal_handler,
signal,
dbus_interface=self._dbus_addr) # noqa
self._signals.pop(signal)
else:
raise BTSignalNameNotRecognisedException
def get_property(self, name=None):
"""
Helper to get a property value by name or all
properties as a dictionary.
See also :py:meth:`set_property`
:param str name: defaults to None which means all properties
in the object's dictionary are returned as a dict.
Otherwise, the property name key is used and its value
is returned.
:return: Property value by property key, or a dictionary of
all properties
:raises KeyError: if the property key is not found in the
object's dictionary
:raises dbus.Exception: org.bluez.Error.DoesNotExist
:raises dbus.Exception: org.bluez.Error.InvalidArguments
"""
if (name):
return self._interface.GetProperties()[name]
else:
return self._interface.GetProperties()
def __getattr__(self, name):
"""Override default getattr behaviours to allow DBus object
properties to be exposed in the class for getting"""
if name in self.__dict__:
return self.__dict__[name]
elif '_properties' in self.__dict__ and name in self._properties:
return self.get_property(name)
def __setattr__(self, name, value):
"""Override default setattr behaviours to allow DBus object
properties to be exposed in the class for setting"""
if '_properties' in self.__dict__ and name not in self.__dict__:
self.set_property(name, value)
else:
self.__dict__[name] = value
def __repr__(self):
"""Stringify the Dbus interface properties as raw"""
return self.__str__()
def __str__(self):
"""Stringify the Dbus interface properties in a nice format"""
return pprint.pformat(self._interface.GetProperties())
|
liamw9534/bt-manager | bt_manager/cod.py | BTCoD.major_service_class | python | def major_service_class(self):
major_service = []
for i in BTCoD._MAJOR_SERVICE_CLASS.keys():
if (self.cod & i):
major_service.append(BTCoD._MAJOR_SERVICE_CLASS[i])
return major_service | Return the major service class property decoded e.g.,
Audio, Telephony, etc | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/cod.py#L167-L176 | null | class BTCoD:
"""
Bluetooth class of device decoder for providing
a human readable form of the device class value.
The class of device is a 24-bit number allowing different
types of bluetooth devices to be described consistently
and succinctly using a hierarchical scheme.
* **Major Service**: The major services that the
device supports. Several values can be OR'd together
to form a device supporting multiple major services
e.g., telephony, networking and audio could be
the combined service set for a device.
* **Major Device**: The form-factor or major type of device
which may only take a single value e.g., Laptop,
Toy, Health Device, Phone, etc.
* **Minor Device**: The minor function of the device whose
range of values depends on the major function e.g.,
Car audio, SmartPhone, etc.
:param integer cod: 24-bit integer value representing the
class of device.
.. note:: The class of device may be obtained from both
the :py:class:`.BTAdapter` and :py:class:`.BTDevice`
classes using the `Class` attribute.
"""
_MAJOR_SERVICE_POS = 13
_MAJOR_SERVICE_MASK = 0xFFE000
_MAJOR_SERVICE_CLASS = {
0x002000: 'Limited Discoverable Mode [Ref #1]',
0x004000: '(reserved)',
0x008000: '(reserved)',
0x010000: 'Positioning (Location identification)',
0x020000: 'Networking (LAN, Ad hoc, ...)',
0x040000: 'Rendering (Printing, Speakers, ...)',
0x080000: 'Capturing (Scanner, Microphone, ...)',
0x100000: 'Object Transfer (v-Inbox, v-Folder, ...)',
0x200000: 'Audio (Speaker, Microphone, Headset service, ...)',
0x400000: 'Telephony (Cordless telephony, Modem, Headset service, ...)', # noqa
0x800000: 'Information (WEB-server, WAP-server, ...)',
}
_MAJOR_DEVICE_POS = 8
_MAJOR_DEVICE_MASK = 0x001F00
_MAJOR_DEVICE_CLASS = {
0x0000: 'Miscellaneous [Ref #2]',
0x0100: 'Computer (desktop, notebook, PDA, organizer, ... )',
0x0200: 'Phone (cellular, cordless, pay phone, modem, ...)',
0x0300: 'LAN /Network Access point',
0x0400: 'Audio/Video (headset, speaker, stereo, video display, VCR, ...', # noqa
0x0500: 'Peripheral (mouse, joystick, keyboard, ... ',
0x0600: 'Imaging (printer, scanner, camera, display, ...)',
0x0700: 'Wearable',
0x0800: 'Toy',
0x0900: 'Health',
0x1F00: 'Uncategorized: device code not specified'
}
_MINOR_DEVICE_CLASS = {
0x0100: [{'mask': 0x1C, 'pos': 2,
0x00: 'Uncategorized, code for device not assigned',
0x04: 'Desktop workstation',
0x08: 'Server-class computer',
0x0C: 'Laptop',
0x10: 'Handheld PC/PDA (clamshell)',
0x14: 'Palm-size PC/PDA',
0x18: 'Wearable computer (watch size)',
0x1C: 'Tablet'}],
0x0200: [{'mask': 0x1C, 'pos': 2,
0x00: 'Uncategorized, code for device not assigned',
0x04: 'Cellular',
0x08: 'Cordless',
0x0C: 'Smartphone',
0x10: 'Wired modem or voice gateway',
0x14: 'Common ISDN access'}],
0x0300: [{'mask': 0xE0, 'pos': 5,
0x00: 'Fully available',
0x20: '1% to 17% utilized',
0x40: '17% to 33% utilized',
0x60: '33% to 50% utilized',
0x80: '50% to 67% utilized',
0xA0: '67% to 83% utilized',
0xC0: '83% to 99% utilized',
0xE0: 'No service available'}],
0x0400: [{'mask': 0x7C, 'pos': 2,
0x00: 'Uncategorized, code not assigned',
0x04: 'Wearable Headset Device',
0x08: 'Hands-free Device',
0x0C: '(Reserved)',
0x10: 'Microphone',
0x14: 'Loudspeaker',
0x18: 'Headphones',
0x1C: 'Portable Audio',
0x20: 'Car audio',
0x24: 'Set-top box',
0x28: 'HiFi Audio Device',
0x2C: 'VCR',
0x30: 'Video Camera',
0x34: 'Camcorder',
0x38: 'Video Monitor',
0x3C: 'Video Display and Loudspeaker',
0x40: 'Video Conferencing',
0x44: '(Reserved)',
0x48: 'Gaming/Toy'}],
0x0500: [{'mask': 0xC0, 'pos': 6,
0x00: 'Not Keyboard / Not Pointing Device',
0x40: 'Keyboard',
0x80: 'Pointing device',
0xC0: 'Combo keyboard/pointing device'},
{'mask': 0x3C, 'pos': 2,
0x00: 'Uncategorized device',
0x04: 'Joystick',
0x08: 'Gamepad',
0x0C: 'Remote control',
0x10: 'Sensing device',
0x14: 'Digitizer tablet',
0x18: 'Card Reader (e.g. SIM Card Reader)',
0x1C: 'Digital Pen',
0x20: 'Handheld scanner for bar-codes, RFID, etc.',
0x24: 'Handheld gestural input device (e.g., "wand" form factor)'}], # noqa
0x0600: [{'mask': 0xF0, 'pos': 4,
0x10: 'Display',
0x20: 'Camera',
0x40: 'Scanner',
0x80: 'Printer'}],
0x0700: [{'mask': 0x1C, 'pos': 2,
0x04: 'Wristwatch',
0x08: 'Pager',
0x0C: 'Jacket',
0x10: 'Helmet',
0x14: 'Glasses'}],
0x0800: [{'mask': 0x1C, 'pos': 2,
0x04: 'Robot',
0x08: 'Vehicle',
0x0C: 'Doll / Action figure',
0x10: 'Controller',
0x14: 'Game'}],
0x0900: [{'mask': 0x3C, 'pos': 2,
0x00: 'Undefined',
0x04: 'Blood Pressure Monitor',
0x08: 'Thermometer',
0x0C: 'Weighing Scale',
0x10: 'Glucose Meter',
0x14: 'Pulse Oximeter',
0x18: 'Heart/Pulse Rate Monitor',
0x1C: 'Health Data Display',
0x20: 'Step Counter',
0x24: 'Body Composition Analyzer',
0x28: 'Peak Flow Monitor',
0x2C: 'Medication Monitor',
0x30: 'Knee Prosthesis',
0x34: 'Ankle Prosthesis',
0x38: 'Generic Health Manager',
0x3C: 'Personal Mobility Device'}]
}
def __init__(self, cod):
self.cod = cod
@property
@property
def major_device_class(self):
"""
Return the major device class property decoded e.g.,
Computer, Audio/Video, Toy, etc.
"""
return BTCoD._MAJOR_DEVICE_CLASS.get(self.cod &
BTCoD._MAJOR_DEVICE_MASK,
'Unknown')
@property
def minor_device_class(self):
"""
Return the minor device class property decoded e.g.,
Scanner, Printer, Loudspeaker, Camera, etc.
"""
minor_device = []
minor_lookup = BTCoD._MINOR_DEVICE_CLASS.get(self.cod &
BTCoD._MAJOR_DEVICE_MASK,
[])
for i in minor_lookup:
minor_value = self.cod & i.get('mask')
minor_device.append(i.get(minor_value, 'Unknown'))
return minor_device
def __str__(self):
"""Stringify all elements of the class of device"""
return '<cod:' + str(hex(self.cod)) + ' Major Service:' + str(self.major_service_class) + \
' Major Device:' + \
self.major_device_class + ' Minor Device:' + \
str(self.minor_device_class) + '>'
def __repr__(self):
return self.__str__()
|
liamw9534/bt-manager | bt_manager/cod.py | BTCoD.minor_device_class | python | def minor_device_class(self):
minor_device = []
minor_lookup = BTCoD._MINOR_DEVICE_CLASS.get(self.cod &
BTCoD._MAJOR_DEVICE_MASK,
[])
for i in minor_lookup:
minor_value = self.cod & i.get('mask')
minor_device.append(i.get(minor_value, 'Unknown'))
return minor_device | Return the minor device class property decoded e.g.,
Scanner, Printer, Loudspeaker, Camera, etc. | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/cod.py#L189-L201 | null | class BTCoD:
"""
Bluetooth class of device decoder for providing
a human readable form of the device class value.
The class of device is a 24-bit number allowing different
types of bluetooth devices to be described consistently
and succinctly using a hierarchical scheme.
* **Major Service**: The major services that the
device supports. Several values can be OR'd together
to form a device supporting multiple major services
e.g., telephony, networking and audio could be
the combined service set for a device.
* **Major Device**: The form-factor or major type of device
which may only take a single value e.g., Laptop,
Toy, Health Device, Phone, etc.
* **Minor Device**: The minor function of the device whose
range of values depends on the major function e.g.,
Car audio, SmartPhone, etc.
:param integer cod: 24-bit integer value representing the
class of device.
.. note:: The class of device may be obtained from both
the :py:class:`.BTAdapter` and :py:class:`.BTDevice`
classes using the `Class` attribute.
"""
_MAJOR_SERVICE_POS = 13
_MAJOR_SERVICE_MASK = 0xFFE000
_MAJOR_SERVICE_CLASS = {
0x002000: 'Limited Discoverable Mode [Ref #1]',
0x004000: '(reserved)',
0x008000: '(reserved)',
0x010000: 'Positioning (Location identification)',
0x020000: 'Networking (LAN, Ad hoc, ...)',
0x040000: 'Rendering (Printing, Speakers, ...)',
0x080000: 'Capturing (Scanner, Microphone, ...)',
0x100000: 'Object Transfer (v-Inbox, v-Folder, ...)',
0x200000: 'Audio (Speaker, Microphone, Headset service, ...)',
0x400000: 'Telephony (Cordless telephony, Modem, Headset service, ...)', # noqa
0x800000: 'Information (WEB-server, WAP-server, ...)',
}
_MAJOR_DEVICE_POS = 8
_MAJOR_DEVICE_MASK = 0x001F00
_MAJOR_DEVICE_CLASS = {
0x0000: 'Miscellaneous [Ref #2]',
0x0100: 'Computer (desktop, notebook, PDA, organizer, ... )',
0x0200: 'Phone (cellular, cordless, pay phone, modem, ...)',
0x0300: 'LAN /Network Access point',
0x0400: 'Audio/Video (headset, speaker, stereo, video display, VCR, ...', # noqa
0x0500: 'Peripheral (mouse, joystick, keyboard, ... ',
0x0600: 'Imaging (printer, scanner, camera, display, ...)',
0x0700: 'Wearable',
0x0800: 'Toy',
0x0900: 'Health',
0x1F00: 'Uncategorized: device code not specified'
}
_MINOR_DEVICE_CLASS = {
0x0100: [{'mask': 0x1C, 'pos': 2,
0x00: 'Uncategorized, code for device not assigned',
0x04: 'Desktop workstation',
0x08: 'Server-class computer',
0x0C: 'Laptop',
0x10: 'Handheld PC/PDA (clamshell)',
0x14: 'Palm-size PC/PDA',
0x18: 'Wearable computer (watch size)',
0x1C: 'Tablet'}],
0x0200: [{'mask': 0x1C, 'pos': 2,
0x00: 'Uncategorized, code for device not assigned',
0x04: 'Cellular',
0x08: 'Cordless',
0x0C: 'Smartphone',
0x10: 'Wired modem or voice gateway',
0x14: 'Common ISDN access'}],
0x0300: [{'mask': 0xE0, 'pos': 5,
0x00: 'Fully available',
0x20: '1% to 17% utilized',
0x40: '17% to 33% utilized',
0x60: '33% to 50% utilized',
0x80: '50% to 67% utilized',
0xA0: '67% to 83% utilized',
0xC0: '83% to 99% utilized',
0xE0: 'No service available'}],
0x0400: [{'mask': 0x7C, 'pos': 2,
0x00: 'Uncategorized, code not assigned',
0x04: 'Wearable Headset Device',
0x08: 'Hands-free Device',
0x0C: '(Reserved)',
0x10: 'Microphone',
0x14: 'Loudspeaker',
0x18: 'Headphones',
0x1C: 'Portable Audio',
0x20: 'Car audio',
0x24: 'Set-top box',
0x28: 'HiFi Audio Device',
0x2C: 'VCR',
0x30: 'Video Camera',
0x34: 'Camcorder',
0x38: 'Video Monitor',
0x3C: 'Video Display and Loudspeaker',
0x40: 'Video Conferencing',
0x44: '(Reserved)',
0x48: 'Gaming/Toy'}],
0x0500: [{'mask': 0xC0, 'pos': 6,
0x00: 'Not Keyboard / Not Pointing Device',
0x40: 'Keyboard',
0x80: 'Pointing device',
0xC0: 'Combo keyboard/pointing device'},
{'mask': 0x3C, 'pos': 2,
0x00: 'Uncategorized device',
0x04: 'Joystick',
0x08: 'Gamepad',
0x0C: 'Remote control',
0x10: 'Sensing device',
0x14: 'Digitizer tablet',
0x18: 'Card Reader (e.g. SIM Card Reader)',
0x1C: 'Digital Pen',
0x20: 'Handheld scanner for bar-codes, RFID, etc.',
0x24: 'Handheld gestural input device (e.g., "wand" form factor)'}], # noqa
0x0600: [{'mask': 0xF0, 'pos': 4,
0x10: 'Display',
0x20: 'Camera',
0x40: 'Scanner',
0x80: 'Printer'}],
0x0700: [{'mask': 0x1C, 'pos': 2,
0x04: 'Wristwatch',
0x08: 'Pager',
0x0C: 'Jacket',
0x10: 'Helmet',
0x14: 'Glasses'}],
0x0800: [{'mask': 0x1C, 'pos': 2,
0x04: 'Robot',
0x08: 'Vehicle',
0x0C: 'Doll / Action figure',
0x10: 'Controller',
0x14: 'Game'}],
0x0900: [{'mask': 0x3C, 'pos': 2,
0x00: 'Undefined',
0x04: 'Blood Pressure Monitor',
0x08: 'Thermometer',
0x0C: 'Weighing Scale',
0x10: 'Glucose Meter',
0x14: 'Pulse Oximeter',
0x18: 'Heart/Pulse Rate Monitor',
0x1C: 'Health Data Display',
0x20: 'Step Counter',
0x24: 'Body Composition Analyzer',
0x28: 'Peak Flow Monitor',
0x2C: 'Medication Monitor',
0x30: 'Knee Prosthesis',
0x34: 'Ankle Prosthesis',
0x38: 'Generic Health Manager',
0x3C: 'Personal Mobility Device'}]
}
def __init__(self, cod):
self.cod = cod
@property
def major_service_class(self):
"""
Return the major service class property decoded e.g.,
Audio, Telephony, etc
"""
major_service = []
for i in BTCoD._MAJOR_SERVICE_CLASS.keys():
if (self.cod & i):
major_service.append(BTCoD._MAJOR_SERVICE_CLASS[i])
return major_service
@property
def major_device_class(self):
"""
Return the major device class property decoded e.g.,
Computer, Audio/Video, Toy, etc.
"""
return BTCoD._MAJOR_DEVICE_CLASS.get(self.cod &
BTCoD._MAJOR_DEVICE_MASK,
'Unknown')
@property
def __str__(self):
"""Stringify all elements of the class of device"""
return '<cod:' + str(hex(self.cod)) + ' Major Service:' + str(self.major_service_class) + \
' Major Device:' + \
self.major_device_class + ' Minor Device:' + \
str(self.minor_device_class) + '>'
def __repr__(self):
return self.__str__()
|
liamw9534/bt-manager | bt_manager/codecs.py | SBCCodec._init_sbc_config | python | def _init_sbc_config(self, config):
if (config.channel_mode == SBCChannelMode.CHANNEL_MODE_MONO):
self.config.mode = self.codec.SBC_MODE_MONO
elif (config.channel_mode == SBCChannelMode.CHANNEL_MODE_STEREO):
self.config.mode = self.codec.SBC_MODE_STEREO
elif (config.channel_mode == SBCChannelMode.CHANNEL_MODE_DUAL):
self.config.mode = self.codec.SBC_MODE_DUAL_CHANNEL
elif (config.channel_mode == SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
self.config.mode = self.codec.SBC_MODE_JOINT_STEREO
if (config.frequency == SBCSamplingFrequency.FREQ_16KHZ):
self.config.frequency = self.codec.SBC_FREQ_16000
elif (config.frequency == SBCSamplingFrequency.FREQ_32KHZ):
self.config.frequency = self.codec.SBC_FREQ_32000
elif (config.frequency == SBCSamplingFrequency.FREQ_44_1KHZ):
self.config.frequency = self.codec.SBC_FREQ_44100
elif (config.frequency == SBCSamplingFrequency.FREQ_48KHZ):
self.config.frequency = self.codec.SBC_FREQ_48000
if (config.allocation_method == SBCAllocationMethod.LOUDNESS):
self.config.allocation = self.codec.SBC_AM_LOUDNESS
elif (config.allocation_method == SBCAllocationMethod.SNR):
self.config.allocation = self.codec.SBC_AM_SNR
if (config.subbands == SBCSubbands.SUBBANDS_4):
self.config.subbands = self.codec.SBC_SB_4
elif (config.subbands == SBCSubbands.SUBBANDS_8):
self.config.subbands = self.codec.SBC_SB_8
if (config.block_length == SBCBlocks.BLOCKS_4):
self.config.blocks = self.codec.SBC_BLK_4
elif (config.block_length == SBCBlocks.BLOCKS_8):
self.config.blocks = self.codec.SBC_BLK_8
elif (config.block_length == SBCBlocks.BLOCKS_12):
self.config.blocks = self.codec.SBC_BLK_12
elif (config.block_length == SBCBlocks.BLOCKS_16):
self.config.blocks = self.codec.SBC_BLK_16
self.config.bitpool = config.max_bitpool
self.config.endian = self.codec.SBC_LE | Translator from namedtuple config representation to
the sbc_t type.
:param namedtuple config: See :py:class:`.SBCCodecConfig`
:returns: | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/codecs.py#L111-L157 | null | class SBCCodec:
"""
Python cass wrapper around CFFI calls into the SBC codec
implemented in C. The main API is defined by sbc.h with
additional functions added to encapsulate an SBC payload
as part of an RTP packet. The API extensions for RTP
are designed to work directly with bluetooth media
transport file descriptors for the A2DP profile. So,
the basic idea is that this class is instantiated as
part of a media endpoint implementation in order to
encode or decode data carried on the media transport.
.. note:: You need two separate instantiations of this
class if you wish to encode and decode at the same
time. Although the class implementation is the same,
the underlying C implementation requires separate
`sbc_t` instances.
:param namedtuple config: Media endpoint negotiated
configuration parameters. These are not used
directly by the codec here but translated to
parameters usable by the codec. See
:py:class:`.SBCCodecConfig`
"""
def __init__(self, config):
import sys
try:
self.codec = ffi.verify(b'#include "rtpsbc.h"',
libraries=[b'rtpsbc'],
ext_package=b'rtpsbc')
except:
print 'Exception:', sys.exc_info()[0]
self.config = ffi.new('sbc_t *')
self.ts = ffi.new('unsigned int *', 0)
self.seq_num = ffi.new('unsigned int *', 0)
self._init_sbc_config(config)
self.codec.sbc_init(self.config, 0)
def encode(self, fd, mtu, data):
"""
Encode the supplied data (byte array) and write to
the media transport file descriptor encapsulated
as RTP packets. The encoder will calculate the
required number of SBC frames and encapsulate as
RTP to fit the MTU size.
:param int fd: Media transport file descriptor
:param int mtu: Media transport MTU size as returned
when the media transport was acquired.
:param array{byte} data: Data to encode and send
over the media transport.
:return:
"""
self.codec.rtp_sbc_encode_to_fd(self.config,
ffi.new('char[]',
data),
len(data),
mtu,
self.ts,
self.seq_num,
fd)
def decode(self, fd, mtu, max_len=2560):
"""
Read the media transport descriptor, depay
the RTP payload and decode the SBC frames into
a byte array. The maximum number of bytes to
be returned may be passed as an argument and all
available bytes are returned to the caller.
:param int fd: Media transport file descriptor
:param int mtu: Media transport MTU size as returned
when the media transport was acquired.
:param int max_len: Optional. Set maximum number of
bytes to read.
:return data: Decoded data bytes as an array.
:rtype: array{byte}
"""
output_buffer = ffi.new('char[]', max_len)
sz = self.codec.rtp_sbc_decode_from_fd(self.config,
output_buffer,
max_len,
mtu,
fd)
return ffi.buffer(output_buffer[0:sz])
|
liamw9534/bt-manager | bt_manager/codecs.py | SBCCodec.encode | python | def encode(self, fd, mtu, data):
self.codec.rtp_sbc_encode_to_fd(self.config,
ffi.new('char[]',
data),
len(data),
mtu,
self.ts,
self.seq_num,
fd) | Encode the supplied data (byte array) and write to
the media transport file descriptor encapsulated
as RTP packets. The encoder will calculate the
required number of SBC frames and encapsulate as
RTP to fit the MTU size.
:param int fd: Media transport file descriptor
:param int mtu: Media transport MTU size as returned
when the media transport was acquired.
:param array{byte} data: Data to encode and send
over the media transport.
:return: | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/codecs.py#L159-L181 | null | class SBCCodec:
"""
Python cass wrapper around CFFI calls into the SBC codec
implemented in C. The main API is defined by sbc.h with
additional functions added to encapsulate an SBC payload
as part of an RTP packet. The API extensions for RTP
are designed to work directly with bluetooth media
transport file descriptors for the A2DP profile. So,
the basic idea is that this class is instantiated as
part of a media endpoint implementation in order to
encode or decode data carried on the media transport.
.. note:: You need two separate instantiations of this
class if you wish to encode and decode at the same
time. Although the class implementation is the same,
the underlying C implementation requires separate
`sbc_t` instances.
:param namedtuple config: Media endpoint negotiated
configuration parameters. These are not used
directly by the codec here but translated to
parameters usable by the codec. See
:py:class:`.SBCCodecConfig`
"""
def __init__(self, config):
import sys
try:
self.codec = ffi.verify(b'#include "rtpsbc.h"',
libraries=[b'rtpsbc'],
ext_package=b'rtpsbc')
except:
print 'Exception:', sys.exc_info()[0]
self.config = ffi.new('sbc_t *')
self.ts = ffi.new('unsigned int *', 0)
self.seq_num = ffi.new('unsigned int *', 0)
self._init_sbc_config(config)
self.codec.sbc_init(self.config, 0)
def _init_sbc_config(self, config):
"""
Translator from namedtuple config representation to
the sbc_t type.
:param namedtuple config: See :py:class:`.SBCCodecConfig`
:returns:
"""
if (config.channel_mode == SBCChannelMode.CHANNEL_MODE_MONO):
self.config.mode = self.codec.SBC_MODE_MONO
elif (config.channel_mode == SBCChannelMode.CHANNEL_MODE_STEREO):
self.config.mode = self.codec.SBC_MODE_STEREO
elif (config.channel_mode == SBCChannelMode.CHANNEL_MODE_DUAL):
self.config.mode = self.codec.SBC_MODE_DUAL_CHANNEL
elif (config.channel_mode == SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
self.config.mode = self.codec.SBC_MODE_JOINT_STEREO
if (config.frequency == SBCSamplingFrequency.FREQ_16KHZ):
self.config.frequency = self.codec.SBC_FREQ_16000
elif (config.frequency == SBCSamplingFrequency.FREQ_32KHZ):
self.config.frequency = self.codec.SBC_FREQ_32000
elif (config.frequency == SBCSamplingFrequency.FREQ_44_1KHZ):
self.config.frequency = self.codec.SBC_FREQ_44100
elif (config.frequency == SBCSamplingFrequency.FREQ_48KHZ):
self.config.frequency = self.codec.SBC_FREQ_48000
if (config.allocation_method == SBCAllocationMethod.LOUDNESS):
self.config.allocation = self.codec.SBC_AM_LOUDNESS
elif (config.allocation_method == SBCAllocationMethod.SNR):
self.config.allocation = self.codec.SBC_AM_SNR
if (config.subbands == SBCSubbands.SUBBANDS_4):
self.config.subbands = self.codec.SBC_SB_4
elif (config.subbands == SBCSubbands.SUBBANDS_8):
self.config.subbands = self.codec.SBC_SB_8
if (config.block_length == SBCBlocks.BLOCKS_4):
self.config.blocks = self.codec.SBC_BLK_4
elif (config.block_length == SBCBlocks.BLOCKS_8):
self.config.blocks = self.codec.SBC_BLK_8
elif (config.block_length == SBCBlocks.BLOCKS_12):
self.config.blocks = self.codec.SBC_BLK_12
elif (config.block_length == SBCBlocks.BLOCKS_16):
self.config.blocks = self.codec.SBC_BLK_16
self.config.bitpool = config.max_bitpool
self.config.endian = self.codec.SBC_LE
def decode(self, fd, mtu, max_len=2560):
"""
Read the media transport descriptor, depay
the RTP payload and decode the SBC frames into
a byte array. The maximum number of bytes to
be returned may be passed as an argument and all
available bytes are returned to the caller.
:param int fd: Media transport file descriptor
:param int mtu: Media transport MTU size as returned
when the media transport was acquired.
:param int max_len: Optional. Set maximum number of
bytes to read.
:return data: Decoded data bytes as an array.
:rtype: array{byte}
"""
output_buffer = ffi.new('char[]', max_len)
sz = self.codec.rtp_sbc_decode_from_fd(self.config,
output_buffer,
max_len,
mtu,
fd)
return ffi.buffer(output_buffer[0:sz])
|
liamw9534/bt-manager | bt_manager/codecs.py | SBCCodec.decode | python | def decode(self, fd, mtu, max_len=2560):
output_buffer = ffi.new('char[]', max_len)
sz = self.codec.rtp_sbc_decode_from_fd(self.config,
output_buffer,
max_len,
mtu,
fd)
return ffi.buffer(output_buffer[0:sz]) | Read the media transport descriptor, depay
the RTP payload and decode the SBC frames into
a byte array. The maximum number of bytes to
be returned may be passed as an argument and all
available bytes are returned to the caller.
:param int fd: Media transport file descriptor
:param int mtu: Media transport MTU size as returned
when the media transport was acquired.
:param int max_len: Optional. Set maximum number of
bytes to read.
:return data: Decoded data bytes as an array.
:rtype: array{byte} | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/codecs.py#L183-L205 | null | class SBCCodec:
"""
Python cass wrapper around CFFI calls into the SBC codec
implemented in C. The main API is defined by sbc.h with
additional functions added to encapsulate an SBC payload
as part of an RTP packet. The API extensions for RTP
are designed to work directly with bluetooth media
transport file descriptors for the A2DP profile. So,
the basic idea is that this class is instantiated as
part of a media endpoint implementation in order to
encode or decode data carried on the media transport.
.. note:: You need two separate instantiations of this
class if you wish to encode and decode at the same
time. Although the class implementation is the same,
the underlying C implementation requires separate
`sbc_t` instances.
:param namedtuple config: Media endpoint negotiated
configuration parameters. These are not used
directly by the codec here but translated to
parameters usable by the codec. See
:py:class:`.SBCCodecConfig`
"""
def __init__(self, config):
import sys
try:
self.codec = ffi.verify(b'#include "rtpsbc.h"',
libraries=[b'rtpsbc'],
ext_package=b'rtpsbc')
except:
print 'Exception:', sys.exc_info()[0]
self.config = ffi.new('sbc_t *')
self.ts = ffi.new('unsigned int *', 0)
self.seq_num = ffi.new('unsigned int *', 0)
self._init_sbc_config(config)
self.codec.sbc_init(self.config, 0)
def _init_sbc_config(self, config):
"""
Translator from namedtuple config representation to
the sbc_t type.
:param namedtuple config: See :py:class:`.SBCCodecConfig`
:returns:
"""
if (config.channel_mode == SBCChannelMode.CHANNEL_MODE_MONO):
self.config.mode = self.codec.SBC_MODE_MONO
elif (config.channel_mode == SBCChannelMode.CHANNEL_MODE_STEREO):
self.config.mode = self.codec.SBC_MODE_STEREO
elif (config.channel_mode == SBCChannelMode.CHANNEL_MODE_DUAL):
self.config.mode = self.codec.SBC_MODE_DUAL_CHANNEL
elif (config.channel_mode == SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
self.config.mode = self.codec.SBC_MODE_JOINT_STEREO
if (config.frequency == SBCSamplingFrequency.FREQ_16KHZ):
self.config.frequency = self.codec.SBC_FREQ_16000
elif (config.frequency == SBCSamplingFrequency.FREQ_32KHZ):
self.config.frequency = self.codec.SBC_FREQ_32000
elif (config.frequency == SBCSamplingFrequency.FREQ_44_1KHZ):
self.config.frequency = self.codec.SBC_FREQ_44100
elif (config.frequency == SBCSamplingFrequency.FREQ_48KHZ):
self.config.frequency = self.codec.SBC_FREQ_48000
if (config.allocation_method == SBCAllocationMethod.LOUDNESS):
self.config.allocation = self.codec.SBC_AM_LOUDNESS
elif (config.allocation_method == SBCAllocationMethod.SNR):
self.config.allocation = self.codec.SBC_AM_SNR
if (config.subbands == SBCSubbands.SUBBANDS_4):
self.config.subbands = self.codec.SBC_SB_4
elif (config.subbands == SBCSubbands.SUBBANDS_8):
self.config.subbands = self.codec.SBC_SB_8
if (config.block_length == SBCBlocks.BLOCKS_4):
self.config.blocks = self.codec.SBC_BLK_4
elif (config.block_length == SBCBlocks.BLOCKS_8):
self.config.blocks = self.codec.SBC_BLK_8
elif (config.block_length == SBCBlocks.BLOCKS_12):
self.config.blocks = self.codec.SBC_BLK_12
elif (config.block_length == SBCBlocks.BLOCKS_16):
self.config.blocks = self.codec.SBC_BLK_16
self.config.bitpool = config.max_bitpool
self.config.endian = self.codec.SBC_LE
def encode(self, fd, mtu, data):
"""
Encode the supplied data (byte array) and write to
the media transport file descriptor encapsulated
as RTP packets. The encoder will calculate the
required number of SBC frames and encapsulate as
RTP to fit the MTU size.
:param int fd: Media transport file descriptor
:param int mtu: Media transport MTU size as returned
when the media transport was acquired.
:param array{byte} data: Data to encode and send
over the media transport.
:return:
"""
self.codec.rtp_sbc_encode_to_fd(self.config,
ffi.new('char[]',
data),
len(data),
mtu,
self.ts,
self.seq_num,
fd)
|
liamw9534/bt-manager | bt_manager/audio.py | SBCAudioCodec._transport_ready_handler | python | def _transport_ready_handler(self, fd, cb_condition):
if(self.user_cb):
self.user_cb(self.user_arg)
return True | Wrapper for calling user callback routine to notify
when transport data is ready to read | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/audio.py#L184-L191 | null | class SBCAudioCodec(GenericEndpoint):
"""
SBCAudioCodec is an implementation of a media endpoint that
provides common functionality enabling SBC audio source and
SBC audio sink media endpoints to be established.
Since certain procedures are specific to whether or not
the endpoint is a source or sink, in particular the trigger
points for when the media transport is acquired/release,
these parts are left to their respective sub-classes.
SBCAudioCodec handles the following steps in establishing
an endpoint:
* Populates `properties` with the capabilities of the codec.
* `SelectConfiguration`: computes and returns best SBC codec
configuration parameters based on device capabilities
* `SetConfiguration`: a sub-class notifier function is called
* `ClearConfiguration`: nothing is done
* `Release`: nothing
In additional to endpoint establishment, the class also has
transport read and write functions which will handle the
required SBC media encoding/decoding and RTP encapsulation.
The user may also register for `transport ready` events
which allows transport read and write operations to be
properly synchronized.
See also: :py:class:`SBCAudioSink` and :py:class:`SBCAudioSource`
"""
def __init__(self, uuid, path):
config = SBCCodecConfig(SBCChannelMode.ALL,
SBCSamplingFrequency.ALL,
SBCAllocationMethod.ALL,
SBCSubbands.ALL,
SBCBlocks.ALL,
2,
64)
caps = SBCAudioCodec._make_config(config)
codec = dbus.Byte(A2DP_CODECS['SBC'])
delayed_reporting = dbus.Boolean(True)
self.tag = None
self.path = None
self.user_cb = None
self.user_arg = None
self.properties = dbus.Dictionary({'UUID': uuid,
'Codec': codec,
'DelayReporting': delayed_reporting,
'Capabilities': caps})
GenericEndpoint.__init__(self, path)
def _install_transport_ready(self):
if ('r' in self.access_type):
io_event = gobject.IO_IN
else:
io_event = gobject.IO_OUT
self.tag = gobject.io_add_watch(self.fd, io_event,
self._transport_ready_handler)
def _uninstall_transport_ready(self):
if (self.tag):
gobject.source_remove(self.tag)
self.tag = None
def register_transport_ready_event(self, user_cb, user_arg):
"""
Register for transport ready events. The `transport ready`
event is raised via a user callback. If the endpoint
is configured as a source, then the user may then
call :py:meth:`write_transport` in order to send data to
the associated sink.
Otherwise, if the endpoint is configured as a sink, then
the user may call :py:meth:`read_transport` to read
from the associated source instead.
:param func user_cb: User defined callback function. It
must take one parameter which is the user's callback
argument.
:param user_arg: User defined callback argument.
:return:
See also: :py:meth:`unregister_transport_ready_event`
"""
self.user_cb = user_cb
self.user_arg = user_arg
def unregister_transport_ready_event(self):
"""
Unregister previously registered `transport ready`
events.
See also: :py:meth:`register_transport_ready_event`
"""
self.user_cb = None
def read_transport(self):
"""
Read data from media transport.
The returned data payload is SBC decoded and has
all RTP encapsulation removed.
:return data: Payload data that has been decoded,
with RTP encapsulation removed.
:rtype: array{byte}
"""
if ('r' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.decode(self.fd, self.read_mtu)
def write_transport(self, data):
"""
Write data to media transport. The data is
encoded using the SBC codec and RTP encapsulated
before being written to the transport file
descriptor.
:param array{byte} data: Payload data to encode,
encapsulate and send.
"""
if ('w' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.encode(self.fd, self.write_mtu, data)
def close_transport(self):
"""
Forcibly close previously acquired media transport.
.. note:: The user should first make sure any transport
event handlers are unregistered first.
"""
if (self.path):
self._release_media_transport(self.path,
self.access_type)
self.path = None
def _notify_media_transport_available(self, path, transport):
"""
Subclass should implement this to trigger setup once
a new media transport is available.
"""
pass
def _acquire_media_transport(self, path, access_type):
"""
Should be called by subclass when it is ready
to acquire the media transport file descriptor
"""
transport = BTMediaTransport(path=path)
(fd, read_mtu, write_mtu) = transport.acquire(access_type)
self.fd = fd.take() # We must do the clean-up later
self.write_mtu = write_mtu
self.read_mtu = read_mtu
self.access_type = access_type
self.path = path
self._install_transport_ready()
def _release_media_transport(self, path, access_type):
"""
Should be called by subclass when it is finished
with the media transport file descriptor
"""
try:
self._uninstall_transport_ready()
os.close(self.fd) # Clean-up previously taken fd
transport = BTMediaTransport(path=path)
transport.release(access_type)
except:
pass
@staticmethod
def _default_bitpool(frequency, channel_mode):
if (frequency ==
SBCSamplingFrequency.FREQ_16KHZ or
frequency ==
SBCSamplingFrequency.FREQ_32KHZ):
return 53
elif (frequency ==
SBCSamplingFrequency.FREQ_44_1KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 31
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 53
else:
# TODO: Invalid channel_mode
return 53
elif (frequency == SBCSamplingFrequency.FREQ_48KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 29
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 51
else:
# TODO: Invalid channel_mode
return 51
else:
# TODO: Invalid frequency
return 53
@staticmethod
def _make_config(config):
"""Helper to turn SBC codec configuration params into a
a2dp_sbc_t structure usable by bluez"""
# The SBC config encoding is taken from a2dp_codecs.h, in particular,
# the a2dp_sbc_t type is converted into a 4-byte array:
# uint8_t channel_mode:4
# uint8_t frequency:4
# uint8_t allocation_method:2
# uint8_t subbands:2
# uint8_t block_length:4
# uint8_t min_bitpool
# uint8_t max_bitpool
return dbus.Array([dbus.Byte(config.channel_mode |
(config.frequency << 4)),
dbus.Byte(config.allocation_method |
(config.subbands << 2) |
(config.block_length << 4)),
dbus.Byte(config.min_bitpool),
dbus.Byte(config.max_bitpool)])
@staticmethod
def _parse_config(config):
"""Helper to turn a2dp_sbc_t structure into a
more usable set of SBC codec configuration params"""
frequency = config[0] >> 4
channel_mode = config[0] & 0xF
allocation_method = config[1] & 0x03
subbands = (config[1] >> 2) & 0x03
block_length = (config[1] >> 4) & 0x0F
min_bitpool = config[2]
max_bitpool = config[3]
return SBCCodecConfig(channel_mode, frequency, allocation_method,
subbands, block_length, min_bitpool, max_bitpool)
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def Release(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def ClearConfiguration(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="ay", out_signature="ay")
def SelectConfiguration(self, caps):
our_caps = SBCAudioCodec._parse_config(self.properties['Capabilities'])
device_caps = SBCAudioCodec._parse_config(caps)
frequency = SBCSamplingFrequency.FREQ_44_1KHZ
if ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_JOINT_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_DUAL):
channel_mode = SBCChannelMode.CHANNEL_MODE_DUAL
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_MONO):
channel_mode = SBCChannelMode.CHANNEL_MODE_MONO
else:
raise BTInvalidConfiguration
if ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_16):
block_length = SBCBlocks.BLOCKS_16
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_12):
block_length = SBCBlocks.BLOCKS_12
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_8):
block_length = SBCBlocks.BLOCKS_8
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_4):
block_length = SBCBlocks.BLOCKS_4
else:
raise BTInvalidConfiguration
if ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_8):
subbands = SBCSubbands.SUBBANDS_8
elif ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_4):
subbands = SBCSubbands.SUBBANDS_4
else:
raise BTInvalidConfiguration
if ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.LOUDNESS):
allocation_method = SBCAllocationMethod.LOUDNESS
elif ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.SNR):
allocation_method = SBCAllocationMethod.SNR
else:
raise BTInvalidConfiguration
min_bitpool = max(our_caps.min_bitpool, device_caps.min_bitpool)
max_bitpool = min(SBCAudioCodec._default_bitpool(frequency,
channel_mode),
device_caps.max_bitpool)
selected_config = SBCCodecConfig(channel_mode,
frequency,
allocation_method,
subbands,
block_length,
min_bitpool,
max_bitpool)
# Create SBC codec based on selected configuration
self.codec = SBCCodec(selected_config)
dbus_val = SBCAudioCodec._make_config(selected_config)
return dbus_val
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="oay", out_signature="")
def SetConfiguration(self, transport, config):
self._notify_media_transport_available(config.get('Device'), transport)
def __repr__(self):
return pprint.pformat(self.__dict__)
|
liamw9534/bt-manager | bt_manager/audio.py | SBCAudioCodec.register_transport_ready_event | python | def register_transport_ready_event(self, user_cb, user_arg):
self.user_cb = user_cb
self.user_arg = user_arg | Register for transport ready events. The `transport ready`
event is raised via a user callback. If the endpoint
is configured as a source, then the user may then
call :py:meth:`write_transport` in order to send data to
the associated sink.
Otherwise, if the endpoint is configured as a sink, then
the user may call :py:meth:`read_transport` to read
from the associated source instead.
:param func user_cb: User defined callback function. It
must take one parameter which is the user's callback
argument.
:param user_arg: User defined callback argument.
:return:
See also: :py:meth:`unregister_transport_ready_event` | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/audio.py#L207-L227 | null | class SBCAudioCodec(GenericEndpoint):
"""
SBCAudioCodec is an implementation of a media endpoint that
provides common functionality enabling SBC audio source and
SBC audio sink media endpoints to be established.
Since certain procedures are specific to whether or not
the endpoint is a source or sink, in particular the trigger
points for when the media transport is acquired/release,
these parts are left to their respective sub-classes.
SBCAudioCodec handles the following steps in establishing
an endpoint:
* Populates `properties` with the capabilities of the codec.
* `SelectConfiguration`: computes and returns best SBC codec
configuration parameters based on device capabilities
* `SetConfiguration`: a sub-class notifier function is called
* `ClearConfiguration`: nothing is done
* `Release`: nothing
In additional to endpoint establishment, the class also has
transport read and write functions which will handle the
required SBC media encoding/decoding and RTP encapsulation.
The user may also register for `transport ready` events
which allows transport read and write operations to be
properly synchronized.
See also: :py:class:`SBCAudioSink` and :py:class:`SBCAudioSource`
"""
def __init__(self, uuid, path):
config = SBCCodecConfig(SBCChannelMode.ALL,
SBCSamplingFrequency.ALL,
SBCAllocationMethod.ALL,
SBCSubbands.ALL,
SBCBlocks.ALL,
2,
64)
caps = SBCAudioCodec._make_config(config)
codec = dbus.Byte(A2DP_CODECS['SBC'])
delayed_reporting = dbus.Boolean(True)
self.tag = None
self.path = None
self.user_cb = None
self.user_arg = None
self.properties = dbus.Dictionary({'UUID': uuid,
'Codec': codec,
'DelayReporting': delayed_reporting,
'Capabilities': caps})
GenericEndpoint.__init__(self, path)
def _transport_ready_handler(self, fd, cb_condition):
"""
Wrapper for calling user callback routine to notify
when transport data is ready to read
"""
if(self.user_cb):
self.user_cb(self.user_arg)
return True
def _install_transport_ready(self):
if ('r' in self.access_type):
io_event = gobject.IO_IN
else:
io_event = gobject.IO_OUT
self.tag = gobject.io_add_watch(self.fd, io_event,
self._transport_ready_handler)
def _uninstall_transport_ready(self):
if (self.tag):
gobject.source_remove(self.tag)
self.tag = None
def unregister_transport_ready_event(self):
"""
Unregister previously registered `transport ready`
events.
See also: :py:meth:`register_transport_ready_event`
"""
self.user_cb = None
def read_transport(self):
"""
Read data from media transport.
The returned data payload is SBC decoded and has
all RTP encapsulation removed.
:return data: Payload data that has been decoded,
with RTP encapsulation removed.
:rtype: array{byte}
"""
if ('r' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.decode(self.fd, self.read_mtu)
def write_transport(self, data):
"""
Write data to media transport. The data is
encoded using the SBC codec and RTP encapsulated
before being written to the transport file
descriptor.
:param array{byte} data: Payload data to encode,
encapsulate and send.
"""
if ('w' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.encode(self.fd, self.write_mtu, data)
def close_transport(self):
"""
Forcibly close previously acquired media transport.
.. note:: The user should first make sure any transport
event handlers are unregistered first.
"""
if (self.path):
self._release_media_transport(self.path,
self.access_type)
self.path = None
def _notify_media_transport_available(self, path, transport):
"""
Subclass should implement this to trigger setup once
a new media transport is available.
"""
pass
def _acquire_media_transport(self, path, access_type):
"""
Should be called by subclass when it is ready
to acquire the media transport file descriptor
"""
transport = BTMediaTransport(path=path)
(fd, read_mtu, write_mtu) = transport.acquire(access_type)
self.fd = fd.take() # We must do the clean-up later
self.write_mtu = write_mtu
self.read_mtu = read_mtu
self.access_type = access_type
self.path = path
self._install_transport_ready()
def _release_media_transport(self, path, access_type):
"""
Should be called by subclass when it is finished
with the media transport file descriptor
"""
try:
self._uninstall_transport_ready()
os.close(self.fd) # Clean-up previously taken fd
transport = BTMediaTransport(path=path)
transport.release(access_type)
except:
pass
@staticmethod
def _default_bitpool(frequency, channel_mode):
if (frequency ==
SBCSamplingFrequency.FREQ_16KHZ or
frequency ==
SBCSamplingFrequency.FREQ_32KHZ):
return 53
elif (frequency ==
SBCSamplingFrequency.FREQ_44_1KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 31
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 53
else:
# TODO: Invalid channel_mode
return 53
elif (frequency == SBCSamplingFrequency.FREQ_48KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 29
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 51
else:
# TODO: Invalid channel_mode
return 51
else:
# TODO: Invalid frequency
return 53
@staticmethod
def _make_config(config):
"""Helper to turn SBC codec configuration params into a
a2dp_sbc_t structure usable by bluez"""
# The SBC config encoding is taken from a2dp_codecs.h, in particular,
# the a2dp_sbc_t type is converted into a 4-byte array:
# uint8_t channel_mode:4
# uint8_t frequency:4
# uint8_t allocation_method:2
# uint8_t subbands:2
# uint8_t block_length:4
# uint8_t min_bitpool
# uint8_t max_bitpool
return dbus.Array([dbus.Byte(config.channel_mode |
(config.frequency << 4)),
dbus.Byte(config.allocation_method |
(config.subbands << 2) |
(config.block_length << 4)),
dbus.Byte(config.min_bitpool),
dbus.Byte(config.max_bitpool)])
@staticmethod
def _parse_config(config):
"""Helper to turn a2dp_sbc_t structure into a
more usable set of SBC codec configuration params"""
frequency = config[0] >> 4
channel_mode = config[0] & 0xF
allocation_method = config[1] & 0x03
subbands = (config[1] >> 2) & 0x03
block_length = (config[1] >> 4) & 0x0F
min_bitpool = config[2]
max_bitpool = config[3]
return SBCCodecConfig(channel_mode, frequency, allocation_method,
subbands, block_length, min_bitpool, max_bitpool)
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def Release(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def ClearConfiguration(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="ay", out_signature="ay")
def SelectConfiguration(self, caps):
our_caps = SBCAudioCodec._parse_config(self.properties['Capabilities'])
device_caps = SBCAudioCodec._parse_config(caps)
frequency = SBCSamplingFrequency.FREQ_44_1KHZ
if ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_JOINT_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_DUAL):
channel_mode = SBCChannelMode.CHANNEL_MODE_DUAL
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_MONO):
channel_mode = SBCChannelMode.CHANNEL_MODE_MONO
else:
raise BTInvalidConfiguration
if ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_16):
block_length = SBCBlocks.BLOCKS_16
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_12):
block_length = SBCBlocks.BLOCKS_12
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_8):
block_length = SBCBlocks.BLOCKS_8
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_4):
block_length = SBCBlocks.BLOCKS_4
else:
raise BTInvalidConfiguration
if ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_8):
subbands = SBCSubbands.SUBBANDS_8
elif ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_4):
subbands = SBCSubbands.SUBBANDS_4
else:
raise BTInvalidConfiguration
if ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.LOUDNESS):
allocation_method = SBCAllocationMethod.LOUDNESS
elif ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.SNR):
allocation_method = SBCAllocationMethod.SNR
else:
raise BTInvalidConfiguration
min_bitpool = max(our_caps.min_bitpool, device_caps.min_bitpool)
max_bitpool = min(SBCAudioCodec._default_bitpool(frequency,
channel_mode),
device_caps.max_bitpool)
selected_config = SBCCodecConfig(channel_mode,
frequency,
allocation_method,
subbands,
block_length,
min_bitpool,
max_bitpool)
# Create SBC codec based on selected configuration
self.codec = SBCCodec(selected_config)
dbus_val = SBCAudioCodec._make_config(selected_config)
return dbus_val
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="oay", out_signature="")
def SetConfiguration(self, transport, config):
self._notify_media_transport_available(config.get('Device'), transport)
def __repr__(self):
return pprint.pformat(self.__dict__)
|
liamw9534/bt-manager | bt_manager/audio.py | SBCAudioCodec.read_transport | python | def read_transport(self):
if ('r' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.decode(self.fd, self.read_mtu) | Read data from media transport.
The returned data payload is SBC decoded and has
all RTP encapsulation removed.
:return data: Payload data that has been decoded,
with RTP encapsulation removed.
:rtype: array{byte} | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/audio.py#L238-L250 | null | class SBCAudioCodec(GenericEndpoint):
"""
SBCAudioCodec is an implementation of a media endpoint that
provides common functionality enabling SBC audio source and
SBC audio sink media endpoints to be established.
Since certain procedures are specific to whether or not
the endpoint is a source or sink, in particular the trigger
points for when the media transport is acquired/release,
these parts are left to their respective sub-classes.
SBCAudioCodec handles the following steps in establishing
an endpoint:
* Populates `properties` with the capabilities of the codec.
* `SelectConfiguration`: computes and returns best SBC codec
configuration parameters based on device capabilities
* `SetConfiguration`: a sub-class notifier function is called
* `ClearConfiguration`: nothing is done
* `Release`: nothing
In additional to endpoint establishment, the class also has
transport read and write functions which will handle the
required SBC media encoding/decoding and RTP encapsulation.
The user may also register for `transport ready` events
which allows transport read and write operations to be
properly synchronized.
See also: :py:class:`SBCAudioSink` and :py:class:`SBCAudioSource`
"""
def __init__(self, uuid, path):
config = SBCCodecConfig(SBCChannelMode.ALL,
SBCSamplingFrequency.ALL,
SBCAllocationMethod.ALL,
SBCSubbands.ALL,
SBCBlocks.ALL,
2,
64)
caps = SBCAudioCodec._make_config(config)
codec = dbus.Byte(A2DP_CODECS['SBC'])
delayed_reporting = dbus.Boolean(True)
self.tag = None
self.path = None
self.user_cb = None
self.user_arg = None
self.properties = dbus.Dictionary({'UUID': uuid,
'Codec': codec,
'DelayReporting': delayed_reporting,
'Capabilities': caps})
GenericEndpoint.__init__(self, path)
def _transport_ready_handler(self, fd, cb_condition):
"""
Wrapper for calling user callback routine to notify
when transport data is ready to read
"""
if(self.user_cb):
self.user_cb(self.user_arg)
return True
def _install_transport_ready(self):
if ('r' in self.access_type):
io_event = gobject.IO_IN
else:
io_event = gobject.IO_OUT
self.tag = gobject.io_add_watch(self.fd, io_event,
self._transport_ready_handler)
def _uninstall_transport_ready(self):
if (self.tag):
gobject.source_remove(self.tag)
self.tag = None
def register_transport_ready_event(self, user_cb, user_arg):
"""
Register for transport ready events. The `transport ready`
event is raised via a user callback. If the endpoint
is configured as a source, then the user may then
call :py:meth:`write_transport` in order to send data to
the associated sink.
Otherwise, if the endpoint is configured as a sink, then
the user may call :py:meth:`read_transport` to read
from the associated source instead.
:param func user_cb: User defined callback function. It
must take one parameter which is the user's callback
argument.
:param user_arg: User defined callback argument.
:return:
See also: :py:meth:`unregister_transport_ready_event`
"""
self.user_cb = user_cb
self.user_arg = user_arg
def unregister_transport_ready_event(self):
"""
Unregister previously registered `transport ready`
events.
See also: :py:meth:`register_transport_ready_event`
"""
self.user_cb = None
def write_transport(self, data):
"""
Write data to media transport. The data is
encoded using the SBC codec and RTP encapsulated
before being written to the transport file
descriptor.
:param array{byte} data: Payload data to encode,
encapsulate and send.
"""
if ('w' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.encode(self.fd, self.write_mtu, data)
def close_transport(self):
"""
Forcibly close previously acquired media transport.
.. note:: The user should first make sure any transport
event handlers are unregistered first.
"""
if (self.path):
self._release_media_transport(self.path,
self.access_type)
self.path = None
def _notify_media_transport_available(self, path, transport):
"""
Subclass should implement this to trigger setup once
a new media transport is available.
"""
pass
def _acquire_media_transport(self, path, access_type):
"""
Should be called by subclass when it is ready
to acquire the media transport file descriptor
"""
transport = BTMediaTransport(path=path)
(fd, read_mtu, write_mtu) = transport.acquire(access_type)
self.fd = fd.take() # We must do the clean-up later
self.write_mtu = write_mtu
self.read_mtu = read_mtu
self.access_type = access_type
self.path = path
self._install_transport_ready()
def _release_media_transport(self, path, access_type):
"""
Should be called by subclass when it is finished
with the media transport file descriptor
"""
try:
self._uninstall_transport_ready()
os.close(self.fd) # Clean-up previously taken fd
transport = BTMediaTransport(path=path)
transport.release(access_type)
except:
pass
@staticmethod
def _default_bitpool(frequency, channel_mode):
if (frequency ==
SBCSamplingFrequency.FREQ_16KHZ or
frequency ==
SBCSamplingFrequency.FREQ_32KHZ):
return 53
elif (frequency ==
SBCSamplingFrequency.FREQ_44_1KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 31
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 53
else:
# TODO: Invalid channel_mode
return 53
elif (frequency == SBCSamplingFrequency.FREQ_48KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 29
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 51
else:
# TODO: Invalid channel_mode
return 51
else:
# TODO: Invalid frequency
return 53
@staticmethod
def _make_config(config):
"""Helper to turn SBC codec configuration params into a
a2dp_sbc_t structure usable by bluez"""
# The SBC config encoding is taken from a2dp_codecs.h, in particular,
# the a2dp_sbc_t type is converted into a 4-byte array:
# uint8_t channel_mode:4
# uint8_t frequency:4
# uint8_t allocation_method:2
# uint8_t subbands:2
# uint8_t block_length:4
# uint8_t min_bitpool
# uint8_t max_bitpool
return dbus.Array([dbus.Byte(config.channel_mode |
(config.frequency << 4)),
dbus.Byte(config.allocation_method |
(config.subbands << 2) |
(config.block_length << 4)),
dbus.Byte(config.min_bitpool),
dbus.Byte(config.max_bitpool)])
@staticmethod
def _parse_config(config):
"""Helper to turn a2dp_sbc_t structure into a
more usable set of SBC codec configuration params"""
frequency = config[0] >> 4
channel_mode = config[0] & 0xF
allocation_method = config[1] & 0x03
subbands = (config[1] >> 2) & 0x03
block_length = (config[1] >> 4) & 0x0F
min_bitpool = config[2]
max_bitpool = config[3]
return SBCCodecConfig(channel_mode, frequency, allocation_method,
subbands, block_length, min_bitpool, max_bitpool)
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def Release(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def ClearConfiguration(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="ay", out_signature="ay")
def SelectConfiguration(self, caps):
our_caps = SBCAudioCodec._parse_config(self.properties['Capabilities'])
device_caps = SBCAudioCodec._parse_config(caps)
frequency = SBCSamplingFrequency.FREQ_44_1KHZ
if ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_JOINT_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_DUAL):
channel_mode = SBCChannelMode.CHANNEL_MODE_DUAL
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_MONO):
channel_mode = SBCChannelMode.CHANNEL_MODE_MONO
else:
raise BTInvalidConfiguration
if ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_16):
block_length = SBCBlocks.BLOCKS_16
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_12):
block_length = SBCBlocks.BLOCKS_12
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_8):
block_length = SBCBlocks.BLOCKS_8
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_4):
block_length = SBCBlocks.BLOCKS_4
else:
raise BTInvalidConfiguration
if ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_8):
subbands = SBCSubbands.SUBBANDS_8
elif ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_4):
subbands = SBCSubbands.SUBBANDS_4
else:
raise BTInvalidConfiguration
if ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.LOUDNESS):
allocation_method = SBCAllocationMethod.LOUDNESS
elif ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.SNR):
allocation_method = SBCAllocationMethod.SNR
else:
raise BTInvalidConfiguration
min_bitpool = max(our_caps.min_bitpool, device_caps.min_bitpool)
max_bitpool = min(SBCAudioCodec._default_bitpool(frequency,
channel_mode),
device_caps.max_bitpool)
selected_config = SBCCodecConfig(channel_mode,
frequency,
allocation_method,
subbands,
block_length,
min_bitpool,
max_bitpool)
# Create SBC codec based on selected configuration
self.codec = SBCCodec(selected_config)
dbus_val = SBCAudioCodec._make_config(selected_config)
return dbus_val
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="oay", out_signature="")
def SetConfiguration(self, transport, config):
self._notify_media_transport_available(config.get('Device'), transport)
def __repr__(self):
return pprint.pformat(self.__dict__)
|
liamw9534/bt-manager | bt_manager/audio.py | SBCAudioCodec.write_transport | python | def write_transport(self, data):
if ('w' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.encode(self.fd, self.write_mtu, data) | Write data to media transport. The data is
encoded using the SBC codec and RTP encapsulated
before being written to the transport file
descriptor.
:param array{byte} data: Payload data to encode,
encapsulate and send. | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/audio.py#L252-L264 | null | class SBCAudioCodec(GenericEndpoint):
"""
SBCAudioCodec is an implementation of a media endpoint that
provides common functionality enabling SBC audio source and
SBC audio sink media endpoints to be established.
Since certain procedures are specific to whether or not
the endpoint is a source or sink, in particular the trigger
points for when the media transport is acquired/release,
these parts are left to their respective sub-classes.
SBCAudioCodec handles the following steps in establishing
an endpoint:
* Populates `properties` with the capabilities of the codec.
* `SelectConfiguration`: computes and returns best SBC codec
configuration parameters based on device capabilities
* `SetConfiguration`: a sub-class notifier function is called
* `ClearConfiguration`: nothing is done
* `Release`: nothing
In additional to endpoint establishment, the class also has
transport read and write functions which will handle the
required SBC media encoding/decoding and RTP encapsulation.
The user may also register for `transport ready` events
which allows transport read and write operations to be
properly synchronized.
See also: :py:class:`SBCAudioSink` and :py:class:`SBCAudioSource`
"""
def __init__(self, uuid, path):
config = SBCCodecConfig(SBCChannelMode.ALL,
SBCSamplingFrequency.ALL,
SBCAllocationMethod.ALL,
SBCSubbands.ALL,
SBCBlocks.ALL,
2,
64)
caps = SBCAudioCodec._make_config(config)
codec = dbus.Byte(A2DP_CODECS['SBC'])
delayed_reporting = dbus.Boolean(True)
self.tag = None
self.path = None
self.user_cb = None
self.user_arg = None
self.properties = dbus.Dictionary({'UUID': uuid,
'Codec': codec,
'DelayReporting': delayed_reporting,
'Capabilities': caps})
GenericEndpoint.__init__(self, path)
def _transport_ready_handler(self, fd, cb_condition):
"""
Wrapper for calling user callback routine to notify
when transport data is ready to read
"""
if(self.user_cb):
self.user_cb(self.user_arg)
return True
def _install_transport_ready(self):
if ('r' in self.access_type):
io_event = gobject.IO_IN
else:
io_event = gobject.IO_OUT
self.tag = gobject.io_add_watch(self.fd, io_event,
self._transport_ready_handler)
def _uninstall_transport_ready(self):
if (self.tag):
gobject.source_remove(self.tag)
self.tag = None
def register_transport_ready_event(self, user_cb, user_arg):
"""
Register for transport ready events. The `transport ready`
event is raised via a user callback. If the endpoint
is configured as a source, then the user may then
call :py:meth:`write_transport` in order to send data to
the associated sink.
Otherwise, if the endpoint is configured as a sink, then
the user may call :py:meth:`read_transport` to read
from the associated source instead.
:param func user_cb: User defined callback function. It
must take one parameter which is the user's callback
argument.
:param user_arg: User defined callback argument.
:return:
See also: :py:meth:`unregister_transport_ready_event`
"""
self.user_cb = user_cb
self.user_arg = user_arg
def unregister_transport_ready_event(self):
"""
Unregister previously registered `transport ready`
events.
See also: :py:meth:`register_transport_ready_event`
"""
self.user_cb = None
def read_transport(self):
"""
Read data from media transport.
The returned data payload is SBC decoded and has
all RTP encapsulation removed.
:return data: Payload data that has been decoded,
with RTP encapsulation removed.
:rtype: array{byte}
"""
if ('r' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.decode(self.fd, self.read_mtu)
def close_transport(self):
"""
Forcibly close previously acquired media transport.
.. note:: The user should first make sure any transport
event handlers are unregistered first.
"""
if (self.path):
self._release_media_transport(self.path,
self.access_type)
self.path = None
def _notify_media_transport_available(self, path, transport):
"""
Subclass should implement this to trigger setup once
a new media transport is available.
"""
pass
def _acquire_media_transport(self, path, access_type):
"""
Should be called by subclass when it is ready
to acquire the media transport file descriptor
"""
transport = BTMediaTransport(path=path)
(fd, read_mtu, write_mtu) = transport.acquire(access_type)
self.fd = fd.take() # We must do the clean-up later
self.write_mtu = write_mtu
self.read_mtu = read_mtu
self.access_type = access_type
self.path = path
self._install_transport_ready()
def _release_media_transport(self, path, access_type):
"""
Should be called by subclass when it is finished
with the media transport file descriptor
"""
try:
self._uninstall_transport_ready()
os.close(self.fd) # Clean-up previously taken fd
transport = BTMediaTransport(path=path)
transport.release(access_type)
except:
pass
@staticmethod
def _default_bitpool(frequency, channel_mode):
if (frequency ==
SBCSamplingFrequency.FREQ_16KHZ or
frequency ==
SBCSamplingFrequency.FREQ_32KHZ):
return 53
elif (frequency ==
SBCSamplingFrequency.FREQ_44_1KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 31
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 53
else:
# TODO: Invalid channel_mode
return 53
elif (frequency == SBCSamplingFrequency.FREQ_48KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 29
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 51
else:
# TODO: Invalid channel_mode
return 51
else:
# TODO: Invalid frequency
return 53
@staticmethod
def _make_config(config):
"""Helper to turn SBC codec configuration params into a
a2dp_sbc_t structure usable by bluez"""
# The SBC config encoding is taken from a2dp_codecs.h, in particular,
# the a2dp_sbc_t type is converted into a 4-byte array:
# uint8_t channel_mode:4
# uint8_t frequency:4
# uint8_t allocation_method:2
# uint8_t subbands:2
# uint8_t block_length:4
# uint8_t min_bitpool
# uint8_t max_bitpool
return dbus.Array([dbus.Byte(config.channel_mode |
(config.frequency << 4)),
dbus.Byte(config.allocation_method |
(config.subbands << 2) |
(config.block_length << 4)),
dbus.Byte(config.min_bitpool),
dbus.Byte(config.max_bitpool)])
@staticmethod
def _parse_config(config):
"""Helper to turn a2dp_sbc_t structure into a
more usable set of SBC codec configuration params"""
frequency = config[0] >> 4
channel_mode = config[0] & 0xF
allocation_method = config[1] & 0x03
subbands = (config[1] >> 2) & 0x03
block_length = (config[1] >> 4) & 0x0F
min_bitpool = config[2]
max_bitpool = config[3]
return SBCCodecConfig(channel_mode, frequency, allocation_method,
subbands, block_length, min_bitpool, max_bitpool)
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def Release(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def ClearConfiguration(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="ay", out_signature="ay")
def SelectConfiguration(self, caps):
our_caps = SBCAudioCodec._parse_config(self.properties['Capabilities'])
device_caps = SBCAudioCodec._parse_config(caps)
frequency = SBCSamplingFrequency.FREQ_44_1KHZ
if ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_JOINT_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_DUAL):
channel_mode = SBCChannelMode.CHANNEL_MODE_DUAL
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_MONO):
channel_mode = SBCChannelMode.CHANNEL_MODE_MONO
else:
raise BTInvalidConfiguration
if ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_16):
block_length = SBCBlocks.BLOCKS_16
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_12):
block_length = SBCBlocks.BLOCKS_12
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_8):
block_length = SBCBlocks.BLOCKS_8
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_4):
block_length = SBCBlocks.BLOCKS_4
else:
raise BTInvalidConfiguration
if ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_8):
subbands = SBCSubbands.SUBBANDS_8
elif ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_4):
subbands = SBCSubbands.SUBBANDS_4
else:
raise BTInvalidConfiguration
if ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.LOUDNESS):
allocation_method = SBCAllocationMethod.LOUDNESS
elif ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.SNR):
allocation_method = SBCAllocationMethod.SNR
else:
raise BTInvalidConfiguration
min_bitpool = max(our_caps.min_bitpool, device_caps.min_bitpool)
max_bitpool = min(SBCAudioCodec._default_bitpool(frequency,
channel_mode),
device_caps.max_bitpool)
selected_config = SBCCodecConfig(channel_mode,
frequency,
allocation_method,
subbands,
block_length,
min_bitpool,
max_bitpool)
# Create SBC codec based on selected configuration
self.codec = SBCCodec(selected_config)
dbus_val = SBCAudioCodec._make_config(selected_config)
return dbus_val
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="oay", out_signature="")
def SetConfiguration(self, transport, config):
self._notify_media_transport_available(config.get('Device'), transport)
def __repr__(self):
return pprint.pformat(self.__dict__)
|
liamw9534/bt-manager | bt_manager/audio.py | SBCAudioCodec.close_transport | python | def close_transport(self):
if (self.path):
self._release_media_transport(self.path,
self.access_type)
self.path = None | Forcibly close previously acquired media transport.
.. note:: The user should first make sure any transport
event handlers are unregistered first. | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/audio.py#L266-L276 | [
"def _release_media_transport(self, path, access_type):\n \"\"\"\n Should be called by subclass when it is finished\n with the media transport file descriptor\n \"\"\"\n try:\n self._uninstall_transport_ready()\n os.close(self.fd) # Clean-up previously taken fd\n transport = BT... | class SBCAudioCodec(GenericEndpoint):
"""
SBCAudioCodec is an implementation of a media endpoint that
provides common functionality enabling SBC audio source and
SBC audio sink media endpoints to be established.
Since certain procedures are specific to whether or not
the endpoint is a source or sink, in particular the trigger
points for when the media transport is acquired/release,
these parts are left to their respective sub-classes.
SBCAudioCodec handles the following steps in establishing
an endpoint:
* Populates `properties` with the capabilities of the codec.
* `SelectConfiguration`: computes and returns best SBC codec
configuration parameters based on device capabilities
* `SetConfiguration`: a sub-class notifier function is called
* `ClearConfiguration`: nothing is done
* `Release`: nothing
In additional to endpoint establishment, the class also has
transport read and write functions which will handle the
required SBC media encoding/decoding and RTP encapsulation.
The user may also register for `transport ready` events
which allows transport read and write operations to be
properly synchronized.
See also: :py:class:`SBCAudioSink` and :py:class:`SBCAudioSource`
"""
def __init__(self, uuid, path):
config = SBCCodecConfig(SBCChannelMode.ALL,
SBCSamplingFrequency.ALL,
SBCAllocationMethod.ALL,
SBCSubbands.ALL,
SBCBlocks.ALL,
2,
64)
caps = SBCAudioCodec._make_config(config)
codec = dbus.Byte(A2DP_CODECS['SBC'])
delayed_reporting = dbus.Boolean(True)
self.tag = None
self.path = None
self.user_cb = None
self.user_arg = None
self.properties = dbus.Dictionary({'UUID': uuid,
'Codec': codec,
'DelayReporting': delayed_reporting,
'Capabilities': caps})
GenericEndpoint.__init__(self, path)
def _transport_ready_handler(self, fd, cb_condition):
"""
Wrapper for calling user callback routine to notify
when transport data is ready to read
"""
if(self.user_cb):
self.user_cb(self.user_arg)
return True
def _install_transport_ready(self):
if ('r' in self.access_type):
io_event = gobject.IO_IN
else:
io_event = gobject.IO_OUT
self.tag = gobject.io_add_watch(self.fd, io_event,
self._transport_ready_handler)
def _uninstall_transport_ready(self):
if (self.tag):
gobject.source_remove(self.tag)
self.tag = None
def register_transport_ready_event(self, user_cb, user_arg):
"""
Register for transport ready events. The `transport ready`
event is raised via a user callback. If the endpoint
is configured as a source, then the user may then
call :py:meth:`write_transport` in order to send data to
the associated sink.
Otherwise, if the endpoint is configured as a sink, then
the user may call :py:meth:`read_transport` to read
from the associated source instead.
:param func user_cb: User defined callback function. It
must take one parameter which is the user's callback
argument.
:param user_arg: User defined callback argument.
:return:
See also: :py:meth:`unregister_transport_ready_event`
"""
self.user_cb = user_cb
self.user_arg = user_arg
def unregister_transport_ready_event(self):
"""
Unregister previously registered `transport ready`
events.
See also: :py:meth:`register_transport_ready_event`
"""
self.user_cb = None
def read_transport(self):
"""
Read data from media transport.
The returned data payload is SBC decoded and has
all RTP encapsulation removed.
:return data: Payload data that has been decoded,
with RTP encapsulation removed.
:rtype: array{byte}
"""
if ('r' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.decode(self.fd, self.read_mtu)
def write_transport(self, data):
"""
Write data to media transport. The data is
encoded using the SBC codec and RTP encapsulated
before being written to the transport file
descriptor.
:param array{byte} data: Payload data to encode,
encapsulate and send.
"""
if ('w' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.encode(self.fd, self.write_mtu, data)
def _notify_media_transport_available(self, path, transport):
"""
Subclass should implement this to trigger setup once
a new media transport is available.
"""
pass
def _acquire_media_transport(self, path, access_type):
"""
Should be called by subclass when it is ready
to acquire the media transport file descriptor
"""
transport = BTMediaTransport(path=path)
(fd, read_mtu, write_mtu) = transport.acquire(access_type)
self.fd = fd.take() # We must do the clean-up later
self.write_mtu = write_mtu
self.read_mtu = read_mtu
self.access_type = access_type
self.path = path
self._install_transport_ready()
def _release_media_transport(self, path, access_type):
"""
Should be called by subclass when it is finished
with the media transport file descriptor
"""
try:
self._uninstall_transport_ready()
os.close(self.fd) # Clean-up previously taken fd
transport = BTMediaTransport(path=path)
transport.release(access_type)
except:
pass
@staticmethod
def _default_bitpool(frequency, channel_mode):
if (frequency ==
SBCSamplingFrequency.FREQ_16KHZ or
frequency ==
SBCSamplingFrequency.FREQ_32KHZ):
return 53
elif (frequency ==
SBCSamplingFrequency.FREQ_44_1KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 31
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 53
else:
# TODO: Invalid channel_mode
return 53
elif (frequency == SBCSamplingFrequency.FREQ_48KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 29
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 51
else:
# TODO: Invalid channel_mode
return 51
else:
# TODO: Invalid frequency
return 53
@staticmethod
def _make_config(config):
"""Helper to turn SBC codec configuration params into a
a2dp_sbc_t structure usable by bluez"""
# The SBC config encoding is taken from a2dp_codecs.h, in particular,
# the a2dp_sbc_t type is converted into a 4-byte array:
# uint8_t channel_mode:4
# uint8_t frequency:4
# uint8_t allocation_method:2
# uint8_t subbands:2
# uint8_t block_length:4
# uint8_t min_bitpool
# uint8_t max_bitpool
return dbus.Array([dbus.Byte(config.channel_mode |
(config.frequency << 4)),
dbus.Byte(config.allocation_method |
(config.subbands << 2) |
(config.block_length << 4)),
dbus.Byte(config.min_bitpool),
dbus.Byte(config.max_bitpool)])
@staticmethod
def _parse_config(config):
"""Helper to turn a2dp_sbc_t structure into a
more usable set of SBC codec configuration params"""
frequency = config[0] >> 4
channel_mode = config[0] & 0xF
allocation_method = config[1] & 0x03
subbands = (config[1] >> 2) & 0x03
block_length = (config[1] >> 4) & 0x0F
min_bitpool = config[2]
max_bitpool = config[3]
return SBCCodecConfig(channel_mode, frequency, allocation_method,
subbands, block_length, min_bitpool, max_bitpool)
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def Release(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def ClearConfiguration(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="ay", out_signature="ay")
def SelectConfiguration(self, caps):
our_caps = SBCAudioCodec._parse_config(self.properties['Capabilities'])
device_caps = SBCAudioCodec._parse_config(caps)
frequency = SBCSamplingFrequency.FREQ_44_1KHZ
if ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_JOINT_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_DUAL):
channel_mode = SBCChannelMode.CHANNEL_MODE_DUAL
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_MONO):
channel_mode = SBCChannelMode.CHANNEL_MODE_MONO
else:
raise BTInvalidConfiguration
if ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_16):
block_length = SBCBlocks.BLOCKS_16
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_12):
block_length = SBCBlocks.BLOCKS_12
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_8):
block_length = SBCBlocks.BLOCKS_8
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_4):
block_length = SBCBlocks.BLOCKS_4
else:
raise BTInvalidConfiguration
if ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_8):
subbands = SBCSubbands.SUBBANDS_8
elif ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_4):
subbands = SBCSubbands.SUBBANDS_4
else:
raise BTInvalidConfiguration
if ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.LOUDNESS):
allocation_method = SBCAllocationMethod.LOUDNESS
elif ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.SNR):
allocation_method = SBCAllocationMethod.SNR
else:
raise BTInvalidConfiguration
min_bitpool = max(our_caps.min_bitpool, device_caps.min_bitpool)
max_bitpool = min(SBCAudioCodec._default_bitpool(frequency,
channel_mode),
device_caps.max_bitpool)
selected_config = SBCCodecConfig(channel_mode,
frequency,
allocation_method,
subbands,
block_length,
min_bitpool,
max_bitpool)
# Create SBC codec based on selected configuration
self.codec = SBCCodec(selected_config)
dbus_val = SBCAudioCodec._make_config(selected_config)
return dbus_val
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="oay", out_signature="")
def SetConfiguration(self, transport, config):
self._notify_media_transport_available(config.get('Device'), transport)
def __repr__(self):
return pprint.pformat(self.__dict__)
|
liamw9534/bt-manager | bt_manager/audio.py | SBCAudioCodec._acquire_media_transport | python | def _acquire_media_transport(self, path, access_type):
transport = BTMediaTransport(path=path)
(fd, read_mtu, write_mtu) = transport.acquire(access_type)
self.fd = fd.take() # We must do the clean-up later
self.write_mtu = write_mtu
self.read_mtu = read_mtu
self.access_type = access_type
self.path = path
self._install_transport_ready() | Should be called by subclass when it is ready
to acquire the media transport file descriptor | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/audio.py#L285-L297 | null | class SBCAudioCodec(GenericEndpoint):
"""
SBCAudioCodec is an implementation of a media endpoint that
provides common functionality enabling SBC audio source and
SBC audio sink media endpoints to be established.
Since certain procedures are specific to whether or not
the endpoint is a source or sink, in particular the trigger
points for when the media transport is acquired/release,
these parts are left to their respective sub-classes.
SBCAudioCodec handles the following steps in establishing
an endpoint:
* Populates `properties` with the capabilities of the codec.
* `SelectConfiguration`: computes and returns best SBC codec
configuration parameters based on device capabilities
* `SetConfiguration`: a sub-class notifier function is called
* `ClearConfiguration`: nothing is done
* `Release`: nothing
In additional to endpoint establishment, the class also has
transport read and write functions which will handle the
required SBC media encoding/decoding and RTP encapsulation.
The user may also register for `transport ready` events
which allows transport read and write operations to be
properly synchronized.
See also: :py:class:`SBCAudioSink` and :py:class:`SBCAudioSource`
"""
def __init__(self, uuid, path):
config = SBCCodecConfig(SBCChannelMode.ALL,
SBCSamplingFrequency.ALL,
SBCAllocationMethod.ALL,
SBCSubbands.ALL,
SBCBlocks.ALL,
2,
64)
caps = SBCAudioCodec._make_config(config)
codec = dbus.Byte(A2DP_CODECS['SBC'])
delayed_reporting = dbus.Boolean(True)
self.tag = None
self.path = None
self.user_cb = None
self.user_arg = None
self.properties = dbus.Dictionary({'UUID': uuid,
'Codec': codec,
'DelayReporting': delayed_reporting,
'Capabilities': caps})
GenericEndpoint.__init__(self, path)
def _transport_ready_handler(self, fd, cb_condition):
"""
Wrapper for calling user callback routine to notify
when transport data is ready to read
"""
if(self.user_cb):
self.user_cb(self.user_arg)
return True
def _install_transport_ready(self):
if ('r' in self.access_type):
io_event = gobject.IO_IN
else:
io_event = gobject.IO_OUT
self.tag = gobject.io_add_watch(self.fd, io_event,
self._transport_ready_handler)
def _uninstall_transport_ready(self):
if (self.tag):
gobject.source_remove(self.tag)
self.tag = None
def register_transport_ready_event(self, user_cb, user_arg):
"""
Register for transport ready events. The `transport ready`
event is raised via a user callback. If the endpoint
is configured as a source, then the user may then
call :py:meth:`write_transport` in order to send data to
the associated sink.
Otherwise, if the endpoint is configured as a sink, then
the user may call :py:meth:`read_transport` to read
from the associated source instead.
:param func user_cb: User defined callback function. It
must take one parameter which is the user's callback
argument.
:param user_arg: User defined callback argument.
:return:
See also: :py:meth:`unregister_transport_ready_event`
"""
self.user_cb = user_cb
self.user_arg = user_arg
def unregister_transport_ready_event(self):
"""
Unregister previously registered `transport ready`
events.
See also: :py:meth:`register_transport_ready_event`
"""
self.user_cb = None
def read_transport(self):
"""
Read data from media transport.
The returned data payload is SBC decoded and has
all RTP encapsulation removed.
:return data: Payload data that has been decoded,
with RTP encapsulation removed.
:rtype: array{byte}
"""
if ('r' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.decode(self.fd, self.read_mtu)
def write_transport(self, data):
"""
Write data to media transport. The data is
encoded using the SBC codec and RTP encapsulated
before being written to the transport file
descriptor.
:param array{byte} data: Payload data to encode,
encapsulate and send.
"""
if ('w' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.encode(self.fd, self.write_mtu, data)
def close_transport(self):
"""
Forcibly close previously acquired media transport.
.. note:: The user should first make sure any transport
event handlers are unregistered first.
"""
if (self.path):
self._release_media_transport(self.path,
self.access_type)
self.path = None
def _notify_media_transport_available(self, path, transport):
"""
Subclass should implement this to trigger setup once
a new media transport is available.
"""
pass
def _release_media_transport(self, path, access_type):
"""
Should be called by subclass when it is finished
with the media transport file descriptor
"""
try:
self._uninstall_transport_ready()
os.close(self.fd) # Clean-up previously taken fd
transport = BTMediaTransport(path=path)
transport.release(access_type)
except:
pass
@staticmethod
def _default_bitpool(frequency, channel_mode):
if (frequency ==
SBCSamplingFrequency.FREQ_16KHZ or
frequency ==
SBCSamplingFrequency.FREQ_32KHZ):
return 53
elif (frequency ==
SBCSamplingFrequency.FREQ_44_1KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 31
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 53
else:
# TODO: Invalid channel_mode
return 53
elif (frequency == SBCSamplingFrequency.FREQ_48KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 29
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 51
else:
# TODO: Invalid channel_mode
return 51
else:
# TODO: Invalid frequency
return 53
@staticmethod
def _make_config(config):
"""Helper to turn SBC codec configuration params into a
a2dp_sbc_t structure usable by bluez"""
# The SBC config encoding is taken from a2dp_codecs.h, in particular,
# the a2dp_sbc_t type is converted into a 4-byte array:
# uint8_t channel_mode:4
# uint8_t frequency:4
# uint8_t allocation_method:2
# uint8_t subbands:2
# uint8_t block_length:4
# uint8_t min_bitpool
# uint8_t max_bitpool
return dbus.Array([dbus.Byte(config.channel_mode |
(config.frequency << 4)),
dbus.Byte(config.allocation_method |
(config.subbands << 2) |
(config.block_length << 4)),
dbus.Byte(config.min_bitpool),
dbus.Byte(config.max_bitpool)])
@staticmethod
def _parse_config(config):
"""Helper to turn a2dp_sbc_t structure into a
more usable set of SBC codec configuration params"""
frequency = config[0] >> 4
channel_mode = config[0] & 0xF
allocation_method = config[1] & 0x03
subbands = (config[1] >> 2) & 0x03
block_length = (config[1] >> 4) & 0x0F
min_bitpool = config[2]
max_bitpool = config[3]
return SBCCodecConfig(channel_mode, frequency, allocation_method,
subbands, block_length, min_bitpool, max_bitpool)
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def Release(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def ClearConfiguration(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="ay", out_signature="ay")
def SelectConfiguration(self, caps):
our_caps = SBCAudioCodec._parse_config(self.properties['Capabilities'])
device_caps = SBCAudioCodec._parse_config(caps)
frequency = SBCSamplingFrequency.FREQ_44_1KHZ
if ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_JOINT_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_DUAL):
channel_mode = SBCChannelMode.CHANNEL_MODE_DUAL
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_MONO):
channel_mode = SBCChannelMode.CHANNEL_MODE_MONO
else:
raise BTInvalidConfiguration
if ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_16):
block_length = SBCBlocks.BLOCKS_16
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_12):
block_length = SBCBlocks.BLOCKS_12
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_8):
block_length = SBCBlocks.BLOCKS_8
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_4):
block_length = SBCBlocks.BLOCKS_4
else:
raise BTInvalidConfiguration
if ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_8):
subbands = SBCSubbands.SUBBANDS_8
elif ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_4):
subbands = SBCSubbands.SUBBANDS_4
else:
raise BTInvalidConfiguration
if ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.LOUDNESS):
allocation_method = SBCAllocationMethod.LOUDNESS
elif ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.SNR):
allocation_method = SBCAllocationMethod.SNR
else:
raise BTInvalidConfiguration
min_bitpool = max(our_caps.min_bitpool, device_caps.min_bitpool)
max_bitpool = min(SBCAudioCodec._default_bitpool(frequency,
channel_mode),
device_caps.max_bitpool)
selected_config = SBCCodecConfig(channel_mode,
frequency,
allocation_method,
subbands,
block_length,
min_bitpool,
max_bitpool)
# Create SBC codec based on selected configuration
self.codec = SBCCodec(selected_config)
dbus_val = SBCAudioCodec._make_config(selected_config)
return dbus_val
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="oay", out_signature="")
def SetConfiguration(self, transport, config):
self._notify_media_transport_available(config.get('Device'), transport)
def __repr__(self):
return pprint.pformat(self.__dict__)
|
liamw9534/bt-manager | bt_manager/audio.py | SBCAudioCodec._release_media_transport | python | def _release_media_transport(self, path, access_type):
try:
self._uninstall_transport_ready()
os.close(self.fd) # Clean-up previously taken fd
transport = BTMediaTransport(path=path)
transport.release(access_type)
except:
pass | Should be called by subclass when it is finished
with the media transport file descriptor | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/audio.py#L299-L310 | [
"def _uninstall_transport_ready(self):\n if (self.tag):\n gobject.source_remove(self.tag)\n self.tag = None\n",
"def release(self, access_type):\n \"\"\"\n Releases file descriptor.\n\n Possible access_type:\n\n * \"r\" : Read only access\n * \"w\" : Write only access\n * \"rw\"... | class SBCAudioCodec(GenericEndpoint):
"""
SBCAudioCodec is an implementation of a media endpoint that
provides common functionality enabling SBC audio source and
SBC audio sink media endpoints to be established.
Since certain procedures are specific to whether or not
the endpoint is a source or sink, in particular the trigger
points for when the media transport is acquired/release,
these parts are left to their respective sub-classes.
SBCAudioCodec handles the following steps in establishing
an endpoint:
* Populates `properties` with the capabilities of the codec.
* `SelectConfiguration`: computes and returns best SBC codec
configuration parameters based on device capabilities
* `SetConfiguration`: a sub-class notifier function is called
* `ClearConfiguration`: nothing is done
* `Release`: nothing
In additional to endpoint establishment, the class also has
transport read and write functions which will handle the
required SBC media encoding/decoding and RTP encapsulation.
The user may also register for `transport ready` events
which allows transport read and write operations to be
properly synchronized.
See also: :py:class:`SBCAudioSink` and :py:class:`SBCAudioSource`
"""
def __init__(self, uuid, path):
config = SBCCodecConfig(SBCChannelMode.ALL,
SBCSamplingFrequency.ALL,
SBCAllocationMethod.ALL,
SBCSubbands.ALL,
SBCBlocks.ALL,
2,
64)
caps = SBCAudioCodec._make_config(config)
codec = dbus.Byte(A2DP_CODECS['SBC'])
delayed_reporting = dbus.Boolean(True)
self.tag = None
self.path = None
self.user_cb = None
self.user_arg = None
self.properties = dbus.Dictionary({'UUID': uuid,
'Codec': codec,
'DelayReporting': delayed_reporting,
'Capabilities': caps})
GenericEndpoint.__init__(self, path)
def _transport_ready_handler(self, fd, cb_condition):
"""
Wrapper for calling user callback routine to notify
when transport data is ready to read
"""
if(self.user_cb):
self.user_cb(self.user_arg)
return True
def _install_transport_ready(self):
if ('r' in self.access_type):
io_event = gobject.IO_IN
else:
io_event = gobject.IO_OUT
self.tag = gobject.io_add_watch(self.fd, io_event,
self._transport_ready_handler)
def _uninstall_transport_ready(self):
if (self.tag):
gobject.source_remove(self.tag)
self.tag = None
def register_transport_ready_event(self, user_cb, user_arg):
"""
Register for transport ready events. The `transport ready`
event is raised via a user callback. If the endpoint
is configured as a source, then the user may then
call :py:meth:`write_transport` in order to send data to
the associated sink.
Otherwise, if the endpoint is configured as a sink, then
the user may call :py:meth:`read_transport` to read
from the associated source instead.
:param func user_cb: User defined callback function. It
must take one parameter which is the user's callback
argument.
:param user_arg: User defined callback argument.
:return:
See also: :py:meth:`unregister_transport_ready_event`
"""
self.user_cb = user_cb
self.user_arg = user_arg
def unregister_transport_ready_event(self):
"""
Unregister previously registered `transport ready`
events.
See also: :py:meth:`register_transport_ready_event`
"""
self.user_cb = None
def read_transport(self):
"""
Read data from media transport.
The returned data payload is SBC decoded and has
all RTP encapsulation removed.
:return data: Payload data that has been decoded,
with RTP encapsulation removed.
:rtype: array{byte}
"""
if ('r' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.decode(self.fd, self.read_mtu)
def write_transport(self, data):
"""
Write data to media transport. The data is
encoded using the SBC codec and RTP encapsulated
before being written to the transport file
descriptor.
:param array{byte} data: Payload data to encode,
encapsulate and send.
"""
if ('w' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.encode(self.fd, self.write_mtu, data)
def close_transport(self):
"""
Forcibly close previously acquired media transport.
.. note:: The user should first make sure any transport
event handlers are unregistered first.
"""
if (self.path):
self._release_media_transport(self.path,
self.access_type)
self.path = None
def _notify_media_transport_available(self, path, transport):
"""
Subclass should implement this to trigger setup once
a new media transport is available.
"""
pass
def _acquire_media_transport(self, path, access_type):
"""
Should be called by subclass when it is ready
to acquire the media transport file descriptor
"""
transport = BTMediaTransport(path=path)
(fd, read_mtu, write_mtu) = transport.acquire(access_type)
self.fd = fd.take() # We must do the clean-up later
self.write_mtu = write_mtu
self.read_mtu = read_mtu
self.access_type = access_type
self.path = path
self._install_transport_ready()
@staticmethod
def _default_bitpool(frequency, channel_mode):
if (frequency ==
SBCSamplingFrequency.FREQ_16KHZ or
frequency ==
SBCSamplingFrequency.FREQ_32KHZ):
return 53
elif (frequency ==
SBCSamplingFrequency.FREQ_44_1KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 31
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 53
else:
# TODO: Invalid channel_mode
return 53
elif (frequency == SBCSamplingFrequency.FREQ_48KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 29
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 51
else:
# TODO: Invalid channel_mode
return 51
else:
# TODO: Invalid frequency
return 53
@staticmethod
def _make_config(config):
"""Helper to turn SBC codec configuration params into a
a2dp_sbc_t structure usable by bluez"""
# The SBC config encoding is taken from a2dp_codecs.h, in particular,
# the a2dp_sbc_t type is converted into a 4-byte array:
# uint8_t channel_mode:4
# uint8_t frequency:4
# uint8_t allocation_method:2
# uint8_t subbands:2
# uint8_t block_length:4
# uint8_t min_bitpool
# uint8_t max_bitpool
return dbus.Array([dbus.Byte(config.channel_mode |
(config.frequency << 4)),
dbus.Byte(config.allocation_method |
(config.subbands << 2) |
(config.block_length << 4)),
dbus.Byte(config.min_bitpool),
dbus.Byte(config.max_bitpool)])
@staticmethod
def _parse_config(config):
"""Helper to turn a2dp_sbc_t structure into a
more usable set of SBC codec configuration params"""
frequency = config[0] >> 4
channel_mode = config[0] & 0xF
allocation_method = config[1] & 0x03
subbands = (config[1] >> 2) & 0x03
block_length = (config[1] >> 4) & 0x0F
min_bitpool = config[2]
max_bitpool = config[3]
return SBCCodecConfig(channel_mode, frequency, allocation_method,
subbands, block_length, min_bitpool, max_bitpool)
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def Release(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def ClearConfiguration(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="ay", out_signature="ay")
def SelectConfiguration(self, caps):
our_caps = SBCAudioCodec._parse_config(self.properties['Capabilities'])
device_caps = SBCAudioCodec._parse_config(caps)
frequency = SBCSamplingFrequency.FREQ_44_1KHZ
if ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_JOINT_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_DUAL):
channel_mode = SBCChannelMode.CHANNEL_MODE_DUAL
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_MONO):
channel_mode = SBCChannelMode.CHANNEL_MODE_MONO
else:
raise BTInvalidConfiguration
if ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_16):
block_length = SBCBlocks.BLOCKS_16
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_12):
block_length = SBCBlocks.BLOCKS_12
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_8):
block_length = SBCBlocks.BLOCKS_8
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_4):
block_length = SBCBlocks.BLOCKS_4
else:
raise BTInvalidConfiguration
if ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_8):
subbands = SBCSubbands.SUBBANDS_8
elif ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_4):
subbands = SBCSubbands.SUBBANDS_4
else:
raise BTInvalidConfiguration
if ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.LOUDNESS):
allocation_method = SBCAllocationMethod.LOUDNESS
elif ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.SNR):
allocation_method = SBCAllocationMethod.SNR
else:
raise BTInvalidConfiguration
min_bitpool = max(our_caps.min_bitpool, device_caps.min_bitpool)
max_bitpool = min(SBCAudioCodec._default_bitpool(frequency,
channel_mode),
device_caps.max_bitpool)
selected_config = SBCCodecConfig(channel_mode,
frequency,
allocation_method,
subbands,
block_length,
min_bitpool,
max_bitpool)
# Create SBC codec based on selected configuration
self.codec = SBCCodec(selected_config)
dbus_val = SBCAudioCodec._make_config(selected_config)
return dbus_val
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="oay", out_signature="")
def SetConfiguration(self, transport, config):
self._notify_media_transport_available(config.get('Device'), transport)
def __repr__(self):
return pprint.pformat(self.__dict__)
|
liamw9534/bt-manager | bt_manager/audio.py | SBCAudioCodec._make_config | python | def _make_config(config):
# The SBC config encoding is taken from a2dp_codecs.h, in particular,
# the a2dp_sbc_t type is converted into a 4-byte array:
# uint8_t channel_mode:4
# uint8_t frequency:4
# uint8_t allocation_method:2
# uint8_t subbands:2
# uint8_t block_length:4
# uint8_t min_bitpool
# uint8_t max_bitpool
return dbus.Array([dbus.Byte(config.channel_mode |
(config.frequency << 4)),
dbus.Byte(config.allocation_method |
(config.subbands << 2) |
(config.block_length << 4)),
dbus.Byte(config.min_bitpool),
dbus.Byte(config.max_bitpool)]) | Helper to turn SBC codec configuration params into a
a2dp_sbc_t structure usable by bluez | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/audio.py#L353-L371 | null | class SBCAudioCodec(GenericEndpoint):
"""
SBCAudioCodec is an implementation of a media endpoint that
provides common functionality enabling SBC audio source and
SBC audio sink media endpoints to be established.
Since certain procedures are specific to whether or not
the endpoint is a source or sink, in particular the trigger
points for when the media transport is acquired/release,
these parts are left to their respective sub-classes.
SBCAudioCodec handles the following steps in establishing
an endpoint:
* Populates `properties` with the capabilities of the codec.
* `SelectConfiguration`: computes and returns best SBC codec
configuration parameters based on device capabilities
* `SetConfiguration`: a sub-class notifier function is called
* `ClearConfiguration`: nothing is done
* `Release`: nothing
In additional to endpoint establishment, the class also has
transport read and write functions which will handle the
required SBC media encoding/decoding and RTP encapsulation.
The user may also register for `transport ready` events
which allows transport read and write operations to be
properly synchronized.
See also: :py:class:`SBCAudioSink` and :py:class:`SBCAudioSource`
"""
def __init__(self, uuid, path):
config = SBCCodecConfig(SBCChannelMode.ALL,
SBCSamplingFrequency.ALL,
SBCAllocationMethod.ALL,
SBCSubbands.ALL,
SBCBlocks.ALL,
2,
64)
caps = SBCAudioCodec._make_config(config)
codec = dbus.Byte(A2DP_CODECS['SBC'])
delayed_reporting = dbus.Boolean(True)
self.tag = None
self.path = None
self.user_cb = None
self.user_arg = None
self.properties = dbus.Dictionary({'UUID': uuid,
'Codec': codec,
'DelayReporting': delayed_reporting,
'Capabilities': caps})
GenericEndpoint.__init__(self, path)
def _transport_ready_handler(self, fd, cb_condition):
"""
Wrapper for calling user callback routine to notify
when transport data is ready to read
"""
if(self.user_cb):
self.user_cb(self.user_arg)
return True
def _install_transport_ready(self):
if ('r' in self.access_type):
io_event = gobject.IO_IN
else:
io_event = gobject.IO_OUT
self.tag = gobject.io_add_watch(self.fd, io_event,
self._transport_ready_handler)
def _uninstall_transport_ready(self):
if (self.tag):
gobject.source_remove(self.tag)
self.tag = None
def register_transport_ready_event(self, user_cb, user_arg):
"""
Register for transport ready events. The `transport ready`
event is raised via a user callback. If the endpoint
is configured as a source, then the user may then
call :py:meth:`write_transport` in order to send data to
the associated sink.
Otherwise, if the endpoint is configured as a sink, then
the user may call :py:meth:`read_transport` to read
from the associated source instead.
:param func user_cb: User defined callback function. It
must take one parameter which is the user's callback
argument.
:param user_arg: User defined callback argument.
:return:
See also: :py:meth:`unregister_transport_ready_event`
"""
self.user_cb = user_cb
self.user_arg = user_arg
def unregister_transport_ready_event(self):
"""
Unregister previously registered `transport ready`
events.
See also: :py:meth:`register_transport_ready_event`
"""
self.user_cb = None
def read_transport(self):
"""
Read data from media transport.
The returned data payload is SBC decoded and has
all RTP encapsulation removed.
:return data: Payload data that has been decoded,
with RTP encapsulation removed.
:rtype: array{byte}
"""
if ('r' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.decode(self.fd, self.read_mtu)
def write_transport(self, data):
"""
Write data to media transport. The data is
encoded using the SBC codec and RTP encapsulated
before being written to the transport file
descriptor.
:param array{byte} data: Payload data to encode,
encapsulate and send.
"""
if ('w' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.encode(self.fd, self.write_mtu, data)
def close_transport(self):
"""
Forcibly close previously acquired media transport.
.. note:: The user should first make sure any transport
event handlers are unregistered first.
"""
if (self.path):
self._release_media_transport(self.path,
self.access_type)
self.path = None
def _notify_media_transport_available(self, path, transport):
"""
Subclass should implement this to trigger setup once
a new media transport is available.
"""
pass
def _acquire_media_transport(self, path, access_type):
"""
Should be called by subclass when it is ready
to acquire the media transport file descriptor
"""
transport = BTMediaTransport(path=path)
(fd, read_mtu, write_mtu) = transport.acquire(access_type)
self.fd = fd.take() # We must do the clean-up later
self.write_mtu = write_mtu
self.read_mtu = read_mtu
self.access_type = access_type
self.path = path
self._install_transport_ready()
def _release_media_transport(self, path, access_type):
"""
Should be called by subclass when it is finished
with the media transport file descriptor
"""
try:
self._uninstall_transport_ready()
os.close(self.fd) # Clean-up previously taken fd
transport = BTMediaTransport(path=path)
transport.release(access_type)
except:
pass
@staticmethod
def _default_bitpool(frequency, channel_mode):
if (frequency ==
SBCSamplingFrequency.FREQ_16KHZ or
frequency ==
SBCSamplingFrequency.FREQ_32KHZ):
return 53
elif (frequency ==
SBCSamplingFrequency.FREQ_44_1KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 31
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 53
else:
# TODO: Invalid channel_mode
return 53
elif (frequency == SBCSamplingFrequency.FREQ_48KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 29
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 51
else:
# TODO: Invalid channel_mode
return 51
else:
# TODO: Invalid frequency
return 53
@staticmethod
@staticmethod
def _parse_config(config):
"""Helper to turn a2dp_sbc_t structure into a
more usable set of SBC codec configuration params"""
frequency = config[0] >> 4
channel_mode = config[0] & 0xF
allocation_method = config[1] & 0x03
subbands = (config[1] >> 2) & 0x03
block_length = (config[1] >> 4) & 0x0F
min_bitpool = config[2]
max_bitpool = config[3]
return SBCCodecConfig(channel_mode, frequency, allocation_method,
subbands, block_length, min_bitpool, max_bitpool)
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def Release(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def ClearConfiguration(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="ay", out_signature="ay")
def SelectConfiguration(self, caps):
our_caps = SBCAudioCodec._parse_config(self.properties['Capabilities'])
device_caps = SBCAudioCodec._parse_config(caps)
frequency = SBCSamplingFrequency.FREQ_44_1KHZ
if ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_JOINT_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_DUAL):
channel_mode = SBCChannelMode.CHANNEL_MODE_DUAL
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_MONO):
channel_mode = SBCChannelMode.CHANNEL_MODE_MONO
else:
raise BTInvalidConfiguration
if ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_16):
block_length = SBCBlocks.BLOCKS_16
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_12):
block_length = SBCBlocks.BLOCKS_12
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_8):
block_length = SBCBlocks.BLOCKS_8
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_4):
block_length = SBCBlocks.BLOCKS_4
else:
raise BTInvalidConfiguration
if ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_8):
subbands = SBCSubbands.SUBBANDS_8
elif ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_4):
subbands = SBCSubbands.SUBBANDS_4
else:
raise BTInvalidConfiguration
if ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.LOUDNESS):
allocation_method = SBCAllocationMethod.LOUDNESS
elif ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.SNR):
allocation_method = SBCAllocationMethod.SNR
else:
raise BTInvalidConfiguration
min_bitpool = max(our_caps.min_bitpool, device_caps.min_bitpool)
max_bitpool = min(SBCAudioCodec._default_bitpool(frequency,
channel_mode),
device_caps.max_bitpool)
selected_config = SBCCodecConfig(channel_mode,
frequency,
allocation_method,
subbands,
block_length,
min_bitpool,
max_bitpool)
# Create SBC codec based on selected configuration
self.codec = SBCCodec(selected_config)
dbus_val = SBCAudioCodec._make_config(selected_config)
return dbus_val
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="oay", out_signature="")
def SetConfiguration(self, transport, config):
self._notify_media_transport_available(config.get('Device'), transport)
def __repr__(self):
return pprint.pformat(self.__dict__)
|
liamw9534/bt-manager | bt_manager/audio.py | SBCAudioCodec._parse_config | python | def _parse_config(config):
frequency = config[0] >> 4
channel_mode = config[0] & 0xF
allocation_method = config[1] & 0x03
subbands = (config[1] >> 2) & 0x03
block_length = (config[1] >> 4) & 0x0F
min_bitpool = config[2]
max_bitpool = config[3]
return SBCCodecConfig(channel_mode, frequency, allocation_method,
subbands, block_length, min_bitpool, max_bitpool) | Helper to turn a2dp_sbc_t structure into a
more usable set of SBC codec configuration params | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/audio.py#L374-L385 | null | class SBCAudioCodec(GenericEndpoint):
"""
SBCAudioCodec is an implementation of a media endpoint that
provides common functionality enabling SBC audio source and
SBC audio sink media endpoints to be established.
Since certain procedures are specific to whether or not
the endpoint is a source or sink, in particular the trigger
points for when the media transport is acquired/release,
these parts are left to their respective sub-classes.
SBCAudioCodec handles the following steps in establishing
an endpoint:
* Populates `properties` with the capabilities of the codec.
* `SelectConfiguration`: computes and returns best SBC codec
configuration parameters based on device capabilities
* `SetConfiguration`: a sub-class notifier function is called
* `ClearConfiguration`: nothing is done
* `Release`: nothing
In additional to endpoint establishment, the class also has
transport read and write functions which will handle the
required SBC media encoding/decoding and RTP encapsulation.
The user may also register for `transport ready` events
which allows transport read and write operations to be
properly synchronized.
See also: :py:class:`SBCAudioSink` and :py:class:`SBCAudioSource`
"""
def __init__(self, uuid, path):
config = SBCCodecConfig(SBCChannelMode.ALL,
SBCSamplingFrequency.ALL,
SBCAllocationMethod.ALL,
SBCSubbands.ALL,
SBCBlocks.ALL,
2,
64)
caps = SBCAudioCodec._make_config(config)
codec = dbus.Byte(A2DP_CODECS['SBC'])
delayed_reporting = dbus.Boolean(True)
self.tag = None
self.path = None
self.user_cb = None
self.user_arg = None
self.properties = dbus.Dictionary({'UUID': uuid,
'Codec': codec,
'DelayReporting': delayed_reporting,
'Capabilities': caps})
GenericEndpoint.__init__(self, path)
def _transport_ready_handler(self, fd, cb_condition):
"""
Wrapper for calling user callback routine to notify
when transport data is ready to read
"""
if(self.user_cb):
self.user_cb(self.user_arg)
return True
def _install_transport_ready(self):
if ('r' in self.access_type):
io_event = gobject.IO_IN
else:
io_event = gobject.IO_OUT
self.tag = gobject.io_add_watch(self.fd, io_event,
self._transport_ready_handler)
def _uninstall_transport_ready(self):
if (self.tag):
gobject.source_remove(self.tag)
self.tag = None
def register_transport_ready_event(self, user_cb, user_arg):
"""
Register for transport ready events. The `transport ready`
event is raised via a user callback. If the endpoint
is configured as a source, then the user may then
call :py:meth:`write_transport` in order to send data to
the associated sink.
Otherwise, if the endpoint is configured as a sink, then
the user may call :py:meth:`read_transport` to read
from the associated source instead.
:param func user_cb: User defined callback function. It
must take one parameter which is the user's callback
argument.
:param user_arg: User defined callback argument.
:return:
See also: :py:meth:`unregister_transport_ready_event`
"""
self.user_cb = user_cb
self.user_arg = user_arg
def unregister_transport_ready_event(self):
"""
Unregister previously registered `transport ready`
events.
See also: :py:meth:`register_transport_ready_event`
"""
self.user_cb = None
def read_transport(self):
"""
Read data from media transport.
The returned data payload is SBC decoded and has
all RTP encapsulation removed.
:return data: Payload data that has been decoded,
with RTP encapsulation removed.
:rtype: array{byte}
"""
if ('r' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.decode(self.fd, self.read_mtu)
def write_transport(self, data):
"""
Write data to media transport. The data is
encoded using the SBC codec and RTP encapsulated
before being written to the transport file
descriptor.
:param array{byte} data: Payload data to encode,
encapsulate and send.
"""
if ('w' not in self.access_type):
raise BTIncompatibleTransportAccessType
return self.codec.encode(self.fd, self.write_mtu, data)
def close_transport(self):
"""
Forcibly close previously acquired media transport.
.. note:: The user should first make sure any transport
event handlers are unregistered first.
"""
if (self.path):
self._release_media_transport(self.path,
self.access_type)
self.path = None
def _notify_media_transport_available(self, path, transport):
"""
Subclass should implement this to trigger setup once
a new media transport is available.
"""
pass
def _acquire_media_transport(self, path, access_type):
"""
Should be called by subclass when it is ready
to acquire the media transport file descriptor
"""
transport = BTMediaTransport(path=path)
(fd, read_mtu, write_mtu) = transport.acquire(access_type)
self.fd = fd.take() # We must do the clean-up later
self.write_mtu = write_mtu
self.read_mtu = read_mtu
self.access_type = access_type
self.path = path
self._install_transport_ready()
def _release_media_transport(self, path, access_type):
"""
Should be called by subclass when it is finished
with the media transport file descriptor
"""
try:
self._uninstall_transport_ready()
os.close(self.fd) # Clean-up previously taken fd
transport = BTMediaTransport(path=path)
transport.release(access_type)
except:
pass
@staticmethod
def _default_bitpool(frequency, channel_mode):
if (frequency ==
SBCSamplingFrequency.FREQ_16KHZ or
frequency ==
SBCSamplingFrequency.FREQ_32KHZ):
return 53
elif (frequency ==
SBCSamplingFrequency.FREQ_44_1KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 31
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 53
else:
# TODO: Invalid channel_mode
return 53
elif (frequency == SBCSamplingFrequency.FREQ_48KHZ):
if (channel_mode ==
SBCChannelMode.CHANNEL_MODE_MONO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_DUAL):
return 29
elif (channel_mode ==
SBCChannelMode.CHANNEL_MODE_STEREO or
channel_mode ==
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
return 51
else:
# TODO: Invalid channel_mode
return 51
else:
# TODO: Invalid frequency
return 53
@staticmethod
def _make_config(config):
"""Helper to turn SBC codec configuration params into a
a2dp_sbc_t structure usable by bluez"""
# The SBC config encoding is taken from a2dp_codecs.h, in particular,
# the a2dp_sbc_t type is converted into a 4-byte array:
# uint8_t channel_mode:4
# uint8_t frequency:4
# uint8_t allocation_method:2
# uint8_t subbands:2
# uint8_t block_length:4
# uint8_t min_bitpool
# uint8_t max_bitpool
return dbus.Array([dbus.Byte(config.channel_mode |
(config.frequency << 4)),
dbus.Byte(config.allocation_method |
(config.subbands << 2) |
(config.block_length << 4)),
dbus.Byte(config.min_bitpool),
dbus.Byte(config.max_bitpool)])
@staticmethod
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def Release(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="", out_signature="")
def ClearConfiguration(self):
pass
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="ay", out_signature="ay")
def SelectConfiguration(self, caps):
our_caps = SBCAudioCodec._parse_config(self.properties['Capabilities'])
device_caps = SBCAudioCodec._parse_config(caps)
frequency = SBCSamplingFrequency.FREQ_44_1KHZ
if ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_JOINT_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_JOINT_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_STEREO):
channel_mode = SBCChannelMode.CHANNEL_MODE_STEREO
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_DUAL):
channel_mode = SBCChannelMode.CHANNEL_MODE_DUAL
elif ((our_caps.channel_mode & device_caps.channel_mode) &
SBCChannelMode.CHANNEL_MODE_MONO):
channel_mode = SBCChannelMode.CHANNEL_MODE_MONO
else:
raise BTInvalidConfiguration
if ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_16):
block_length = SBCBlocks.BLOCKS_16
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_12):
block_length = SBCBlocks.BLOCKS_12
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_8):
block_length = SBCBlocks.BLOCKS_8
elif ((our_caps.block_length & device_caps.block_length) &
SBCBlocks.BLOCKS_4):
block_length = SBCBlocks.BLOCKS_4
else:
raise BTInvalidConfiguration
if ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_8):
subbands = SBCSubbands.SUBBANDS_8
elif ((our_caps.subbands & device_caps.subbands) &
SBCSubbands.SUBBANDS_4):
subbands = SBCSubbands.SUBBANDS_4
else:
raise BTInvalidConfiguration
if ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.LOUDNESS):
allocation_method = SBCAllocationMethod.LOUDNESS
elif ((our_caps.allocation_method & device_caps.allocation_method) &
SBCAllocationMethod.SNR):
allocation_method = SBCAllocationMethod.SNR
else:
raise BTInvalidConfiguration
min_bitpool = max(our_caps.min_bitpool, device_caps.min_bitpool)
max_bitpool = min(SBCAudioCodec._default_bitpool(frequency,
channel_mode),
device_caps.max_bitpool)
selected_config = SBCCodecConfig(channel_mode,
frequency,
allocation_method,
subbands,
block_length,
min_bitpool,
max_bitpool)
# Create SBC codec based on selected configuration
self.codec = SBCCodec(selected_config)
dbus_val = SBCAudioCodec._make_config(selected_config)
return dbus_val
@dbus.service.method("org.bluez.MediaEndpoint",
in_signature="oay", out_signature="")
def SetConfiguration(self, transport, config):
self._notify_media_transport_available(config.get('Device'), transport)
def __repr__(self):
return pprint.pformat(self.__dict__)
|
liamw9534/bt-manager | bt_manager/audio.py | SBCAudioSink._property_change_event_handler | python | def _property_change_event_handler(self, signal, transport, *args):
current_state = self.source.State
if (self.state == 'connected' and current_state == 'playing'):
self._acquire_media_transport(transport, 'r')
elif (self.state == 'playing' and current_state == 'connected'):
self._release_media_transport(transport, 'r')
self.state = current_state | Handler for property change event. We catch certain state
transitions in order to trigger media transport
acquisition/release | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/audio.py#L496-L507 | null | class SBCAudioSink(SBCAudioCodec):
"""
SBC audio sink media endpoint
SBCAudioSink implies the BT adapter takes on the role of
a sink and the external device is the source e.g.,
iPhone, media player.
Refer to :py:class:`SBCAudioCodec` for basic overview of
endpoint steps
"""
def __init__(self,
path='/endpoint/a2dpsink'):
uuid = dbus.String(SERVICES['AudioSink'].uuid)
SBCAudioCodec.__init__(self, uuid, path)
def _notify_media_transport_available(self, path, transport):
"""
Called by the endpoint when a new media transport is
available
"""
self.source = BTAudioSource(dev_path=path)
self.state = self.source.State
self.source.add_signal_receiver(self._property_change_event_handler,
BTAudioSource.SIGNAL_PROPERTY_CHANGED, # noqa
transport)
|
liamw9534/bt-manager | bt_manager/audio.py | SBCAudioSink._notify_media_transport_available | python | def _notify_media_transport_available(self, path, transport):
self.source = BTAudioSource(dev_path=path)
self.state = self.source.State
self.source.add_signal_receiver(self._property_change_event_handler,
BTAudioSource.SIGNAL_PROPERTY_CHANGED, # noqa
transport) | Called by the endpoint when a new media transport is
available | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/audio.py#L509-L518 | null | class SBCAudioSink(SBCAudioCodec):
"""
SBC audio sink media endpoint
SBCAudioSink implies the BT adapter takes on the role of
a sink and the external device is the source e.g.,
iPhone, media player.
Refer to :py:class:`SBCAudioCodec` for basic overview of
endpoint steps
"""
def __init__(self,
path='/endpoint/a2dpsink'):
uuid = dbus.String(SERVICES['AudioSink'].uuid)
SBCAudioCodec.__init__(self, uuid, path)
def _property_change_event_handler(self, signal, transport, *args):
"""
Handler for property change event. We catch certain state
transitions in order to trigger media transport
acquisition/release
"""
current_state = self.source.State
if (self.state == 'connected' and current_state == 'playing'):
self._acquire_media_transport(transport, 'r')
elif (self.state == 'playing' and current_state == 'connected'):
self._release_media_transport(transport, 'r')
self.state = current_state
|
liamw9534/bt-manager | bt_manager/audio.py | SBCAudioSource._notify_media_transport_available | python | def _notify_media_transport_available(self, path, transport):
self.sink = BTAudioSink(dev_path=path)
self.state = self.sink.State
self.sink.add_signal_receiver(self._property_change_event_handler,
BTAudioSource.SIGNAL_PROPERTY_CHANGED, # noqa
transport) | Called by the endpoint when a new media transport is
available | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/audio.py#L551-L560 | null | class SBCAudioSource(SBCAudioCodec):
"""
SBC audio source media endpoint.
SBCAudioSource implies the adapter takes on the role of
source and the external device is the sink e.g., speaker.
Refer to :py:class:`SBCAudioCodec` for basic overview of
endpoint steps
"""
def __init__(self,
path='/endpoint/a2dpsource'):
uuid = dbus.String(SERVICES['AudioSource'].uuid)
SBCAudioCodec.__init__(self, uuid, path)
def _property_change_event_handler(self, signal, transport, *args):
"""
Handler for property change event. We catch certain state
transitions in order to trigger media transport
acquisition/release
"""
current_state = self.sink.State
if ((self.state == 'disconnected' and current_state == 'connected') or
(self.state == 'connecting' and
current_state == 'connected')):
self._acquire_media_transport(transport, 'w')
elif (self.state == 'connected' and current_state == 'disconnected'):
self._release_media_transport(transport, 'w')
self.state = current_state
|
liamw9534/bt-manager | bt_manager/adapter.py | BTAdapter.create_paired_device | python | def create_paired_device(self, dev_id, agent_path,
capability, cb_notify_device, cb_notify_error):
return self._interface.CreatePairedDevice(dev_id,
agent_path,
capability,
reply_handler=cb_notify_device, # noqa
error_handler=cb_notify_error) | Creates a new object path for a remote device. This
method will connect to the remote device and retrieve
all SDP records and then initiate the pairing.
If a previously :py:meth:`create_device` was used
successfully, this method will only initiate the pairing.
Compared to :py:meth:`create_device` this method will
fail if the pairing already exists, but not if the object
path already has been created. This allows applications
to use :py:meth:`create_device` first and then, if needed,
use :py:meth:`create_paired_device` to initiate pairing.
The agent object path is assumed to reside within the
process (D-Bus connection instance) that calls this
method. No separate registration procedure is needed
for it and it gets automatically released once the
pairing operation is complete.
:param str dev_id: New device MAC address create
e.g., '11:22:33:44:55:66'
:param str agent_path: Path used when creating the
bluetooth agent e.g., '/test/agent'
:param str capability: Pairing agent capability
e.g., 'DisplayYesNo', etc
:param func cb_notify_device: Callback on success. The
callback is called with the new device's object
path as an argument.
:param func cb_notify_error: Callback on error. The
callback is called with the error reason.
:return:
:raises dbus.Exception: org.bluez.Error.InvalidArguments
:raises dbus.Exception: org.bluez.Error.Failed | train | https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/adapter.py#L185-L226 | null | class BTAdapter(BTInterface):
"""
Wrapper around dbus to encapsulate org.bluez.adapter interface.
:param str adapter_path: Object path to bluetooth adapter.
If not given, can use adapter_id instead.
:param str adapter_id: Adapter's MAC address to look-up to find
path e.g., '11:22:33:44:55:66'
:Properties:
* **Address(str) [readonly]**: The Bluetooth device address
of the adapter.
* **Name(str) [readonly]**: The Bluetooth system name
(pretty hostname).
This property is either a static system default
or controlled by an external daemon providing
access to the pretty hostname configuration.
* **Alias(str) [readwrite]**: The Bluetooth friendly name.
This value can be changed.
In case no alias is set, it will return the system
provided name. Setting an empty string as alias will
convert it back to the system provided name.
When resetting the alias with an empty string, the
property will default back to system name.
On a well configured system, this property never
needs to be changed since it defaults to the system
name and provides the pretty hostname. Only if the
local name needs to be different from the pretty
hostname, this property should be used as last
resort.
* **Class(uint32) [readonly]**: The Bluetooth class of
device.
This property represents the value that is either
automatically configured by DMI/ACPI information
or provided as static configuration.
* **Powered(boolean) [readwrite]**: Switch an adapter on or
off. This will also set the appropriate connectable
state of the controller.
The value of this property is not persistent. After
restart or unplugging of the adapter it will reset
back to false.
* **Discoverable(boolean) [readwrite]**: Switch an adapter
to discoverable or non-discoverable to either make it
visible or hide it. This is a global setting and should
only be used by the settings application.
If DiscoverableTimeout is set to a non-zero
value then the system will set this value back to
false after the timer expired.
In case the adapter is switched off, setting this
value will fail.
When changing the Powered property the new state of
this property will be updated via a
:py:attr:`.BTInterface.SIGNAL_PROPERTY_CHANGED`
signal.
For any new adapter this settings defaults to false.
* **Pairable(boolean) [readwrite]**: Switch an adapter to
pairable or non-pairable. This is a global setting and
should only be used by the settings application.
* **PairableTimeout(uint32) [readwrite]**:
The pairable timeout in seconds. A value of zero
means that the timeout is disabled and it will stay in
pairable mode forever.
The default value for pairable timeout should be
disabled (value 0).
* **DiscoverableTimeout(uint32) [readwrite]**:
The discoverable timeout in seconds. A value of zero
means that the timeout is disabled and it will stay in
discoverable/limited mode forever.
The default value for the discoverable timeout should
be 180 seconds (3 minutes).
* **Discovering(boolean) [readonly]**:
Indicates that a device discovery procedure is active.
* **UUIDs(array{str}) [readonly]**:
List of 128-bit UUIDs that represents the available
local services.
* **Modalias(str) [readonly, optional]**:
Local Device ID information in modalias format
used by the kernel and udev.
See also: :py:class:`.BTManager`
"""
SIGNAL_DEVICE_FOUND = 'DeviceFound'
"""
:signal DeviceFound(signal_name, user_arg, device_path): Signal
notifying when a new device has been found
"""
SIGNAL_DEVICE_REMOVED = 'DeviceRemoved'
"""
:signal DeviceRemoved(signal_name, user_arg, device_path):
Signal notifying when a device has been removed
"""
SIGNAL_DEVICE_CREATED = 'DeviceCreated'
"""
:signal DeviceCreated(signal_name, user_arg, device_path):
Signal notifying when a new device is created
"""
SIGNAL_DEVICE_DISAPPEARED = 'DeviceDisappeared'
"""
:signal DeviceDisappeared(signal_name, user_arg, device_path):
Signal notifying when a device is now out-of-range
"""
def __init__(self, adapter_path=None, adapter_id=None):
manager = BTManager()
if (adapter_path is None):
if (adapter_id is None):
adapter_path = manager.default_adapter()
else:
adapter_path = manager.find_adapter(adapter_id)
BTInterface.__init__(self, adapter_path, 'org.bluez.Adapter')
self._register_signal_name(BTAdapter.SIGNAL_DEVICE_FOUND)
self._register_signal_name(BTAdapter.SIGNAL_DEVICE_REMOVED)
self._register_signal_name(BTAdapter.SIGNAL_DEVICE_CREATED)
self._register_signal_name(BTAdapter.SIGNAL_DEVICE_DISAPPEARED)
def start_discovery(self):
"""
This method starts the device discovery session. This
includes an inquiry procedure and remote device name
resolving. Use :py:meth:`stop_discovery` to release the sessions
acquired.
This process will start emitting :py:attr:`SIGNAL_DEVICE_FOUND`
and :py:attr:`.SIGNAL_PROPERTY_CHANGED` 'discovering' signals.
:return:
:raises dbus.Exception: org.bluez.Error.NotReady
:raises dbus.Exception: org.bluez.Error.Failed
"""
return self._interface.StartDiscovery()
def stop_discovery(self):
"""
This method will cancel any previous :py:meth:`start_discovery`
transaction.
Note that a discovery procedure is shared between all
discovery sessions thus calling py:meth:`stop_discovery` will
only release a single session.
:return:
:raises dbus.Exception: org.bluez.Error.NotReady
:raises dbus.Exception: org.bluez.Error.Failed
:raises dbus.Exception: org.bluez.Error.NotAuthorized
"""
return self._interface.StopDiscovery()
def find_device(self, dev_id):
"""
Returns the object path of device for given address.
The device object needs to be first created via
:py:meth:`create_device` or
:py:meth:`create_paired_device`
:param str dev_id: Device MAC address to look-up e.g.,
'11:22:33:44:55:66'
:return: Device object path e.g.,
'/org/bluez/985/hci0/dev_00_11_67_D2_AB_EE'
:rtype: str
:raises dbus.Exception: org.bluez.Error.DoesNotExist
:raises dbus.Exception: org.bluez.Error.InvalidArguments
"""
return self._interface.FindDevice(dev_id)
def list_devices(self):
"""
Returns list of device object paths.
:return: List of device object paths
:rtype: list
:raises dbus.Exception: org.bluez.Error.InvalidArguments
:raises dbus.Exception: org.bluez.Error.Failed
:raises dbus.Exception: org.bluez.Error.OutOfMemory
"""
return self._interface.ListDevices()
# noqa
def remove_device(self, dev_path):
"""
This removes the remote device object at the given
path. It will remove also the pairing information.
:param str dev_path: Device object path to remove
e.g., '/org/bluez/985/hci0/dev_00_11_67_D2_AB_EE'
:return:
:raises dbus.Exception: org.bluez.Error.InvalidArguments
:raises dbus.Exception: org.bluez.Error.Failed
"""
return self._interface.RemoveDevice(dev_path)
def register_agent(self, path, capability):
"""
This registers the adapter wide agent.
The object path defines the path the of the agent
that will be called when user input is needed.
If an application disconnects from the bus all
of its registered agents will be removed.
:param str path: Freely definable path for agent e.g., '/test/agent'
:param str capability: The capability parameter can have the values
"DisplayOnly", "DisplayYesNo", "KeyboardOnly" and "NoInputNoOutput"
which reflects the input and output capabilities of the agent.
If an empty string is used it will fallback to "DisplayYesNo".
:return:
:raises dbus.Exception: org.bluez.Error.InvalidArguments
:raises dbus.Exception: org.bluez.Error.AlreadyExists
"""
return self._interface.RegisterAgent(path, capability)
def unregister_agent(self, path):
"""
This unregisters the agent that has been previously
registered. The object path parameter must match the
same value that has been used on registration.
:param str path: Previously defined path for agent
e.g., '/test/agent'
:return:
:raises dbus.Exception: org.bluez.Error.DoesNotExist
"""
return self._interface.UnregisterAgent(path)
|
tkem/uritools | uritools/join.py | urijoin | python | def urijoin(base, ref, strict=False):
if isinstance(base, type(ref)):
return urisplit(base).transform(ref, strict).geturi()
elif isinstance(base, bytes):
return urisplit(base.decode()).transform(ref, strict).geturi()
else:
return urisplit(base).transform(ref.decode(), strict).geturi() | Convert a URI reference relative to a base URI to its target URI
string. | train | https://github.com/tkem/uritools/blob/e77ba4acd937b68da9850138563debd4c925ef9f/uritools/join.py#L4-L14 | [
"def urisplit(uristring):\n \"\"\"Split a well-formed URI reference string into a tuple with five\n components corresponding to a URI's general structure::\n\n <scheme>://<authority>/<path>?<query>#<fragment>\n\n \"\"\"\n if isinstance(uristring, bytes):\n result = SplitResultBytes\n else... | from .split import urisplit
|
tkem/uritools | uritools/defrag.py | uridefrag | python | def uridefrag(uristring):
if isinstance(uristring, bytes):
parts = uristring.partition(b'#')
else:
parts = uristring.partition(u'#')
return DefragResult(parts[0], parts[2] if parts[1] else None) | Remove an existing fragment component from a URI reference string. | train | https://github.com/tkem/uritools/blob/e77ba4acd937b68da9850138563debd4c925ef9f/uritools/defrag.py#L33-L41 | null | import collections
from .encoding import uridecode
class DefragResult(collections.namedtuple('DefragResult', 'uri fragment')):
"""Class to hold :func:`uridefrag` results."""
__slots__ = () # prevent creation of instance dictionary
def geturi(self):
"""Return the recombined version of the original URI as a string."""
fragment = self.fragment
if fragment is None:
return self.uri
elif isinstance(fragment, bytes):
return self.uri + b'#' + fragment
else:
return self.uri + u'#' + fragment
def getfragment(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded fragment identifier, or `default` if the
original URI did not contain a fragment component.
"""
fragment = self.fragment
if fragment is not None:
return uridecode(fragment, encoding, errors)
else:
return default
|
tkem/uritools | uritools/defrag.py | DefragResult.geturi | python | def geturi(self):
fragment = self.fragment
if fragment is None:
return self.uri
elif isinstance(fragment, bytes):
return self.uri + b'#' + fragment
else:
return self.uri + u'#' + fragment | Return the recombined version of the original URI as a string. | train | https://github.com/tkem/uritools/blob/e77ba4acd937b68da9850138563debd4c925ef9f/uritools/defrag.py#L11-L19 | null | class DefragResult(collections.namedtuple('DefragResult', 'uri fragment')):
"""Class to hold :func:`uridefrag` results."""
__slots__ = () # prevent creation of instance dictionary
def getfragment(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded fragment identifier, or `default` if the
original URI did not contain a fragment component.
"""
fragment = self.fragment
if fragment is not None:
return uridecode(fragment, encoding, errors)
else:
return default
|
tkem/uritools | uritools/defrag.py | DefragResult.getfragment | python | def getfragment(self, default=None, encoding='utf-8', errors='strict'):
fragment = self.fragment
if fragment is not None:
return uridecode(fragment, encoding, errors)
else:
return default | Return the decoded fragment identifier, or `default` if the
original URI did not contain a fragment component. | train | https://github.com/tkem/uritools/blob/e77ba4acd937b68da9850138563debd4c925ef9f/uritools/defrag.py#L21-L30 | [
"def uridecode(uristring, encoding='utf-8', errors='strict'):\n \"\"\"Decode a URI string or string component.\"\"\"\n if not isinstance(uristring, bytes):\n uristring = uristring.encode(encoding or 'ascii', errors)\n parts = uristring.split(b'%')\n result = [parts[0]]\n append = result.append... | class DefragResult(collections.namedtuple('DefragResult', 'uri fragment')):
"""Class to hold :func:`uridefrag` results."""
__slots__ = () # prevent creation of instance dictionary
def geturi(self):
"""Return the recombined version of the original URI as a string."""
fragment = self.fragment
if fragment is None:
return self.uri
elif isinstance(fragment, bytes):
return self.uri + b'#' + fragment
else:
return self.uri + u'#' + fragment
|
tkem/uritools | uritools/split.py | urisplit | python | def urisplit(uristring):
if isinstance(uristring, bytes):
result = SplitResultBytes
else:
result = SplitResultUnicode
return result(*result.RE.match(uristring).groups()) | Split a well-formed URI reference string into a tuple with five
components corresponding to a URI's general structure::
<scheme>://<authority>/<path>?<query>#<fragment> | train | https://github.com/tkem/uritools/blob/e77ba4acd937b68da9850138563debd4c925ef9f/uritools/split.py#L374-L385 | null | import collections
import ipaddress
import re
from .encoding import uridecode
_URI_COMPONENTS = ('scheme', 'authority', 'path', 'query', 'fragment')
def _ip_literal(address):
# RFC 3986 3.2.2: In anticipation of future, as-yet-undefined IP
# literal address formats, an implementation may use an optional
# version flag to indicate such a format explicitly rather than
# rely on heuristic determination.
#
# IP-literal = "[" ( IPv6address / IPvFuture ) "]"
#
# IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
#
# If a URI containing an IP-literal that starts with "v"
# (case-insensitive), indicating that the version flag is present,
# is dereferenced by an application that does not know the meaning
# of that version flag, then the application should return an
# appropriate error for "address mechanism not supported".
if isinstance(address, bytes):
address = address.decode('ascii')
if address.startswith(u'v'):
raise ValueError('address mechanism not supported')
return ipaddress.IPv6Address(address)
def _ipv4_address(address):
try:
if isinstance(address, bytes):
return ipaddress.IPv4Address(address.decode('ascii'))
else:
return ipaddress.IPv4Address(address)
except ValueError:
return None
class SplitResult(collections.namedtuple('SplitResult', _URI_COMPONENTS)):
"""Base class to hold :func:`urisplit` results."""
__slots__ = () # prevent creation of instance dictionary
@property
def userinfo(self):
authority = self.authority
if authority is None:
return None
userinfo, present, _ = authority.rpartition(self.AT)
if present:
return userinfo
else:
return None
@property
def host(self):
authority = self.authority
if authority is None:
return None
_, _, hostinfo = authority.rpartition(self.AT)
host, _, port = hostinfo.rpartition(self.COLON)
if port.lstrip(self.DIGITS):
return hostinfo
else:
return host
@property
def port(self):
authority = self.authority
if authority is None:
return None
_, present, port = authority.rpartition(self.COLON)
if present and not port.lstrip(self.DIGITS):
return port
else:
return None
def geturi(self):
"""Return the re-combined version of the original URI reference as a
string.
"""
scheme, authority, path, query, fragment = self
# RFC 3986 5.3. Component Recomposition
result = []
if scheme is not None:
result.extend([scheme, self.COLON])
if authority is not None:
result.extend([self.SLASH, self.SLASH, authority])
result.append(path)
if query is not None:
result.extend([self.QUEST, query])
if fragment is not None:
result.extend([self.HASH, fragment])
return self.EMPTY.join(result)
def getscheme(self, default=None):
"""Return the URI scheme in canonical (lowercase) form, or `default`
if the original URI reference did not contain a scheme component.
"""
scheme = self.scheme
if scheme is None:
return default
elif isinstance(scheme, bytes):
return scheme.decode('ascii').lower()
else:
return scheme.lower()
def getauthority(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded userinfo, host and port subcomponents of the URI
authority as a three-item tuple.
"""
# TBD: (userinfo, host, port) kwargs, default string?
if default is None:
default = (None, None, None)
elif not isinstance(default, collections.Iterable):
raise TypeError('Invalid default type')
elif len(default) != 3:
raise ValueError('Invalid default length')
# TODO: this could be much more efficient by using a dedicated regex
return (
self.getuserinfo(default[0], encoding, errors),
self.gethost(default[1], errors),
self.getport(default[2])
)
def getuserinfo(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded userinfo subcomponent of the URI authority, or
`default` if the original URI reference did not contain a
userinfo field.
"""
userinfo = self.userinfo
if userinfo is None:
return default
else:
return uridecode(userinfo, encoding, errors)
def gethost(self, default=None, errors='strict'):
"""Return the decoded host subcomponent of the URI authority as a
string or an :mod:`ipaddress` address object, or `default` if
the original URI reference did not contain a host.
"""
host = self.host
if host is None or (not host and default is not None):
return default
elif host.startswith(self.LBRACKET) and host.endswith(self.RBRACKET):
return _ip_literal(host[1:-1])
elif host.startswith(self.LBRACKET) or host.endswith(self.RBRACKET):
raise ValueError('Invalid host %r' % host)
# TODO: faster check for IPv4 address?
return _ipv4_address(host) or uridecode(host, 'utf-8', errors).lower()
def getport(self, default=None):
"""Return the port subcomponent of the URI authority as an
:class:`int`, or `default` if the original URI reference did
not contain a port or if the port was empty.
"""
port = self.port
if port:
return int(port)
else:
return default
def getpath(self, encoding='utf-8', errors='strict'):
"""Return the normalized decoded URI path."""
path = self.__remove_dot_segments(self.path)
return uridecode(path, encoding, errors)
def getquery(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded query string, or `default` if the original URI
reference did not contain a query component.
"""
query = self.query
if query is None:
return default
else:
return uridecode(query, encoding, errors)
def getquerydict(self, sep='&', encoding='utf-8', errors='strict'):
"""Split the query component into individual `name=value` pairs
separated by `sep` and return a dictionary of query variables.
The dictionary keys are the unique query variable names and
the values are lists of values for each name.
"""
dict = collections.defaultdict(list)
for name, value in self.getquerylist(sep, encoding, errors):
dict[name].append(value)
return dict
def getquerylist(self, sep='&', encoding='utf-8', errors='strict'):
"""Split the query component into individual `name=value` pairs
separated by `sep`, and return a list of `(name, value)`
tuples.
"""
if not self.query:
return []
elif isinstance(sep, type(self.query)):
qsl = self.query.split(sep)
elif isinstance(sep, bytes):
qsl = self.query.split(sep.decode('ascii'))
else:
qsl = self.query.split(sep.encode('ascii'))
items = []
for parts in [qs.partition(self.EQ) for qs in qsl if qs]:
name = uridecode(parts[0], encoding, errors)
if parts[1]:
value = uridecode(parts[2], encoding, errors)
else:
value = None
items.append((name, value))
return items
def getfragment(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded fragment identifier, or `default` if the
original URI reference did not contain a fragment component.
"""
fragment = self.fragment
if fragment is None:
return default
else:
return uridecode(fragment, encoding, errors)
def isuri(self):
"""Return :const:`True` if this is a URI."""
return self.scheme is not None
def isabsuri(self):
"""Return :const:`True` if this is an absolute URI."""
return self.scheme is not None and self.fragment is None
def isnetpath(self):
"""Return :const:`True` if this is a network-path reference."""
return self.scheme is None and self.authority is not None
def isabspath(self):
"""Return :const:`True` if this is an absolute-path reference."""
return (self.scheme is None and self.authority is None and
self.path.startswith(self.SLASH))
def isrelpath(self):
"""Return :const:`True` if this is a relative-path reference."""
return (self.scheme is None and self.authority is None and
not self.path.startswith(self.SLASH))
def issamedoc(self):
"""Return :const:`True` if this is a same-document reference."""
return (self.scheme is None and self.authority is None and
not self.path and self.query is None)
def transform(self, ref, strict=False):
"""Transform a URI reference relative to `self` into a
:class:`SplitResult` representing its target URI.
"""
scheme, authority, path, query, fragment = self.RE.match(ref).groups()
# RFC 3986 5.2.2. Transform References
if scheme is not None and (strict or scheme != self.scheme):
path = self.__remove_dot_segments(path)
elif authority is not None:
scheme = self.scheme
path = self.__remove_dot_segments(path)
elif not path:
scheme = self.scheme
authority = self.authority
path = self.path
query = self.query if query is None else query
elif path.startswith(self.SLASH):
scheme = self.scheme
authority = self.authority
path = self.__remove_dot_segments(path)
else:
scheme = self.scheme
authority = self.authority
path = self.__remove_dot_segments(self.__merge(path))
return type(self)(scheme, authority, path, query, fragment)
def __merge(self, path):
# RFC 3986 5.2.3. Merge Paths
if self.authority is not None and not self.path:
return self.SLASH + path
else:
parts = self.path.rpartition(self.SLASH)
return parts[1].join((parts[0], path))
@classmethod
def __remove_dot_segments(cls, path):
# RFC 3986 5.2.4. Remove Dot Segments
pseg = []
for s in path.split(cls.SLASH):
if s == cls.DOT:
continue
elif s != cls.DOTDOT:
pseg.append(s)
elif len(pseg) == 1 and not pseg[0]:
continue
elif pseg and pseg[-1] != cls.DOTDOT:
pseg.pop()
else:
pseg.append(s)
# adjust for trailing '/.' or '/..'
if path.rpartition(cls.SLASH)[2] in (cls.DOT, cls.DOTDOT):
pseg.append(cls.EMPTY)
if path and len(pseg) == 1 and pseg[0] == cls.EMPTY:
pseg.insert(0, cls.DOT)
return cls.SLASH.join(pseg)
class SplitResultBytes(SplitResult):
__slots__ = () # prevent creation of instance dictionary
# RFC 3986 Appendix B
RE = re.compile(br"""
(?:([A-Za-z][A-Za-z0-9+.-]*):)? # scheme (RFC 3986 3.1)
(?://([^/?#]*))? # authority
([^?#]*) # path
(?:\?([^#]*))? # query
(?:\#(.*))? # fragment
""", flags=re.VERBOSE)
# RFC 3986 2.2 gen-delims
COLON, SLASH, QUEST, HASH, LBRACKET, RBRACKET, AT = (
b':', b'/', b'?', b'#', b'[', b']', b'@'
)
# RFC 3986 3.3 dot-segments
DOT, DOTDOT = b'.', b'..'
EMPTY, EQ = b'', b'='
DIGITS = b'0123456789'
class SplitResultUnicode(SplitResult):
__slots__ = () # prevent creation of instance dictionary
# RFC 3986 Appendix B
RE = re.compile(r"""
(?:([A-Za-z][A-Za-z0-9+.-]*):)? # scheme (RFC 3986 3.1)
(?://([^/?#]*))? # authority
([^?#]*) # path
(?:\?([^#]*))? # query
(?:\#(.*))? # fragment
""", flags=re.VERBOSE)
# RFC 3986 2.2 gen-delims
COLON, SLASH, QUEST, HASH, LBRACKET, RBRACKET, AT = (
u':', u'/', u'?', u'#', u'[', u']', u'@'
)
# RFC 3986 3.3 dot-segments
DOT, DOTDOT = u'.', u'..'
EMPTY, EQ = u'', u'='
DIGITS = u'0123456789'
def uriunsplit(parts):
"""Combine the elements of a five-item iterable into a URI reference's
string representation.
"""
scheme, authority, path, query, fragment = parts
if isinstance(path, bytes):
result = SplitResultBytes
else:
result = SplitResultUnicode
return result(scheme, authority, path, query, fragment).geturi()
|
tkem/uritools | uritools/split.py | uriunsplit | python | def uriunsplit(parts):
scheme, authority, path, query, fragment = parts
if isinstance(path, bytes):
result = SplitResultBytes
else:
result = SplitResultUnicode
return result(scheme, authority, path, query, fragment).geturi() | Combine the elements of a five-item iterable into a URI reference's
string representation. | train | https://github.com/tkem/uritools/blob/e77ba4acd937b68da9850138563debd4c925ef9f/uritools/split.py#L388-L398 | null | import collections
import ipaddress
import re
from .encoding import uridecode
_URI_COMPONENTS = ('scheme', 'authority', 'path', 'query', 'fragment')
def _ip_literal(address):
# RFC 3986 3.2.2: In anticipation of future, as-yet-undefined IP
# literal address formats, an implementation may use an optional
# version flag to indicate such a format explicitly rather than
# rely on heuristic determination.
#
# IP-literal = "[" ( IPv6address / IPvFuture ) "]"
#
# IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
#
# If a URI containing an IP-literal that starts with "v"
# (case-insensitive), indicating that the version flag is present,
# is dereferenced by an application that does not know the meaning
# of that version flag, then the application should return an
# appropriate error for "address mechanism not supported".
if isinstance(address, bytes):
address = address.decode('ascii')
if address.startswith(u'v'):
raise ValueError('address mechanism not supported')
return ipaddress.IPv6Address(address)
def _ipv4_address(address):
try:
if isinstance(address, bytes):
return ipaddress.IPv4Address(address.decode('ascii'))
else:
return ipaddress.IPv4Address(address)
except ValueError:
return None
class SplitResult(collections.namedtuple('SplitResult', _URI_COMPONENTS)):
"""Base class to hold :func:`urisplit` results."""
__slots__ = () # prevent creation of instance dictionary
@property
def userinfo(self):
authority = self.authority
if authority is None:
return None
userinfo, present, _ = authority.rpartition(self.AT)
if present:
return userinfo
else:
return None
@property
def host(self):
authority = self.authority
if authority is None:
return None
_, _, hostinfo = authority.rpartition(self.AT)
host, _, port = hostinfo.rpartition(self.COLON)
if port.lstrip(self.DIGITS):
return hostinfo
else:
return host
@property
def port(self):
authority = self.authority
if authority is None:
return None
_, present, port = authority.rpartition(self.COLON)
if present and not port.lstrip(self.DIGITS):
return port
else:
return None
def geturi(self):
"""Return the re-combined version of the original URI reference as a
string.
"""
scheme, authority, path, query, fragment = self
# RFC 3986 5.3. Component Recomposition
result = []
if scheme is not None:
result.extend([scheme, self.COLON])
if authority is not None:
result.extend([self.SLASH, self.SLASH, authority])
result.append(path)
if query is not None:
result.extend([self.QUEST, query])
if fragment is not None:
result.extend([self.HASH, fragment])
return self.EMPTY.join(result)
def getscheme(self, default=None):
"""Return the URI scheme in canonical (lowercase) form, or `default`
if the original URI reference did not contain a scheme component.
"""
scheme = self.scheme
if scheme is None:
return default
elif isinstance(scheme, bytes):
return scheme.decode('ascii').lower()
else:
return scheme.lower()
def getauthority(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded userinfo, host and port subcomponents of the URI
authority as a three-item tuple.
"""
# TBD: (userinfo, host, port) kwargs, default string?
if default is None:
default = (None, None, None)
elif not isinstance(default, collections.Iterable):
raise TypeError('Invalid default type')
elif len(default) != 3:
raise ValueError('Invalid default length')
# TODO: this could be much more efficient by using a dedicated regex
return (
self.getuserinfo(default[0], encoding, errors),
self.gethost(default[1], errors),
self.getport(default[2])
)
def getuserinfo(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded userinfo subcomponent of the URI authority, or
`default` if the original URI reference did not contain a
userinfo field.
"""
userinfo = self.userinfo
if userinfo is None:
return default
else:
return uridecode(userinfo, encoding, errors)
def gethost(self, default=None, errors='strict'):
"""Return the decoded host subcomponent of the URI authority as a
string or an :mod:`ipaddress` address object, or `default` if
the original URI reference did not contain a host.
"""
host = self.host
if host is None or (not host and default is not None):
return default
elif host.startswith(self.LBRACKET) and host.endswith(self.RBRACKET):
return _ip_literal(host[1:-1])
elif host.startswith(self.LBRACKET) or host.endswith(self.RBRACKET):
raise ValueError('Invalid host %r' % host)
# TODO: faster check for IPv4 address?
return _ipv4_address(host) or uridecode(host, 'utf-8', errors).lower()
def getport(self, default=None):
"""Return the port subcomponent of the URI authority as an
:class:`int`, or `default` if the original URI reference did
not contain a port or if the port was empty.
"""
port = self.port
if port:
return int(port)
else:
return default
def getpath(self, encoding='utf-8', errors='strict'):
"""Return the normalized decoded URI path."""
path = self.__remove_dot_segments(self.path)
return uridecode(path, encoding, errors)
def getquery(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded query string, or `default` if the original URI
reference did not contain a query component.
"""
query = self.query
if query is None:
return default
else:
return uridecode(query, encoding, errors)
def getquerydict(self, sep='&', encoding='utf-8', errors='strict'):
"""Split the query component into individual `name=value` pairs
separated by `sep` and return a dictionary of query variables.
The dictionary keys are the unique query variable names and
the values are lists of values for each name.
"""
dict = collections.defaultdict(list)
for name, value in self.getquerylist(sep, encoding, errors):
dict[name].append(value)
return dict
def getquerylist(self, sep='&', encoding='utf-8', errors='strict'):
"""Split the query component into individual `name=value` pairs
separated by `sep`, and return a list of `(name, value)`
tuples.
"""
if not self.query:
return []
elif isinstance(sep, type(self.query)):
qsl = self.query.split(sep)
elif isinstance(sep, bytes):
qsl = self.query.split(sep.decode('ascii'))
else:
qsl = self.query.split(sep.encode('ascii'))
items = []
for parts in [qs.partition(self.EQ) for qs in qsl if qs]:
name = uridecode(parts[0], encoding, errors)
if parts[1]:
value = uridecode(parts[2], encoding, errors)
else:
value = None
items.append((name, value))
return items
def getfragment(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded fragment identifier, or `default` if the
original URI reference did not contain a fragment component.
"""
fragment = self.fragment
if fragment is None:
return default
else:
return uridecode(fragment, encoding, errors)
def isuri(self):
"""Return :const:`True` if this is a URI."""
return self.scheme is not None
def isabsuri(self):
"""Return :const:`True` if this is an absolute URI."""
return self.scheme is not None and self.fragment is None
def isnetpath(self):
"""Return :const:`True` if this is a network-path reference."""
return self.scheme is None and self.authority is not None
def isabspath(self):
"""Return :const:`True` if this is an absolute-path reference."""
return (self.scheme is None and self.authority is None and
self.path.startswith(self.SLASH))
def isrelpath(self):
"""Return :const:`True` if this is a relative-path reference."""
return (self.scheme is None and self.authority is None and
not self.path.startswith(self.SLASH))
def issamedoc(self):
"""Return :const:`True` if this is a same-document reference."""
return (self.scheme is None and self.authority is None and
not self.path and self.query is None)
def transform(self, ref, strict=False):
"""Transform a URI reference relative to `self` into a
:class:`SplitResult` representing its target URI.
"""
scheme, authority, path, query, fragment = self.RE.match(ref).groups()
# RFC 3986 5.2.2. Transform References
if scheme is not None and (strict or scheme != self.scheme):
path = self.__remove_dot_segments(path)
elif authority is not None:
scheme = self.scheme
path = self.__remove_dot_segments(path)
elif not path:
scheme = self.scheme
authority = self.authority
path = self.path
query = self.query if query is None else query
elif path.startswith(self.SLASH):
scheme = self.scheme
authority = self.authority
path = self.__remove_dot_segments(path)
else:
scheme = self.scheme
authority = self.authority
path = self.__remove_dot_segments(self.__merge(path))
return type(self)(scheme, authority, path, query, fragment)
def __merge(self, path):
# RFC 3986 5.2.3. Merge Paths
if self.authority is not None and not self.path:
return self.SLASH + path
else:
parts = self.path.rpartition(self.SLASH)
return parts[1].join((parts[0], path))
@classmethod
def __remove_dot_segments(cls, path):
# RFC 3986 5.2.4. Remove Dot Segments
pseg = []
for s in path.split(cls.SLASH):
if s == cls.DOT:
continue
elif s != cls.DOTDOT:
pseg.append(s)
elif len(pseg) == 1 and not pseg[0]:
continue
elif pseg and pseg[-1] != cls.DOTDOT:
pseg.pop()
else:
pseg.append(s)
# adjust for trailing '/.' or '/..'
if path.rpartition(cls.SLASH)[2] in (cls.DOT, cls.DOTDOT):
pseg.append(cls.EMPTY)
if path and len(pseg) == 1 and pseg[0] == cls.EMPTY:
pseg.insert(0, cls.DOT)
return cls.SLASH.join(pseg)
class SplitResultBytes(SplitResult):
__slots__ = () # prevent creation of instance dictionary
# RFC 3986 Appendix B
RE = re.compile(br"""
(?:([A-Za-z][A-Za-z0-9+.-]*):)? # scheme (RFC 3986 3.1)
(?://([^/?#]*))? # authority
([^?#]*) # path
(?:\?([^#]*))? # query
(?:\#(.*))? # fragment
""", flags=re.VERBOSE)
# RFC 3986 2.2 gen-delims
COLON, SLASH, QUEST, HASH, LBRACKET, RBRACKET, AT = (
b':', b'/', b'?', b'#', b'[', b']', b'@'
)
# RFC 3986 3.3 dot-segments
DOT, DOTDOT = b'.', b'..'
EMPTY, EQ = b'', b'='
DIGITS = b'0123456789'
class SplitResultUnicode(SplitResult):
__slots__ = () # prevent creation of instance dictionary
# RFC 3986 Appendix B
RE = re.compile(r"""
(?:([A-Za-z][A-Za-z0-9+.-]*):)? # scheme (RFC 3986 3.1)
(?://([^/?#]*))? # authority
([^?#]*) # path
(?:\?([^#]*))? # query
(?:\#(.*))? # fragment
""", flags=re.VERBOSE)
# RFC 3986 2.2 gen-delims
COLON, SLASH, QUEST, HASH, LBRACKET, RBRACKET, AT = (
u':', u'/', u'?', u'#', u'[', u']', u'@'
)
# RFC 3986 3.3 dot-segments
DOT, DOTDOT = u'.', u'..'
EMPTY, EQ = u'', u'='
DIGITS = u'0123456789'
def urisplit(uristring):
"""Split a well-formed URI reference string into a tuple with five
components corresponding to a URI's general structure::
<scheme>://<authority>/<path>?<query>#<fragment>
"""
if isinstance(uristring, bytes):
result = SplitResultBytes
else:
result = SplitResultUnicode
return result(*result.RE.match(uristring).groups())
|
tkem/uritools | uritools/split.py | SplitResult.geturi | python | def geturi(self):
scheme, authority, path, query, fragment = self
# RFC 3986 5.3. Component Recomposition
result = []
if scheme is not None:
result.extend([scheme, self.COLON])
if authority is not None:
result.extend([self.SLASH, self.SLASH, authority])
result.append(path)
if query is not None:
result.extend([self.QUEST, query])
if fragment is not None:
result.extend([self.HASH, fragment])
return self.EMPTY.join(result) | Return the re-combined version of the original URI reference as a
string. | train | https://github.com/tkem/uritools/blob/e77ba4acd937b68da9850138563debd4c925ef9f/uritools/split.py#L81-L99 | null | class SplitResult(collections.namedtuple('SplitResult', _URI_COMPONENTS)):
"""Base class to hold :func:`urisplit` results."""
__slots__ = () # prevent creation of instance dictionary
@property
def userinfo(self):
authority = self.authority
if authority is None:
return None
userinfo, present, _ = authority.rpartition(self.AT)
if present:
return userinfo
else:
return None
@property
def host(self):
authority = self.authority
if authority is None:
return None
_, _, hostinfo = authority.rpartition(self.AT)
host, _, port = hostinfo.rpartition(self.COLON)
if port.lstrip(self.DIGITS):
return hostinfo
else:
return host
@property
def port(self):
authority = self.authority
if authority is None:
return None
_, present, port = authority.rpartition(self.COLON)
if present and not port.lstrip(self.DIGITS):
return port
else:
return None
def getscheme(self, default=None):
"""Return the URI scheme in canonical (lowercase) form, or `default`
if the original URI reference did not contain a scheme component.
"""
scheme = self.scheme
if scheme is None:
return default
elif isinstance(scheme, bytes):
return scheme.decode('ascii').lower()
else:
return scheme.lower()
def getauthority(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded userinfo, host and port subcomponents of the URI
authority as a three-item tuple.
"""
# TBD: (userinfo, host, port) kwargs, default string?
if default is None:
default = (None, None, None)
elif not isinstance(default, collections.Iterable):
raise TypeError('Invalid default type')
elif len(default) != 3:
raise ValueError('Invalid default length')
# TODO: this could be much more efficient by using a dedicated regex
return (
self.getuserinfo(default[0], encoding, errors),
self.gethost(default[1], errors),
self.getport(default[2])
)
def getuserinfo(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded userinfo subcomponent of the URI authority, or
`default` if the original URI reference did not contain a
userinfo field.
"""
userinfo = self.userinfo
if userinfo is None:
return default
else:
return uridecode(userinfo, encoding, errors)
def gethost(self, default=None, errors='strict'):
"""Return the decoded host subcomponent of the URI authority as a
string or an :mod:`ipaddress` address object, or `default` if
the original URI reference did not contain a host.
"""
host = self.host
if host is None or (not host and default is not None):
return default
elif host.startswith(self.LBRACKET) and host.endswith(self.RBRACKET):
return _ip_literal(host[1:-1])
elif host.startswith(self.LBRACKET) or host.endswith(self.RBRACKET):
raise ValueError('Invalid host %r' % host)
# TODO: faster check for IPv4 address?
return _ipv4_address(host) or uridecode(host, 'utf-8', errors).lower()
def getport(self, default=None):
"""Return the port subcomponent of the URI authority as an
:class:`int`, or `default` if the original URI reference did
not contain a port or if the port was empty.
"""
port = self.port
if port:
return int(port)
else:
return default
def getpath(self, encoding='utf-8', errors='strict'):
"""Return the normalized decoded URI path."""
path = self.__remove_dot_segments(self.path)
return uridecode(path, encoding, errors)
def getquery(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded query string, or `default` if the original URI
reference did not contain a query component.
"""
query = self.query
if query is None:
return default
else:
return uridecode(query, encoding, errors)
def getquerydict(self, sep='&', encoding='utf-8', errors='strict'):
"""Split the query component into individual `name=value` pairs
separated by `sep` and return a dictionary of query variables.
The dictionary keys are the unique query variable names and
the values are lists of values for each name.
"""
dict = collections.defaultdict(list)
for name, value in self.getquerylist(sep, encoding, errors):
dict[name].append(value)
return dict
def getquerylist(self, sep='&', encoding='utf-8', errors='strict'):
"""Split the query component into individual `name=value` pairs
separated by `sep`, and return a list of `(name, value)`
tuples.
"""
if not self.query:
return []
elif isinstance(sep, type(self.query)):
qsl = self.query.split(sep)
elif isinstance(sep, bytes):
qsl = self.query.split(sep.decode('ascii'))
else:
qsl = self.query.split(sep.encode('ascii'))
items = []
for parts in [qs.partition(self.EQ) for qs in qsl if qs]:
name = uridecode(parts[0], encoding, errors)
if parts[1]:
value = uridecode(parts[2], encoding, errors)
else:
value = None
items.append((name, value))
return items
def getfragment(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded fragment identifier, or `default` if the
original URI reference did not contain a fragment component.
"""
fragment = self.fragment
if fragment is None:
return default
else:
return uridecode(fragment, encoding, errors)
def isuri(self):
"""Return :const:`True` if this is a URI."""
return self.scheme is not None
def isabsuri(self):
"""Return :const:`True` if this is an absolute URI."""
return self.scheme is not None and self.fragment is None
def isnetpath(self):
"""Return :const:`True` if this is a network-path reference."""
return self.scheme is None and self.authority is not None
def isabspath(self):
"""Return :const:`True` if this is an absolute-path reference."""
return (self.scheme is None and self.authority is None and
self.path.startswith(self.SLASH))
def isrelpath(self):
"""Return :const:`True` if this is a relative-path reference."""
return (self.scheme is None and self.authority is None and
not self.path.startswith(self.SLASH))
def issamedoc(self):
"""Return :const:`True` if this is a same-document reference."""
return (self.scheme is None and self.authority is None and
not self.path and self.query is None)
def transform(self, ref, strict=False):
"""Transform a URI reference relative to `self` into a
:class:`SplitResult` representing its target URI.
"""
scheme, authority, path, query, fragment = self.RE.match(ref).groups()
# RFC 3986 5.2.2. Transform References
if scheme is not None and (strict or scheme != self.scheme):
path = self.__remove_dot_segments(path)
elif authority is not None:
scheme = self.scheme
path = self.__remove_dot_segments(path)
elif not path:
scheme = self.scheme
authority = self.authority
path = self.path
query = self.query if query is None else query
elif path.startswith(self.SLASH):
scheme = self.scheme
authority = self.authority
path = self.__remove_dot_segments(path)
else:
scheme = self.scheme
authority = self.authority
path = self.__remove_dot_segments(self.__merge(path))
return type(self)(scheme, authority, path, query, fragment)
def __merge(self, path):
# RFC 3986 5.2.3. Merge Paths
if self.authority is not None and not self.path:
return self.SLASH + path
else:
parts = self.path.rpartition(self.SLASH)
return parts[1].join((parts[0], path))
@classmethod
def __remove_dot_segments(cls, path):
# RFC 3986 5.2.4. Remove Dot Segments
pseg = []
for s in path.split(cls.SLASH):
if s == cls.DOT:
continue
elif s != cls.DOTDOT:
pseg.append(s)
elif len(pseg) == 1 and not pseg[0]:
continue
elif pseg and pseg[-1] != cls.DOTDOT:
pseg.pop()
else:
pseg.append(s)
# adjust for trailing '/.' or '/..'
if path.rpartition(cls.SLASH)[2] in (cls.DOT, cls.DOTDOT):
pseg.append(cls.EMPTY)
if path and len(pseg) == 1 and pseg[0] == cls.EMPTY:
pseg.insert(0, cls.DOT)
return cls.SLASH.join(pseg)
|
tkem/uritools | uritools/split.py | SplitResult.getscheme | python | def getscheme(self, default=None):
scheme = self.scheme
if scheme is None:
return default
elif isinstance(scheme, bytes):
return scheme.decode('ascii').lower()
else:
return scheme.lower() | Return the URI scheme in canonical (lowercase) form, or `default`
if the original URI reference did not contain a scheme component. | train | https://github.com/tkem/uritools/blob/e77ba4acd937b68da9850138563debd4c925ef9f/uritools/split.py#L101-L112 | null | class SplitResult(collections.namedtuple('SplitResult', _URI_COMPONENTS)):
"""Base class to hold :func:`urisplit` results."""
__slots__ = () # prevent creation of instance dictionary
@property
def userinfo(self):
authority = self.authority
if authority is None:
return None
userinfo, present, _ = authority.rpartition(self.AT)
if present:
return userinfo
else:
return None
@property
def host(self):
authority = self.authority
if authority is None:
return None
_, _, hostinfo = authority.rpartition(self.AT)
host, _, port = hostinfo.rpartition(self.COLON)
if port.lstrip(self.DIGITS):
return hostinfo
else:
return host
@property
def port(self):
authority = self.authority
if authority is None:
return None
_, present, port = authority.rpartition(self.COLON)
if present and not port.lstrip(self.DIGITS):
return port
else:
return None
def geturi(self):
"""Return the re-combined version of the original URI reference as a
string.
"""
scheme, authority, path, query, fragment = self
# RFC 3986 5.3. Component Recomposition
result = []
if scheme is not None:
result.extend([scheme, self.COLON])
if authority is not None:
result.extend([self.SLASH, self.SLASH, authority])
result.append(path)
if query is not None:
result.extend([self.QUEST, query])
if fragment is not None:
result.extend([self.HASH, fragment])
return self.EMPTY.join(result)
def getauthority(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded userinfo, host and port subcomponents of the URI
authority as a three-item tuple.
"""
# TBD: (userinfo, host, port) kwargs, default string?
if default is None:
default = (None, None, None)
elif not isinstance(default, collections.Iterable):
raise TypeError('Invalid default type')
elif len(default) != 3:
raise ValueError('Invalid default length')
# TODO: this could be much more efficient by using a dedicated regex
return (
self.getuserinfo(default[0], encoding, errors),
self.gethost(default[1], errors),
self.getport(default[2])
)
def getuserinfo(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded userinfo subcomponent of the URI authority, or
`default` if the original URI reference did not contain a
userinfo field.
"""
userinfo = self.userinfo
if userinfo is None:
return default
else:
return uridecode(userinfo, encoding, errors)
def gethost(self, default=None, errors='strict'):
"""Return the decoded host subcomponent of the URI authority as a
string or an :mod:`ipaddress` address object, or `default` if
the original URI reference did not contain a host.
"""
host = self.host
if host is None or (not host and default is not None):
return default
elif host.startswith(self.LBRACKET) and host.endswith(self.RBRACKET):
return _ip_literal(host[1:-1])
elif host.startswith(self.LBRACKET) or host.endswith(self.RBRACKET):
raise ValueError('Invalid host %r' % host)
# TODO: faster check for IPv4 address?
return _ipv4_address(host) or uridecode(host, 'utf-8', errors).lower()
def getport(self, default=None):
"""Return the port subcomponent of the URI authority as an
:class:`int`, or `default` if the original URI reference did
not contain a port or if the port was empty.
"""
port = self.port
if port:
return int(port)
else:
return default
def getpath(self, encoding='utf-8', errors='strict'):
"""Return the normalized decoded URI path."""
path = self.__remove_dot_segments(self.path)
return uridecode(path, encoding, errors)
def getquery(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded query string, or `default` if the original URI
reference did not contain a query component.
"""
query = self.query
if query is None:
return default
else:
return uridecode(query, encoding, errors)
def getquerydict(self, sep='&', encoding='utf-8', errors='strict'):
"""Split the query component into individual `name=value` pairs
separated by `sep` and return a dictionary of query variables.
The dictionary keys are the unique query variable names and
the values are lists of values for each name.
"""
dict = collections.defaultdict(list)
for name, value in self.getquerylist(sep, encoding, errors):
dict[name].append(value)
return dict
def getquerylist(self, sep='&', encoding='utf-8', errors='strict'):
"""Split the query component into individual `name=value` pairs
separated by `sep`, and return a list of `(name, value)`
tuples.
"""
if not self.query:
return []
elif isinstance(sep, type(self.query)):
qsl = self.query.split(sep)
elif isinstance(sep, bytes):
qsl = self.query.split(sep.decode('ascii'))
else:
qsl = self.query.split(sep.encode('ascii'))
items = []
for parts in [qs.partition(self.EQ) for qs in qsl if qs]:
name = uridecode(parts[0], encoding, errors)
if parts[1]:
value = uridecode(parts[2], encoding, errors)
else:
value = None
items.append((name, value))
return items
def getfragment(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded fragment identifier, or `default` if the
original URI reference did not contain a fragment component.
"""
fragment = self.fragment
if fragment is None:
return default
else:
return uridecode(fragment, encoding, errors)
def isuri(self):
"""Return :const:`True` if this is a URI."""
return self.scheme is not None
def isabsuri(self):
"""Return :const:`True` if this is an absolute URI."""
return self.scheme is not None and self.fragment is None
def isnetpath(self):
"""Return :const:`True` if this is a network-path reference."""
return self.scheme is None and self.authority is not None
def isabspath(self):
"""Return :const:`True` if this is an absolute-path reference."""
return (self.scheme is None and self.authority is None and
self.path.startswith(self.SLASH))
def isrelpath(self):
"""Return :const:`True` if this is a relative-path reference."""
return (self.scheme is None and self.authority is None and
not self.path.startswith(self.SLASH))
def issamedoc(self):
"""Return :const:`True` if this is a same-document reference."""
return (self.scheme is None and self.authority is None and
not self.path and self.query is None)
def transform(self, ref, strict=False):
"""Transform a URI reference relative to `self` into a
:class:`SplitResult` representing its target URI.
"""
scheme, authority, path, query, fragment = self.RE.match(ref).groups()
# RFC 3986 5.2.2. Transform References
if scheme is not None and (strict or scheme != self.scheme):
path = self.__remove_dot_segments(path)
elif authority is not None:
scheme = self.scheme
path = self.__remove_dot_segments(path)
elif not path:
scheme = self.scheme
authority = self.authority
path = self.path
query = self.query if query is None else query
elif path.startswith(self.SLASH):
scheme = self.scheme
authority = self.authority
path = self.__remove_dot_segments(path)
else:
scheme = self.scheme
authority = self.authority
path = self.__remove_dot_segments(self.__merge(path))
return type(self)(scheme, authority, path, query, fragment)
def __merge(self, path):
# RFC 3986 5.2.3. Merge Paths
if self.authority is not None and not self.path:
return self.SLASH + path
else:
parts = self.path.rpartition(self.SLASH)
return parts[1].join((parts[0], path))
@classmethod
def __remove_dot_segments(cls, path):
# RFC 3986 5.2.4. Remove Dot Segments
pseg = []
for s in path.split(cls.SLASH):
if s == cls.DOT:
continue
elif s != cls.DOTDOT:
pseg.append(s)
elif len(pseg) == 1 and not pseg[0]:
continue
elif pseg and pseg[-1] != cls.DOTDOT:
pseg.pop()
else:
pseg.append(s)
# adjust for trailing '/.' or '/..'
if path.rpartition(cls.SLASH)[2] in (cls.DOT, cls.DOTDOT):
pseg.append(cls.EMPTY)
if path and len(pseg) == 1 and pseg[0] == cls.EMPTY:
pseg.insert(0, cls.DOT)
return cls.SLASH.join(pseg)
|
tkem/uritools | uritools/split.py | SplitResult.getauthority | python | def getauthority(self, default=None, encoding='utf-8', errors='strict'):
# TBD: (userinfo, host, port) kwargs, default string?
if default is None:
default = (None, None, None)
elif not isinstance(default, collections.Iterable):
raise TypeError('Invalid default type')
elif len(default) != 3:
raise ValueError('Invalid default length')
# TODO: this could be much more efficient by using a dedicated regex
return (
self.getuserinfo(default[0], encoding, errors),
self.gethost(default[1], errors),
self.getport(default[2])
) | Return the decoded userinfo, host and port subcomponents of the URI
authority as a three-item tuple. | train | https://github.com/tkem/uritools/blob/e77ba4acd937b68da9850138563debd4c925ef9f/uritools/split.py#L114-L131 | null | class SplitResult(collections.namedtuple('SplitResult', _URI_COMPONENTS)):
"""Base class to hold :func:`urisplit` results."""
__slots__ = () # prevent creation of instance dictionary
@property
def userinfo(self):
authority = self.authority
if authority is None:
return None
userinfo, present, _ = authority.rpartition(self.AT)
if present:
return userinfo
else:
return None
@property
def host(self):
authority = self.authority
if authority is None:
return None
_, _, hostinfo = authority.rpartition(self.AT)
host, _, port = hostinfo.rpartition(self.COLON)
if port.lstrip(self.DIGITS):
return hostinfo
else:
return host
@property
def port(self):
authority = self.authority
if authority is None:
return None
_, present, port = authority.rpartition(self.COLON)
if present and not port.lstrip(self.DIGITS):
return port
else:
return None
def geturi(self):
"""Return the re-combined version of the original URI reference as a
string.
"""
scheme, authority, path, query, fragment = self
# RFC 3986 5.3. Component Recomposition
result = []
if scheme is not None:
result.extend([scheme, self.COLON])
if authority is not None:
result.extend([self.SLASH, self.SLASH, authority])
result.append(path)
if query is not None:
result.extend([self.QUEST, query])
if fragment is not None:
result.extend([self.HASH, fragment])
return self.EMPTY.join(result)
def getscheme(self, default=None):
"""Return the URI scheme in canonical (lowercase) form, or `default`
if the original URI reference did not contain a scheme component.
"""
scheme = self.scheme
if scheme is None:
return default
elif isinstance(scheme, bytes):
return scheme.decode('ascii').lower()
else:
return scheme.lower()
def getuserinfo(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded userinfo subcomponent of the URI authority, or
`default` if the original URI reference did not contain a
userinfo field.
"""
userinfo = self.userinfo
if userinfo is None:
return default
else:
return uridecode(userinfo, encoding, errors)
def gethost(self, default=None, errors='strict'):
"""Return the decoded host subcomponent of the URI authority as a
string or an :mod:`ipaddress` address object, or `default` if
the original URI reference did not contain a host.
"""
host = self.host
if host is None or (not host and default is not None):
return default
elif host.startswith(self.LBRACKET) and host.endswith(self.RBRACKET):
return _ip_literal(host[1:-1])
elif host.startswith(self.LBRACKET) or host.endswith(self.RBRACKET):
raise ValueError('Invalid host %r' % host)
# TODO: faster check for IPv4 address?
return _ipv4_address(host) or uridecode(host, 'utf-8', errors).lower()
def getport(self, default=None):
"""Return the port subcomponent of the URI authority as an
:class:`int`, or `default` if the original URI reference did
not contain a port or if the port was empty.
"""
port = self.port
if port:
return int(port)
else:
return default
def getpath(self, encoding='utf-8', errors='strict'):
"""Return the normalized decoded URI path."""
path = self.__remove_dot_segments(self.path)
return uridecode(path, encoding, errors)
def getquery(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded query string, or `default` if the original URI
reference did not contain a query component.
"""
query = self.query
if query is None:
return default
else:
return uridecode(query, encoding, errors)
def getquerydict(self, sep='&', encoding='utf-8', errors='strict'):
"""Split the query component into individual `name=value` pairs
separated by `sep` and return a dictionary of query variables.
The dictionary keys are the unique query variable names and
the values are lists of values for each name.
"""
dict = collections.defaultdict(list)
for name, value in self.getquerylist(sep, encoding, errors):
dict[name].append(value)
return dict
def getquerylist(self, sep='&', encoding='utf-8', errors='strict'):
"""Split the query component into individual `name=value` pairs
separated by `sep`, and return a list of `(name, value)`
tuples.
"""
if not self.query:
return []
elif isinstance(sep, type(self.query)):
qsl = self.query.split(sep)
elif isinstance(sep, bytes):
qsl = self.query.split(sep.decode('ascii'))
else:
qsl = self.query.split(sep.encode('ascii'))
items = []
for parts in [qs.partition(self.EQ) for qs in qsl if qs]:
name = uridecode(parts[0], encoding, errors)
if parts[1]:
value = uridecode(parts[2], encoding, errors)
else:
value = None
items.append((name, value))
return items
def getfragment(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded fragment identifier, or `default` if the
original URI reference did not contain a fragment component.
"""
fragment = self.fragment
if fragment is None:
return default
else:
return uridecode(fragment, encoding, errors)
def isuri(self):
"""Return :const:`True` if this is a URI."""
return self.scheme is not None
def isabsuri(self):
"""Return :const:`True` if this is an absolute URI."""
return self.scheme is not None and self.fragment is None
def isnetpath(self):
"""Return :const:`True` if this is a network-path reference."""
return self.scheme is None and self.authority is not None
def isabspath(self):
"""Return :const:`True` if this is an absolute-path reference."""
return (self.scheme is None and self.authority is None and
self.path.startswith(self.SLASH))
def isrelpath(self):
"""Return :const:`True` if this is a relative-path reference."""
return (self.scheme is None and self.authority is None and
not self.path.startswith(self.SLASH))
def issamedoc(self):
"""Return :const:`True` if this is a same-document reference."""
return (self.scheme is None and self.authority is None and
not self.path and self.query is None)
def transform(self, ref, strict=False):
"""Transform a URI reference relative to `self` into a
:class:`SplitResult` representing its target URI.
"""
scheme, authority, path, query, fragment = self.RE.match(ref).groups()
# RFC 3986 5.2.2. Transform References
if scheme is not None and (strict or scheme != self.scheme):
path = self.__remove_dot_segments(path)
elif authority is not None:
scheme = self.scheme
path = self.__remove_dot_segments(path)
elif not path:
scheme = self.scheme
authority = self.authority
path = self.path
query = self.query if query is None else query
elif path.startswith(self.SLASH):
scheme = self.scheme
authority = self.authority
path = self.__remove_dot_segments(path)
else:
scheme = self.scheme
authority = self.authority
path = self.__remove_dot_segments(self.__merge(path))
return type(self)(scheme, authority, path, query, fragment)
def __merge(self, path):
# RFC 3986 5.2.3. Merge Paths
if self.authority is not None and not self.path:
return self.SLASH + path
else:
parts = self.path.rpartition(self.SLASH)
return parts[1].join((parts[0], path))
@classmethod
def __remove_dot_segments(cls, path):
# RFC 3986 5.2.4. Remove Dot Segments
pseg = []
for s in path.split(cls.SLASH):
if s == cls.DOT:
continue
elif s != cls.DOTDOT:
pseg.append(s)
elif len(pseg) == 1 and not pseg[0]:
continue
elif pseg and pseg[-1] != cls.DOTDOT:
pseg.pop()
else:
pseg.append(s)
# adjust for trailing '/.' or '/..'
if path.rpartition(cls.SLASH)[2] in (cls.DOT, cls.DOTDOT):
pseg.append(cls.EMPTY)
if path and len(pseg) == 1 and pseg[0] == cls.EMPTY:
pseg.insert(0, cls.DOT)
return cls.SLASH.join(pseg)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.