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 |
|---|---|---|---|---|---|---|---|---|---|
erikvw/django-collect-offline | django_collect_offline/offline_model.py | OfflineModel.primary_key_field | python | def primary_key_field(self):
return [field for field in self.instance._meta.fields if field.primary_key][0] | Return the primary key field.
Is `id` in most cases. Is `history_id` for Historical models. | train | https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/offline_model.py#L103-L108 | null | class OfflineModel:
"""A wrapper for offline model instances to add methods called in
signals for synchronization.
"""
def __init__(self, instance):
try:
self.is_serialized = settings.ALLOW_MODEL_SERIALIZATION
except AttributeError:
self.is_serialized = True
... |
erikvw/django-collect-offline | django_collect_offline/offline_model.py | OfflineModel.to_outgoing_transaction | python | def to_outgoing_transaction(self, using, created=None, deleted=None):
OutgoingTransaction = django_apps.get_model(
"django_collect_offline", "OutgoingTransaction"
)
created = True if created is None else created
action = INSERT if created else UPDATE
timestamp_datetim... | Serialize the model instance to an AES encrypted json object
and saves the json object to the OutgoingTransaction model. | train | https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/offline_model.py#L110-L139 | [
"def encrypted_json(self):\n \"\"\"Returns an encrypted json serialized from self.\n \"\"\"\n json = serialize(objects=[self.instance])\n encrypted_json = Cryptor().aes_encrypt(json, LOCAL_MODE)\n return encrypted_json\n"
] | class OfflineModel:
"""A wrapper for offline model instances to add methods called in
signals for synchronization.
"""
def __init__(self, instance):
try:
self.is_serialized = settings.ALLOW_MODEL_SERIALIZATION
except AttributeError:
self.is_serialized = True
... |
erikvw/django-collect-offline | django_collect_offline/offline_model.py | OfflineModel.encrypted_json | python | def encrypted_json(self):
json = serialize(objects=[self.instance])
encrypted_json = Cryptor().aes_encrypt(json, LOCAL_MODE)
return encrypted_json | Returns an encrypted json serialized from self. | train | https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/offline_model.py#L141-L146 | [
"def serialize(objects=None):\n \"\"\"A simple wrapper of Django's serializer with defaults\n for JSON and natural keys.\n\n Note: use_natural_primary_keys is False as once\n a pk is set, it should not be changed throughout the\n distributed data.\n \"\"\"\n\n return serializers.serialize(\n ... | class OfflineModel:
"""A wrapper for offline model instances to add methods called in
signals for synchronization.
"""
def __init__(self, instance):
try:
self.is_serialized = settings.ALLOW_MODEL_SERIALIZATION
except AttributeError:
self.is_serialized = True
... |
erikvw/django-collect-offline | django_collect_offline/transaction/serialize.py | serialize | python | def serialize(objects=None):
return serializers.serialize(
"json",
objects,
ensure_ascii=True,
use_natural_foreign_keys=True,
use_natural_primary_keys=False,
) | A simple wrapper of Django's serializer with defaults
for JSON and natural keys.
Note: use_natural_primary_keys is False as once
a pk is set, it should not be changed throughout the
distributed data. | train | https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/transaction/serialize.py#L4-L19 | null | from django.core import serializers
|
erikvw/django-collect-offline | django_collect_offline/transaction/deserialize.py | deserialize | python | def deserialize(json_text=None):
return serializers.deserialize(
"json",
json_text,
ensure_ascii=True,
use_natural_foreign_keys=True,
use_natural_primary_keys=False,
) | Returns a generator of deserialized objects.
Wraps django deserialize with defaults for JSON
and natural keys.
See https://docs.djangoproject.com/en/2.1/topics/serialization/ | train | https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/transaction/deserialize.py#L4-L19 | null | from django.core import serializers
|
erikvw/django-collect-offline | django_collect_offline/signals.py | create_auth_token | python | def create_auth_token(sender, instance, raw, created, **kwargs):
if not raw:
if created:
sender.objects.create(user=instance) | Create token when a user is created (from rest_framework). | train | https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/signals.py#L10-L15 | null | from django.db.models.signals import post_save, m2m_changed, post_delete
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from simple_history.signals import post_create_historical_record
from .site_offline_models import site_offline_models, ModelNotRegistered
@receiver(post_save... |
erikvw/django-collect-offline | django_collect_offline/signals.py | serialize_m2m_on_save | python | def serialize_m2m_on_save(sender, action, instance, using, **kwargs):
if action == "post_add":
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, ... | Part of the serialize transaction process that ensures m2m are
serialized correctly.
Skip those not registered. | train | https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/signals.py#L19-L31 | [
"def get_wrapped_instance(self, instance=None):\n \"\"\"Returns a wrapped model instance.\n \"\"\"\n if instance._meta.label_lower not in self.registry:\n raise ModelNotRegistered(f\"{repr(instance)} is not registered with {self}.\")\n wrapper_cls = self.registry.get(instance._meta.label_lower) o... | from django.db.models.signals import post_save, m2m_changed, post_delete
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from simple_history.signals import post_create_historical_record
from .site_offline_models import site_offline_models, ModelNotRegistered
@receiver(post_save... |
erikvw/django-collect-offline | django_collect_offline/signals.py | serialize_on_save | python | def serialize_on_save(sender, instance, raw, created, using, **kwargs):
if not raw:
if "historical" not in instance._meta.label_lower:
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
... | Serialize the model instance as an OutgoingTransaction.
Skip those not registered. | train | https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/signals.py#L35-L47 | [
"def get_wrapped_instance(self, instance=None):\n \"\"\"Returns a wrapped model instance.\n \"\"\"\n if instance._meta.label_lower not in self.registry:\n raise ModelNotRegistered(f\"{repr(instance)} is not registered with {self}.\")\n wrapper_cls = self.registry.get(instance._meta.label_lower) o... | from django.db.models.signals import post_save, m2m_changed, post_delete
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from simple_history.signals import post_create_historical_record
from .site_offline_models import site_offline_models, ModelNotRegistered
@receiver(post_save... |
erikvw/django-collect-offline | django_collect_offline/signals.py | serialize_history_on_post_create | python | def serialize_history_on_post_create(history_instance, using, **kwargs):
try:
wrapped_instance = site_offline_models.get_wrapped_instance(history_instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=True) | Serialize the history instance as an OutgoingTransaction.
Skip those not registered. | train | https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/signals.py#L55-L65 | [
"def get_wrapped_instance(self, instance=None):\n \"\"\"Returns a wrapped model instance.\n \"\"\"\n if instance._meta.label_lower not in self.registry:\n raise ModelNotRegistered(f\"{repr(instance)} is not registered with {self}.\")\n wrapper_cls = self.registry.get(instance._meta.label_lower) o... | from django.db.models.signals import post_save, m2m_changed, post_delete
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from simple_history.signals import post_create_historical_record
from .site_offline_models import site_offline_models, ModelNotRegistered
@receiver(post_save... |
erikvw/django-collect-offline | django_collect_offline/signals.py | serialize_on_post_delete | python | def serialize_on_post_delete(sender, instance, using, **kwargs):
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=False, deleted=True) | Creates a serialized OutgoingTransaction when
a model instance is deleted.
Skip those not registered. | train | https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/signals.py#L69-L80 | [
"def get_wrapped_instance(self, instance=None):\n \"\"\"Returns a wrapped model instance.\n \"\"\"\n if instance._meta.label_lower not in self.registry:\n raise ModelNotRegistered(f\"{repr(instance)} is not registered with {self}.\")\n wrapper_cls = self.registry.get(instance._meta.label_lower) o... | from django.db.models.signals import post_save, m2m_changed, post_delete
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from simple_history.signals import post_create_historical_record
from .site_offline_models import site_offline_models, ModelNotRegistered
@receiver(post_save... |
mathiasertl/xmpp-backends | xmpp_backends/ejabberd_xmlrpc.py | EjabberdXMLRPCBackend.rpc | python | def rpc(self, cmd, **kwargs):
func = getattr(self.client, cmd)
try:
if self.credentials is None:
return func(kwargs)
else:
return func(self.credentials, kwargs)
except socket.error as e:
raise BackendConnectionError(e)
... | Generic helper function to call an RPC method. | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/ejabberd_xmlrpc.py#L107-L120 | null | class EjabberdXMLRPCBackend(EjabberdBackendBase):
"""This backend uses the Ejabberd XMLRPC interface.
In addition to an XMLRPC endpoint, this backend requires ``mod_admin_extra`` to be installed.
.. WARNING::
The backend does not handle UTF-8 characters correctly if you use ejabberd <= 14.07 and
... |
mathiasertl/xmpp-backends | xmpp_backends/ejabberd_xmlrpc.py | EjabberdXMLRPCBackend.message_user | python | def message_user(self, username, domain, subject, message):
kwargs = {
'body': message,
'from': domain,
'to': '%s@%s' % (username, domain),
}
if self.api_version <= (14, 7):
# TODO: it's unclear when send_message was introduced
comman... | Currently use send_message_chat and discard subject, because headline messages are not
stored by mod_offline. | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/ejabberd_xmlrpc.py#L263-L285 | [
"def rpc(self, cmd, **kwargs):\n \"\"\"Generic helper function to call an RPC method.\"\"\"\n\n func = getattr(self.client, cmd)\n try:\n if self.credentials is None:\n return func(kwargs)\n else:\n return func(self.credentials, kwargs)\n except socket.error as e:\n ... | class EjabberdXMLRPCBackend(EjabberdBackendBase):
"""This backend uses the Ejabberd XMLRPC interface.
In addition to an XMLRPC endpoint, this backend requires ``mod_admin_extra`` to be installed.
.. WARNING::
The backend does not handle UTF-8 characters correctly if you use ejabberd <= 14.07 and
... |
mathiasertl/xmpp-backends | xmpp_backends/base.py | XmppBackendBase.module | python | def module(self):
if self._module is None:
if self.library is None:
raise ValueError(
"Backend '%s' doesn't specify a library attribute" % self.__class__)
try:
if '.' in self.library:
mod_path, cls_name = self.libr... | The module specified by the ``library`` attribute. | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L174-L192 | null | class XmppBackendBase(object):
"""Base class for all XMPP backends."""
library = None
"""Import-party of any third-party library you need.
Set this attribute to an import path and you will be able to access the module as ``self.module``. This
way you don't have to do a module-level import, which w... |
mathiasertl/xmpp-backends | xmpp_backends/base.py | XmppBackendBase.datetime_to_timestamp | python | def datetime_to_timestamp(self, dt):
if dt is None:
return int(time.time())
if six.PY3:
if not dt.tzinfo:
dt = pytz.utc.localize(dt)
return int(dt.timestamp())
else:
if dt.tzinfo:
dt = dt.replace(tzinfo=None) - dt.u... | Helper function to convert a datetime object to a timestamp.
If datetime instance ``dt`` is naive, it is assumed that it is in UTC.
In Python 3, this just calls ``datetime.timestamp()``, in Python 2, it substracts any timezone offset
and returns the difference since 1970-01-01 00:00:00.
... | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L194-L224 | null | class XmppBackendBase(object):
"""Base class for all XMPP backends."""
library = None
"""Import-party of any third-party library you need.
Set this attribute to an import path and you will be able to access the module as ``self.module``. This
way you don't have to do a module-level import, which w... |
mathiasertl/xmpp-backends | xmpp_backends/base.py | XmppBackendBase.get_random_password | python | def get_random_password(self, length=32, chars=None):
if chars is None:
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for x in range(length)) | Helper function that gets a random password.
:param length: The length of the random password.
:type length: int
:param chars: A string with characters to choose from. Defaults to all ASCII letters and digits.
:type chars: str | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L226-L236 | null | class XmppBackendBase(object):
"""Base class for all XMPP backends."""
library = None
"""Import-party of any third-party library you need.
Set this attribute to an import path and you will be able to access the module as ``self.module``. This
way you don't have to do a module-level import, which w... |
mathiasertl/xmpp-backends | xmpp_backends/base.py | XmppBackendBase.api_version | python | def api_version(self):
now = datetime.utcnow()
if self.version_cache_timestamp and self.version_cache_timestamp + self.version_cache_timeout > now:
return self.version_cache_value # we have a cached value
self.version_cache_value = self.get_api_version()
if self.minimum_... | Cached version of :py:func:`~xmpp_backends.base.XmppBackendBase.get_api_version`. | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L239-L254 | [
"def get_api_version(self):\n \"\"\"Get the API version used by this backend.\n\n Note that this function is usually not invoked directly but through\n :py:attr:`~xmpp_backends.base.XmppBackendBase.api_version`.\n\n The value returned by this function is used by various backends to determine how to call... | class XmppBackendBase(object):
"""Base class for all XMPP backends."""
library = None
"""Import-party of any third-party library you need.
Set this attribute to an import path and you will be able to access the module as ``self.module``. This
way you don't have to do a module-level import, which w... |
mathiasertl/xmpp-backends | xmpp_backends/base.py | XmppBackendBase.create_reservation | python | def create_reservation(self, username, domain, email=None):
password = self.get_random_password()
self.create(username=username, domain=domain, password=password, email=email) | Reserve a new account.
This method is called when a user account should be reserved, meaning that the account can no longer
be registered by anybody else but the user cannot yet log in either. This is useful if e.g. an email
confirmation is still pending.
The default implementation cal... | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L325-L343 | [
"def get_random_password(self, length=32, chars=None):\n \"\"\"Helper function that gets a random password.\n\n :param length: The length of the random password.\n :type length: int\n :param chars: A string with characters to choose from. Defaults to all ASCII letters and digits.\n :type chars: s... | class XmppBackendBase(object):
"""Base class for all XMPP backends."""
library = None
"""Import-party of any third-party library you need.
Set this attribute to an import path and you will be able to access the module as ``self.module``. This
way you don't have to do a module-level import, which w... |
mathiasertl/xmpp-backends | xmpp_backends/base.py | XmppBackendBase.confirm_reservation | python | def confirm_reservation(self, username, domain, password, email=None):
self.set_password(username=username, domain=domain, password=password)
if email is not None:
self.set_email(username=username, domain=domain, email=email) | Confirm a reservation for a username.
The default implementation just calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` and
optionally :py:func:`~xmpp_backends.base.XmppBackendBase.set_email`. | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L345-L353 | [
"def set_password(self, username, domain, password):\n \"\"\"Set the password of a user.\n\n :param username: The username of the user.\n :type username: str\n :param domain: The domain of the user.\n :type domain: str\n :param password: The password to set.\n :type password: str\n \"... | class XmppBackendBase(object):
"""Base class for all XMPP backends."""
library = None
"""Import-party of any third-party library you need.
Set this attribute to an import path and you will be able to access the module as ``self.module``. This
way you don't have to do a module-level import, which w... |
mathiasertl/xmpp-backends | xmpp_backends/base.py | XmppBackendBase.block_user | python | def block_user(self, username, domain):
self.set_password(username, domain, self.get_random_password()) | Block the specified user.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L416-L427 | [
"def get_random_password(self, length=32, chars=None):\n \"\"\"Helper function that gets a random password.\n\n :param length: The length of the random password.\n :type length: int\n :param chars: A string with characters to choose from. Defaults to all ASCII letters and digits.\n :type chars: s... | class XmppBackendBase(object):
"""Base class for all XMPP backends."""
library = None
"""Import-party of any third-party library you need.
Set this attribute to an import path and you will be able to access the module as ``self.module``. This
way you don't have to do a module-level import, which w... |
mathiasertl/xmpp-backends | xmpp_backends/base.py | EjabberdBackendBase.parse_connection_string | python | def parse_connection_string(self, connection):
# TODO: Websockets, HTTP Polling
if connection == 'c2s_tls':
return CONNECTION_XMPP, True, False
elif connection == 'c2s_compressed_tls':
return CONNECTION_XMPP, True, True
elif connection == 'http_bind':
... | Parse string as returned by the ``connected_users_info`` or ``user_sessions_info`` API calls.
>>> EjabberdBackendBase().parse_connection_string('c2s_tls')
(0, True, False)
>>> EjabberdBackendBase().parse_connection_string('c2s_compressed_tls')
(0, True, True)
>>> EjabberdBackend... | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L564-L590 | null | class EjabberdBackendBase(XmppBackendBase):
"""Base class for ejabberd related backends.
This class overwrites a few methods common to all ejabberd backends.
"""
minimum_version = (14, 7)
def parse_version_string(self, version):
return tuple(int(t) for t in version.split('.'))
def pa... |
mathiasertl/xmpp-backends | xmpp_backends/base.py | EjabberdBackendBase.parse_ip_address | python | def parse_ip_address(self, ip_address):
if ip_address.startswith('::FFFF:'):
ip_address = ip_address[7:]
if six.PY2 and isinstance(ip_address, str):
# ipaddress constructor does not eat str in py2 :-/
ip_address = ip_address.decode('utf-8')
return ipaddress.i... | Parse an address as returned by the ``connected_users_info`` or ``user_sessions_info`` API calls.
Example::
>>> EjabberdBackendBase().parse_ip_address('192.168.0.1') # doctest: +FORCE_TEXT
IPv4Address('192.168.0.1')
>>> EjabberdBackendBase().parse_ip_address('::FFFF:192.16... | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L592-L615 | null | class EjabberdBackendBase(XmppBackendBase):
"""Base class for ejabberd related backends.
This class overwrites a few methods common to all ejabberd backends.
"""
minimum_version = (14, 7)
def parse_version_string(self, version):
return tuple(int(t) for t in version.split('.'))
def pa... |
mathiasertl/xmpp-backends | xmpp_backends/ejabberdctl.py | EjabberdctlBackend.message_user | python | def message_user(self, username, domain, subject, message):
jid = '%s@%s' % (username, domain)
if self.api_version <= (14, 7):
# TODO: it's unclear when send_message was introduced
command = 'send_message_chat'
args = domain, '%s@%s' % (username, domain), message
... | Currently use send_message_chat and discard subject, because headline messages are not stored by
mod_offline. | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/ejabberdctl.py#L236-L250 | [
"def ctl(self, *args):\n cmd = self.ejabberdctl + list(args)\n\n p = Popen(cmd, stdout=PIPE, stderr=PIPE)\n stdout, stderr = p.communicate()\n return p.returncode, stdout, stderr\n"
] | class EjabberdctlBackend(EjabberdBackendBase):
"""This backend uses the ejabberdctl command line utility.
This backend requires ejabberds ``mod_admin_extra`` to be installed.
.. WARNING::
This backend is not very secure because ejabberdctl gets any passwords in clear text via the
commandlin... |
mathiasertl/xmpp-backends | xmpp_backends/django/models.py | XmppBackendUser.set_password | python | def set_password(self, raw_password):
if raw_password is None:
self.set_unusable_password()
else:
xmpp_backend.set_password(self.node, self.domain, raw_password) | Calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` for the user.
If password is ``None``, calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_unusable_password`. | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/django/models.py#L39-L47 | null | class XmppBackendUser(AbstractBaseUser):
"""An abstract base model using xmpp as backend for various functions.
The model assumes that the username as returned by :py:func:`get_username` is the full JID of the user.
"""
class Meta:
verbose_name = _('user')
verbose_name_plural = _('user... |
mathiasertl/xmpp-backends | xmpp_backends/django/models.py | XmppBackendUser.check_password | python | def check_password(self, raw_password):
return xmpp_backend.check_password(self.node, self.domain, raw_password) | Calls :py:func:`~xmpp_backends.base.XmppBackendBase.check_password` for the user. | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/django/models.py#L49-L51 | null | class XmppBackendUser(AbstractBaseUser):
"""An abstract base model using xmpp as backend for various functions.
The model assumes that the username as returned by :py:func:`get_username` is the full JID of the user.
"""
class Meta:
verbose_name = _('user')
verbose_name_plural = _('user... |
mathiasertl/xmpp-backends | xmpp_backends/dummy.py | DummyBackend.start_user_session | python | def start_user_session(self, username, domain, resource, **kwargs):
kwargs.setdefault('uptime', pytz.utc.localize(datetime.utcnow()))
kwargs.setdefault('priority', 0)
kwargs.setdefault('status', 'online')
kwargs.setdefault('status_text', '')
kwargs.setdefault('connection_type', ... | Method to add a user session for debugging.
Accepted parameters are the same as to the constructor of :py:class:`~xmpp_backends.base.UserSession`. | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/dummy.py#L66-L103 | null | class DummyBackend(XmppBackendBase):
"""A dummy backend for development using Djangos caching framework.
By default, Djangos caching framework uses in-memory data structures, so every registration will be
removed if you restart the development server. You can configure a different cache (e.g. memcached), ... |
mathiasertl/xmpp-backends | xmpp_backends/xmlrpclib.py | dumps | python | def dumps(params, methodname=None, methodresponse=None, encoding=None,
allow_none=0, utf8_encoding='standard'):
assert isinstance(params, TupleType) or isinstance(params, Fault),\
"argument must be tuple or Fault instance"
if isinstance(params, Fault):
methodresponse = 1
elif ... | data [,options] -> marshalled data
Convert an argument tuple or a Fault instance to an XML-RPC
request (or response, if the methodresponse option is used).
In addition to the data object, the following options can be given
as keyword arguments:
methodname: the method name for a methodCall pac... | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/xmlrpclib.py#L1139-L1207 | null | # -*- coding: utf-8 -*-
#
# XML-RPC CLIENT LIBRARY
# $Id$
#
# This is a copy of the xmlrpclib library shipping with Python 2.7.
# It is modified to encode UTF-8 characters in several different ways.
#
# The problem is that this library does not encode UTF-8 correctly and PHP's
# library doesn't encode them correctly ei... |
mathiasertl/xmpp-backends | xmpp_backends/xmlrpclib.py | gzip_encode | python | def gzip_encode(data):
if not gzip:
raise NotImplementedError
f = StringIO.StringIO()
gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1)
gzf.write(data)
gzf.close()
encoded = f.getvalue()
f.close()
return encoded | data -> gzip encoded data
Encode data using the gzip content encoding as described in RFC 1952 | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/xmlrpclib.py#L1240-L1253 | null | # -*- coding: utf-8 -*-
#
# XML-RPC CLIENT LIBRARY
# $Id$
#
# This is a copy of the xmlrpclib library shipping with Python 2.7.
# It is modified to encode UTF-8 characters in several different ways.
#
# The problem is that this library does not encode UTF-8 correctly and PHP's
# library doesn't encode them correctly ei... |
mathiasertl/xmpp-backends | xmpp_backends/xmlrpclib.py | gzip_decode | python | def gzip_decode(data, max_decode=20971520):
if not gzip:
raise NotImplementedError
f = StringIO.StringIO(data)
gzf = gzip.GzipFile(mode="rb", fileobj=f)
try:
if max_decode < 0: # no limit
decoded = gzf.read()
else:
decoded = gzf.read(max_decode + 1)
ex... | gzip encoded data -> unencoded data
Decode data using the gzip content encoding as described in RFC 1952 | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/xmlrpclib.py#L1267-L1287 | null | # -*- coding: utf-8 -*-
#
# XML-RPC CLIENT LIBRARY
# $Id$
#
# This is a copy of the xmlrpclib library shipping with Python 2.7.
# It is modified to encode UTF-8 characters in several different ways.
#
# The problem is that this library does not encode UTF-8 correctly and PHP's
# library doesn't encode them correctly ei... |
radzak/rtv-downloader | rtv/utils.py | suppress_stdout | python | def suppress_stdout():
save_stdout = sys.stdout
sys.stdout = DevNull()
yield
sys.stdout = save_stdout | Context manager that suppresses stdout.
Examples:
>>> with suppress_stdout():
... print('Test print')
>>> print('test')
test | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L25-L40 | null | import contextlib
import os
import re
import sys
import urllib.parse
import tldextract
import validators
from rtv.exceptions import WrongUrlError
class DevNull:
"""
DevNull class that has a no-op write and flush method.
"""
def write(self, *args, **kwargs):
pass
def flush(self):
... |
radzak/rtv-downloader | rtv/utils.py | get_domain_name | python | def get_domain_name(url):
if not validate_url(url):
raise WrongUrlError(f'Couldn\'t match domain name of this url: {url}')
ext = tldextract.extract(url)
return f'{ext.domain}.{ext.suffix}' | Extract a domain name from the url (without subdomain).
Args:
url (str): Url.
Returns:
str: Domain name.
Raises:
DomainNotMatchedError: If url is wrong.
Examples:
>>> get_domain_name('https://vod.tvp.pl/video/')
'tvp.pl'
>>> get_domain_name('https://v... | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L68-L95 | [
"def validate_url(url):\n \"\"\"\n Validate url using validators package.\n\n Args:\n url (str): Url.\n\n Returns:\n bool: True if valid, False otherwise.\n\n Examples:\n >>> validate_url('http://google.com')\n True\n\n >>> validate_url('http://google') # doctest: ... | import contextlib
import os
import re
import sys
import urllib.parse
import tldextract
import validators
from rtv.exceptions import WrongUrlError
class DevNull:
"""
DevNull class that has a no-op write and flush method.
"""
def write(self, *args, **kwargs):
pass
def flush(self):
... |
radzak/rtv-downloader | rtv/utils.py | clean_video_data | python | def clean_video_data(_data):
data = _data.copy()
# TODO: fix this ugliness
title = data.get('title')
if title:
data['title'] = clean_title(title)
return data | Clean video data:
-> cleans title
-> ...
Args:
_data (dict): Information about the video.
Returns:
dict: Refined video data. | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L98-L119 | [
"def clean_title(title):\n \"\"\"\n Clean title -> remove dates, remove duplicated spaces and strip title.\n\n Args:\n title (str): Title.\n\n Returns:\n str: Clean title without dates, duplicated, trailing and leading spaces.\n\n \"\"\"\n date_pattern = re.compile(r'\\W*'\n ... | import contextlib
import os
import re
import sys
import urllib.parse
import tldextract
import validators
from rtv.exceptions import WrongUrlError
class DevNull:
"""
DevNull class that has a no-op write and flush method.
"""
def write(self, *args, **kwargs):
pass
def flush(self):
... |
radzak/rtv-downloader | rtv/utils.py | clean_title | python | def clean_title(title):
date_pattern = re.compile(r'\W*'
r'\d{1,2}'
r'[/\-.]'
r'\d{1,2}'
r'[/\-.]'
r'(?=\d*)(?:.{4}|.{2})'
r'\W*')
t... | Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces. | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L122-L143 | null | import contextlib
import os
import re
import sys
import urllib.parse
import tldextract
import validators
from rtv.exceptions import WrongUrlError
class DevNull:
"""
DevNull class that has a no-op write and flush method.
"""
def write(self, *args, **kwargs):
pass
def flush(self):
... |
radzak/rtv-downloader | rtv/utils.py | get_ext | python | def get_ext(url):
parsed = urllib.parse.urlparse(url)
root, ext = os.path.splitext(parsed.path)
return ext.lstrip('.') | Extract an extension from the url.
Args:
url (str): String representation of a url.
Returns:
str: Filename extension from a url (without a dot), '' if extension is not present. | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L176-L190 | null | import contextlib
import os
import re
import sys
import urllib.parse
import tldextract
import validators
from rtv.exceptions import WrongUrlError
class DevNull:
"""
DevNull class that has a no-op write and flush method.
"""
def write(self, *args, **kwargs):
pass
def flush(self):
... |
radzak/rtv-downloader | rtv/utils.py | delete_duplicates | python | def delete_duplicates(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | Remove duplicates from an iterable, preserving the order.
Args:
seq: Iterable of various type.
Returns:
list: List of unique objects. | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L193-L206 | null | import contextlib
import os
import re
import sys
import urllib.parse
import tldextract
import validators
from rtv.exceptions import WrongUrlError
class DevNull:
"""
DevNull class that has a no-op write and flush method.
"""
def write(self, *args, **kwargs):
pass
def flush(self):
... |
radzak/rtv-downloader | rtv/extractors/vodtvp.py | VodTVP.get_show_name | python | def get_show_name(self):
div = self.soup.find('div', attrs={'data-hover': True})
data = json.loads(div['data-hover'])
show_name = data.get('title')
return show_name | Get video show name from the website. It's located in the div with 'data-hover'
attribute under the 'title' key.
Returns:
str: Video show name. | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/vodtvp.py#L43-L56 | null | class VodTVP(Extractor):
SITE_NAME = 'vod.tvp.pl'
_VALID_URL = (
r'https?://(?:www\.)?vod.tvp\.pl/'
r'.*?'
r'(?:,(?P<date>[\d\-]+))?'
r','
r'(?P<object_id>\d+)'
)
# TODO: change _VALID_URLs to just plain domain name and move date, showname, etc. regexes
# to f... |
radzak/rtv-downloader | rtv/extractors/common.py | Extractor.validate_url | python | def validate_url(cls, url: str) -> Optional[Match[str]]:
match = re.match(cls._VALID_URL, url)
return match | Check if the Extractor can handle the given url. | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/common.py#L29-L32 | null | class Extractor:
SITE_NAME: ClassVar[str]
_VALID_URL: ClassVar[str]
url: str
html: str
videos: List[Video]
response: requests.models.Response
def __init__(self, url: str) -> None:
self.url = url
self.videos = []
@classmethod
def load_html(self) -> None:
r... |
radzak/rtv-downloader | rtv/extractors/common.py | Extractor.get_info | python | def get_info(self) -> dict:
with suppress_stdout():
with youtube_dl.YoutubeDL() as ydl:
info_dict = ydl.extract_info(self.url, download=False)
return info_dict | Get information about the videos from YoutubeDL package. | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/common.py#L40-L45 | null | class Extractor:
SITE_NAME: ClassVar[str]
_VALID_URL: ClassVar[str]
url: str
html: str
videos: List[Video]
response: requests.models.Response
def __init__(self, url: str) -> None:
self.url = url
self.videos = []
@classmethod
def validate_url(cls, url: str) -> Optio... |
radzak/rtv-downloader | rtv/extractors/common.py | Extractor.update_entries | python | def update_entries(entries: Entries, data: dict) -> None:
# TODO: Is mutating the list okay, making copies is such a pain in the ass
for entry in entries:
entry.update(data) | Update each entry in the list with some data. | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/common.py#L48-L52 | null | class Extractor:
SITE_NAME: ClassVar[str]
_VALID_URL: ClassVar[str]
url: str
html: str
videos: List[Video]
response: requests.models.Response
def __init__(self, url: str) -> None:
self.url = url
self.videos = []
@classmethod
def validate_url(cls, url: str) -> Optio... |
radzak/rtv-downloader | rtv/extractors/rmf24.py | Rmf24.extract_entry | python | def extract_entry(scraped_info):
quality_mapping = { # ascending in terms of quality
'lo': 0,
'hi': 1
}
entry = scraped_info['tracks'][0]
'''
The structure of entry is as follows:
'src': {
'hi': [
{
's... | Transform scraped_info dictionary into an entry, under the assumption that there is only
one track in 'track' list, since each video/audio is instantiated individually
on the RMF website and each of them is scraped independently, so there shouldn't be cases
when there are 2 unrelated tracks in o... | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/rmf24.py#L32-L96 | [
"def get_ext(url):\n \"\"\"\n Extract an extension from the url.\n\n Args:\n url (str): String representation of a url.\n\n Returns:\n str: Filename extension from a url (without a dot), '' if extension is not present.\n\n \"\"\"\n\n parsed = urllib.parse.urlparse(url)\n root, ext... | class Rmf24(GenericTitleMixin, GenericDescriptionMixin, Extractor):
SITE_NAME = 'rmf24.pl'
_VALID_URL = r'https?://(?:www\.)?rmf24\.pl/'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.load_html()
self.soup = BeautifulSoup(self.html, 'lxml')
# TOD... |
radzak/rtv-downloader | rtv/extractors/tokfm.py | TokFm._extract_id | python | def _extract_id(self) -> str:
match = re.match(self._VALID_URL, self.url)
if match:
return match.group('video_id')
else:
raise VideoIdNotMatchedError | Get video_id needed to obtain the real_url of the video.
Raises:
VideoIdNotMatchedError: If video_id is not matched with regular expression. | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/tokfm.py#L35-L48 | null | class TokFm(GenericTitleMixin, GenericDescriptionMixin, Extractor):
SITE_NAME = 'tokfm.pl'
_VALID_URL = r'https?://(?:www\.)?audycje\.tokfm\.pl/.*/(?P<video_id>[a-z0-9-]*)'
VideoInfo = namedtuple('VideoInfo', ('date', 'showname', 'host', 'guests'))
def __init__(self, *args, **kwargs) -> None:
s... |
radzak/rtv-downloader | rtv/extractors/tokfm.py | TokFm._process_info | python | def _process_info(raw_info: VideoInfo) -> VideoInfo:
raw_date = raw_info.date
date = datetime.strptime(raw_date, '%Y-%m-%d %H:%M') # 2018-04-05 17:00
video_info = raw_info._replace(date=date)
return video_info | Process raw information about the video (parse date, etc.). | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/tokfm.py#L51-L56 | null | class TokFm(GenericTitleMixin, GenericDescriptionMixin, Extractor):
SITE_NAME = 'tokfm.pl'
_VALID_URL = r'https?://(?:www\.)?audycje\.tokfm\.pl/.*/(?P<video_id>[a-z0-9-]*)'
VideoInfo = namedtuple('VideoInfo', ('date', 'showname', 'host', 'guests'))
def __init__(self, *args, **kwargs) -> None:
s... |
radzak/rtv-downloader | rtv/downloaders/common.py | VideoDownloader.render_path | python | def render_path(self) -> str:
# TODO: Fix defaults when date is not found (empty string or None)
# https://stackoverflow.com/questions/23407295/default-kwarg-values-for-pythons-str-format-method
from string import Formatter
class UnseenFormatter(Formatter):
def get_value(se... | Render path by filling the path template with video information. | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/downloaders/common.py#L37-L66 | [
"def clean_filename(filename):\n \"\"\"\n Remove unsupported filename characters.\n On Windows file names cannot contain any of \\/:*?\"<>| characters.\n Effectively remove all characters except alphanumeric, -_#.,() and spaces.\n\n Args:\n filename (str): Name of a file.\n\n Returns:\n ... | class VideoDownloader:
def __init__(self, video, quality=None, download_dir=None, templates=None) -> None:
"""
Create a VideoDownloader for a given video.
Args:
video (Video): Video object.
quality (str): Quality of the video (best/worst). Audio quality defaults to b... |
radzak/rtv-downloader | rtv/onetab.py | get_urls_from_onetab | python | def get_urls_from_onetab(onetab):
html = requests.get(onetab).text
soup = BeautifulSoup(html, 'lxml')
divs = soup.findAll('div', {'style': 'padding-left: 24px; '
'padding-top: 8px; '
'position: relative; '
... | Get video urls from a link to the onetab shared page.
Args:
onetab (str): Link to a onetab shared page.
Returns:
list: List of links to the videos. | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/onetab.py#L5-L24 | null | import requests
from bs4 import BeautifulSoup
|
radzak/rtv-downloader | rtv/extractors/wp.py | Wp.quality_comparator | python | def quality_comparator(video_data):
def parse_resolution(res: str) -> Tuple[int, ...]:
return tuple(map(int, res.split('x')))
raw_resolution = video_data['resolution']
resolution = parse_resolution(raw_resolution)
return resolution | Custom comparator used to choose the right format based on the resolution. | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/wp.py#L56-L63 | [
"def parse_resolution(res: str) -> Tuple[int, ...]:\n return tuple(map(int, res.split('x')))\n"
] | class Wp(Extractor):
SITE_NAME = 'wp.pl'
_VALID_URL = r'https?://(?:www\.)?video\.wp\.pl/.*'
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.load_html()
self.soup = BeautifulSoup(self.html, 'lxml')
self.data = self._fetch_data()
@stat... |
radzak/rtv-downloader | rtv/options.py | parse_options | python | def parse_options():
parser = argparse.ArgumentParser(description='Video downloader by radzak.',
prog='RTVdownloader')
urls_group = parser.add_mutually_exclusive_group(required=True)
urls_group.add_argument('urls',
type=str,
... | Parse command line arguments.
Returns:
options, args | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/options.py#L24-L67 | null | import argparse
from pathlib import Path
DEFAULT_OPTIONS = {
'download_dir': Path.home() / 'Desktop' / 'RTV',
'templates': {
'ipla.tv': '{date:%d} {title}.{ext}',
'polsatnews.pl': '{date:%d} {title}.{ext}',
'polskieradio.pl': '{date:%d} {title}.{ext}',
'radiozet.pl': '{date:%d} ... |
radzak/rtv-downloader | rtv/extractors/tvpinfo.py | TvpInfo.get_article_url | python | def get_article_url(self):
html = requests.get(self.url).text
soup = BeautifulSoup(html, 'lxml')
div = soup.find('div', class_='more-back')
if div:
parsed_uri = urlparse(self.url)
domain = '{uri.scheme}://{uri.netloc}'.format(uri=parsed_uri)
suffix = ... | Get the url of the TVP Info article itself, not the url of the preview with
the 'Przejdź do artykułu' hyperlink.
Returns:
(str): Url of the article with the video. | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/tvpinfo.py#L39-L59 | null | class TvpInfo(Extractor):
SITE_NAME = 'tvp.info'
_VALID_URL = r'https?://(?:www\.)?tvp\.info/'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.url = self.get_article_url()
# some data will be scraped from the article page
self.load_html()
... |
elemoine/papyrus | papyrus/xsd.py | XSDGenerator.add_column_xsd | python | def add_column_xsd(self, tb, column, attrs):
if column.nullable:
attrs['minOccurs'] = str(0)
attrs['nillable'] = 'true'
for cls, xsd_type in six.iteritems(self.SIMPLE_XSD_TYPES):
if isinstance(column.type, cls):
attrs['type'] = xsd_type
... | Add the XSD for a column to tb (a TreeBuilder) | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/xsd.py#L73-L144 | [
"def element_callback(self, tb, column):\n pass\n"
] | class XSDGenerator(object):
""" XSD Generator """
SIMPLE_XSD_TYPES = {
# SQLAlchemy types
sqlalchemy.BigInteger: 'xsd:integer',
sqlalchemy.Boolean: 'xsd:boolean',
sqlalchemy.Date: 'xsd:date',
sqlalchemy.DateTime: 'xsd:dateTime',
sqlalchemy.Float: 'xsd:double',
... |
elemoine/papyrus | papyrus/xsd.py | XSDGenerator.add_column_property_xsd | python | def add_column_property_xsd(self, tb, column_property):
if len(column_property.columns) != 1:
raise NotImplementedError # pragma: no cover
column = column_property.columns[0]
if column.primary_key and not self.include_primary_keys:
return
if column.foreign_keys a... | Add the XSD for a column property to the ``TreeBuilder``. | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/xsd.py#L146-L160 | [
"def add_column_xsd(self, tb, column, attrs):\n \"\"\" Add the XSD for a column to tb (a TreeBuilder) \"\"\"\n if column.nullable:\n attrs['minOccurs'] = str(0)\n attrs['nillable'] = 'true'\n for cls, xsd_type in six.iteritems(self.SIMPLE_XSD_TYPES):\n if isinstance(column.type, cls):\... | class XSDGenerator(object):
""" XSD Generator """
SIMPLE_XSD_TYPES = {
# SQLAlchemy types
sqlalchemy.BigInteger: 'xsd:integer',
sqlalchemy.Boolean: 'xsd:boolean',
sqlalchemy.Date: 'xsd:date',
sqlalchemy.DateTime: 'xsd:dateTime',
sqlalchemy.Float: 'xsd:double',
... |
elemoine/papyrus | papyrus/xsd.py | XSDGenerator.add_class_properties_xsd | python | def add_class_properties_xsd(self, tb, cls):
for p in class_mapper(cls).iterate_properties:
if isinstance(p, ColumnProperty):
self.add_column_property_xsd(tb, p)
if self.sequence_callback:
self.sequence_callback(tb, cls) | Add the XSD for the class properties to the ``TreeBuilder``. And
call the user ``sequence_callback``. | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/xsd.py#L162-L169 | [
"def add_column_property_xsd(self, tb, column_property):\n \"\"\" Add the XSD for a column property to the ``TreeBuilder``. \"\"\"\n if len(column_property.columns) != 1:\n raise NotImplementedError # pragma: no cover\n column = column_property.columns[0]\n if column.primary_key and not self.inc... | class XSDGenerator(object):
""" XSD Generator """
SIMPLE_XSD_TYPES = {
# SQLAlchemy types
sqlalchemy.BigInteger: 'xsd:integer',
sqlalchemy.Boolean: 'xsd:boolean',
sqlalchemy.Date: 'xsd:date',
sqlalchemy.DateTime: 'xsd:dateTime',
sqlalchemy.Float: 'xsd:double',
... |
elemoine/papyrus | papyrus/xsd.py | XSDGenerator.get_class_xsd | python | def get_class_xsd(self, io, cls):
attrs = {}
attrs['xmlns:gml'] = 'http://www.opengis.net/gml'
attrs['xmlns:xsd'] = 'http://www.w3.org/2001/XMLSchema'
tb = TreeBuilder()
with tag(tb, 'xsd:schema', attrs) as tb:
with tag(tb, 'xsd:complexType', {'name': cls.__name__}) a... | Returns the XSD for a mapped class. | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/xsd.py#L171-L186 | [
"def add_class_properties_xsd(self, tb, cls):\n \"\"\" Add the XSD for the class properties to the ``TreeBuilder``. And\n call the user ``sequence_callback``. \"\"\"\n for p in class_mapper(cls).iterate_properties:\n if isinstance(p, ColumnProperty):\n self.add_column_property_xsd(tb, p)\... | class XSDGenerator(object):
""" XSD Generator """
SIMPLE_XSD_TYPES = {
# SQLAlchemy types
sqlalchemy.BigInteger: 'xsd:integer',
sqlalchemy.Boolean: 'xsd:boolean',
sqlalchemy.Date: 'xsd:date',
sqlalchemy.DateTime: 'xsd:dateTime',
sqlalchemy.Float: 'xsd:double',
... |
elemoine/papyrus | papyrus/protocol.py | _get_col_epsg | python | def _get_col_epsg(mapped_class, geom_attr):
col = class_mapper(mapped_class).get_property(geom_attr).columns[0]
return col.type.srid | Get the EPSG code associated with a geometry attribute.
Arguments:
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class. | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L44-L56 | null |
# Copyright (c) 2008-2011 Camptocamp. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the ... |
elemoine/papyrus | papyrus/protocol.py | create_geom_filter | python | def create_geom_filter(request, mapped_class, geom_attr):
tolerance = float(request.params.get('tolerance', 0.0))
epsg = None
if 'epsg' in request.params:
epsg = int(request.params['epsg'])
box = request.params.get('bbox')
shape = None
if box is not None:
box = [float(x) for x in... | Create MapFish geometry filter based on the request params. Either
a box or within or geometry filter, depending on the request params.
Additional named arguments are passed to the spatial filter.
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
geom_... | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L59-L103 | [
"def _get_col_epsg(mapped_class, geom_attr):\n \"\"\"Get the EPSG code associated with a geometry attribute.\n\n Arguments:\n\n\n geom_attr\n the key of the geometry property as defined in the SQLAlchemy\n mapper. If you use ``declarative_base`` this is the name of\n the geometry attri... |
# Copyright (c) 2008-2011 Camptocamp. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the ... |
elemoine/papyrus | papyrus/protocol.py | create_attr_filter | python | def create_attr_filter(request, mapped_class):
mapping = {
'eq': '__eq__',
'ne': '__ne__',
'lt': '__lt__',
'lte': '__le__',
'gt': '__gt__',
'gte': '__ge__',
'like': 'like',
'ilike': 'ilike'
}
filters = []
if 'queryable' in request.params:
... | Create an ``and_`` SQLAlchemy filter (a ClauseList object) based
on the request params (``queryable``, ``eq``, ``ne``, ...).
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class. | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L106-L141 | null |
# Copyright (c) 2008-2011 Camptocamp. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the ... |
elemoine/papyrus | papyrus/protocol.py | create_filter | python | def create_filter(request, mapped_class, geom_attr, **kwargs):
attr_filter = create_attr_filter(request, mapped_class)
geom_filter = create_geom_filter(request, mapped_class, geom_attr,
**kwargs)
if geom_filter is None and attr_filter is None:
return None
if ... | Create MapFish default filter based on the request params.
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
... | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L144-L172 | [
"def create_geom_filter(request, mapped_class, geom_attr):\n \"\"\"Create MapFish geometry filter based on the request params. Either\n a box or within or geometry filter, depending on the request params.\n Additional named arguments are passed to the spatial filter.\n\n Arguments:\n\n request\n ... |
# Copyright (c) 2008-2011 Camptocamp. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the ... |
elemoine/papyrus | papyrus/protocol.py | Protocol._filter_attrs | python | def _filter_attrs(self, feature, request):
if 'attrs' in request.params:
attrs = request.params['attrs'].split(',')
props = feature.properties
new_props = {}
for name in attrs:
if name in props:
new_props[name] = props[name]
... | Remove some attributes from the feature and set the geometry to None
in the feature based ``attrs`` and the ``no_geom`` parameters. | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L233-L246 | [
"def asbool(val):\n # Convert the passed value to a boolean.\n if isinstance(val, six.string_types):\n return val.lower() not in ['false', '0']\n else:\n return bool(val)\n"
] | class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_bas... |
elemoine/papyrus | papyrus/protocol.py | Protocol._get_order_by | python | def _get_order_by(self, request):
attr = request.params.get('sort', request.params.get('order_by'))
if attr is None or not hasattr(self.mapped_class, attr):
return None
if request.params.get('dir', '').upper() == 'DESC':
return desc(getattr(self.mapped_class, attr))
... | Return an SA order_by | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L248-L256 | null | class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_bas... |
elemoine/papyrus | papyrus/protocol.py | Protocol._query | python | def _query(self, request, filter=None):
limit = None
offset = None
if 'maxfeatures' in request.params:
limit = int(request.params['maxfeatures'])
if 'limit' in request.params:
limit = int(request.params['limit'])
if 'offset' in request.params:
... | Build a query based on the filter and the request params,
and send the query to the database. | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L258-L278 | [
"def create_filter(request, mapped_class, geom_attr, **kwargs):\n \"\"\" Create MapFish default filter based on the request params.\n\n Arguments:\n\n request\n the request.\n\n mapped_class\n the SQLAlchemy mapped class.\n\n geom_attr\n the key of the geometry property as define... | class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_bas... |
elemoine/papyrus | papyrus/protocol.py | Protocol.count | python | def count(self, request, filter=None):
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
return query.count() | Return the number of records matching the given filter. | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L280-L287 | [
"def create_filter(request, mapped_class, geom_attr, **kwargs):\n \"\"\" Create MapFish default filter based on the request params.\n\n Arguments:\n\n request\n the request.\n\n mapped_class\n the SQLAlchemy mapped class.\n\n geom_attr\n the key of the geometry property as define... | class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_bas... |
elemoine/papyrus | papyrus/protocol.py | Protocol.read | python | def read(self, request, filter=None, id=None):
ret = None
if id is not None:
o = self.Session().query(self.mapped_class).get(id)
if o is None:
return HTTPNotFound()
# FIXME: we return a Feature here, not a mapped object, do
# we really want... | Build a query based on the filter or the idenfier, send the query
to the database, and return a Feature or a FeatureCollection. | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L289-L305 | [
"def _filter_attrs(self, feature, request):\n \"\"\" Remove some attributes from the feature and set the geometry to None\n in the feature based ``attrs`` and the ``no_geom`` parameters. \"\"\"\n if 'attrs' in request.params:\n attrs = request.params['attrs'].split(',')\n props = feature.... | class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_bas... |
elemoine/papyrus | papyrus/protocol.py | Protocol.create | python | def create(self, request):
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
collection = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(collection, FeatureCollection):
return HTTPBadRequest()
session = self.Sess... | Read the GeoJSON feature collection from the request body and
create new objects in the database. | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L307-L335 | null | class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_bas... |
elemoine/papyrus | papyrus/protocol.py | Protocol.update | python | def update(self, request, id):
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
feature = loads(request.body, object_... | Read the GeoJSON feature from the request body and update the
corresponding object in the database. | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L337-L354 | null | class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_bas... |
elemoine/papyrus | papyrus/protocol.py | Protocol.delete | python | def delete(self, request, id):
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
if self.before_delete is not None:
... | Remove the targeted feature from the database | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L356-L367 | null | class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_bas... |
elemoine/papyrus | papyrus/__init__.py | add_papyrus_handler | python | def add_papyrus_handler(self, route_name_prefix, base_url, handler):
route_name = route_name_prefix + '_read_many'
self.add_handler(route_name, base_url, handler,
action='read_many', request_method='GET')
route_name = route_name_prefix + '_read_one'
self.add_handler(route_name, base... | Add a Papyrus handler, i.e. a handler defining the MapFish
HTTP interface.
Example::
import papyrus
config.include(papyrus)
config.add_papyrus_handler(
'spots', '/spots', 'mypackage.handlers.SpotHandler')
Arguments:
``route_name_prefix`` The prefix used for the ro... | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/__init__.py#L2-L41 | null |
def add_papyrus_routes(self, route_name_prefix, base_url):
""" A helper method that adds routes to view callables that, together,
implement the MapFish HTTP interface.
Example::
import papyrus
config.include(papyrus)
config.add_papyrus_routes('spots', '/spots')
config.s... |
elemoine/papyrus | papyrus/__init__.py | add_papyrus_routes | python | def add_papyrus_routes(self, route_name_prefix, base_url):
route_name = route_name_prefix + '_read_many'
self.add_route(route_name, base_url, request_method='GET')
route_name = route_name_prefix + '_read_one'
self.add_route(route_name, base_url + '/{id}', request_method='GET')
route_name = route_nam... | A helper method that adds routes to view callables that, together,
implement the MapFish HTTP interface.
Example::
import papyrus
config.include(papyrus)
config.add_papyrus_routes('spots', '/spots')
config.scan()
Arguments:
``route_name_prefix' The prefix used for the... | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/__init__.py#L44-L74 | null |
def add_papyrus_handler(self, route_name_prefix, base_url, handler):
""" Add a Papyrus handler, i.e. a handler defining the MapFish
HTTP interface.
Example::
import papyrus
config.include(papyrus)
config.add_papyrus_handler(
'spots', '/spots', 'mypackage.handlers.SpotH... |
sacherjj/array_devices | array_devices/array3710.py | ProgramStep.setting | python | def setting(self):
prog_type = self.__program.program_type
return self._setting / self.SETTING_DIVIDES[prog_type] | Load setting (Amps, Watts, or Ohms depending on program mode) | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L51-L56 | null | class ProgramStep(object):
"""
Represents a single step in an Array3710Program
"""
# Max Settings based on PROG_TYPE modes as index
# 1: 30A, 2: 200W, 3: 500ohms
MAX_SETTINGS = (0, 30, 200, 500)
# Display units
SETTING_UNITS = ('', 'amps', 'watts', 'ohms')
# Conversions between inter... |
sacherjj/array_devices | array_devices/array3710.py | Program.partial_steps_data | python | def partial_steps_data(self, start=0):
cnt = 0
if len(self._prog_steps) >= start:
# yields actual steps for encoding
for step in self._prog_steps[start:start+5]:
yield((step.raw_data))
cnt += 1
while cnt < 5:
yield((0, 0))
... | Iterates 5 steps from start position and
provides tuple for packing into buffer.
returns (0, 0) if stpe doesn't exist.
:param start: Position to start from (typically 0 or 5)
:yield: (setting, duration) | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L136-L154 | null | class Program(object):
"""
Represents a 10 step program for the load
"""
PROG_TYPE_CURRENT = 0x01
PROG_TYPE_POWER = 0x02
PROG_TYPE_RESISTANCE = 0x03
RUN_ONCE = 0x00
RUN_REPEAT = 0x01
def __init__(self, program_type=0x01, program_mode=0x00):
if not program_type in (self.PROG... |
sacherjj/array_devices | array_devices/array3710.py | Program.add_step | python | def add_step(self, setting, duration):
if len(self._prog_steps) < 10:
self._prog_steps.append(ProgramStep(self, setting, duration))
else:
raise IndexError("Maximum of 10 steps are allowed") | Adds steps to a program.
:param setting: Current, Wattage or Resistance, depending on program mode.
:param duration: Length of step in seconds.
:return: None | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L156-L166 | null | class Program(object):
"""
Represents a 10 step program for the load
"""
PROG_TYPE_CURRENT = 0x01
PROG_TYPE_POWER = 0x02
PROG_TYPE_RESISTANCE = 0x03
RUN_ONCE = 0x00
RUN_REPEAT = 0x01
def __init__(self, program_type=0x01, program_mode=0x00):
if not program_type in (self.PROG... |
sacherjj/array_devices | array_devices/array3710.py | Program.load_buffer_one_to_five | python | def load_buffer_one_to_five(self, out_buffer):
struct.pack_into(b"< 2B", out_buffer, 3, self._program_type, len(self._prog_steps))
offset = 5
for ind, step in enumerate(self.partial_steps_data(0)):
struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1]) | Loads first program buffer (0x93) with everything but
first three bytes and checksum | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L174-L182 | [
"def partial_steps_data(self, start=0):\n \"\"\"\n Iterates 5 steps from start position and\n provides tuple for packing into buffer.\n\n returns (0, 0) if stpe doesn't exist.\n\n :param start: Position to start from (typically 0 or 5)\n :yield: (setting, duration)\n \"\"\"\n cnt = 0\n if... | class Program(object):
"""
Represents a 10 step program for the load
"""
PROG_TYPE_CURRENT = 0x01
PROG_TYPE_POWER = 0x02
PROG_TYPE_RESISTANCE = 0x03
RUN_ONCE = 0x00
RUN_REPEAT = 0x01
def __init__(self, program_type=0x01, program_mode=0x00):
if not program_type in (self.PROG... |
sacherjj/array_devices | array_devices/array3710.py | Program.load_buffer_six_to_ten | python | def load_buffer_six_to_ten(self, out_buffer):
offset = 3
for ind, step in enumerate(self.partial_steps_data(5)):
struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1])
struct.pack_into(b"< B x", out_buffer, 23, self._program_mode) | Loads second program buffer (0x94) with everything but
first three bytes and checksum | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L184-L192 | [
"def partial_steps_data(self, start=0):\n \"\"\"\n Iterates 5 steps from start position and\n provides tuple for packing into buffer.\n\n returns (0, 0) if stpe doesn't exist.\n\n :param start: Position to start from (typically 0 or 5)\n :yield: (setting, duration)\n \"\"\"\n cnt = 0\n if... | class Program(object):
"""
Represents a 10 step program for the load
"""
PROG_TYPE_CURRENT = 0x01
PROG_TYPE_POWER = 0x02
PROG_TYPE_RESISTANCE = 0x03
RUN_ONCE = 0x00
RUN_REPEAT = 0x01
def __init__(self, program_type=0x01, program_mode=0x00):
if not program_type in (self.PROG... |
sacherjj/array_devices | array_devices/array3710.py | Load.set_load_resistance | python | def set_load_resistance(self, resistance):
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters... | Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L309-L322 | null | class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x9... |
sacherjj/array_devices | array_devices/array3710.py | Load.set_load_power | python | def set_load_power(self, power_watts):
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters() | Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return: | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L324-L337 | null | class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x9... |
sacherjj/array_devices | array_devices/array3710.py | Load.set_load_current | python | def set_load_current(self, current_amps):
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters() | Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L339-L352 | null | class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x9... |
sacherjj/array_devices | array_devices/array3710.py | Load.__set_buffer_start | python | def __set_buffer_start(self, command):
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command) | This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L414-L420 | null | class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x9... |
sacherjj/array_devices | array_devices/array3710.py | Load.__set_checksum | python | def __set_checksum(self):
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum) | Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L434-L441 | [
"def __get_checksum(byte_str):\n \"\"\"\n Calculates checksum of string, excluding last character.\n Checksum is generated by summing all byte values, except last,\n and taking lowest byte of result.\n\n :param byte_str: string to checksum, plus extra character on end\n :return: checksum value as ... | class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x9... |
sacherjj/array_devices | array_devices/array3710.py | Load.__clear_in_buffer | python | def __clear_in_buffer(self):
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer)) | Zeros out the in buffer
:return: None | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L451-L456 | null | class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x9... |
sacherjj/array_devices | array_devices/array3710.py | Load.__send_buffer | python | def __send_buffer(self):
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size... | Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L458-L469 | null | class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x9... |
sacherjj/array_devices | array_devices/array3710.py | Load.__send_receive_buffer | python | def __send_receive_buffer(self):
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
... | Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L471-L487 | null | class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x9... |
sacherjj/array_devices | array_devices/array3710.py | Load.__set_parameters | python | def __set_parameters(self):
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET... | Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L489-L505 | null | class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x9... |
sacherjj/array_devices | array_devices/array3710.py | Load.update_status | python | def update_status(self, retry_count=2):
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
... | Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_t... | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L507-L557 | [
"def __is_valid_checksum(self, byte_str):\n \"\"\"\n Verifies last byte checksum of full packet\n :param byte_str: byte string message\n :return: boolean\n \"\"\"\n return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)\n",
"def __update_status(self):\n self.__set_buffer_start(self.CM... | class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x9... |
sacherjj/array_devices | array_devices/array3710.py | Load.set_program_sequence | python | def set_program_sequence(self, array_program):
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buff... | Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L575-L589 | [
"def load_buffer_one_to_five(self, out_buffer):\n \"\"\"\n Loads first program buffer (0x93) with everything but\n first three bytes and checksum\n \"\"\"\n struct.pack_into(b\"< 2B\", out_buffer, 3, self._program_type, len(self._prog_steps))\n offset = 5\n for ind, step in enumerate(self.parti... | class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x9... |
sacherjj/array_devices | array_devices/array3710.py | Load.start_program | python | def start_program(self, turn_on_load=True):
self.__set_buffer_start(self.CMD_START_PROG)
self.__set_checksum()
self.__send_buffer()
# Turn on Load if not on
if turn_on_load and not self.load_on:
self.load_on = True | Starts running programmed test sequence
:return: None | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L591-L601 | [
"def __set_buffer_start(self, command):\n \"\"\"\n This sets the first three bytes and clears the other 23 bytes.\n :param command: Command Code to set\n :return: None\n \"\"\"\n self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)\n",
"def __set_checksu... | class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x9... |
sacherjj/array_devices | array_devices/array3710.py | Load.stop_program | python | def stop_program(self, turn_off_load=True):
self.__set_buffer_start(self.CMD_STOP_PROG)
self.__set_checksum()
self.__send_buffer()
if turn_off_load and self.load_on:
self.load_on = False | Stops running programmed test sequence
:return: None | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L603-L612 | [
"def __set_buffer_start(self, command):\n \"\"\"\n This sets the first three bytes and clears the other 23 bytes.\n :param command: Command Code to set\n :return: None\n \"\"\"\n self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)\n",
"def __set_checksu... | class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x9... |
flowroute/txjason | txjason/handler.py | Handler.addToService | python | def addToService(self, service, namespace=None, seperator='.'):
if namespace is None:
namespace = []
if isinstance(namespace, basestring):
namespace = [namespace]
for n, m in inspect.getmembers(self, inspect.ismethod):
if hasattr(m, 'export_rpc'):
... | Add this Handler's exported methods to an RPC Service instance. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/handler.py#L44-L59 | null | class Handler(object):
"""
Define RPC methods in subclasses of Handler. @exportRPC decorator indicates
that a method should be exported. Call .addHandler on a subclass of txjason's
BaseClientFactory (e.g., netstring.JSONRPCServerFactory) and pass an instance
of a Handler subclass to expose the RPC m... |
flowroute/txjason | txjason/service.py | JSONRPCService.add | python | def add(self, f, name=None, types=None, required=None):
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types']... | Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, f... | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L108-L137 | null | class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
... |
flowroute/txjason | txjason/service.py | JSONRPCService.stopServing | python | def stopServing(self, exception=None):
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None) | Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L139-L151 | null | class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
... |
flowroute/txjason | txjason/service.py | JSONRPCService.call | python | def call(self, jsondata):
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result)) | Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L163-L175 | null | class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
... |
flowroute/txjason | txjason/service.py | JSONRPCService.call_py | python | def call_py(self, jsondata):
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
... | Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L178-L263 | [
"def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):\n \"\"\"\n Returns jsonrpc error message.\n \"\"\"\n # Do not respond to notifications when the request is valid.\n if not id \\\n and not isinstance(e, ParseError) \\\n and not isinstance(e, InvalidRequestError):\n ... | class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
... |
flowroute/txjason | txjason/service.py | JSONRPCService._get_err | python | def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
... | Returns jsonrpc error message. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L265-L290 | [
"def _fill_ver(self, iver, respond):\n \"\"\"\n Fills version information to the respond from the internal integer\n version.\n \"\"\"\n if iver == 20:\n respond['jsonrpc'] = '2.0'\n if iver == 11:\n respond['version'] = '1.1'\n"
] | class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
... |
flowroute/txjason | txjason/service.py | JSONRPCService._man_args | python | def _man_args(self, f):
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults) | Returns number of mandatory arguments required by given function. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L312-L325 | null | class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
... |
flowroute/txjason | txjason/service.py | JSONRPCService._max_args | python | def _max_args(self, f):
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults) | Returns maximum number of arguments accepted by given function. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L327-L334 | null | class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
... |
flowroute/txjason | txjason/service.py | JSONRPCService._get_id | python | def _get_id(self, rdata):
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
... | Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L358-L376 | null | class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
... |
flowroute/txjason | txjason/service.py | JSONRPCService._get_method | python | def _get_method(self, rdata):
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
... | Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L378-L395 | null | class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
... |
flowroute/txjason | txjason/service.py | JSONRPCService._get_params | python | def _get_params(self, rdata):
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
... | Returns a list of jsonrpc request's method parameters. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L397-L410 | null | class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
... |
flowroute/txjason | txjason/service.py | JSONRPCService._fill_request | python | def _fill_request(self, request, rdata):
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata... | Fills request with data from the jsonrpc call. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L412-L420 | null | class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
... |
flowroute/txjason | txjason/service.py | JSONRPCService._call_method | python | def _call_method(self, request):
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
... | Calls given method with given params and returns it value. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L423-L457 | null | class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
... |
flowroute/txjason | txjason/service.py | JSONRPCService._handle_request | python | def _handle_request(self, request):
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
... | Handles given request and returns its response. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L465-L505 | null | class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
... |
flowroute/txjason | txjason/service.py | JSONRPCService._validate_params_types | python | def _validate_params_types(self, method, params):
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
... | Validates request's parameter types. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L514-L546 | null | class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
... |
flowroute/txjason | txjason/service.py | JSONRPCClientService.startService | python | def startService(self):
self.clientFactory.connect().addErrback(
log.err, 'error starting the JSON-RPC client service %r' % (self,))
service.Service.startService(self) | Start the service and connect the JSONRPCClientFactory. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L560-L566 | null | class JSONRPCClientService(service.Service):
"""
A service that manages a JSONRPCClientFactory.
Starting and stopping this service connects and disconnects the underlying
JSONRPCClientFactory.
"""
def __init__(self, clientFactory):
self.clientFactory = clientFactory
def stopServi... |
flowroute/txjason | txjason/service.py | JSONRPCClientService.callRemote | python | def callRemote(self, *a, **kw):
if not self.running:
return defer.fail(ServiceStopped())
return self.clientFactory.callRemote(*a, **kw) | Make a callRemote request of the JSONRPCClientFactory. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L575-L581 | null | class JSONRPCClientService(service.Service):
"""
A service that manages a JSONRPCClientFactory.
Starting and stopping this service connects and disconnects the underlying
JSONRPCClientFactory.
"""
def __init__(self, clientFactory):
self.clientFactory = clientFactory
def startServi... |
flowroute/txjason | txjason/service.py | JSONRPCError.dumps | python | def dumps(self):
error = {'code': self.code,
'message': str(self.message)}
if self.data is not None:
error['data'] = self.data
return error | Return the Exception data in a format for JSON-RPC. | train | https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L615-L624 | null | class JSONRPCError(Exception):
"""
JSONRPCError class based on the JSON-RPC 2.0 specs.
code - number
message - string
data - object
"""
code = 0
message = None
data = None
def __init__(self, message=None):
"""Setup the Exception and overwrite the default message."""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.