repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
bruth/django-preserialize | preserialize/serialize.py | model_to_dict | def model_to_dict(instance, **options):
"Takes a model instance and converts it into a dict."
options = _defaults(options)
attrs = {}
if options['prehook']:
if isinstance(options['prehook'], collections.Callable):
instance = options['prehook'](instance)
if instance is None:
return attrs
# Items in the `fields` list are the output aliases, not the raw
# accessors (field, method, property names)
for alias in options['fields']:
# Get the accessor for the object
accessor = options['aliases'].get(alias, alias)
# Create the key that will be used in the output dict
key = options['prefix'] + alias
# Optionally camelcase the key
if options['camelcase']:
key = convert_to_camel(key)
# Get the field value. Use the mapped value to the actually property or
# method name. `value` may be a number of things, so the various types
# are checked below.
value = get_field_value(instance, accessor,
allow_missing=options['allow_missing'])
# Related objects, perform some checks on their options
if isinstance(value, (models.Model, QuerySet)):
_options = _defaults(options['related'].get(accessor, {}))
# If the `prefix` follows the below template, generate the
# `prefix` for the related object
if '%(accessor)s' in _options['prefix']:
_options['prefix'] = _options['prefix'] % {'accessor': alias}
if isinstance(value, models.Model):
if len(_options['fields']) == 1 and _options['flat'] \
and not _options['merge']:
value = list(serialize(value, **_options).values())[0]
else:
# Recurse, get the dict representation
_attrs = serialize(value, **_options)
# Check if this object should be merged into the parent,
# otherwise nest it under the accessor name
if _options['merge']:
attrs.update(_attrs)
continue
value = _attrs
else:
value = serialize(value, **_options)
attrs[key] = value
# Apply post-hook to serialized attributes
if options['posthook']:
attrs = options['posthook'](instance, attrs)
return attrs | python | def model_to_dict(instance, **options):
"Takes a model instance and converts it into a dict."
options = _defaults(options)
attrs = {}
if options['prehook']:
if isinstance(options['prehook'], collections.Callable):
instance = options['prehook'](instance)
if instance is None:
return attrs
# Items in the `fields` list are the output aliases, not the raw
# accessors (field, method, property names)
for alias in options['fields']:
# Get the accessor for the object
accessor = options['aliases'].get(alias, alias)
# Create the key that will be used in the output dict
key = options['prefix'] + alias
# Optionally camelcase the key
if options['camelcase']:
key = convert_to_camel(key)
# Get the field value. Use the mapped value to the actually property or
# method name. `value` may be a number of things, so the various types
# are checked below.
value = get_field_value(instance, accessor,
allow_missing=options['allow_missing'])
# Related objects, perform some checks on their options
if isinstance(value, (models.Model, QuerySet)):
_options = _defaults(options['related'].get(accessor, {}))
# If the `prefix` follows the below template, generate the
# `prefix` for the related object
if '%(accessor)s' in _options['prefix']:
_options['prefix'] = _options['prefix'] % {'accessor': alias}
if isinstance(value, models.Model):
if len(_options['fields']) == 1 and _options['flat'] \
and not _options['merge']:
value = list(serialize(value, **_options).values())[0]
else:
# Recurse, get the dict representation
_attrs = serialize(value, **_options)
# Check if this object should be merged into the parent,
# otherwise nest it under the accessor name
if _options['merge']:
attrs.update(_attrs)
continue
value = _attrs
else:
value = serialize(value, **_options)
attrs[key] = value
# Apply post-hook to serialized attributes
if options['posthook']:
attrs = options['posthook'](instance, attrs)
return attrs | [
"def",
"model_to_dict",
"(",
"instance",
",",
"*",
"*",
"options",
")",
":",
"options",
"=",
"_defaults",
"(",
"options",
")",
"attrs",
"=",
"{",
"}",
"if",
"options",
"[",
"'prehook'",
"]",
":",
"if",
"isinstance",
"(",
"options",
"[",
"'prehook'",
"]",
",",
"collections",
".",
"Callable",
")",
":",
"instance",
"=",
"options",
"[",
"'prehook'",
"]",
"(",
"instance",
")",
"if",
"instance",
"is",
"None",
":",
"return",
"attrs",
"# Items in the `fields` list are the output aliases, not the raw",
"# accessors (field, method, property names)",
"for",
"alias",
"in",
"options",
"[",
"'fields'",
"]",
":",
"# Get the accessor for the object",
"accessor",
"=",
"options",
"[",
"'aliases'",
"]",
".",
"get",
"(",
"alias",
",",
"alias",
")",
"# Create the key that will be used in the output dict",
"key",
"=",
"options",
"[",
"'prefix'",
"]",
"+",
"alias",
"# Optionally camelcase the key",
"if",
"options",
"[",
"'camelcase'",
"]",
":",
"key",
"=",
"convert_to_camel",
"(",
"key",
")",
"# Get the field value. Use the mapped value to the actually property or",
"# method name. `value` may be a number of things, so the various types",
"# are checked below.",
"value",
"=",
"get_field_value",
"(",
"instance",
",",
"accessor",
",",
"allow_missing",
"=",
"options",
"[",
"'allow_missing'",
"]",
")",
"# Related objects, perform some checks on their options",
"if",
"isinstance",
"(",
"value",
",",
"(",
"models",
".",
"Model",
",",
"QuerySet",
")",
")",
":",
"_options",
"=",
"_defaults",
"(",
"options",
"[",
"'related'",
"]",
".",
"get",
"(",
"accessor",
",",
"{",
"}",
")",
")",
"# If the `prefix` follows the below template, generate the",
"# `prefix` for the related object",
"if",
"'%(accessor)s'",
"in",
"_options",
"[",
"'prefix'",
"]",
":",
"_options",
"[",
"'prefix'",
"]",
"=",
"_options",
"[",
"'prefix'",
"]",
"%",
"{",
"'accessor'",
":",
"alias",
"}",
"if",
"isinstance",
"(",
"value",
",",
"models",
".",
"Model",
")",
":",
"if",
"len",
"(",
"_options",
"[",
"'fields'",
"]",
")",
"==",
"1",
"and",
"_options",
"[",
"'flat'",
"]",
"and",
"not",
"_options",
"[",
"'merge'",
"]",
":",
"value",
"=",
"list",
"(",
"serialize",
"(",
"value",
",",
"*",
"*",
"_options",
")",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
"else",
":",
"# Recurse, get the dict representation",
"_attrs",
"=",
"serialize",
"(",
"value",
",",
"*",
"*",
"_options",
")",
"# Check if this object should be merged into the parent,",
"# otherwise nest it under the accessor name",
"if",
"_options",
"[",
"'merge'",
"]",
":",
"attrs",
".",
"update",
"(",
"_attrs",
")",
"continue",
"value",
"=",
"_attrs",
"else",
":",
"value",
"=",
"serialize",
"(",
"value",
",",
"*",
"*",
"_options",
")",
"attrs",
"[",
"key",
"]",
"=",
"value",
"# Apply post-hook to serialized attributes",
"if",
"options",
"[",
"'posthook'",
"]",
":",
"attrs",
"=",
"options",
"[",
"'posthook'",
"]",
"(",
"instance",
",",
"attrs",
")",
"return",
"attrs"
] | Takes a model instance and converts it into a dict. | [
"Takes",
"a",
"model",
"instance",
"and",
"converts",
"it",
"into",
"a",
"dict",
"."
] | d772c224bd8c2c9e9ff997d82c54fe6ebb9444b6 | https://github.com/bruth/django-preserialize/blob/d772c224bd8c2c9e9ff997d82c54fe6ebb9444b6/preserialize/serialize.py#L59-L124 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/screenshot.py | set_save_directory | def set_save_directory(base, source):
"""Sets the root save directory for saving screenshots.
Screenshots will be saved in subdirectories under this directory by
browser window size. """
root = os.path.join(base, source)
if not os.path.isdir(root):
os.makedirs(root)
world.screenshot_root = root | python | def set_save_directory(base, source):
"""Sets the root save directory for saving screenshots.
Screenshots will be saved in subdirectories under this directory by
browser window size. """
root = os.path.join(base, source)
if not os.path.isdir(root):
os.makedirs(root)
world.screenshot_root = root | [
"def",
"set_save_directory",
"(",
"base",
",",
"source",
")",
":",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"source",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"root",
")",
":",
"os",
".",
"makedirs",
"(",
"root",
")",
"world",
".",
"screenshot_root",
"=",
"root"
] | Sets the root save directory for saving screenshots.
Screenshots will be saved in subdirectories under this directory by
browser window size. | [
"Sets",
"the",
"root",
"save",
"directory",
"for",
"saving",
"screenshots",
".",
"Screenshots",
"will",
"be",
"saved",
"in",
"subdirectories",
"under",
"this",
"directory",
"by",
"browser",
"window",
"size",
"."
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/screenshot.py#L13-L22 | train |
qacafe/cdrouter.py | cdrouter/users.py | UsersService.change_password | def change_password(self, id, new, old=None, change_token=True): # pylint: disable=invalid-name,redefined-builtin
"""Change a user's password.
:param id: User ID as an int.
:param new: New password as string.
:param old: (optional) Old password as string (required if performing action as non-admin).
:param change_token: (optional) If bool `True`, also generate a new API token for user.
:return: :class:`users.User <users.User>` object
:rtype: users.User
"""
schema = UserSchema(exclude=('password', 'password_confirm'))
resp = self.service.post(self.base+str(id)+'/password/',
params={'change_token': change_token},
json={'old': old, 'new': new, 'new_confirm': new})
return self.service.decode(schema, resp) | python | def change_password(self, id, new, old=None, change_token=True): # pylint: disable=invalid-name,redefined-builtin
"""Change a user's password.
:param id: User ID as an int.
:param new: New password as string.
:param old: (optional) Old password as string (required if performing action as non-admin).
:param change_token: (optional) If bool `True`, also generate a new API token for user.
:return: :class:`users.User <users.User>` object
:rtype: users.User
"""
schema = UserSchema(exclude=('password', 'password_confirm'))
resp = self.service.post(self.base+str(id)+'/password/',
params={'change_token': change_token},
json={'old': old, 'new': new, 'new_confirm': new})
return self.service.decode(schema, resp) | [
"def",
"change_password",
"(",
"self",
",",
"id",
",",
"new",
",",
"old",
"=",
"None",
",",
"change_token",
"=",
"True",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"schema",
"=",
"UserSchema",
"(",
"exclude",
"=",
"(",
"'password'",
",",
"'password_confirm'",
")",
")",
"resp",
"=",
"self",
".",
"service",
".",
"post",
"(",
"self",
".",
"base",
"+",
"str",
"(",
"id",
")",
"+",
"'/password/'",
",",
"params",
"=",
"{",
"'change_token'",
":",
"change_token",
"}",
",",
"json",
"=",
"{",
"'old'",
":",
"old",
",",
"'new'",
":",
"new",
",",
"'new_confirm'",
":",
"new",
"}",
")",
"return",
"self",
".",
"service",
".",
"decode",
"(",
"schema",
",",
"resp",
")"
] | Change a user's password.
:param id: User ID as an int.
:param new: New password as string.
:param old: (optional) Old password as string (required if performing action as non-admin).
:param change_token: (optional) If bool `True`, also generate a new API token for user.
:return: :class:`users.User <users.User>` object
:rtype: users.User | [
"Change",
"a",
"user",
"s",
"password",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/users.py#L154-L168 | train |
qacafe/cdrouter.py | cdrouter/users.py | UsersService.change_token | def change_token(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Change a user's token.
:param id: User ID as an int.
:return: :class:`users.User <users.User>` object
:rtype: users.User
"""
schema = UserSchema(exclude=('password', 'password_confirm'))
resp = self.service.post(self.base+str(id)+'/token/')
return self.service.decode(schema, resp) | python | def change_token(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Change a user's token.
:param id: User ID as an int.
:return: :class:`users.User <users.User>` object
:rtype: users.User
"""
schema = UserSchema(exclude=('password', 'password_confirm'))
resp = self.service.post(self.base+str(id)+'/token/')
return self.service.decode(schema, resp) | [
"def",
"change_token",
"(",
"self",
",",
"id",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"schema",
"=",
"UserSchema",
"(",
"exclude",
"=",
"(",
"'password'",
",",
"'password_confirm'",
")",
")",
"resp",
"=",
"self",
".",
"service",
".",
"post",
"(",
"self",
".",
"base",
"+",
"str",
"(",
"id",
")",
"+",
"'/token/'",
")",
"return",
"self",
".",
"service",
".",
"decode",
"(",
"schema",
",",
"resp",
")"
] | Change a user's token.
:param id: User ID as an int.
:return: :class:`users.User <users.User>` object
:rtype: users.User | [
"Change",
"a",
"user",
"s",
"token",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/users.py#L170-L179 | train |
qacafe/cdrouter.py | cdrouter/users.py | UsersService.bulk_copy | def bulk_copy(self, ids):
"""Bulk copy a set of users.
:param ids: Int list of user IDs.
:return: :class:`users.User <users.User>` list
"""
schema = UserSchema()
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) | python | def bulk_copy(self, ids):
"""Bulk copy a set of users.
:param ids: Int list of user IDs.
:return: :class:`users.User <users.User>` list
"""
schema = UserSchema()
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) | [
"def",
"bulk_copy",
"(",
"self",
",",
"ids",
")",
":",
"schema",
"=",
"UserSchema",
"(",
")",
"return",
"self",
".",
"service",
".",
"bulk_copy",
"(",
"self",
".",
"base",
",",
"self",
".",
"RESOURCE",
",",
"ids",
",",
"schema",
")"
] | Bulk copy a set of users.
:param ids: Int list of user IDs.
:return: :class:`users.User <users.User>` list | [
"Bulk",
"copy",
"a",
"set",
"of",
"users",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/users.py#L188-L195 | train |
qacafe/cdrouter.py | cdrouter/attachments.py | AttachmentsService.list | def list(self, id, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=invalid-name,redefined-builtin
"""Get a list of a device's attachments.
:param id: Device ID as an int.
:param filter: (optional) Filters to apply as a string list.
:param type: (optional) `union` or `inter` as string.
:param sort: (optional) Sort fields to apply as string list.
:param limit: (optional) Limit returned list length.
:param page: (optional) Page to return.
:return: :class:`attachments.Page <attachments.Page>` object
"""
schema = AttachmentSchema(exclude=('path'))
resp = self.service.list(self._base(id), filter, type, sort, limit, page)
at, l = self.service.decode(schema, resp, many=True, links=True)
return Page(at, l) | python | def list(self, id, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=invalid-name,redefined-builtin
"""Get a list of a device's attachments.
:param id: Device ID as an int.
:param filter: (optional) Filters to apply as a string list.
:param type: (optional) `union` or `inter` as string.
:param sort: (optional) Sort fields to apply as string list.
:param limit: (optional) Limit returned list length.
:param page: (optional) Page to return.
:return: :class:`attachments.Page <attachments.Page>` object
"""
schema = AttachmentSchema(exclude=('path'))
resp = self.service.list(self._base(id), filter, type, sort, limit, page)
at, l = self.service.decode(schema, resp, many=True, links=True)
return Page(at, l) | [
"def",
"list",
"(",
"self",
",",
"id",
",",
"filter",
"=",
"None",
",",
"type",
"=",
"None",
",",
"sort",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"page",
"=",
"None",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"schema",
"=",
"AttachmentSchema",
"(",
"exclude",
"=",
"(",
"'path'",
")",
")",
"resp",
"=",
"self",
".",
"service",
".",
"list",
"(",
"self",
".",
"_base",
"(",
"id",
")",
",",
"filter",
",",
"type",
",",
"sort",
",",
"limit",
",",
"page",
")",
"at",
",",
"l",
"=",
"self",
".",
"service",
".",
"decode",
"(",
"schema",
",",
"resp",
",",
"many",
"=",
"True",
",",
"links",
"=",
"True",
")",
"return",
"Page",
"(",
"at",
",",
"l",
")"
] | Get a list of a device's attachments.
:param id: Device ID as an int.
:param filter: (optional) Filters to apply as a string list.
:param type: (optional) `union` or `inter` as string.
:param sort: (optional) Sort fields to apply as string list.
:param limit: (optional) Limit returned list length.
:param page: (optional) Page to return.
:return: :class:`attachments.Page <attachments.Page>` object | [
"Get",
"a",
"list",
"of",
"a",
"device",
"s",
"attachments",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/attachments.py#L68-L82 | train |
qacafe/cdrouter.py | cdrouter/attachments.py | AttachmentsService.iter_list | def iter_list(self, id, *args, **kwargs):
"""Get a list of attachments. Whereas ``list`` fetches a single page
of attachments according to its ``limit`` and ``page``
arguments, ``iter_list`` returns all attachments by internally
making successive calls to ``list``.
:param id: Device ID as an int.
:param args: Arguments that ``list`` takes.
:param kwargs: Optional arguments that ``list`` takes.
:return: :class:`attachments.Attachment <attachments.Attachment>` list
"""
l = partial(self.list, id)
return self.service.iter_list(l, *args, **kwargs) | python | def iter_list(self, id, *args, **kwargs):
"""Get a list of attachments. Whereas ``list`` fetches a single page
of attachments according to its ``limit`` and ``page``
arguments, ``iter_list`` returns all attachments by internally
making successive calls to ``list``.
:param id: Device ID as an int.
:param args: Arguments that ``list`` takes.
:param kwargs: Optional arguments that ``list`` takes.
:return: :class:`attachments.Attachment <attachments.Attachment>` list
"""
l = partial(self.list, id)
return self.service.iter_list(l, *args, **kwargs) | [
"def",
"iter_list",
"(",
"self",
",",
"id",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"l",
"=",
"partial",
"(",
"self",
".",
"list",
",",
"id",
")",
"return",
"self",
".",
"service",
".",
"iter_list",
"(",
"l",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Get a list of attachments. Whereas ``list`` fetches a single page
of attachments according to its ``limit`` and ``page``
arguments, ``iter_list`` returns all attachments by internally
making successive calls to ``list``.
:param id: Device ID as an int.
:param args: Arguments that ``list`` takes.
:param kwargs: Optional arguments that ``list`` takes.
:return: :class:`attachments.Attachment <attachments.Attachment>` list | [
"Get",
"a",
"list",
"of",
"attachments",
".",
"Whereas",
"list",
"fetches",
"a",
"single",
"page",
"of",
"attachments",
"according",
"to",
"its",
"limit",
"and",
"page",
"arguments",
"iter_list",
"returns",
"all",
"attachments",
"by",
"internally",
"making",
"successive",
"calls",
"to",
"list",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/attachments.py#L84-L97 | train |
qacafe/cdrouter.py | cdrouter/attachments.py | AttachmentsService.get | def get(self, id, attid): # pylint: disable=invalid-name,redefined-builtin
"""Get a device's attachment.
:param id: Device ID as an int.
:param attid: Attachment ID as an int.
:return: :class:`attachments.Attachment <attachments.Attachment>` object
:rtype: attachments.Attachment
"""
schema = AttachmentSchema()
resp = self.service.get_id(self._base(id), attid)
return self.service.decode(schema, resp) | python | def get(self, id, attid): # pylint: disable=invalid-name,redefined-builtin
"""Get a device's attachment.
:param id: Device ID as an int.
:param attid: Attachment ID as an int.
:return: :class:`attachments.Attachment <attachments.Attachment>` object
:rtype: attachments.Attachment
"""
schema = AttachmentSchema()
resp = self.service.get_id(self._base(id), attid)
return self.service.decode(schema, resp) | [
"def",
"get",
"(",
"self",
",",
"id",
",",
"attid",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"schema",
"=",
"AttachmentSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"get_id",
"(",
"self",
".",
"_base",
"(",
"id",
")",
",",
"attid",
")",
"return",
"self",
".",
"service",
".",
"decode",
"(",
"schema",
",",
"resp",
")"
] | Get a device's attachment.
:param id: Device ID as an int.
:param attid: Attachment ID as an int.
:return: :class:`attachments.Attachment <attachments.Attachment>` object
:rtype: attachments.Attachment | [
"Get",
"a",
"device",
"s",
"attachment",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/attachments.py#L99-L109 | train |
qacafe/cdrouter.py | cdrouter/attachments.py | AttachmentsService.create | def create(self, id, fd, filename='attachment-name'): # pylint: disable=invalid-name,redefined-builtin
"""Add an attachment to a device.
:param id: Device ID as an int.
:param fd: File-like object to upload.
:param filename: (optional) Name to use for new attachment as a string.
:return: :class:`attachments.Attachment <attachments.Attachment>` object
:rtype: attachments.Attachment
"""
schema = AttachmentSchema(exclude=('id', 'created', 'updated', 'size', 'path', 'device_id'))
resp = self.service.post(self._base(id),
files={'file': (filename, fd)})
return self.service.decode(schema, resp) | python | def create(self, id, fd, filename='attachment-name'): # pylint: disable=invalid-name,redefined-builtin
"""Add an attachment to a device.
:param id: Device ID as an int.
:param fd: File-like object to upload.
:param filename: (optional) Name to use for new attachment as a string.
:return: :class:`attachments.Attachment <attachments.Attachment>` object
:rtype: attachments.Attachment
"""
schema = AttachmentSchema(exclude=('id', 'created', 'updated', 'size', 'path', 'device_id'))
resp = self.service.post(self._base(id),
files={'file': (filename, fd)})
return self.service.decode(schema, resp) | [
"def",
"create",
"(",
"self",
",",
"id",
",",
"fd",
",",
"filename",
"=",
"'attachment-name'",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"schema",
"=",
"AttachmentSchema",
"(",
"exclude",
"=",
"(",
"'id'",
",",
"'created'",
",",
"'updated'",
",",
"'size'",
",",
"'path'",
",",
"'device_id'",
")",
")",
"resp",
"=",
"self",
".",
"service",
".",
"post",
"(",
"self",
".",
"_base",
"(",
"id",
")",
",",
"files",
"=",
"{",
"'file'",
":",
"(",
"filename",
",",
"fd",
")",
"}",
")",
"return",
"self",
".",
"service",
".",
"decode",
"(",
"schema",
",",
"resp",
")"
] | Add an attachment to a device.
:param id: Device ID as an int.
:param fd: File-like object to upload.
:param filename: (optional) Name to use for new attachment as a string.
:return: :class:`attachments.Attachment <attachments.Attachment>` object
:rtype: attachments.Attachment | [
"Add",
"an",
"attachment",
"to",
"a",
"device",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/attachments.py#L111-L123 | train |
qacafe/cdrouter.py | cdrouter/attachments.py | AttachmentsService.download | def download(self, id, attid): # pylint: disable=invalid-name,redefined-builtin
"""Download a device's attachment.
:param id: Device ID as an int.
:param attid: Attachment ID as an int.
:rtype: tuple `(io.BytesIO, 'filename')`
"""
resp = self.service.get_id(self._base(id), attid, params={'format': 'download'}, stream=True)
b = io.BytesIO()
stream.stream_response_to_file(resp, path=b)
resp.close()
b.seek(0)
return (b, self.service.filename(resp)) | python | def download(self, id, attid): # pylint: disable=invalid-name,redefined-builtin
"""Download a device's attachment.
:param id: Device ID as an int.
:param attid: Attachment ID as an int.
:rtype: tuple `(io.BytesIO, 'filename')`
"""
resp = self.service.get_id(self._base(id), attid, params={'format': 'download'}, stream=True)
b = io.BytesIO()
stream.stream_response_to_file(resp, path=b)
resp.close()
b.seek(0)
return (b, self.service.filename(resp)) | [
"def",
"download",
"(",
"self",
",",
"id",
",",
"attid",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"resp",
"=",
"self",
".",
"service",
".",
"get_id",
"(",
"self",
".",
"_base",
"(",
"id",
")",
",",
"attid",
",",
"params",
"=",
"{",
"'format'",
":",
"'download'",
"}",
",",
"stream",
"=",
"True",
")",
"b",
"=",
"io",
".",
"BytesIO",
"(",
")",
"stream",
".",
"stream_response_to_file",
"(",
"resp",
",",
"path",
"=",
"b",
")",
"resp",
".",
"close",
"(",
")",
"b",
".",
"seek",
"(",
"0",
")",
"return",
"(",
"b",
",",
"self",
".",
"service",
".",
"filename",
"(",
"resp",
")",
")"
] | Download a device's attachment.
:param id: Device ID as an int.
:param attid: Attachment ID as an int.
:rtype: tuple `(io.BytesIO, 'filename')` | [
"Download",
"a",
"device",
"s",
"attachment",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/attachments.py#L125-L137 | train |
qacafe/cdrouter.py | cdrouter/attachments.py | AttachmentsService.edit | def edit(self, resource): # pylint: disable=invalid-name,redefined-builtin
"""Edit a device's attachment.
:param resource: :class:`attachments.Attachment <attachments.Attachment>` object
:return: :class:`attachments.Attachment <attachments.Attachment>` object
:rtype: attachments.Attachment
"""
schema = AttachmentSchema(exclude=('id', 'created', 'updated', 'size', 'path', 'device_id'))
json = self.service.encode(schema, resource)
schema = AttachmentSchema()
resp = self.service.edit(self._base(resource.device_id), resource.id, json)
return self.service.decode(schema, resp) | python | def edit(self, resource): # pylint: disable=invalid-name,redefined-builtin
"""Edit a device's attachment.
:param resource: :class:`attachments.Attachment <attachments.Attachment>` object
:return: :class:`attachments.Attachment <attachments.Attachment>` object
:rtype: attachments.Attachment
"""
schema = AttachmentSchema(exclude=('id', 'created', 'updated', 'size', 'path', 'device_id'))
json = self.service.encode(schema, resource)
schema = AttachmentSchema()
resp = self.service.edit(self._base(resource.device_id), resource.id, json)
return self.service.decode(schema, resp) | [
"def",
"edit",
"(",
"self",
",",
"resource",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"schema",
"=",
"AttachmentSchema",
"(",
"exclude",
"=",
"(",
"'id'",
",",
"'created'",
",",
"'updated'",
",",
"'size'",
",",
"'path'",
",",
"'device_id'",
")",
")",
"json",
"=",
"self",
".",
"service",
".",
"encode",
"(",
"schema",
",",
"resource",
")",
"schema",
"=",
"AttachmentSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"edit",
"(",
"self",
".",
"_base",
"(",
"resource",
".",
"device_id",
")",
",",
"resource",
".",
"id",
",",
"json",
")",
"return",
"self",
".",
"service",
".",
"decode",
"(",
"schema",
",",
"resp",
")"
] | Edit a device's attachment.
:param resource: :class:`attachments.Attachment <attachments.Attachment>` object
:return: :class:`attachments.Attachment <attachments.Attachment>` object
:rtype: attachments.Attachment | [
"Edit",
"a",
"device",
"s",
"attachment",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/attachments.py#L156-L168 | train |
qacafe/cdrouter.py | cdrouter/attachments.py | AttachmentsService.delete | def delete(self, id, attid): # pylint: disable=invalid-name,redefined-builtin
"""Delete a device's attachment.
:param id: Device ID as an int.
:param attid: Attachment ID as an int.
"""
return self.service.edit(self._base(id), attid) | python | def delete(self, id, attid): # pylint: disable=invalid-name,redefined-builtin
"""Delete a device's attachment.
:param id: Device ID as an int.
:param attid: Attachment ID as an int.
"""
return self.service.edit(self._base(id), attid) | [
"def",
"delete",
"(",
"self",
",",
"id",
",",
"attid",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"return",
"self",
".",
"service",
".",
"edit",
"(",
"self",
".",
"_base",
"(",
"id",
")",
",",
"attid",
")"
] | Delete a device's attachment.
:param id: Device ID as an int.
:param attid: Attachment ID as an int. | [
"Delete",
"a",
"device",
"s",
"attachment",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/attachments.py#L170-L176 | train |
qacafe/cdrouter.py | cdrouter/devices.py | DevicesService.get_by_name | def get_by_name(self, name): # pylint: disable=invalid-name,redefined-builtin
"""Get a device by name.
:param name: Device name as string.
:return: :class:`devices.Device <devices.Device>` object
:rtype: devices.Device
"""
rs, _ = self.list(filter=field('name').eq(name), limit=1)
if len(rs) is 0:
raise CDRouterError('no such device')
return rs[0] | python | def get_by_name(self, name): # pylint: disable=invalid-name,redefined-builtin
"""Get a device by name.
:param name: Device name as string.
:return: :class:`devices.Device <devices.Device>` object
:rtype: devices.Device
"""
rs, _ = self.list(filter=field('name').eq(name), limit=1)
if len(rs) is 0:
raise CDRouterError('no such device')
return rs[0] | [
"def",
"get_by_name",
"(",
"self",
",",
"name",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"rs",
",",
"_",
"=",
"self",
".",
"list",
"(",
"filter",
"=",
"field",
"(",
"'name'",
")",
".",
"eq",
"(",
"name",
")",
",",
"limit",
"=",
"1",
")",
"if",
"len",
"(",
"rs",
")",
"is",
"0",
":",
"raise",
"CDRouterError",
"(",
"'no such device'",
")",
"return",
"rs",
"[",
"0",
"]"
] | Get a device by name.
:param name: Device name as string.
:return: :class:`devices.Device <devices.Device>` object
:rtype: devices.Device | [
"Get",
"a",
"device",
"by",
"name",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/devices.py#L229-L239 | train |
qacafe/cdrouter.py | cdrouter/devices.py | DevicesService.edit | def edit(self, resource):
"""Edit a device.
:param resource: :class:`devices.Device <devices.Device>` object
:return: :class:`devices.Device <devices.Device>` object
:rtype: devices.Device
"""
schema = DeviceSchema(exclude=('id', 'created', 'updated', 'result_id', 'attachments_dir'))
json = self.service.encode(schema, resource)
schema = DeviceSchema()
resp = self.service.edit(self.base, resource.id, json)
return self.service.decode(schema, resp) | python | def edit(self, resource):
"""Edit a device.
:param resource: :class:`devices.Device <devices.Device>` object
:return: :class:`devices.Device <devices.Device>` object
:rtype: devices.Device
"""
schema = DeviceSchema(exclude=('id', 'created', 'updated', 'result_id', 'attachments_dir'))
json = self.service.encode(schema, resource)
schema = DeviceSchema()
resp = self.service.edit(self.base, resource.id, json)
return self.service.decode(schema, resp) | [
"def",
"edit",
"(",
"self",
",",
"resource",
")",
":",
"schema",
"=",
"DeviceSchema",
"(",
"exclude",
"=",
"(",
"'id'",
",",
"'created'",
",",
"'updated'",
",",
"'result_id'",
",",
"'attachments_dir'",
")",
")",
"json",
"=",
"self",
".",
"service",
".",
"encode",
"(",
"schema",
",",
"resource",
")",
"schema",
"=",
"DeviceSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"edit",
"(",
"self",
".",
"base",
",",
"resource",
".",
"id",
",",
"json",
")",
"return",
"self",
".",
"service",
".",
"decode",
"(",
"schema",
",",
"resp",
")"
] | Edit a device.
:param resource: :class:`devices.Device <devices.Device>` object
:return: :class:`devices.Device <devices.Device>` object
:rtype: devices.Device | [
"Edit",
"a",
"device",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/devices.py#L255-L267 | train |
qacafe/cdrouter.py | cdrouter/devices.py | DevicesService.get_connection | def get_connection(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Get information on proxy connection to a device's management interface.
:param id: Device ID as an int.
:return: :class:`devices.Connection <devices.Connection>` object
:rtype: devices.Connection
"""
schema = ConnectionSchema()
resp = self.service.get(self.base+str(id)+'/connect/')
return self.service.decode(schema, resp) | python | def get_connection(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Get information on proxy connection to a device's management interface.
:param id: Device ID as an int.
:return: :class:`devices.Connection <devices.Connection>` object
:rtype: devices.Connection
"""
schema = ConnectionSchema()
resp = self.service.get(self.base+str(id)+'/connect/')
return self.service.decode(schema, resp) | [
"def",
"get_connection",
"(",
"self",
",",
"id",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"schema",
"=",
"ConnectionSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"get",
"(",
"self",
".",
"base",
"+",
"str",
"(",
"id",
")",
"+",
"'/connect/'",
")",
"return",
"self",
".",
"service",
".",
"decode",
"(",
"schema",
",",
"resp",
")"
] | Get information on proxy connection to a device's management interface.
:param id: Device ID as an int.
:return: :class:`devices.Connection <devices.Connection>` object
:rtype: devices.Connection | [
"Get",
"information",
"on",
"proxy",
"connection",
"to",
"a",
"device",
"s",
"management",
"interface",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/devices.py#L301-L310 | train |
qacafe/cdrouter.py | cdrouter/devices.py | DevicesService.connect | def connect(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Open proxy connection to a device's management interface.
:param id: Device ID as an int.
:return: :class:`devices.Connection <devices.Connection>` object
:rtype: devices.Connection
"""
schema = ConnectionSchema()
resp = self.service.post(self.base+str(id)+'/connect/')
return self.service.decode(schema, resp) | python | def connect(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Open proxy connection to a device's management interface.
:param id: Device ID as an int.
:return: :class:`devices.Connection <devices.Connection>` object
:rtype: devices.Connection
"""
schema = ConnectionSchema()
resp = self.service.post(self.base+str(id)+'/connect/')
return self.service.decode(schema, resp) | [
"def",
"connect",
"(",
"self",
",",
"id",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"schema",
"=",
"ConnectionSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"post",
"(",
"self",
".",
"base",
"+",
"str",
"(",
"id",
")",
"+",
"'/connect/'",
")",
"return",
"self",
".",
"service",
".",
"decode",
"(",
"schema",
",",
"resp",
")"
] | Open proxy connection to a device's management interface.
:param id: Device ID as an int.
:return: :class:`devices.Connection <devices.Connection>` object
:rtype: devices.Connection | [
"Open",
"proxy",
"connection",
"to",
"a",
"device",
"s",
"management",
"interface",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/devices.py#L312-L321 | train |
qacafe/cdrouter.py | cdrouter/devices.py | DevicesService.disconnect | def disconnect(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Close proxy connection to a device's management interface.
:param id: Device ID as an int.
"""
return self.service.post(self.base+str(id)+'/disconnect/') | python | def disconnect(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Close proxy connection to a device's management interface.
:param id: Device ID as an int.
"""
return self.service.post(self.base+str(id)+'/disconnect/') | [
"def",
"disconnect",
"(",
"self",
",",
"id",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"return",
"self",
".",
"service",
".",
"post",
"(",
"self",
".",
"base",
"+",
"str",
"(",
"id",
")",
"+",
"'/disconnect/'",
")"
] | Close proxy connection to a device's management interface.
:param id: Device ID as an int. | [
"Close",
"proxy",
"connection",
"to",
"a",
"device",
"s",
"management",
"interface",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/devices.py#L323-L328 | train |
qacafe/cdrouter.py | cdrouter/devices.py | DevicesService.power_on | def power_on(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Power on a device using it's power on command.
:param id: Device ID as an int.
:return: :class:`devices.PowerCmd <devices.PowerCmd>` object
:rtype: devices.PowerCmd
"""
schema = PowerCmdSchema()
resp = self.service.post(self.base+str(id)+'/power/on/')
return self.service.decode(schema, resp) | python | def power_on(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Power on a device using it's power on command.
:param id: Device ID as an int.
:return: :class:`devices.PowerCmd <devices.PowerCmd>` object
:rtype: devices.PowerCmd
"""
schema = PowerCmdSchema()
resp = self.service.post(self.base+str(id)+'/power/on/')
return self.service.decode(schema, resp) | [
"def",
"power_on",
"(",
"self",
",",
"id",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"schema",
"=",
"PowerCmdSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"post",
"(",
"self",
".",
"base",
"+",
"str",
"(",
"id",
")",
"+",
"'/power/on/'",
")",
"return",
"self",
".",
"service",
".",
"decode",
"(",
"schema",
",",
"resp",
")"
] | Power on a device using it's power on command.
:param id: Device ID as an int.
:return: :class:`devices.PowerCmd <devices.PowerCmd>` object
:rtype: devices.PowerCmd | [
"Power",
"on",
"a",
"device",
"using",
"it",
"s",
"power",
"on",
"command",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/devices.py#L330-L339 | train |
qacafe/cdrouter.py | cdrouter/devices.py | DevicesService.bulk_copy | def bulk_copy(self, ids):
"""Bulk copy a set of devices.
:param ids: Int list of device IDs.
:return: :class:`devices.Device <devices.Device>` list
"""
schema = DeviceSchema()
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) | python | def bulk_copy(self, ids):
"""Bulk copy a set of devices.
:param ids: Int list of device IDs.
:return: :class:`devices.Device <devices.Device>` list
"""
schema = DeviceSchema()
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) | [
"def",
"bulk_copy",
"(",
"self",
",",
"ids",
")",
":",
"schema",
"=",
"DeviceSchema",
"(",
")",
"return",
"self",
".",
"service",
".",
"bulk_copy",
"(",
"self",
".",
"base",
",",
"self",
".",
"RESOURCE",
",",
"ids",
",",
"schema",
")"
] | Bulk copy a set of devices.
:param ids: Int list of device IDs.
:return: :class:`devices.Device <devices.Device>` list | [
"Bulk",
"copy",
"a",
"set",
"of",
"devices",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/devices.py#L360-L367 | train |
ASMfreaK/yandex_weather_api | yandex_weather_api/types.py | ensure_list | def ensure_list(value: Union[T, Sequence[T]]) -> Sequence[T]:
"""Wrap value in list if it is not one."""
if value is None:
return []
return value if isinstance(value, list) else [value] | python | def ensure_list(value: Union[T, Sequence[T]]) -> Sequence[T]:
"""Wrap value in list if it is not one."""
if value is None:
return []
return value if isinstance(value, list) else [value] | [
"def",
"ensure_list",
"(",
"value",
":",
"Union",
"[",
"T",
",",
"Sequence",
"[",
"T",
"]",
"]",
")",
"->",
"Sequence",
"[",
"T",
"]",
":",
"if",
"value",
"is",
"None",
":",
"return",
"[",
"]",
"return",
"value",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
"else",
"[",
"value",
"]"
] | Wrap value in list if it is not one. | [
"Wrap",
"value",
"in",
"list",
"if",
"it",
"is",
"not",
"one",
"."
] | d58ad80f7389dc3b58c721bb42c2441e9ff3e351 | https://github.com/ASMfreaK/yandex_weather_api/blob/d58ad80f7389dc3b58c721bb42c2441e9ff3e351/yandex_weather_api/types.py#L28-L32 | train |
NetworkAutomation/jaide | jaide/color_utils.py | color | def color(out_string, color='grn'):
""" Highlight string for terminal color coding.
Purpose: We use this utility function to insert a ANSI/win32 color code
| and Bright style marker before a string, and reset the color and
| style after the string. We then return the string with these
| codes inserted.
@param out_string: the string to be colored
@type out_string: str
@param color: a string signifying which color to use. Defaults to 'grn'.
| Accepts the following colors:
| ['blk', 'blu', 'cyn', 'grn', 'mag', 'red', 'wht', 'yel']
@type color: str
@returns: the modified string, including the ANSI/win32 color codes.
@rtype: str
"""
c = {
'blk': Fore.BLACK,
'blu': Fore.BLUE,
'cyn': Fore.CYAN,
'grn': Fore.GREEN,
'mag': Fore.MAGENTA,
'red': Fore.RED,
'wht': Fore.WHITE,
'yel': Fore.YELLOW,
}
try:
init()
return (c[color] + Style.BRIGHT + out_string + Fore.RESET + Style.NORMAL)
except AttributeError:
return out_string | python | def color(out_string, color='grn'):
""" Highlight string for terminal color coding.
Purpose: We use this utility function to insert a ANSI/win32 color code
| and Bright style marker before a string, and reset the color and
| style after the string. We then return the string with these
| codes inserted.
@param out_string: the string to be colored
@type out_string: str
@param color: a string signifying which color to use. Defaults to 'grn'.
| Accepts the following colors:
| ['blk', 'blu', 'cyn', 'grn', 'mag', 'red', 'wht', 'yel']
@type color: str
@returns: the modified string, including the ANSI/win32 color codes.
@rtype: str
"""
c = {
'blk': Fore.BLACK,
'blu': Fore.BLUE,
'cyn': Fore.CYAN,
'grn': Fore.GREEN,
'mag': Fore.MAGENTA,
'red': Fore.RED,
'wht': Fore.WHITE,
'yel': Fore.YELLOW,
}
try:
init()
return (c[color] + Style.BRIGHT + out_string + Fore.RESET + Style.NORMAL)
except AttributeError:
return out_string | [
"def",
"color",
"(",
"out_string",
",",
"color",
"=",
"'grn'",
")",
":",
"c",
"=",
"{",
"'blk'",
":",
"Fore",
".",
"BLACK",
",",
"'blu'",
":",
"Fore",
".",
"BLUE",
",",
"'cyn'",
":",
"Fore",
".",
"CYAN",
",",
"'grn'",
":",
"Fore",
".",
"GREEN",
",",
"'mag'",
":",
"Fore",
".",
"MAGENTA",
",",
"'red'",
":",
"Fore",
".",
"RED",
",",
"'wht'",
":",
"Fore",
".",
"WHITE",
",",
"'yel'",
":",
"Fore",
".",
"YELLOW",
",",
"}",
"try",
":",
"init",
"(",
")",
"return",
"(",
"c",
"[",
"color",
"]",
"+",
"Style",
".",
"BRIGHT",
"+",
"out_string",
"+",
"Fore",
".",
"RESET",
"+",
"Style",
".",
"NORMAL",
")",
"except",
"AttributeError",
":",
"return",
"out_string"
] | Highlight string for terminal color coding.
Purpose: We use this utility function to insert a ANSI/win32 color code
| and Bright style marker before a string, and reset the color and
| style after the string. We then return the string with these
| codes inserted.
@param out_string: the string to be colored
@type out_string: str
@param color: a string signifying which color to use. Defaults to 'grn'.
| Accepts the following colors:
| ['blk', 'blu', 'cyn', 'grn', 'mag', 'red', 'wht', 'yel']
@type color: str
@returns: the modified string, including the ANSI/win32 color codes.
@rtype: str | [
"Highlight",
"string",
"for",
"terminal",
"color",
"coding",
"."
] | 8571b987a8c24c246dc09f1bcc11cb0f045ec33f | https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/color_utils.py#L6-L38 | train |
NetworkAutomation/jaide | jaide/color_utils.py | color_diffs | def color_diffs(string):
""" Add color ANSI codes for diff lines.
Purpose: Adds the ANSI/win32 color coding for terminal output to output
| produced from difflib.
@param string: The string to be replacing
@type string: str
@returns: The new string with ANSI codes injected.
@rtype: str
"""
string = string.replace('--- ', color('--- ', 'red'))
string = string.replace('\n+++ ', color('\n+++ '))
string = string.replace('\n-', color('\n-', 'red'))
string = string.replace('\n+', color('\n+'))
string = string.replace('\n@@ ', color('\n@@ ', 'yel'))
return string | python | def color_diffs(string):
""" Add color ANSI codes for diff lines.
Purpose: Adds the ANSI/win32 color coding for terminal output to output
| produced from difflib.
@param string: The string to be replacing
@type string: str
@returns: The new string with ANSI codes injected.
@rtype: str
"""
string = string.replace('--- ', color('--- ', 'red'))
string = string.replace('\n+++ ', color('\n+++ '))
string = string.replace('\n-', color('\n-', 'red'))
string = string.replace('\n+', color('\n+'))
string = string.replace('\n@@ ', color('\n@@ ', 'yel'))
return string | [
"def",
"color_diffs",
"(",
"string",
")",
":",
"string",
"=",
"string",
".",
"replace",
"(",
"'--- '",
",",
"color",
"(",
"'--- '",
",",
"'red'",
")",
")",
"string",
"=",
"string",
".",
"replace",
"(",
"'\\n+++ '",
",",
"color",
"(",
"'\\n+++ '",
")",
")",
"string",
"=",
"string",
".",
"replace",
"(",
"'\\n-'",
",",
"color",
"(",
"'\\n-'",
",",
"'red'",
")",
")",
"string",
"=",
"string",
".",
"replace",
"(",
"'\\n+'",
",",
"color",
"(",
"'\\n+'",
")",
")",
"string",
"=",
"string",
".",
"replace",
"(",
"'\\n@@ '",
",",
"color",
"(",
"'\\n@@ '",
",",
"'yel'",
")",
")",
"return",
"string"
] | Add color ANSI codes for diff lines.
Purpose: Adds the ANSI/win32 color coding for terminal output to output
| produced from difflib.
@param string: The string to be replacing
@type string: str
@returns: The new string with ANSI codes injected.
@rtype: str | [
"Add",
"color",
"ANSI",
"codes",
"for",
"diff",
"lines",
"."
] | 8571b987a8c24c246dc09f1bcc11cb0f045ec33f | https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/color_utils.py#L57-L74 | train |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/views/settings.py | index | def index():
"""List linked accounts."""
oauth = current_app.extensions['oauthlib.client']
services = []
service_map = {}
i = 0
for appid, conf in six.iteritems(
current_app.config['OAUTHCLIENT_REMOTE_APPS']):
if not conf.get('hide', False):
services.append(dict(
appid=appid,
title=conf['title'],
icon=conf.get('icon', None),
description=conf.get('description', None),
account=None
))
service_map[oauth.remote_apps[appid].consumer_key] = i
i += 1
# Fetch already linked accounts
accounts = RemoteAccount.query.filter_by(
user_id=current_user.get_id()
).all()
for a in accounts:
if a.client_id in service_map:
services[service_map[a.client_id]]['account'] = a
# Sort according to title
services.sort(key=itemgetter('title'))
return render_template(
'invenio_oauthclient/settings/index.html',
services=services
) | python | def index():
"""List linked accounts."""
oauth = current_app.extensions['oauthlib.client']
services = []
service_map = {}
i = 0
for appid, conf in six.iteritems(
current_app.config['OAUTHCLIENT_REMOTE_APPS']):
if not conf.get('hide', False):
services.append(dict(
appid=appid,
title=conf['title'],
icon=conf.get('icon', None),
description=conf.get('description', None),
account=None
))
service_map[oauth.remote_apps[appid].consumer_key] = i
i += 1
# Fetch already linked accounts
accounts = RemoteAccount.query.filter_by(
user_id=current_user.get_id()
).all()
for a in accounts:
if a.client_id in service_map:
services[service_map[a.client_id]]['account'] = a
# Sort according to title
services.sort(key=itemgetter('title'))
return render_template(
'invenio_oauthclient/settings/index.html',
services=services
) | [
"def",
"index",
"(",
")",
":",
"oauth",
"=",
"current_app",
".",
"extensions",
"[",
"'oauthlib.client'",
"]",
"services",
"=",
"[",
"]",
"service_map",
"=",
"{",
"}",
"i",
"=",
"0",
"for",
"appid",
",",
"conf",
"in",
"six",
".",
"iteritems",
"(",
"current_app",
".",
"config",
"[",
"'OAUTHCLIENT_REMOTE_APPS'",
"]",
")",
":",
"if",
"not",
"conf",
".",
"get",
"(",
"'hide'",
",",
"False",
")",
":",
"services",
".",
"append",
"(",
"dict",
"(",
"appid",
"=",
"appid",
",",
"title",
"=",
"conf",
"[",
"'title'",
"]",
",",
"icon",
"=",
"conf",
".",
"get",
"(",
"'icon'",
",",
"None",
")",
",",
"description",
"=",
"conf",
".",
"get",
"(",
"'description'",
",",
"None",
")",
",",
"account",
"=",
"None",
")",
")",
"service_map",
"[",
"oauth",
".",
"remote_apps",
"[",
"appid",
"]",
".",
"consumer_key",
"]",
"=",
"i",
"i",
"+=",
"1",
"# Fetch already linked accounts",
"accounts",
"=",
"RemoteAccount",
".",
"query",
".",
"filter_by",
"(",
"user_id",
"=",
"current_user",
".",
"get_id",
"(",
")",
")",
".",
"all",
"(",
")",
"for",
"a",
"in",
"accounts",
":",
"if",
"a",
".",
"client_id",
"in",
"service_map",
":",
"services",
"[",
"service_map",
"[",
"a",
".",
"client_id",
"]",
"]",
"[",
"'account'",
"]",
"=",
"a",
"# Sort according to title",
"services",
".",
"sort",
"(",
"key",
"=",
"itemgetter",
"(",
"'title'",
")",
")",
"return",
"render_template",
"(",
"'invenio_oauthclient/settings/index.html'",
",",
"services",
"=",
"services",
")"
] | List linked accounts. | [
"List",
"linked",
"accounts",
"."
] | 2500dc6935738107617aeade79e050d7608004bb | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/views/settings.py#L47-L83 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/util.py | element_id_by_label | def element_id_by_label(browser, label):
"""Return the id of a label's for attribute"""
label = XPathSelector(browser,
unicode('//label[contains(., "%s")]' % label))
if not label:
return False
return label.get_attribute('for') | python | def element_id_by_label(browser, label):
"""Return the id of a label's for attribute"""
label = XPathSelector(browser,
unicode('//label[contains(., "%s")]' % label))
if not label:
return False
return label.get_attribute('for') | [
"def",
"element_id_by_label",
"(",
"browser",
",",
"label",
")",
":",
"label",
"=",
"XPathSelector",
"(",
"browser",
",",
"unicode",
"(",
"'//label[contains(., \"%s\")]'",
"%",
"label",
")",
")",
"if",
"not",
"label",
":",
"return",
"False",
"return",
"label",
".",
"get_attribute",
"(",
"'for'",
")"
] | Return the id of a label's for attribute | [
"Return",
"the",
"id",
"of",
"a",
"label",
"s",
"for",
"attribute"
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/util.py#L141-L147 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/util.py | find_field | def find_field(browser, field, value):
"""Locate an input field of a given value
This first looks for the value as the id of the element, then
the name of the element, then a label for the element.
"""
return find_field_by_id(browser, field, value) + \
find_field_by_name(browser, field, value) + \
find_field_by_label(browser, field, value) | python | def find_field(browser, field, value):
"""Locate an input field of a given value
This first looks for the value as the id of the element, then
the name of the element, then a label for the element.
"""
return find_field_by_id(browser, field, value) + \
find_field_by_name(browser, field, value) + \
find_field_by_label(browser, field, value) | [
"def",
"find_field",
"(",
"browser",
",",
"field",
",",
"value",
")",
":",
"return",
"find_field_by_id",
"(",
"browser",
",",
"field",
",",
"value",
")",
"+",
"find_field_by_name",
"(",
"browser",
",",
"field",
",",
"value",
")",
"+",
"find_field_by_label",
"(",
"browser",
",",
"field",
",",
"value",
")"
] | Locate an input field of a given value
This first looks for the value as the id of the element, then
the name of the element, then a label for the element. | [
"Locate",
"an",
"input",
"field",
"of",
"a",
"given",
"value"
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/util.py#L197-L206 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/util.py | find_any_field | def find_any_field(browser, field_types, field_name):
"""
Find a field of any of the specified types.
"""
return reduce(
operator.add,
(find_field(browser, field_type, field_name)
for field_type in field_types)
) | python | def find_any_field(browser, field_types, field_name):
"""
Find a field of any of the specified types.
"""
return reduce(
operator.add,
(find_field(browser, field_type, field_name)
for field_type in field_types)
) | [
"def",
"find_any_field",
"(",
"browser",
",",
"field_types",
",",
"field_name",
")",
":",
"return",
"reduce",
"(",
"operator",
".",
"add",
",",
"(",
"find_field",
"(",
"browser",
",",
"field_type",
",",
"field_name",
")",
"for",
"field_type",
"in",
"field_types",
")",
")"
] | Find a field of any of the specified types. | [
"Find",
"a",
"field",
"of",
"any",
"of",
"the",
"specified",
"types",
"."
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/util.py#L209-L218 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/util.py | find_field_by_label | def find_field_by_label(browser, field, label):
"""Locate the control input that has a label pointing to it
This will first locate the label element that has a label of the given
name. It then pulls the id out of the 'for' attribute, and uses it to
locate the element by its id.
"""
return XPathSelector(browser,
field_xpath(field, 'id', escape=False) %
u'//label[contains(., "{0}")]/@for'.format(label)) | python | def find_field_by_label(browser, field, label):
"""Locate the control input that has a label pointing to it
This will first locate the label element that has a label of the given
name. It then pulls the id out of the 'for' attribute, and uses it to
locate the element by its id.
"""
return XPathSelector(browser,
field_xpath(field, 'id', escape=False) %
u'//label[contains(., "{0}")]/@for'.format(label)) | [
"def",
"find_field_by_label",
"(",
"browser",
",",
"field",
",",
"label",
")",
":",
"return",
"XPathSelector",
"(",
"browser",
",",
"field_xpath",
"(",
"field",
",",
"'id'",
",",
"escape",
"=",
"False",
")",
"%",
"u'//label[contains(., \"{0}\")]/@for'",
".",
"format",
"(",
"label",
")",
")"
] | Locate the control input that has a label pointing to it
This will first locate the label element that has a label of the given
name. It then pulls the id out of the 'for' attribute, and uses it to
locate the element by its id. | [
"Locate",
"the",
"control",
"input",
"that",
"has",
"a",
"label",
"pointing",
"to",
"it"
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/util.py#L246-L257 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/util.py | wait_for | def wait_for(func):
"""
A decorator to invoke a function periodically until it returns a truthy
value.
"""
def wrapped(*args, **kwargs):
timeout = kwargs.pop('timeout', 15)
start = time()
result = None
while time() - start < timeout:
result = func(*args, **kwargs)
if result:
break
sleep(0.2)
return result
return wrapped | python | def wait_for(func):
"""
A decorator to invoke a function periodically until it returns a truthy
value.
"""
def wrapped(*args, **kwargs):
timeout = kwargs.pop('timeout', 15)
start = time()
result = None
while time() - start < timeout:
result = func(*args, **kwargs)
if result:
break
sleep(0.2)
return result
return wrapped | [
"def",
"wait_for",
"(",
"func",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"15",
")",
"start",
"=",
"time",
"(",
")",
"result",
"=",
"None",
"while",
"time",
"(",
")",
"-",
"start",
"<",
"timeout",
":",
"result",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"result",
":",
"break",
"sleep",
"(",
"0.2",
")",
"return",
"result",
"return",
"wrapped"
] | A decorator to invoke a function periodically until it returns a truthy
value. | [
"A",
"decorator",
"to",
"invoke",
"a",
"function",
"periodically",
"until",
"it",
"returns",
"a",
"truthy",
"value",
"."
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/util.py#L278-L298 | train |
mcieslik-mctp/papy | src/papy/util/config.py | get_defaults | def get_defaults():
"""
Returns a dictionary of variables and their possibly os-dependent defaults.
"""
DEFAULTS = {}
# Determine the run-time pipe read/write buffer.
if 'PC_PIPE_BUF' in os.pathconf_names:
# unix
x, y = os.pipe()
DEFAULTS['PIPE_BUF'] = os.fpathconf(x, "PC_PIPE_BUF")
else:
# in Jython 16384
# on windows 512
# in jython in windows 512
DEFAULTS['PIPE_BUF'] = 512
# Determine the run-time socket buffers.
# Note that this number is determine on the papy server
# and inherited by the clients.
tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
DEFAULTS['TCP_SNDBUF'] = tcp_sock.getsockopt(socket.SOL_SOCKET, \
socket.SO_SNDBUF)
DEFAULTS['TCP_RCVBUF'] = tcp_sock.getsockopt(socket.SOL_SOCKET, \
socket.SO_RCVBUF)
udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
DEFAULTS['UDP_SNDBUF'] = udp_sock.getsockopt(socket.SOL_SOCKET, \
socket.SO_SNDBUF)
DEFAULTS['UDP_RCVBUF'] = udp_sock.getsockopt(socket.SOL_SOCKET, \
socket.SO_RCVBUF)
# check the ip visible from the world.
DEFAULTS['WHATS_MYIP_URL'] = \
'http://www.whatismyip.com/automation/n09230945.asp'
return DEFAULTS | python | def get_defaults():
"""
Returns a dictionary of variables and their possibly os-dependent defaults.
"""
DEFAULTS = {}
# Determine the run-time pipe read/write buffer.
if 'PC_PIPE_BUF' in os.pathconf_names:
# unix
x, y = os.pipe()
DEFAULTS['PIPE_BUF'] = os.fpathconf(x, "PC_PIPE_BUF")
else:
# in Jython 16384
# on windows 512
# in jython in windows 512
DEFAULTS['PIPE_BUF'] = 512
# Determine the run-time socket buffers.
# Note that this number is determine on the papy server
# and inherited by the clients.
tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
DEFAULTS['TCP_SNDBUF'] = tcp_sock.getsockopt(socket.SOL_SOCKET, \
socket.SO_SNDBUF)
DEFAULTS['TCP_RCVBUF'] = tcp_sock.getsockopt(socket.SOL_SOCKET, \
socket.SO_RCVBUF)
udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
DEFAULTS['UDP_SNDBUF'] = udp_sock.getsockopt(socket.SOL_SOCKET, \
socket.SO_SNDBUF)
DEFAULTS['UDP_RCVBUF'] = udp_sock.getsockopt(socket.SOL_SOCKET, \
socket.SO_RCVBUF)
# check the ip visible from the world.
DEFAULTS['WHATS_MYIP_URL'] = \
'http://www.whatismyip.com/automation/n09230945.asp'
return DEFAULTS | [
"def",
"get_defaults",
"(",
")",
":",
"DEFAULTS",
"=",
"{",
"}",
"# Determine the run-time pipe read/write buffer.",
"if",
"'PC_PIPE_BUF'",
"in",
"os",
".",
"pathconf_names",
":",
"# unix",
"x",
",",
"y",
"=",
"os",
".",
"pipe",
"(",
")",
"DEFAULTS",
"[",
"'PIPE_BUF'",
"]",
"=",
"os",
".",
"fpathconf",
"(",
"x",
",",
"\"PC_PIPE_BUF\"",
")",
"else",
":",
"# in Jython 16384",
"# on windows 512",
"# in jython in windows 512",
"DEFAULTS",
"[",
"'PIPE_BUF'",
"]",
"=",
"512",
"# Determine the run-time socket buffers.",
"# Note that this number is determine on the papy server",
"# and inherited by the clients.",
"tcp_sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"DEFAULTS",
"[",
"'TCP_SNDBUF'",
"]",
"=",
"tcp_sock",
".",
"getsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_SNDBUF",
")",
"DEFAULTS",
"[",
"'TCP_RCVBUF'",
"]",
"=",
"tcp_sock",
".",
"getsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_RCVBUF",
")",
"udp_sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"DEFAULTS",
"[",
"'UDP_SNDBUF'",
"]",
"=",
"udp_sock",
".",
"getsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_SNDBUF",
")",
"DEFAULTS",
"[",
"'UDP_RCVBUF'",
"]",
"=",
"udp_sock",
".",
"getsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_RCVBUF",
")",
"# check the ip visible from the world.",
"DEFAULTS",
"[",
"'WHATS_MYIP_URL'",
"]",
"=",
"'http://www.whatismyip.com/automation/n09230945.asp'",
"return",
"DEFAULTS"
] | Returns a dictionary of variables and their possibly os-dependent defaults. | [
"Returns",
"a",
"dictionary",
"of",
"variables",
"and",
"their",
"possibly",
"os",
"-",
"dependent",
"defaults",
"."
] | 708e50827b5db46bbea081982cb74b9b0e464064 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/util/config.py#L16-L50 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/django.py | site_url | def site_url(url):
"""
Determine the server URL.
"""
base_url = 'http://%s' % socket.gethostname()
if server.port is not 80:
base_url += ':%d' % server.port
return urlparse.urljoin(base_url, url) | python | def site_url(url):
"""
Determine the server URL.
"""
base_url = 'http://%s' % socket.gethostname()
if server.port is not 80:
base_url += ':%d' % server.port
return urlparse.urljoin(base_url, url) | [
"def",
"site_url",
"(",
"url",
")",
":",
"base_url",
"=",
"'http://%s'",
"%",
"socket",
".",
"gethostname",
"(",
")",
"if",
"server",
".",
"port",
"is",
"not",
"80",
":",
"base_url",
"+=",
"':%d'",
"%",
"server",
".",
"port",
"return",
"urlparse",
".",
"urljoin",
"(",
"base_url",
",",
"url",
")"
] | Determine the server URL. | [
"Determine",
"the",
"server",
"URL",
"."
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/django.py#L15-L24 | train |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/utils.py | _get_external_id | def _get_external_id(account_info):
"""Get external id from account info."""
if all(k in account_info for k in ('external_id', 'external_method')):
return dict(id=account_info['external_id'],
method=account_info['external_method'])
return None | python | def _get_external_id(account_info):
"""Get external id from account info."""
if all(k in account_info for k in ('external_id', 'external_method')):
return dict(id=account_info['external_id'],
method=account_info['external_method'])
return None | [
"def",
"_get_external_id",
"(",
"account_info",
")",
":",
"if",
"all",
"(",
"k",
"in",
"account_info",
"for",
"k",
"in",
"(",
"'external_id'",
",",
"'external_method'",
")",
")",
":",
"return",
"dict",
"(",
"id",
"=",
"account_info",
"[",
"'external_id'",
"]",
",",
"method",
"=",
"account_info",
"[",
"'external_method'",
"]",
")",
"return",
"None"
] | Get external id from account info. | [
"Get",
"external",
"id",
"from",
"account",
"info",
"."
] | 2500dc6935738107617aeade79e050d7608004bb | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/utils.py#L40-L45 | train |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/utils.py | oauth_get_user | def oauth_get_user(client_id, account_info=None, access_token=None):
"""Retrieve user object for the given request.
Uses either the access token or extracted account information to retrieve
the user object.
:param client_id: The client id.
:param account_info: The dictionary with the account info.
(Default: ``None``)
:param access_token: The access token. (Default: ``None``)
:returns: A :class:`invenio_accounts.models.User` instance or ``None``.
"""
if access_token:
token = RemoteToken.get_by_token(client_id, access_token)
if token:
return token.remote_account.user
if account_info:
external_id = _get_external_id(account_info)
if external_id:
user_identity = UserIdentity.query.filter_by(
id=external_id['id'], method=external_id['method']).first()
if user_identity:
return user_identity.user
email = account_info.get('user', {}).get('email')
if email:
return User.query.filter_by(email=email).one_or_none()
return None | python | def oauth_get_user(client_id, account_info=None, access_token=None):
"""Retrieve user object for the given request.
Uses either the access token or extracted account information to retrieve
the user object.
:param client_id: The client id.
:param account_info: The dictionary with the account info.
(Default: ``None``)
:param access_token: The access token. (Default: ``None``)
:returns: A :class:`invenio_accounts.models.User` instance or ``None``.
"""
if access_token:
token = RemoteToken.get_by_token(client_id, access_token)
if token:
return token.remote_account.user
if account_info:
external_id = _get_external_id(account_info)
if external_id:
user_identity = UserIdentity.query.filter_by(
id=external_id['id'], method=external_id['method']).first()
if user_identity:
return user_identity.user
email = account_info.get('user', {}).get('email')
if email:
return User.query.filter_by(email=email).one_or_none()
return None | [
"def",
"oauth_get_user",
"(",
"client_id",
",",
"account_info",
"=",
"None",
",",
"access_token",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"token",
"=",
"RemoteToken",
".",
"get_by_token",
"(",
"client_id",
",",
"access_token",
")",
"if",
"token",
":",
"return",
"token",
".",
"remote_account",
".",
"user",
"if",
"account_info",
":",
"external_id",
"=",
"_get_external_id",
"(",
"account_info",
")",
"if",
"external_id",
":",
"user_identity",
"=",
"UserIdentity",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"external_id",
"[",
"'id'",
"]",
",",
"method",
"=",
"external_id",
"[",
"'method'",
"]",
")",
".",
"first",
"(",
")",
"if",
"user_identity",
":",
"return",
"user_identity",
".",
"user",
"email",
"=",
"account_info",
".",
"get",
"(",
"'user'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'email'",
")",
"if",
"email",
":",
"return",
"User",
".",
"query",
".",
"filter_by",
"(",
"email",
"=",
"email",
")",
".",
"one_or_none",
"(",
")",
"return",
"None"
] | Retrieve user object for the given request.
Uses either the access token or extracted account information to retrieve
the user object.
:param client_id: The client id.
:param account_info: The dictionary with the account info.
(Default: ``None``)
:param access_token: The access token. (Default: ``None``)
:returns: A :class:`invenio_accounts.models.User` instance or ``None``. | [
"Retrieve",
"user",
"object",
"for",
"the",
"given",
"request",
"."
] | 2500dc6935738107617aeade79e050d7608004bb | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/utils.py#L48-L75 | train |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/utils.py | oauth_authenticate | def oauth_authenticate(client_id, user, require_existing_link=False):
"""Authenticate an oauth authorized callback.
:param client_id: The client id.
:param user: A user instance.
:param require_existing_link: If ``True``, check if remote account exists.
(Default: ``False``)
:returns: ``True`` if the user is successfully authenticated.
"""
# Authenticate via the access token (access token used to get user_id)
if not requires_confirmation(user):
after_this_request(_commit)
if login_user(user, remember=False):
if require_existing_link:
account = RemoteAccount.get(user.id, client_id)
if account is None:
logout_user()
return False
return True
return False | python | def oauth_authenticate(client_id, user, require_existing_link=False):
"""Authenticate an oauth authorized callback.
:param client_id: The client id.
:param user: A user instance.
:param require_existing_link: If ``True``, check if remote account exists.
(Default: ``False``)
:returns: ``True`` if the user is successfully authenticated.
"""
# Authenticate via the access token (access token used to get user_id)
if not requires_confirmation(user):
after_this_request(_commit)
if login_user(user, remember=False):
if require_existing_link:
account = RemoteAccount.get(user.id, client_id)
if account is None:
logout_user()
return False
return True
return False | [
"def",
"oauth_authenticate",
"(",
"client_id",
",",
"user",
",",
"require_existing_link",
"=",
"False",
")",
":",
"# Authenticate via the access token (access token used to get user_id)",
"if",
"not",
"requires_confirmation",
"(",
"user",
")",
":",
"after_this_request",
"(",
"_commit",
")",
"if",
"login_user",
"(",
"user",
",",
"remember",
"=",
"False",
")",
":",
"if",
"require_existing_link",
":",
"account",
"=",
"RemoteAccount",
".",
"get",
"(",
"user",
".",
"id",
",",
"client_id",
")",
"if",
"account",
"is",
"None",
":",
"logout_user",
"(",
")",
"return",
"False",
"return",
"True",
"return",
"False"
] | Authenticate an oauth authorized callback.
:param client_id: The client id.
:param user: A user instance.
:param require_existing_link: If ``True``, check if remote account exists.
(Default: ``False``)
:returns: ``True`` if the user is successfully authenticated. | [
"Authenticate",
"an",
"oauth",
"authorized",
"callback",
"."
] | 2500dc6935738107617aeade79e050d7608004bb | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/utils.py#L78-L97 | train |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/utils.py | oauth_register | def oauth_register(form):
"""Register user if possible.
:param form: A form instance.
:returns: A :class:`invenio_accounts.models.User` instance.
"""
if form.validate():
data = form.to_dict()
if not data.get('password'):
data['password'] = ''
user = register_user(**data)
if not data['password']:
user.password = None
_datastore.commit()
return user | python | def oauth_register(form):
"""Register user if possible.
:param form: A form instance.
:returns: A :class:`invenio_accounts.models.User` instance.
"""
if form.validate():
data = form.to_dict()
if not data.get('password'):
data['password'] = ''
user = register_user(**data)
if not data['password']:
user.password = None
_datastore.commit()
return user | [
"def",
"oauth_register",
"(",
"form",
")",
":",
"if",
"form",
".",
"validate",
"(",
")",
":",
"data",
"=",
"form",
".",
"to_dict",
"(",
")",
"if",
"not",
"data",
".",
"get",
"(",
"'password'",
")",
":",
"data",
"[",
"'password'",
"]",
"=",
"''",
"user",
"=",
"register_user",
"(",
"*",
"*",
"data",
")",
"if",
"not",
"data",
"[",
"'password'",
"]",
":",
"user",
".",
"password",
"=",
"None",
"_datastore",
".",
"commit",
"(",
")",
"return",
"user"
] | Register user if possible.
:param form: A form instance.
:returns: A :class:`invenio_accounts.models.User` instance. | [
"Register",
"user",
"if",
"possible",
"."
] | 2500dc6935738107617aeade79e050d7608004bb | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/utils.py#L100-L114 | train |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/utils.py | oauth_link_external_id | def oauth_link_external_id(user, external_id=None):
"""Link a user to an external id.
:param user: A :class:`invenio_accounts.models.User` instance.
:param external_id: The external id associated with the user.
(Default: ``None``)
:raises invenio_oauthclient.errors.AlreadyLinkedError: Raised if already
exists a link.
"""
try:
with db.session.begin_nested():
db.session.add(UserIdentity(
id=external_id['id'],
method=external_id['method'],
id_user=user.id
))
except IntegrityError:
raise AlreadyLinkedError(user, external_id) | python | def oauth_link_external_id(user, external_id=None):
"""Link a user to an external id.
:param user: A :class:`invenio_accounts.models.User` instance.
:param external_id: The external id associated with the user.
(Default: ``None``)
:raises invenio_oauthclient.errors.AlreadyLinkedError: Raised if already
exists a link.
"""
try:
with db.session.begin_nested():
db.session.add(UserIdentity(
id=external_id['id'],
method=external_id['method'],
id_user=user.id
))
except IntegrityError:
raise AlreadyLinkedError(user, external_id) | [
"def",
"oauth_link_external_id",
"(",
"user",
",",
"external_id",
"=",
"None",
")",
":",
"try",
":",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"db",
".",
"session",
".",
"add",
"(",
"UserIdentity",
"(",
"id",
"=",
"external_id",
"[",
"'id'",
"]",
",",
"method",
"=",
"external_id",
"[",
"'method'",
"]",
",",
"id_user",
"=",
"user",
".",
"id",
")",
")",
"except",
"IntegrityError",
":",
"raise",
"AlreadyLinkedError",
"(",
"user",
",",
"external_id",
")"
] | Link a user to an external id.
:param user: A :class:`invenio_accounts.models.User` instance.
:param external_id: The external id associated with the user.
(Default: ``None``)
:raises invenio_oauthclient.errors.AlreadyLinkedError: Raised if already
exists a link. | [
"Link",
"a",
"user",
"to",
"an",
"external",
"id",
"."
] | 2500dc6935738107617aeade79e050d7608004bb | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/utils.py#L117-L134 | train |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/utils.py | oauth_unlink_external_id | def oauth_unlink_external_id(external_id):
"""Unlink a user from an external id.
:param external_id: The external id associated with the user.
"""
with db.session.begin_nested():
UserIdentity.query.filter_by(id=external_id['id'],
method=external_id['method']).delete() | python | def oauth_unlink_external_id(external_id):
"""Unlink a user from an external id.
:param external_id: The external id associated with the user.
"""
with db.session.begin_nested():
UserIdentity.query.filter_by(id=external_id['id'],
method=external_id['method']).delete() | [
"def",
"oauth_unlink_external_id",
"(",
"external_id",
")",
":",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"UserIdentity",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"external_id",
"[",
"'id'",
"]",
",",
"method",
"=",
"external_id",
"[",
"'method'",
"]",
")",
".",
"delete",
"(",
")"
] | Unlink a user from an external id.
:param external_id: The external id associated with the user. | [
"Unlink",
"a",
"user",
"from",
"an",
"external",
"id",
"."
] | 2500dc6935738107617aeade79e050d7608004bb | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/utils.py#L137-L144 | train |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/utils.py | create_registrationform | def create_registrationform(*args, **kwargs):
"""Make a registration form."""
class RegistrationForm(_security.confirm_register_form):
password = None
recaptcha = None
return RegistrationForm(*args, **kwargs) | python | def create_registrationform(*args, **kwargs):
"""Make a registration form."""
class RegistrationForm(_security.confirm_register_form):
password = None
recaptcha = None
return RegistrationForm(*args, **kwargs) | [
"def",
"create_registrationform",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"class",
"RegistrationForm",
"(",
"_security",
".",
"confirm_register_form",
")",
":",
"password",
"=",
"None",
"recaptcha",
"=",
"None",
"return",
"RegistrationForm",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Make a registration form. | [
"Make",
"a",
"registration",
"form",
"."
] | 2500dc6935738107617aeade79e050d7608004bb | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/utils.py#L184-L189 | train |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/utils.py | fill_form | def fill_form(form, data):
"""Prefill form with data.
:param form: The form to fill.
:param data: The data to insert in the form.
:returns: A pre-filled form.
"""
for (key, value) in data.items():
if hasattr(form, key):
if isinstance(value, dict):
fill_form(getattr(form, key), value)
else:
getattr(form, key).data = value
return form | python | def fill_form(form, data):
"""Prefill form with data.
:param form: The form to fill.
:param data: The data to insert in the form.
:returns: A pre-filled form.
"""
for (key, value) in data.items():
if hasattr(form, key):
if isinstance(value, dict):
fill_form(getattr(form, key), value)
else:
getattr(form, key).data = value
return form | [
"def",
"fill_form",
"(",
"form",
",",
"data",
")",
":",
"for",
"(",
"key",
",",
"value",
")",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"form",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"fill_form",
"(",
"getattr",
"(",
"form",
",",
"key",
")",
",",
"value",
")",
"else",
":",
"getattr",
"(",
"form",
",",
"key",
")",
".",
"data",
"=",
"value",
"return",
"form"
] | Prefill form with data.
:param form: The form to fill.
:param data: The data to insert in the form.
:returns: A pre-filled form. | [
"Prefill",
"form",
"with",
"data",
"."
] | 2500dc6935738107617aeade79e050d7608004bb | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/utils.py#L197-L210 | train |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/utils.py | _get_csrf_disabled_param | def _get_csrf_disabled_param():
"""Return the right param to disable CSRF depending on WTF-Form version.
From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of
`meta={csrf: True/False}`.
"""
import flask_wtf
from pkg_resources import parse_version
supports_meta = parse_version(flask_wtf.__version__) >= parse_version(
"0.14.0")
return dict(meta={'csrf': False}) if supports_meta else \
dict(csrf_enabled=False) | python | def _get_csrf_disabled_param():
"""Return the right param to disable CSRF depending on WTF-Form version.
From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of
`meta={csrf: True/False}`.
"""
import flask_wtf
from pkg_resources import parse_version
supports_meta = parse_version(flask_wtf.__version__) >= parse_version(
"0.14.0")
return dict(meta={'csrf': False}) if supports_meta else \
dict(csrf_enabled=False) | [
"def",
"_get_csrf_disabled_param",
"(",
")",
":",
"import",
"flask_wtf",
"from",
"pkg_resources",
"import",
"parse_version",
"supports_meta",
"=",
"parse_version",
"(",
"flask_wtf",
".",
"__version__",
")",
">=",
"parse_version",
"(",
"\"0.14.0\"",
")",
"return",
"dict",
"(",
"meta",
"=",
"{",
"'csrf'",
":",
"False",
"}",
")",
"if",
"supports_meta",
"else",
"dict",
"(",
"csrf_enabled",
"=",
"False",
")"
] | Return the right param to disable CSRF depending on WTF-Form version.
From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of
`meta={csrf: True/False}`. | [
"Return",
"the",
"right",
"param",
"to",
"disable",
"CSRF",
"depending",
"on",
"WTF",
"-",
"Form",
"version",
"."
] | 2500dc6935738107617aeade79e050d7608004bb | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/utils.py#L224-L235 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/parallel_runner.py | ParallelRunner.run | def run(self):
""" Find and load step definitions, and them find and load
features under `base_path` specified on constructor
"""
try:
self.loader.find_and_load_step_definitions()
except StepLoadingError, e:
print "Error loading step definitions:\n", e
return
results = []
if self.explicit_features:
features_files = self.explicit_features
else:
features_files = self.loader.find_feature_files()
if self.random:
random.shuffle(features_files)
if not features_files:
self.output.print_no_features_found(self.loader.base_dir)
return
processes = Pool(processes=self.parallelization)
test_results_it = processes.imap_unordered(
worker_process, [(self, filename) for filename in features_files]
)
all_total = ParallelTotalResult()
for result in test_results_it:
all_total += result['total']
sys.stdout.write(result['stdout'])
sys.stderr.write(result['stderr'])
return all_total | python | def run(self):
""" Find and load step definitions, and them find and load
features under `base_path` specified on constructor
"""
try:
self.loader.find_and_load_step_definitions()
except StepLoadingError, e:
print "Error loading step definitions:\n", e
return
results = []
if self.explicit_features:
features_files = self.explicit_features
else:
features_files = self.loader.find_feature_files()
if self.random:
random.shuffle(features_files)
if not features_files:
self.output.print_no_features_found(self.loader.base_dir)
return
processes = Pool(processes=self.parallelization)
test_results_it = processes.imap_unordered(
worker_process, [(self, filename) for filename in features_files]
)
all_total = ParallelTotalResult()
for result in test_results_it:
all_total += result['total']
sys.stdout.write(result['stdout'])
sys.stderr.write(result['stderr'])
return all_total | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"loader",
".",
"find_and_load_step_definitions",
"(",
")",
"except",
"StepLoadingError",
",",
"e",
":",
"print",
"\"Error loading step definitions:\\n\"",
",",
"e",
"return",
"results",
"=",
"[",
"]",
"if",
"self",
".",
"explicit_features",
":",
"features_files",
"=",
"self",
".",
"explicit_features",
"else",
":",
"features_files",
"=",
"self",
".",
"loader",
".",
"find_feature_files",
"(",
")",
"if",
"self",
".",
"random",
":",
"random",
".",
"shuffle",
"(",
"features_files",
")",
"if",
"not",
"features_files",
":",
"self",
".",
"output",
".",
"print_no_features_found",
"(",
"self",
".",
"loader",
".",
"base_dir",
")",
"return",
"processes",
"=",
"Pool",
"(",
"processes",
"=",
"self",
".",
"parallelization",
")",
"test_results_it",
"=",
"processes",
".",
"imap_unordered",
"(",
"worker_process",
",",
"[",
"(",
"self",
",",
"filename",
")",
"for",
"filename",
"in",
"features_files",
"]",
")",
"all_total",
"=",
"ParallelTotalResult",
"(",
")",
"for",
"result",
"in",
"test_results_it",
":",
"all_total",
"+=",
"result",
"[",
"'total'",
"]",
"sys",
".",
"stdout",
".",
"write",
"(",
"result",
"[",
"'stdout'",
"]",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"result",
"[",
"'stderr'",
"]",
")",
"return",
"all_total"
] | Find and load step definitions, and them find and load
features under `base_path` specified on constructor | [
"Find",
"and",
"load",
"step",
"definitions",
"and",
"them",
"find",
"and",
"load",
"features",
"under",
"base_path",
"specified",
"on",
"constructor"
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/parallel_runner.py#L107-L140 | train |
NetworkAutomation/jaide | jaide/wrap.py | open_connection | def open_connection(ip, username, password, function, args, write=False,
conn_timeout=5, sess_timeout=300, port=22):
""" Open a Jaide session with the device.
To open a Jaide session to the device, and run the appropriate function
against the device. Arguments for the downstream function are passed
through.
@param ip: String of the IP or hostname of the device to connect to.
@type ip: str
@param username: The string username used to connect to the device.
@type useranme: str
@param password: The string password used to connect to the device.
@type password: str
@param function: The downstream jaide.wrap function we'll be handing
| off the jaide.Jaide() object to execute the command
| once we've established the connection.
@type function: function pointer.
@param args: The arguments that we will hand off to the downstream
| function.
@type args: list
@param write: If set, it would be a tuple that we pass back as part of
| our return statement, so that any callback function
| can know how and where to put the output from the device.
@type write: False or tuple.
@param conn_timeout: Sets the connection timeout value. This is how
| we'll wait when connecting before classifying
| the device unreachable.
@type conn_timeout: int
@param sess_timeout: Sets the session timeout value. A higher value may
| be desired for long running commands, such as
| 'request system snapshot slice alternate'
@type sess_timeout: int
@param port: The port to connect to the device on. Defaults to 22.
@type port: int
@returns: We could return either just a string of the output from the
| device, or a tuple containing the information needed to write
| to a file and the string output from the device.
@rtype: Tuple or str
"""
# start with the header line on the output.
output = color('=' * 50 + '\nResults from device: %s\n' % ip, 'yel')
try:
# create the Jaide session object for the device.
conn = Jaide(ip, username, password, connect_timeout=conn_timeout,
session_timeout=sess_timeout, port=port)
if write is not False:
return write, output + function(conn, *args)
else:
return output + function(conn, *args)
except errors.SSHError:
output += color('Unable to connect to port %s on device: %s\n' %
(str(port), ip), 'red')
except errors.AuthenticationError: # NCClient auth failure
output += color('Authentication failed for device: %s' % ip, 'red')
except AuthenticationException: # Paramiko auth failure
output += color('Authentication failed for device: %s' % ip, 'red')
except SSHException as e:
output += color('Error connecting to device: %s\nError: %s' %
(ip, str(e)), 'red')
except socket.timeout:
output += color('Timeout exceeded connecting to device: %s' % ip, 'red')
except socket.gaierror:
output += color('No route to host, or invalid hostname: %s' % ip, 'red')
except socket.error:
output += color('The device refused the connection on port %s, or '
'no route to host.' % port, 'red')
if write is not False:
return write, output
else:
return output | python | def open_connection(ip, username, password, function, args, write=False,
conn_timeout=5, sess_timeout=300, port=22):
""" Open a Jaide session with the device.
To open a Jaide session to the device, and run the appropriate function
against the device. Arguments for the downstream function are passed
through.
@param ip: String of the IP or hostname of the device to connect to.
@type ip: str
@param username: The string username used to connect to the device.
@type useranme: str
@param password: The string password used to connect to the device.
@type password: str
@param function: The downstream jaide.wrap function we'll be handing
| off the jaide.Jaide() object to execute the command
| once we've established the connection.
@type function: function pointer.
@param args: The arguments that we will hand off to the downstream
| function.
@type args: list
@param write: If set, it would be a tuple that we pass back as part of
| our return statement, so that any callback function
| can know how and where to put the output from the device.
@type write: False or tuple.
@param conn_timeout: Sets the connection timeout value. This is how
| we'll wait when connecting before classifying
| the device unreachable.
@type conn_timeout: int
@param sess_timeout: Sets the session timeout value. A higher value may
| be desired for long running commands, such as
| 'request system snapshot slice alternate'
@type sess_timeout: int
@param port: The port to connect to the device on. Defaults to 22.
@type port: int
@returns: We could return either just a string of the output from the
| device, or a tuple containing the information needed to write
| to a file and the string output from the device.
@rtype: Tuple or str
"""
# start with the header line on the output.
output = color('=' * 50 + '\nResults from device: %s\n' % ip, 'yel')
try:
# create the Jaide session object for the device.
conn = Jaide(ip, username, password, connect_timeout=conn_timeout,
session_timeout=sess_timeout, port=port)
if write is not False:
return write, output + function(conn, *args)
else:
return output + function(conn, *args)
except errors.SSHError:
output += color('Unable to connect to port %s on device: %s\n' %
(str(port), ip), 'red')
except errors.AuthenticationError: # NCClient auth failure
output += color('Authentication failed for device: %s' % ip, 'red')
except AuthenticationException: # Paramiko auth failure
output += color('Authentication failed for device: %s' % ip, 'red')
except SSHException as e:
output += color('Error connecting to device: %s\nError: %s' %
(ip, str(e)), 'red')
except socket.timeout:
output += color('Timeout exceeded connecting to device: %s' % ip, 'red')
except socket.gaierror:
output += color('No route to host, or invalid hostname: %s' % ip, 'red')
except socket.error:
output += color('The device refused the connection on port %s, or '
'no route to host.' % port, 'red')
if write is not False:
return write, output
else:
return output | [
"def",
"open_connection",
"(",
"ip",
",",
"username",
",",
"password",
",",
"function",
",",
"args",
",",
"write",
"=",
"False",
",",
"conn_timeout",
"=",
"5",
",",
"sess_timeout",
"=",
"300",
",",
"port",
"=",
"22",
")",
":",
"# start with the header line on the output.",
"output",
"=",
"color",
"(",
"'='",
"*",
"50",
"+",
"'\\nResults from device: %s\\n'",
"%",
"ip",
",",
"'yel'",
")",
"try",
":",
"# create the Jaide session object for the device.",
"conn",
"=",
"Jaide",
"(",
"ip",
",",
"username",
",",
"password",
",",
"connect_timeout",
"=",
"conn_timeout",
",",
"session_timeout",
"=",
"sess_timeout",
",",
"port",
"=",
"port",
")",
"if",
"write",
"is",
"not",
"False",
":",
"return",
"write",
",",
"output",
"+",
"function",
"(",
"conn",
",",
"*",
"args",
")",
"else",
":",
"return",
"output",
"+",
"function",
"(",
"conn",
",",
"*",
"args",
")",
"except",
"errors",
".",
"SSHError",
":",
"output",
"+=",
"color",
"(",
"'Unable to connect to port %s on device: %s\\n'",
"%",
"(",
"str",
"(",
"port",
")",
",",
"ip",
")",
",",
"'red'",
")",
"except",
"errors",
".",
"AuthenticationError",
":",
"# NCClient auth failure",
"output",
"+=",
"color",
"(",
"'Authentication failed for device: %s'",
"%",
"ip",
",",
"'red'",
")",
"except",
"AuthenticationException",
":",
"# Paramiko auth failure",
"output",
"+=",
"color",
"(",
"'Authentication failed for device: %s'",
"%",
"ip",
",",
"'red'",
")",
"except",
"SSHException",
"as",
"e",
":",
"output",
"+=",
"color",
"(",
"'Error connecting to device: %s\\nError: %s'",
"%",
"(",
"ip",
",",
"str",
"(",
"e",
")",
")",
",",
"'red'",
")",
"except",
"socket",
".",
"timeout",
":",
"output",
"+=",
"color",
"(",
"'Timeout exceeded connecting to device: %s'",
"%",
"ip",
",",
"'red'",
")",
"except",
"socket",
".",
"gaierror",
":",
"output",
"+=",
"color",
"(",
"'No route to host, or invalid hostname: %s'",
"%",
"ip",
",",
"'red'",
")",
"except",
"socket",
".",
"error",
":",
"output",
"+=",
"color",
"(",
"'The device refused the connection on port %s, or '",
"'no route to host.'",
"%",
"port",
",",
"'red'",
")",
"if",
"write",
"is",
"not",
"False",
":",
"return",
"write",
",",
"output",
"else",
":",
"return",
"output"
] | Open a Jaide session with the device.
To open a Jaide session to the device, and run the appropriate function
against the device. Arguments for the downstream function are passed
through.
@param ip: String of the IP or hostname of the device to connect to.
@type ip: str
@param username: The string username used to connect to the device.
@type useranme: str
@param password: The string password used to connect to the device.
@type password: str
@param function: The downstream jaide.wrap function we'll be handing
| off the jaide.Jaide() object to execute the command
| once we've established the connection.
@type function: function pointer.
@param args: The arguments that we will hand off to the downstream
| function.
@type args: list
@param write: If set, it would be a tuple that we pass back as part of
| our return statement, so that any callback function
| can know how and where to put the output from the device.
@type write: False or tuple.
@param conn_timeout: Sets the connection timeout value. This is how
| we'll wait when connecting before classifying
| the device unreachable.
@type conn_timeout: int
@param sess_timeout: Sets the session timeout value. A higher value may
| be desired for long running commands, such as
| 'request system snapshot slice alternate'
@type sess_timeout: int
@param port: The port to connect to the device on. Defaults to 22.
@type port: int
@returns: We could return either just a string of the output from the
| device, or a tuple containing the information needed to write
| to a file and the string output from the device.
@rtype: Tuple or str | [
"Open",
"a",
"Jaide",
"session",
"with",
"the",
"device",
"."
] | 8571b987a8c24c246dc09f1bcc11cb0f045ec33f | https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/wrap.py#L32-L103 | train |
NetworkAutomation/jaide | jaide/wrap.py | command | def command(jaide, commands, format="text", xpath=False):
""" Run an operational command.
@param jaide: The jaide connection to the device.
@type jaide: jaide.Jaide object
@param commands: the operational commands to send to the device.
@type commands: str or list
@param format: The desired output format from the device, either 'text'
| or 'xml' is supported.
@type format: str
@param xpath: The xpath expression to filter the results from the device.
| If set, this forces the output to be requested in xml format.
@type xpath: str
@returns: The output from the device, and xpath filtered if desired.
@rtype: str
"""
output = ""
for cmd in clean_lines(commands):
expression = ""
output += color('> ' + cmd + '\n', 'yel')
# Get xpath expression from the command, if it is there.
# If there is an xpath expr, the output will be xml,
# overriding the req_format parameter
#
# Example command forcing xpath: show route % //rt-entry
if len(cmd.split('%')) == 2:
expression = cmd.split('%')[1].strip()
cmd = cmd.split('%')[0] + '\n'
elif xpath is not False:
expression = xpath
if expression:
try:
output += jaide.op_cmd(command=cmd, req_format='xml',
xpath_expr=expression) + '\n'
except lxml.etree.XMLSyntaxError:
output += color('Xpath expression resulted in no response.\n',
'red')
else:
output += jaide.op_cmd(cmd, req_format=format) + '\n'
return output | python | def command(jaide, commands, format="text", xpath=False):
""" Run an operational command.
@param jaide: The jaide connection to the device.
@type jaide: jaide.Jaide object
@param commands: the operational commands to send to the device.
@type commands: str or list
@param format: The desired output format from the device, either 'text'
| or 'xml' is supported.
@type format: str
@param xpath: The xpath expression to filter the results from the device.
| If set, this forces the output to be requested in xml format.
@type xpath: str
@returns: The output from the device, and xpath filtered if desired.
@rtype: str
"""
output = ""
for cmd in clean_lines(commands):
expression = ""
output += color('> ' + cmd + '\n', 'yel')
# Get xpath expression from the command, if it is there.
# If there is an xpath expr, the output will be xml,
# overriding the req_format parameter
#
# Example command forcing xpath: show route % //rt-entry
if len(cmd.split('%')) == 2:
expression = cmd.split('%')[1].strip()
cmd = cmd.split('%')[0] + '\n'
elif xpath is not False:
expression = xpath
if expression:
try:
output += jaide.op_cmd(command=cmd, req_format='xml',
xpath_expr=expression) + '\n'
except lxml.etree.XMLSyntaxError:
output += color('Xpath expression resulted in no response.\n',
'red')
else:
output += jaide.op_cmd(cmd, req_format=format) + '\n'
return output | [
"def",
"command",
"(",
"jaide",
",",
"commands",
",",
"format",
"=",
"\"text\"",
",",
"xpath",
"=",
"False",
")",
":",
"output",
"=",
"\"\"",
"for",
"cmd",
"in",
"clean_lines",
"(",
"commands",
")",
":",
"expression",
"=",
"\"\"",
"output",
"+=",
"color",
"(",
"'> '",
"+",
"cmd",
"+",
"'\\n'",
",",
"'yel'",
")",
"# Get xpath expression from the command, if it is there.",
"# If there is an xpath expr, the output will be xml,",
"# overriding the req_format parameter",
"#",
"# Example command forcing xpath: show route % //rt-entry",
"if",
"len",
"(",
"cmd",
".",
"split",
"(",
"'%'",
")",
")",
"==",
"2",
":",
"expression",
"=",
"cmd",
".",
"split",
"(",
"'%'",
")",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"cmd",
"=",
"cmd",
".",
"split",
"(",
"'%'",
")",
"[",
"0",
"]",
"+",
"'\\n'",
"elif",
"xpath",
"is",
"not",
"False",
":",
"expression",
"=",
"xpath",
"if",
"expression",
":",
"try",
":",
"output",
"+=",
"jaide",
".",
"op_cmd",
"(",
"command",
"=",
"cmd",
",",
"req_format",
"=",
"'xml'",
",",
"xpath_expr",
"=",
"expression",
")",
"+",
"'\\n'",
"except",
"lxml",
".",
"etree",
".",
"XMLSyntaxError",
":",
"output",
"+=",
"color",
"(",
"'Xpath expression resulted in no response.\\n'",
",",
"'red'",
")",
"else",
":",
"output",
"+=",
"jaide",
".",
"op_cmd",
"(",
"cmd",
",",
"req_format",
"=",
"format",
")",
"+",
"'\\n'",
"return",
"output"
] | Run an operational command.
@param jaide: The jaide connection to the device.
@type jaide: jaide.Jaide object
@param commands: the operational commands to send to the device.
@type commands: str or list
@param format: The desired output format from the device, either 'text'
| or 'xml' is supported.
@type format: str
@param xpath: The xpath expression to filter the results from the device.
| If set, this forces the output to be requested in xml format.
@type xpath: str
@returns: The output from the device, and xpath filtered if desired.
@rtype: str | [
"Run",
"an",
"operational",
"command",
"."
] | 8571b987a8c24c246dc09f1bcc11cb0f045ec33f | https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/wrap.py#L106-L146 | train |
NetworkAutomation/jaide | jaide/wrap.py | shell | def shell(jaide, commands):
""" Send shell commands to a device.
@param jaide: The jaide connection to the device.
@type jaide: jaide.Jaide object
@param commands: The shell commands to send to the device.
@type commands: str or list.
@returns: The output of the commands.
@rtype str
"""
out = ""
for cmd in clean_lines(commands):
out += color('> %s\n' % cmd, 'yel')
out += jaide.shell_cmd(cmd) + '\n'
return out | python | def shell(jaide, commands):
""" Send shell commands to a device.
@param jaide: The jaide connection to the device.
@type jaide: jaide.Jaide object
@param commands: The shell commands to send to the device.
@type commands: str or list.
@returns: The output of the commands.
@rtype str
"""
out = ""
for cmd in clean_lines(commands):
out += color('> %s\n' % cmd, 'yel')
out += jaide.shell_cmd(cmd) + '\n'
return out | [
"def",
"shell",
"(",
"jaide",
",",
"commands",
")",
":",
"out",
"=",
"\"\"",
"for",
"cmd",
"in",
"clean_lines",
"(",
"commands",
")",
":",
"out",
"+=",
"color",
"(",
"'> %s\\n'",
"%",
"cmd",
",",
"'yel'",
")",
"out",
"+=",
"jaide",
".",
"shell_cmd",
"(",
"cmd",
")",
"+",
"'\\n'",
"return",
"out"
] | Send shell commands to a device.
@param jaide: The jaide connection to the device.
@type jaide: jaide.Jaide object
@param commands: The shell commands to send to the device.
@type commands: str or list.
@returns: The output of the commands.
@rtype str | [
"Send",
"shell",
"commands",
"to",
"a",
"device",
"."
] | 8571b987a8c24c246dc09f1bcc11cb0f045ec33f | https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/wrap.py#L454-L469 | train |
crossbario/txaio-etcd | txaioetcd/cli/exporter.py | get_all_keys | def get_all_keys(reactor, key_type, value_type, etcd_address):
"""Returns all keys from etcd.
:param reactor: reference to Twisted' reactor.
:param etcd_address: Address with port number where etcd is
running.
:return: An instance of txaioetcd.Range containing all keys and
their values.
"""
etcd = Client(reactor, etcd_address)
result = yield etcd.get(b'\x00', range_end=b'\x00')
res = {}
for item in result.kvs:
if key_type == u'utf8':
key = item.key.decode('utf8')
elif key_type == u'binary':
key = binascii.b2a_base64(item.key).decode().strip()
else:
raise Exception('logic error')
if value_type == u'json':
value = json.loads(item.value.decode('utf8'))
elif value_type == u'binary':
value = binascii.b2a_base64(item.value).decode().strip()
elif value_type == u'utf8':
value = item.value.decode('utf8')
else:
raise Exception('logic error')
res[key] = value
returnValue(res) | python | def get_all_keys(reactor, key_type, value_type, etcd_address):
"""Returns all keys from etcd.
:param reactor: reference to Twisted' reactor.
:param etcd_address: Address with port number where etcd is
running.
:return: An instance of txaioetcd.Range containing all keys and
their values.
"""
etcd = Client(reactor, etcd_address)
result = yield etcd.get(b'\x00', range_end=b'\x00')
res = {}
for item in result.kvs:
if key_type == u'utf8':
key = item.key.decode('utf8')
elif key_type == u'binary':
key = binascii.b2a_base64(item.key).decode().strip()
else:
raise Exception('logic error')
if value_type == u'json':
value = json.loads(item.value.decode('utf8'))
elif value_type == u'binary':
value = binascii.b2a_base64(item.value).decode().strip()
elif value_type == u'utf8':
value = item.value.decode('utf8')
else:
raise Exception('logic error')
res[key] = value
returnValue(res) | [
"def",
"get_all_keys",
"(",
"reactor",
",",
"key_type",
",",
"value_type",
",",
"etcd_address",
")",
":",
"etcd",
"=",
"Client",
"(",
"reactor",
",",
"etcd_address",
")",
"result",
"=",
"yield",
"etcd",
".",
"get",
"(",
"b'\\x00'",
",",
"range_end",
"=",
"b'\\x00'",
")",
"res",
"=",
"{",
"}",
"for",
"item",
"in",
"result",
".",
"kvs",
":",
"if",
"key_type",
"==",
"u'utf8'",
":",
"key",
"=",
"item",
".",
"key",
".",
"decode",
"(",
"'utf8'",
")",
"elif",
"key_type",
"==",
"u'binary'",
":",
"key",
"=",
"binascii",
".",
"b2a_base64",
"(",
"item",
".",
"key",
")",
".",
"decode",
"(",
")",
".",
"strip",
"(",
")",
"else",
":",
"raise",
"Exception",
"(",
"'logic error'",
")",
"if",
"value_type",
"==",
"u'json'",
":",
"value",
"=",
"json",
".",
"loads",
"(",
"item",
".",
"value",
".",
"decode",
"(",
"'utf8'",
")",
")",
"elif",
"value_type",
"==",
"u'binary'",
":",
"value",
"=",
"binascii",
".",
"b2a_base64",
"(",
"item",
".",
"value",
")",
".",
"decode",
"(",
")",
".",
"strip",
"(",
")",
"elif",
"value_type",
"==",
"u'utf8'",
":",
"value",
"=",
"item",
".",
"value",
".",
"decode",
"(",
"'utf8'",
")",
"else",
":",
"raise",
"Exception",
"(",
"'logic error'",
")",
"res",
"[",
"key",
"]",
"=",
"value",
"returnValue",
"(",
"res",
")"
] | Returns all keys from etcd.
:param reactor: reference to Twisted' reactor.
:param etcd_address: Address with port number where etcd is
running.
:return: An instance of txaioetcd.Range containing all keys and
their values. | [
"Returns",
"all",
"keys",
"from",
"etcd",
"."
] | c9aebff7f288a0b219bffc9d2579d22cf543baa5 | https://github.com/crossbario/txaio-etcd/blob/c9aebff7f288a0b219bffc9d2579d22cf543baa5/txaioetcd/cli/exporter.py#L49-L81 | train |
andresriancho/w3af-api-client | w3af_api_client/scan.py | Scan.stop | def stop(self, timeout=None):
"""
Send the GET request required to stop the scan
If timeout is not specified we just send the request and return. When
it is the method will wait for (at most) :timeout: seconds until the
scan changes it's status/stops. If the timeout is reached then an
exception is raised.
:param timeout: The timeout in seconds
:return: None, an exception is raised if the timeout is exceeded
"""
assert self.scan_id is not None, 'No scan_id has been set'
#
# Simple stop
#
if timeout is None:
url = '/scans/%s/stop' % self.scan_id
self.conn.send_request(url, method='GET')
return
#
# Stop with timeout
#
self.stop()
for _ in xrange(timeout):
time.sleep(1)
is_running = self.get_status()['is_running']
if not is_running:
return
msg = 'Failed to stop the scan in %s seconds'
raise ScanStopTimeoutException(msg % timeout) | python | def stop(self, timeout=None):
"""
Send the GET request required to stop the scan
If timeout is not specified we just send the request and return. When
it is the method will wait for (at most) :timeout: seconds until the
scan changes it's status/stops. If the timeout is reached then an
exception is raised.
:param timeout: The timeout in seconds
:return: None, an exception is raised if the timeout is exceeded
"""
assert self.scan_id is not None, 'No scan_id has been set'
#
# Simple stop
#
if timeout is None:
url = '/scans/%s/stop' % self.scan_id
self.conn.send_request(url, method='GET')
return
#
# Stop with timeout
#
self.stop()
for _ in xrange(timeout):
time.sleep(1)
is_running = self.get_status()['is_running']
if not is_running:
return
msg = 'Failed to stop the scan in %s seconds'
raise ScanStopTimeoutException(msg % timeout) | [
"def",
"stop",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"assert",
"self",
".",
"scan_id",
"is",
"not",
"None",
",",
"'No scan_id has been set'",
"#",
"# Simple stop",
"#",
"if",
"timeout",
"is",
"None",
":",
"url",
"=",
"'/scans/%s/stop'",
"%",
"self",
".",
"scan_id",
"self",
".",
"conn",
".",
"send_request",
"(",
"url",
",",
"method",
"=",
"'GET'",
")",
"return",
"#",
"# Stop with timeout",
"#",
"self",
".",
"stop",
"(",
")",
"for",
"_",
"in",
"xrange",
"(",
"timeout",
")",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"is_running",
"=",
"self",
".",
"get_status",
"(",
")",
"[",
"'is_running'",
"]",
"if",
"not",
"is_running",
":",
"return",
"msg",
"=",
"'Failed to stop the scan in %s seconds'",
"raise",
"ScanStopTimeoutException",
"(",
"msg",
"%",
"timeout",
")"
] | Send the GET request required to stop the scan
If timeout is not specified we just send the request and return. When
it is the method will wait for (at most) :timeout: seconds until the
scan changes it's status/stops. If the timeout is reached then an
exception is raised.
:param timeout: The timeout in seconds
:return: None, an exception is raised if the timeout is exceeded | [
"Send",
"the",
"GET",
"request",
"required",
"to",
"stop",
"the",
"scan"
] | adeb79bad75264d754de69f0bb981b366da96f32 | https://github.com/andresriancho/w3af-api-client/blob/adeb79bad75264d754de69f0bb981b366da96f32/w3af_api_client/scan.py#L56-L91 | train |
dourvaris/nano-python | src/nano/accounts.py | xrb_address_to_public_key | def xrb_address_to_public_key(address):
"""
Convert an xrb address to public key in bytes
>>> xrb_address_to_public_key('xrb_1e3i81r51e3i81r51e3i81r51e3i'\
'81r51e3i81r51e3i81r51e3imxssakuq')
b'00000000000000000000000000000000'
:param address: xrb address
:type address: bytes
:return: public key in bytes
:rtype: bytes
:raises ValueError:
"""
address = bytearray(address, 'ascii')
if not address.startswith(b'xrb_'):
raise ValueError('address does not start with xrb_: %s' % address)
if len(address) != 64:
raise ValueError('address must be 64 chars long: %s' % address)
address = bytes(address)
key_b32xrb = b'1111' + address[4:56]
key_bytes = b32xrb_decode(key_b32xrb)[3:]
checksum = address[56:]
if b32xrb_encode(address_checksum(key_bytes)) != checksum:
raise ValueError('invalid address, invalid checksum: %s' % address)
return key_bytes | python | def xrb_address_to_public_key(address):
"""
Convert an xrb address to public key in bytes
>>> xrb_address_to_public_key('xrb_1e3i81r51e3i81r51e3i81r51e3i'\
'81r51e3i81r51e3i81r51e3imxssakuq')
b'00000000000000000000000000000000'
:param address: xrb address
:type address: bytes
:return: public key in bytes
:rtype: bytes
:raises ValueError:
"""
address = bytearray(address, 'ascii')
if not address.startswith(b'xrb_'):
raise ValueError('address does not start with xrb_: %s' % address)
if len(address) != 64:
raise ValueError('address must be 64 chars long: %s' % address)
address = bytes(address)
key_b32xrb = b'1111' + address[4:56]
key_bytes = b32xrb_decode(key_b32xrb)[3:]
checksum = address[56:]
if b32xrb_encode(address_checksum(key_bytes)) != checksum:
raise ValueError('invalid address, invalid checksum: %s' % address)
return key_bytes | [
"def",
"xrb_address_to_public_key",
"(",
"address",
")",
":",
"address",
"=",
"bytearray",
"(",
"address",
",",
"'ascii'",
")",
"if",
"not",
"address",
".",
"startswith",
"(",
"b'xrb_'",
")",
":",
"raise",
"ValueError",
"(",
"'address does not start with xrb_: %s'",
"%",
"address",
")",
"if",
"len",
"(",
"address",
")",
"!=",
"64",
":",
"raise",
"ValueError",
"(",
"'address must be 64 chars long: %s'",
"%",
"address",
")",
"address",
"=",
"bytes",
"(",
"address",
")",
"key_b32xrb",
"=",
"b'1111'",
"+",
"address",
"[",
"4",
":",
"56",
"]",
"key_bytes",
"=",
"b32xrb_decode",
"(",
"key_b32xrb",
")",
"[",
"3",
":",
"]",
"checksum",
"=",
"address",
"[",
"56",
":",
"]",
"if",
"b32xrb_encode",
"(",
"address_checksum",
"(",
"key_bytes",
")",
")",
"!=",
"checksum",
":",
"raise",
"ValueError",
"(",
"'invalid address, invalid checksum: %s'",
"%",
"address",
")",
"return",
"key_bytes"
] | Convert an xrb address to public key in bytes
>>> xrb_address_to_public_key('xrb_1e3i81r51e3i81r51e3i81r51e3i'\
'81r51e3i81r51e3i81r51e3imxssakuq')
b'00000000000000000000000000000000'
:param address: xrb address
:type address: bytes
:return: public key in bytes
:rtype: bytes
:raises ValueError: | [
"Convert",
"an",
"xrb",
"address",
"to",
"public",
"key",
"in",
"bytes"
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/accounts.py#L73-L106 | train |
dourvaris/nano-python | src/nano/accounts.py | generate_account | def generate_account(seed=None, index=0):
"""
Generates an adhoc account and keypair
>>> account = generate_account(seed=unhexlify('0'*64))
{'address': u'xrb_3i1aq1cchnmbn9x5rsbap8b15akfh7wj7pwskuzi7ahz8oq6cobd99d4r3b7',
'private_key_bytes': '\x9f\x0eDLi\xf7zI\xbd\x0b\xe8\x9d\xb9,8\xfeq>\tc\x16\\\xca\x12\xfa\xf5q-vW\x12\x0f',
'private_key_hex': '9f0e444c69f77a49bd0be89db92c38fe713e0963165cca12faf5712d7657120f',
'public_key_bytes': '\xc0\x08\xb8\x14\xa7\xd2i\xa1\xfa<e(\xb1\x92\x01\xa2Myy\x12\xdb\x99\x96\xff\x02\xa1\xff5nEU+',
'public_key_hex': 'c008b814a7d269a1fa3c6528b19201a24d797912db9996ff02a1ff356e45552b'}
:param seed: the seed in bytes to use to generate the account, if not
provided one is generated randomly
:type seed: bytes
:param index: the index offset for deterministic account generation
:type index: int
:return: dict containing the account address and pub/priv keys in hex/bytes
:rtype: dict
"""
if not seed:
seed = unhexlify(''.join(random.choice('0123456789ABCDEF') for i in range(64)))
pair = keypair_from_seed(seed, index=index)
result = {
'address': public_key_to_xrb_address(pair['public']),
'private_key_bytes': pair['private'],
'public_key_bytes': pair['public'],
}
result['private_key_hex'] = hexlify(pair['private'])
result['public_key_hex'] = hexlify(pair['public'])
return result | python | def generate_account(seed=None, index=0):
"""
Generates an adhoc account and keypair
>>> account = generate_account(seed=unhexlify('0'*64))
{'address': u'xrb_3i1aq1cchnmbn9x5rsbap8b15akfh7wj7pwskuzi7ahz8oq6cobd99d4r3b7',
'private_key_bytes': '\x9f\x0eDLi\xf7zI\xbd\x0b\xe8\x9d\xb9,8\xfeq>\tc\x16\\\xca\x12\xfa\xf5q-vW\x12\x0f',
'private_key_hex': '9f0e444c69f77a49bd0be89db92c38fe713e0963165cca12faf5712d7657120f',
'public_key_bytes': '\xc0\x08\xb8\x14\xa7\xd2i\xa1\xfa<e(\xb1\x92\x01\xa2Myy\x12\xdb\x99\x96\xff\x02\xa1\xff5nEU+',
'public_key_hex': 'c008b814a7d269a1fa3c6528b19201a24d797912db9996ff02a1ff356e45552b'}
:param seed: the seed in bytes to use to generate the account, if not
provided one is generated randomly
:type seed: bytes
:param index: the index offset for deterministic account generation
:type index: int
:return: dict containing the account address and pub/priv keys in hex/bytes
:rtype: dict
"""
if not seed:
seed = unhexlify(''.join(random.choice('0123456789ABCDEF') for i in range(64)))
pair = keypair_from_seed(seed, index=index)
result = {
'address': public_key_to_xrb_address(pair['public']),
'private_key_bytes': pair['private'],
'public_key_bytes': pair['public'],
}
result['private_key_hex'] = hexlify(pair['private'])
result['public_key_hex'] = hexlify(pair['public'])
return result | [
"def",
"generate_account",
"(",
"seed",
"=",
"None",
",",
"index",
"=",
"0",
")",
":",
"if",
"not",
"seed",
":",
"seed",
"=",
"unhexlify",
"(",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"'0123456789ABCDEF'",
")",
"for",
"i",
"in",
"range",
"(",
"64",
")",
")",
")",
"pair",
"=",
"keypair_from_seed",
"(",
"seed",
",",
"index",
"=",
"index",
")",
"result",
"=",
"{",
"'address'",
":",
"public_key_to_xrb_address",
"(",
"pair",
"[",
"'public'",
"]",
")",
",",
"'private_key_bytes'",
":",
"pair",
"[",
"'private'",
"]",
",",
"'public_key_bytes'",
":",
"pair",
"[",
"'public'",
"]",
",",
"}",
"result",
"[",
"'private_key_hex'",
"]",
"=",
"hexlify",
"(",
"pair",
"[",
"'private'",
"]",
")",
"result",
"[",
"'public_key_hex'",
"]",
"=",
"hexlify",
"(",
"pair",
"[",
"'public'",
"]",
")",
"return",
"result"
] | Generates an adhoc account and keypair
>>> account = generate_account(seed=unhexlify('0'*64))
{'address': u'xrb_3i1aq1cchnmbn9x5rsbap8b15akfh7wj7pwskuzi7ahz8oq6cobd99d4r3b7',
'private_key_bytes': '\x9f\x0eDLi\xf7zI\xbd\x0b\xe8\x9d\xb9,8\xfeq>\tc\x16\\\xca\x12\xfa\xf5q-vW\x12\x0f',
'private_key_hex': '9f0e444c69f77a49bd0be89db92c38fe713e0963165cca12faf5712d7657120f',
'public_key_bytes': '\xc0\x08\xb8\x14\xa7\xd2i\xa1\xfa<e(\xb1\x92\x01\xa2Myy\x12\xdb\x99\x96\xff\x02\xa1\xff5nEU+',
'public_key_hex': 'c008b814a7d269a1fa3c6528b19201a24d797912db9996ff02a1ff356e45552b'}
:param seed: the seed in bytes to use to generate the account, if not
provided one is generated randomly
:type seed: bytes
:param index: the index offset for deterministic account generation
:type index: int
:return: dict containing the account address and pub/priv keys in hex/bytes
:rtype: dict | [
"Generates",
"an",
"adhoc",
"account",
"and",
"keypair"
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/accounts.py#L109-L143 | train |
mcieslik-mctp/papy | src/papy/util/func.py | spasser | def spasser(inbox, s=None):
"""
Passes inputs with indecies in s. By default passes the whole inbox.
Arguments:
- s(sequence) [default: ``None``] The default translates to a range for
all inputs of the "inbox" i.e. ``range(len(inbox))``
"""
seq = (s or range(len(inbox)))
return [input_ for i, input_ in enumerate(inbox) if i in seq] | python | def spasser(inbox, s=None):
"""
Passes inputs with indecies in s. By default passes the whole inbox.
Arguments:
- s(sequence) [default: ``None``] The default translates to a range for
all inputs of the "inbox" i.e. ``range(len(inbox))``
"""
seq = (s or range(len(inbox)))
return [input_ for i, input_ in enumerate(inbox) if i in seq] | [
"def",
"spasser",
"(",
"inbox",
",",
"s",
"=",
"None",
")",
":",
"seq",
"=",
"(",
"s",
"or",
"range",
"(",
"len",
"(",
"inbox",
")",
")",
")",
"return",
"[",
"input_",
"for",
"i",
",",
"input_",
"in",
"enumerate",
"(",
"inbox",
")",
"if",
"i",
"in",
"seq",
"]"
] | Passes inputs with indecies in s. By default passes the whole inbox.
Arguments:
- s(sequence) [default: ``None``] The default translates to a range for
all inputs of the "inbox" i.e. ``range(len(inbox))`` | [
"Passes",
"inputs",
"with",
"indecies",
"in",
"s",
".",
"By",
"default",
"passes",
"the",
"whole",
"inbox",
"."
] | 708e50827b5db46bbea081982cb74b9b0e464064 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/util/func.py#L67-L78 | train |
mcieslik-mctp/papy | src/papy/util/func.py | sjoiner | def sjoiner(inbox, s=None, join=""):
"""
String joins input with indices in s.
Arguments:
- s(sequence) [default: ``None``] ``tuple`` or ``list`` of indices of the
elements which will be joined.
- join(``str``) [default: ``""``] String which will join the elements of
the inbox i.e. ``join.join()``.
"""
return join.join([input_ for i, input_ in enumerate(inbox) if i in s]) | python | def sjoiner(inbox, s=None, join=""):
"""
String joins input with indices in s.
Arguments:
- s(sequence) [default: ``None``] ``tuple`` or ``list`` of indices of the
elements which will be joined.
- join(``str``) [default: ``""``] String which will join the elements of
the inbox i.e. ``join.join()``.
"""
return join.join([input_ for i, input_ in enumerate(inbox) if i in s]) | [
"def",
"sjoiner",
"(",
"inbox",
",",
"s",
"=",
"None",
",",
"join",
"=",
"\"\"",
")",
":",
"return",
"join",
".",
"join",
"(",
"[",
"input_",
"for",
"i",
",",
"input_",
"in",
"enumerate",
"(",
"inbox",
")",
"if",
"i",
"in",
"s",
"]",
")"
] | String joins input with indices in s.
Arguments:
- s(sequence) [default: ``None``] ``tuple`` or ``list`` of indices of the
elements which will be joined.
- join(``str``) [default: ``""``] String which will join the elements of
the inbox i.e. ``join.join()``. | [
"String",
"joins",
"input",
"with",
"indices",
"in",
"s",
"."
] | 708e50827b5db46bbea081982cb74b9b0e464064 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/util/func.py#L119-L131 | train |
mcieslik-mctp/papy | src/papy/util/func.py | load_item | def load_item(inbox, type="string", remove=True, buffer=None):
"""
Loads data from a file. Determines the file type automatically ``"file"``,
``"fifo"``, ``"socket"``, but allows to specify the representation type
``"string"`` or ``"mmap"`` for memory mapped access to the file. Returns
the loaded item as a ``str`` or ``mmap`` object. Internally creates an item
from a ``file``.
Arguments:
- type(``"string"`` or ``"mmap"``) [default: ``"string"``] Determines the
type of ``object`` the worker returns i.e. the ``file`` is read as a
string or a memmory map. FIFOs cannot be memory mapped.
- remove(``bool``) [default: ``True``] Should the file be removed from the
filesystem? This is mandatory for FIFOs and sockets. Only Files can be
used to store data persistantly.
"""
is_file, is_fifo, is_socket = False, False, False
file = inbox[0]
try:
file_type = file[0]
except:
raise ValueError("invalid inbox item")
if file_type == "file":
is_file = os.path.exists(file[1])
elif file_type == "fifo":
is_fifo = stat.S_ISFIFO(os.stat(file[1]).st_mode)
elif file_type == "socket":
# how to test is valid socket?
is_socket = True
else:
raise ValueError("type: %s not undertood" % file_type)
if (is_fifo or is_socket) and (type == 'mmap'):
raise ValueError("mmap is not supported for FIFOs and sockets")
if (is_fifo or is_socket) and not remove:
raise ValueError("FIFOs and sockets have to be removed")
# get a fd and start/stop
start = 0
if is_fifo or is_file:
stop = os.stat(file[1]).st_size - 1
fd = os.open(file[1], os.O_RDONLY)
BUFFER = (buffer or PAPY_DEFAULTS['PIPE_BUF'])
elif is_socket:
host, port = socket.gethostbyname(file[1]), file[2]
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
stop = -1
fd = sock.fileno()
BUFFER = (buffer or PAPY_DEFAULTS['TCP_RCVBUF'])
else:
raise ValueError("got unknown inbox: %s" % (repr(inbox)))
# get the data
if type == 'mmap':
offset = start - (start % (getattr(mmap, 'ALLOCATIONGRANULARITY', None)\
or getattr(mmap, 'PAGESIZE')))
start = start - offset
stop = stop - offset + 1
try:
data = mmap.mmap(fd, stop, access=mmap.ACCESS_READ, offset=offset)
except TypeError:
# we're on Python 2.5
data = mmap.mmap(fd, stop, access=mmap.ACCESS_READ)
data.seek(start)
elif type == 'string':
data = []
if stop == -1:
while True:
buffer_ = os.read(fd, BUFFER)
if not buffer_:
break
data.append(buffer_)
data = "".join(data)
# data = sock.recv(socket.MSG_WAITALL)
# this would read all the data from a socket
else:
os.lseek(fd, start, 0)
data = os.read(fd, stop - start + 1)
else:
raise ValueError('type: %s not understood.' % type)
# remove the file or close the socket
if remove:
if is_socket:
# closes client socket
sock.close()
else:
# pipes and files are just removed
os.close(fd)
os.unlink(file[1])
else:
os.close(fd)
# returns a string or mmap
return data | python | def load_item(inbox, type="string", remove=True, buffer=None):
"""
Loads data from a file. Determines the file type automatically ``"file"``,
``"fifo"``, ``"socket"``, but allows to specify the representation type
``"string"`` or ``"mmap"`` for memory mapped access to the file. Returns
the loaded item as a ``str`` or ``mmap`` object. Internally creates an item
from a ``file``.
Arguments:
- type(``"string"`` or ``"mmap"``) [default: ``"string"``] Determines the
type of ``object`` the worker returns i.e. the ``file`` is read as a
string or a memmory map. FIFOs cannot be memory mapped.
- remove(``bool``) [default: ``True``] Should the file be removed from the
filesystem? This is mandatory for FIFOs and sockets. Only Files can be
used to store data persistantly.
"""
is_file, is_fifo, is_socket = False, False, False
file = inbox[0]
try:
file_type = file[0]
except:
raise ValueError("invalid inbox item")
if file_type == "file":
is_file = os.path.exists(file[1])
elif file_type == "fifo":
is_fifo = stat.S_ISFIFO(os.stat(file[1]).st_mode)
elif file_type == "socket":
# how to test is valid socket?
is_socket = True
else:
raise ValueError("type: %s not undertood" % file_type)
if (is_fifo or is_socket) and (type == 'mmap'):
raise ValueError("mmap is not supported for FIFOs and sockets")
if (is_fifo or is_socket) and not remove:
raise ValueError("FIFOs and sockets have to be removed")
# get a fd and start/stop
start = 0
if is_fifo or is_file:
stop = os.stat(file[1]).st_size - 1
fd = os.open(file[1], os.O_RDONLY)
BUFFER = (buffer or PAPY_DEFAULTS['PIPE_BUF'])
elif is_socket:
host, port = socket.gethostbyname(file[1]), file[2]
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
stop = -1
fd = sock.fileno()
BUFFER = (buffer or PAPY_DEFAULTS['TCP_RCVBUF'])
else:
raise ValueError("got unknown inbox: %s" % (repr(inbox)))
# get the data
if type == 'mmap':
offset = start - (start % (getattr(mmap, 'ALLOCATIONGRANULARITY', None)\
or getattr(mmap, 'PAGESIZE')))
start = start - offset
stop = stop - offset + 1
try:
data = mmap.mmap(fd, stop, access=mmap.ACCESS_READ, offset=offset)
except TypeError:
# we're on Python 2.5
data = mmap.mmap(fd, stop, access=mmap.ACCESS_READ)
data.seek(start)
elif type == 'string':
data = []
if stop == -1:
while True:
buffer_ = os.read(fd, BUFFER)
if not buffer_:
break
data.append(buffer_)
data = "".join(data)
# data = sock.recv(socket.MSG_WAITALL)
# this would read all the data from a socket
else:
os.lseek(fd, start, 0)
data = os.read(fd, stop - start + 1)
else:
raise ValueError('type: %s not understood.' % type)
# remove the file or close the socket
if remove:
if is_socket:
# closes client socket
sock.close()
else:
# pipes and files are just removed
os.close(fd)
os.unlink(file[1])
else:
os.close(fd)
# returns a string or mmap
return data | [
"def",
"load_item",
"(",
"inbox",
",",
"type",
"=",
"\"string\"",
",",
"remove",
"=",
"True",
",",
"buffer",
"=",
"None",
")",
":",
"is_file",
",",
"is_fifo",
",",
"is_socket",
"=",
"False",
",",
"False",
",",
"False",
"file",
"=",
"inbox",
"[",
"0",
"]",
"try",
":",
"file_type",
"=",
"file",
"[",
"0",
"]",
"except",
":",
"raise",
"ValueError",
"(",
"\"invalid inbox item\"",
")",
"if",
"file_type",
"==",
"\"file\"",
":",
"is_file",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"file",
"[",
"1",
"]",
")",
"elif",
"file_type",
"==",
"\"fifo\"",
":",
"is_fifo",
"=",
"stat",
".",
"S_ISFIFO",
"(",
"os",
".",
"stat",
"(",
"file",
"[",
"1",
"]",
")",
".",
"st_mode",
")",
"elif",
"file_type",
"==",
"\"socket\"",
":",
"# how to test is valid socket?",
"is_socket",
"=",
"True",
"else",
":",
"raise",
"ValueError",
"(",
"\"type: %s not undertood\"",
"%",
"file_type",
")",
"if",
"(",
"is_fifo",
"or",
"is_socket",
")",
"and",
"(",
"type",
"==",
"'mmap'",
")",
":",
"raise",
"ValueError",
"(",
"\"mmap is not supported for FIFOs and sockets\"",
")",
"if",
"(",
"is_fifo",
"or",
"is_socket",
")",
"and",
"not",
"remove",
":",
"raise",
"ValueError",
"(",
"\"FIFOs and sockets have to be removed\"",
")",
"# get a fd and start/stop",
"start",
"=",
"0",
"if",
"is_fifo",
"or",
"is_file",
":",
"stop",
"=",
"os",
".",
"stat",
"(",
"file",
"[",
"1",
"]",
")",
".",
"st_size",
"-",
"1",
"fd",
"=",
"os",
".",
"open",
"(",
"file",
"[",
"1",
"]",
",",
"os",
".",
"O_RDONLY",
")",
"BUFFER",
"=",
"(",
"buffer",
"or",
"PAPY_DEFAULTS",
"[",
"'PIPE_BUF'",
"]",
")",
"elif",
"is_socket",
":",
"host",
",",
"port",
"=",
"socket",
".",
"gethostbyname",
"(",
"file",
"[",
"1",
"]",
")",
",",
"file",
"[",
"2",
"]",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"sock",
".",
"connect",
"(",
"(",
"host",
",",
"port",
")",
")",
"stop",
"=",
"-",
"1",
"fd",
"=",
"sock",
".",
"fileno",
"(",
")",
"BUFFER",
"=",
"(",
"buffer",
"or",
"PAPY_DEFAULTS",
"[",
"'TCP_RCVBUF'",
"]",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"got unknown inbox: %s\"",
"%",
"(",
"repr",
"(",
"inbox",
")",
")",
")",
"# get the data",
"if",
"type",
"==",
"'mmap'",
":",
"offset",
"=",
"start",
"-",
"(",
"start",
"%",
"(",
"getattr",
"(",
"mmap",
",",
"'ALLOCATIONGRANULARITY'",
",",
"None",
")",
"or",
"getattr",
"(",
"mmap",
",",
"'PAGESIZE'",
")",
")",
")",
"start",
"=",
"start",
"-",
"offset",
"stop",
"=",
"stop",
"-",
"offset",
"+",
"1",
"try",
":",
"data",
"=",
"mmap",
".",
"mmap",
"(",
"fd",
",",
"stop",
",",
"access",
"=",
"mmap",
".",
"ACCESS_READ",
",",
"offset",
"=",
"offset",
")",
"except",
"TypeError",
":",
"# we're on Python 2.5",
"data",
"=",
"mmap",
".",
"mmap",
"(",
"fd",
",",
"stop",
",",
"access",
"=",
"mmap",
".",
"ACCESS_READ",
")",
"data",
".",
"seek",
"(",
"start",
")",
"elif",
"type",
"==",
"'string'",
":",
"data",
"=",
"[",
"]",
"if",
"stop",
"==",
"-",
"1",
":",
"while",
"True",
":",
"buffer_",
"=",
"os",
".",
"read",
"(",
"fd",
",",
"BUFFER",
")",
"if",
"not",
"buffer_",
":",
"break",
"data",
".",
"append",
"(",
"buffer_",
")",
"data",
"=",
"\"\"",
".",
"join",
"(",
"data",
")",
"# data = sock.recv(socket.MSG_WAITALL) ",
"# this would read all the data from a socket",
"else",
":",
"os",
".",
"lseek",
"(",
"fd",
",",
"start",
",",
"0",
")",
"data",
"=",
"os",
".",
"read",
"(",
"fd",
",",
"stop",
"-",
"start",
"+",
"1",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'type: %s not understood.'",
"%",
"type",
")",
"# remove the file or close the socket",
"if",
"remove",
":",
"if",
"is_socket",
":",
"# closes client socket",
"sock",
".",
"close",
"(",
")",
"else",
":",
"# pipes and files are just removed",
"os",
".",
"close",
"(",
"fd",
")",
"os",
".",
"unlink",
"(",
"file",
"[",
"1",
"]",
")",
"else",
":",
"os",
".",
"close",
"(",
"fd",
")",
"# returns a string or mmap",
"return",
"data"
] | Loads data from a file. Determines the file type automatically ``"file"``,
``"fifo"``, ``"socket"``, but allows to specify the representation type
``"string"`` or ``"mmap"`` for memory mapped access to the file. Returns
the loaded item as a ``str`` or ``mmap`` object. Internally creates an item
from a ``file``.
Arguments:
- type(``"string"`` or ``"mmap"``) [default: ``"string"``] Determines the
type of ``object`` the worker returns i.e. the ``file`` is read as a
string or a memmory map. FIFOs cannot be memory mapped.
- remove(``bool``) [default: ``True``] Should the file be removed from the
filesystem? This is mandatory for FIFOs and sockets. Only Files can be
used to store data persistantly. | [
"Loads",
"data",
"from",
"a",
"file",
".",
"Determines",
"the",
"file",
"type",
"automatically",
"file",
"fifo",
"socket",
"but",
"allows",
"to",
"specify",
"the",
"representation",
"type",
"string",
"or",
"mmap",
"for",
"memory",
"mapped",
"access",
"to",
"the",
"file",
".",
"Returns",
"the",
"loaded",
"item",
"as",
"a",
"str",
"or",
"mmap",
"object",
".",
"Internally",
"creates",
"an",
"item",
"from",
"a",
"file",
"."
] | 708e50827b5db46bbea081982cb74b9b0e464064 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/util/func.py#L379-L478 | train |
mcieslik-mctp/papy | src/papy/util/func.py | pickle_dumps | def pickle_dumps(inbox):
"""
Serializes the first element of the input using the pickle protocol using
the fastes binary protocol.
"""
# http://bugs.python.org/issue4074
gc.disable()
str_ = cPickle.dumps(inbox[0], cPickle.HIGHEST_PROTOCOL)
gc.enable()
return str_ | python | def pickle_dumps(inbox):
"""
Serializes the first element of the input using the pickle protocol using
the fastes binary protocol.
"""
# http://bugs.python.org/issue4074
gc.disable()
str_ = cPickle.dumps(inbox[0], cPickle.HIGHEST_PROTOCOL)
gc.enable()
return str_ | [
"def",
"pickle_dumps",
"(",
"inbox",
")",
":",
"# http://bugs.python.org/issue4074",
"gc",
".",
"disable",
"(",
")",
"str_",
"=",
"cPickle",
".",
"dumps",
"(",
"inbox",
"[",
"0",
"]",
",",
"cPickle",
".",
"HIGHEST_PROTOCOL",
")",
"gc",
".",
"enable",
"(",
")",
"return",
"str_"
] | Serializes the first element of the input using the pickle protocol using
the fastes binary protocol. | [
"Serializes",
"the",
"first",
"element",
"of",
"the",
"input",
"using",
"the",
"pickle",
"protocol",
"using",
"the",
"fastes",
"binary",
"protocol",
"."
] | 708e50827b5db46bbea081982cb74b9b0e464064 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/util/func.py#L510-L520 | train |
mcieslik-mctp/papy | src/papy/util/func.py | pickle_loads | def pickle_loads(inbox):
"""
Deserializes the first element of the input using the pickle protocol.
"""
gc.disable()
obj = cPickle.loads(inbox[0])
gc.enable()
return obj | python | def pickle_loads(inbox):
"""
Deserializes the first element of the input using the pickle protocol.
"""
gc.disable()
obj = cPickle.loads(inbox[0])
gc.enable()
return obj | [
"def",
"pickle_loads",
"(",
"inbox",
")",
":",
"gc",
".",
"disable",
"(",
")",
"obj",
"=",
"cPickle",
".",
"loads",
"(",
"inbox",
"[",
"0",
"]",
")",
"gc",
".",
"enable",
"(",
")",
"return",
"obj"
] | Deserializes the first element of the input using the pickle protocol. | [
"Deserializes",
"the",
"first",
"element",
"of",
"the",
"input",
"using",
"the",
"pickle",
"protocol",
"."
] | 708e50827b5db46bbea081982cb74b9b0e464064 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/util/func.py#L523-L531 | train |
mcieslik-mctp/papy | src/papy/util/func.py | json_dumps | def json_dumps(inbox):
"""
Serializes the first element of the input using the JSON protocol as
implemented by the ``json`` Python 2.6 library.
"""
gc.disable()
str_ = json.dumps(inbox[0])
gc.enable()
return str_ | python | def json_dumps(inbox):
"""
Serializes the first element of the input using the JSON protocol as
implemented by the ``json`` Python 2.6 library.
"""
gc.disable()
str_ = json.dumps(inbox[0])
gc.enable()
return str_ | [
"def",
"json_dumps",
"(",
"inbox",
")",
":",
"gc",
".",
"disable",
"(",
")",
"str_",
"=",
"json",
".",
"dumps",
"(",
"inbox",
"[",
"0",
"]",
")",
"gc",
".",
"enable",
"(",
")",
"return",
"str_"
] | Serializes the first element of the input using the JSON protocol as
implemented by the ``json`` Python 2.6 library. | [
"Serializes",
"the",
"first",
"element",
"of",
"the",
"input",
"using",
"the",
"JSON",
"protocol",
"as",
"implemented",
"by",
"the",
"json",
"Python",
"2",
".",
"6",
"library",
"."
] | 708e50827b5db46bbea081982cb74b9b0e464064 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/util/func.py#L535-L544 | train |
mcieslik-mctp/papy | src/papy/util/func.py | json_loads | def json_loads(inbox):
"""
Deserializes the first element of the input using the JSON protocol as
implemented by the ``json`` Python 2.6 library.
"""
gc.disable()
obj = json.loads(inbox[0])
gc.enable()
return obj | python | def json_loads(inbox):
"""
Deserializes the first element of the input using the JSON protocol as
implemented by the ``json`` Python 2.6 library.
"""
gc.disable()
obj = json.loads(inbox[0])
gc.enable()
return obj | [
"def",
"json_loads",
"(",
"inbox",
")",
":",
"gc",
".",
"disable",
"(",
")",
"obj",
"=",
"json",
".",
"loads",
"(",
"inbox",
"[",
"0",
"]",
")",
"gc",
".",
"enable",
"(",
")",
"return",
"obj"
] | Deserializes the first element of the input using the JSON protocol as
implemented by the ``json`` Python 2.6 library. | [
"Deserializes",
"the",
"first",
"element",
"of",
"the",
"input",
"using",
"the",
"JSON",
"protocol",
"as",
"implemented",
"by",
"the",
"json",
"Python",
"2",
".",
"6",
"library",
"."
] | 708e50827b5db46bbea081982cb74b9b0e464064 | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/util/func.py#L547-L556 | train |
NetworkAutomation/jaide | jaide/cli.py | at_time_validate | def at_time_validate(ctx, param, value):
""" Callback validating the at_time commit option.
Purpose: Validates the `at time` option for the commit command. Only the
| the following two formats are supported: 'hh:mm[:ss]' or
| 'yyyy-mm-dd hh:mm[:ss]' (seconds are optional).
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator. Callback
| functions such as this one receive this automatically.
@type ctx: click.Context
@param param: param is passed into a validation callback function by click.
| We do not use it.
@type param: None
@param value: The value that the user supplied for the at_time option.
@type value: str
@returns: The value that the user supplied, if it passed validation.
| Otherwise, raises click.BadParameter
@rtype: str
"""
# if they are doing commit_at, ensure the input is formatted correctly.
if value is not None:
if (re.search(r'([0-2]\d)(:[0-5]\d){1,2}', value) is None and
re.search(r'\d{4}-[01]\d-[0-3]\d [0-2]\d:[0-5]\d(:[0-5]\d)?',
value) is None):
raise click.BadParameter("A commit at time must be in one of the "
"two formats: 'hh:mm[:ss]' or "
"'yyyy-mm-dd hh:mm[:ss]' (seconds are "
"optional).")
ctx.obj['at_time'] = value
return value | python | def at_time_validate(ctx, param, value):
""" Callback validating the at_time commit option.
Purpose: Validates the `at time` option for the commit command. Only the
| the following two formats are supported: 'hh:mm[:ss]' or
| 'yyyy-mm-dd hh:mm[:ss]' (seconds are optional).
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator. Callback
| functions such as this one receive this automatically.
@type ctx: click.Context
@param param: param is passed into a validation callback function by click.
| We do not use it.
@type param: None
@param value: The value that the user supplied for the at_time option.
@type value: str
@returns: The value that the user supplied, if it passed validation.
| Otherwise, raises click.BadParameter
@rtype: str
"""
# if they are doing commit_at, ensure the input is formatted correctly.
if value is not None:
if (re.search(r'([0-2]\d)(:[0-5]\d){1,2}', value) is None and
re.search(r'\d{4}-[01]\d-[0-3]\d [0-2]\d:[0-5]\d(:[0-5]\d)?',
value) is None):
raise click.BadParameter("A commit at time must be in one of the "
"two formats: 'hh:mm[:ss]' or "
"'yyyy-mm-dd hh:mm[:ss]' (seconds are "
"optional).")
ctx.obj['at_time'] = value
return value | [
"def",
"at_time_validate",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"# if they are doing commit_at, ensure the input is formatted correctly.",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"(",
"re",
".",
"search",
"(",
"r'([0-2]\\d)(:[0-5]\\d){1,2}'",
",",
"value",
")",
"is",
"None",
"and",
"re",
".",
"search",
"(",
"r'\\d{4}-[01]\\d-[0-3]\\d [0-2]\\d:[0-5]\\d(:[0-5]\\d)?'",
",",
"value",
")",
"is",
"None",
")",
":",
"raise",
"click",
".",
"BadParameter",
"(",
"\"A commit at time must be in one of the \"",
"\"two formats: 'hh:mm[:ss]' or \"",
"\"'yyyy-mm-dd hh:mm[:ss]' (seconds are \"",
"\"optional).\"",
")",
"ctx",
".",
"obj",
"[",
"'at_time'",
"]",
"=",
"value",
"return",
"value"
] | Callback validating the at_time commit option.
Purpose: Validates the `at time` option for the commit command. Only the
| the following two formats are supported: 'hh:mm[:ss]' or
| 'yyyy-mm-dd hh:mm[:ss]' (seconds are optional).
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator. Callback
| functions such as this one receive this automatically.
@type ctx: click.Context
@param param: param is passed into a validation callback function by click.
| We do not use it.
@type param: None
@param value: The value that the user supplied for the at_time option.
@type value: str
@returns: The value that the user supplied, if it passed validation.
| Otherwise, raises click.BadParameter
@rtype: str | [
"Callback",
"validating",
"the",
"at_time",
"commit",
"option",
"."
] | 8571b987a8c24c246dc09f1bcc11cb0f045ec33f | https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/cli.py#L54-L86 | train |
NetworkAutomation/jaide | jaide/cli.py | write_validate | def write_validate(ctx, param, value):
""" Validate the -w option.
Purpose: Validates the `-w`|`--write` option. Two arguments are expected.
| The first is the mode, which must be in ['s', 'single', 'm',
| 'multiple']. The mode determins if we're writing to one file for
| all device output, or to a separate file for each device being
| handled.
|
| The second expected argument is the filepath of the desired
| output file. This will automatically be prepended with the IP or
| hostname of the device if we're writing to multiple files.
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator. Callback
| functions such as this one receive this automatically.
@type ctx: click.Context
@param param: param is passed into a validation callback function by click.
| We do not use it.
@type param: None
@param value: The value that the user supplied for the write option.
@type value: str
@returns: The value that the user supplied, if it passed validation.
| Otherwise, raises click.BadParameter
@rtype: str
"""
if value != ("default", "default"):
try:
mode, dest_file = (value[0], value[1])
except IndexError:
raise click.BadParameter('Expecting two arguments, one for how to '
'output (s, single, m, multiple), and '
'the second is a filepath where to put'
' the output.')
if mode.lower() not in ['s', 'single', 'm', 'multiple']:
raise click.BadParameter('The first argument of the -w/--write '
'option must specifies whether to write'
' to one file per device, or all device'
' output to a single file. Valid options'
' are "s", "single", "m", and "multiple"')
# we've passed the checks, so set the 'out' context variable to our
# tuple of the mode, and the destination file.
ctx.obj['out'] = (mode.lower(), dest_file)
else: # they didn't use -w, so set the context variable accordingly.
ctx.obj['out'] = None | python | def write_validate(ctx, param, value):
""" Validate the -w option.
Purpose: Validates the `-w`|`--write` option. Two arguments are expected.
| The first is the mode, which must be in ['s', 'single', 'm',
| 'multiple']. The mode determins if we're writing to one file for
| all device output, or to a separate file for each device being
| handled.
|
| The second expected argument is the filepath of the desired
| output file. This will automatically be prepended with the IP or
| hostname of the device if we're writing to multiple files.
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator. Callback
| functions such as this one receive this automatically.
@type ctx: click.Context
@param param: param is passed into a validation callback function by click.
| We do not use it.
@type param: None
@param value: The value that the user supplied for the write option.
@type value: str
@returns: The value that the user supplied, if it passed validation.
| Otherwise, raises click.BadParameter
@rtype: str
"""
if value != ("default", "default"):
try:
mode, dest_file = (value[0], value[1])
except IndexError:
raise click.BadParameter('Expecting two arguments, one for how to '
'output (s, single, m, multiple), and '
'the second is a filepath where to put'
' the output.')
if mode.lower() not in ['s', 'single', 'm', 'multiple']:
raise click.BadParameter('The first argument of the -w/--write '
'option must specifies whether to write'
' to one file per device, or all device'
' output to a single file. Valid options'
' are "s", "single", "m", and "multiple"')
# we've passed the checks, so set the 'out' context variable to our
# tuple of the mode, and the destination file.
ctx.obj['out'] = (mode.lower(), dest_file)
else: # they didn't use -w, so set the context variable accordingly.
ctx.obj['out'] = None | [
"def",
"write_validate",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"value",
"!=",
"(",
"\"default\"",
",",
"\"default\"",
")",
":",
"try",
":",
"mode",
",",
"dest_file",
"=",
"(",
"value",
"[",
"0",
"]",
",",
"value",
"[",
"1",
"]",
")",
"except",
"IndexError",
":",
"raise",
"click",
".",
"BadParameter",
"(",
"'Expecting two arguments, one for how to '",
"'output (s, single, m, multiple), and '",
"'the second is a filepath where to put'",
"' the output.'",
")",
"if",
"mode",
".",
"lower",
"(",
")",
"not",
"in",
"[",
"'s'",
",",
"'single'",
",",
"'m'",
",",
"'multiple'",
"]",
":",
"raise",
"click",
".",
"BadParameter",
"(",
"'The first argument of the -w/--write '",
"'option must specifies whether to write'",
"' to one file per device, or all device'",
"' output to a single file. Valid options'",
"' are \"s\", \"single\", \"m\", and \"multiple\"'",
")",
"# we've passed the checks, so set the 'out' context variable to our",
"# tuple of the mode, and the destination file.",
"ctx",
".",
"obj",
"[",
"'out'",
"]",
"=",
"(",
"mode",
".",
"lower",
"(",
")",
",",
"dest_file",
")",
"else",
":",
"# they didn't use -w, so set the context variable accordingly.",
"ctx",
".",
"obj",
"[",
"'out'",
"]",
"=",
"None"
] | Validate the -w option.
Purpose: Validates the `-w`|`--write` option. Two arguments are expected.
| The first is the mode, which must be in ['s', 'single', 'm',
| 'multiple']. The mode determins if we're writing to one file for
| all device output, or to a separate file for each device being
| handled.
|
| The second expected argument is the filepath of the desired
| output file. This will automatically be prepended with the IP or
| hostname of the device if we're writing to multiple files.
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator. Callback
| functions such as this one receive this automatically.
@type ctx: click.Context
@param param: param is passed into a validation callback function by click.
| We do not use it.
@type param: None
@param value: The value that the user supplied for the write option.
@type value: str
@returns: The value that the user supplied, if it passed validation.
| Otherwise, raises click.BadParameter
@rtype: str | [
"Validate",
"the",
"-",
"w",
"option",
"."
] | 8571b987a8c24c246dc09f1bcc11cb0f045ec33f | https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/cli.py#L90-L136 | train |
NetworkAutomation/jaide | jaide/cli.py | write_out | def write_out(input):
""" Callback function to write the output from the script.
@param input: A tuple containing two things:
| 1. None or Tuple of file mode and destination filepath
| 2. The output of the jaide command that will be either
| written to sys.stdout or to a file, depending on the
| first index in the tuple.
|
| If the first index of the tuple *is not* another tuple,
| the output will be written to sys.stdout. If the first
| index *is* a tuple, that tuple is further broken down
| into the mode ('single' for single file or 'multiple'
| for one file for each IP), and the destination filepath.
@type input: tuple
@returns: None
"""
# peel off the to_file metadata from the output.
to_file, output = input
if to_file != "quiet":
try:
# split the to_file metadata into it's separate parts.
mode, dest_file = to_file
except TypeError:
# just dump the output if we had an internal problem with getting
# the metadata.
click.echo(output)
else:
ip = output.split('device: ')[1].split('\n')[0].strip()
if mode in ['m', 'multiple']:
# put the IP in front of the filename if we're writing each
# device to its own file.
dest_file = path.join(path.split(dest_file)[0], ip + "_" +
path.split(dest_file)[1])
try:
out_file = open(dest_file, 'a+b')
except IOError as e:
print(color("Could not open output file '%s' for writing. "
"Output would have been:\n%s" %
(dest_file, output), 'red'))
print(color('Here is the error for opening the output file:' +
str(e), 'red'))
else:
click.echo(output, nl=False, file=out_file)
print(color('%s output appended to: %s' % (ip, dest_file)))
out_file.close() | python | def write_out(input):
""" Callback function to write the output from the script.
@param input: A tuple containing two things:
| 1. None or Tuple of file mode and destination filepath
| 2. The output of the jaide command that will be either
| written to sys.stdout or to a file, depending on the
| first index in the tuple.
|
| If the first index of the tuple *is not* another tuple,
| the output will be written to sys.stdout. If the first
| index *is* a tuple, that tuple is further broken down
| into the mode ('single' for single file or 'multiple'
| for one file for each IP), and the destination filepath.
@type input: tuple
@returns: None
"""
# peel off the to_file metadata from the output.
to_file, output = input
if to_file != "quiet":
try:
# split the to_file metadata into it's separate parts.
mode, dest_file = to_file
except TypeError:
# just dump the output if we had an internal problem with getting
# the metadata.
click.echo(output)
else:
ip = output.split('device: ')[1].split('\n')[0].strip()
if mode in ['m', 'multiple']:
# put the IP in front of the filename if we're writing each
# device to its own file.
dest_file = path.join(path.split(dest_file)[0], ip + "_" +
path.split(dest_file)[1])
try:
out_file = open(dest_file, 'a+b')
except IOError as e:
print(color("Could not open output file '%s' for writing. "
"Output would have been:\n%s" %
(dest_file, output), 'red'))
print(color('Here is the error for opening the output file:' +
str(e), 'red'))
else:
click.echo(output, nl=False, file=out_file)
print(color('%s output appended to: %s' % (ip, dest_file)))
out_file.close() | [
"def",
"write_out",
"(",
"input",
")",
":",
"# peel off the to_file metadata from the output.",
"to_file",
",",
"output",
"=",
"input",
"if",
"to_file",
"!=",
"\"quiet\"",
":",
"try",
":",
"# split the to_file metadata into it's separate parts.",
"mode",
",",
"dest_file",
"=",
"to_file",
"except",
"TypeError",
":",
"# just dump the output if we had an internal problem with getting",
"# the metadata.",
"click",
".",
"echo",
"(",
"output",
")",
"else",
":",
"ip",
"=",
"output",
".",
"split",
"(",
"'device: '",
")",
"[",
"1",
"]",
".",
"split",
"(",
"'\\n'",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"if",
"mode",
"in",
"[",
"'m'",
",",
"'multiple'",
"]",
":",
"# put the IP in front of the filename if we're writing each",
"# device to its own file.",
"dest_file",
"=",
"path",
".",
"join",
"(",
"path",
".",
"split",
"(",
"dest_file",
")",
"[",
"0",
"]",
",",
"ip",
"+",
"\"_\"",
"+",
"path",
".",
"split",
"(",
"dest_file",
")",
"[",
"1",
"]",
")",
"try",
":",
"out_file",
"=",
"open",
"(",
"dest_file",
",",
"'a+b'",
")",
"except",
"IOError",
"as",
"e",
":",
"print",
"(",
"color",
"(",
"\"Could not open output file '%s' for writing. \"",
"\"Output would have been:\\n%s\"",
"%",
"(",
"dest_file",
",",
"output",
")",
",",
"'red'",
")",
")",
"print",
"(",
"color",
"(",
"'Here is the error for opening the output file:'",
"+",
"str",
"(",
"e",
")",
",",
"'red'",
")",
")",
"else",
":",
"click",
".",
"echo",
"(",
"output",
",",
"nl",
"=",
"False",
",",
"file",
"=",
"out_file",
")",
"print",
"(",
"color",
"(",
"'%s output appended to: %s'",
"%",
"(",
"ip",
",",
"dest_file",
")",
")",
")",
"out_file",
".",
"close",
"(",
")"
] | Callback function to write the output from the script.
@param input: A tuple containing two things:
| 1. None or Tuple of file mode and destination filepath
| 2. The output of the jaide command that will be either
| written to sys.stdout or to a file, depending on the
| first index in the tuple.
|
| If the first index of the tuple *is not* another tuple,
| the output will be written to sys.stdout. If the first
| index *is* a tuple, that tuple is further broken down
| into the mode ('single' for single file or 'multiple'
| for one file for each IP), and the destination filepath.
@type input: tuple
@returns: None | [
"Callback",
"function",
"to",
"write",
"the",
"output",
"from",
"the",
"script",
"."
] | 8571b987a8c24c246dc09f1bcc11cb0f045ec33f | https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/cli.py#L139-L185 | train |
NetworkAutomation/jaide | jaide/cli.py | main | def main(ctx, host, password, port, quiet, session_timeout, connect_timeout,
username):
""" Manipulate one or more Junos devices.
Purpose: The main function is the entry point for the jaide tool. Click
| handles arguments, commands and options. The parameters passed to
| this function are all potential options (required or not) that
| must come *before* the command from the group in the command line.
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator.
@type ctx: click.Context
@param host: The IP(s) or hostname(s) of the devices to connect to.
@type host: str
@param password: The string password used to connect to the device.
@type password: str
@param port: The numerical port to establish the connection to. Defauls
| to 22.
@type port: int
@param quiet: An option that the user can set to suppress all output
| from jaide.
@type quiet: bool
@param session_timeout: Sets the session timeout value. A higher value may
| be desired for long running commands, such as
| 'request system snapshot slice alternate'
@type session_timeout: int
@param connect_timeout: Sets the connection timeout value. This is how
| we'll wait when connecting before classifying
| the device unreachable.
@type connect_timeout: int
@param username: The string username used to connect to the device.
@type useranme: str
@returns: None. Functions part of click relating to the command group
| 'main' do not return anything. Click handles passing context
| between the functions and maintaing command order and chaining.
"""
# build the list of hosts
ctx.obj['hosts'] = [ip for ip in clean_lines(host)]
# set the connection parameters
ctx.obj['conn'] = {
"username": username,
"password": password,
"port": port,
"session_timeout": session_timeout,
"connect_timeout": connect_timeout
}
if quiet:
ctx.obj['out'] = "quiet" | python | def main(ctx, host, password, port, quiet, session_timeout, connect_timeout,
username):
""" Manipulate one or more Junos devices.
Purpose: The main function is the entry point for the jaide tool. Click
| handles arguments, commands and options. The parameters passed to
| this function are all potential options (required or not) that
| must come *before* the command from the group in the command line.
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator.
@type ctx: click.Context
@param host: The IP(s) or hostname(s) of the devices to connect to.
@type host: str
@param password: The string password used to connect to the device.
@type password: str
@param port: The numerical port to establish the connection to. Defauls
| to 22.
@type port: int
@param quiet: An option that the user can set to suppress all output
| from jaide.
@type quiet: bool
@param session_timeout: Sets the session timeout value. A higher value may
| be desired for long running commands, such as
| 'request system snapshot slice alternate'
@type session_timeout: int
@param connect_timeout: Sets the connection timeout value. This is how
| we'll wait when connecting before classifying
| the device unreachable.
@type connect_timeout: int
@param username: The string username used to connect to the device.
@type useranme: str
@returns: None. Functions part of click relating to the command group
| 'main' do not return anything. Click handles passing context
| between the functions and maintaing command order and chaining.
"""
# build the list of hosts
ctx.obj['hosts'] = [ip for ip in clean_lines(host)]
# set the connection parameters
ctx.obj['conn'] = {
"username": username,
"password": password,
"port": port,
"session_timeout": session_timeout,
"connect_timeout": connect_timeout
}
if quiet:
ctx.obj['out'] = "quiet" | [
"def",
"main",
"(",
"ctx",
",",
"host",
",",
"password",
",",
"port",
",",
"quiet",
",",
"session_timeout",
",",
"connect_timeout",
",",
"username",
")",
":",
"# build the list of hosts",
"ctx",
".",
"obj",
"[",
"'hosts'",
"]",
"=",
"[",
"ip",
"for",
"ip",
"in",
"clean_lines",
"(",
"host",
")",
"]",
"# set the connection parameters",
"ctx",
".",
"obj",
"[",
"'conn'",
"]",
"=",
"{",
"\"username\"",
":",
"username",
",",
"\"password\"",
":",
"password",
",",
"\"port\"",
":",
"port",
",",
"\"session_timeout\"",
":",
"session_timeout",
",",
"\"connect_timeout\"",
":",
"connect_timeout",
"}",
"if",
"quiet",
":",
"ctx",
".",
"obj",
"[",
"'out'",
"]",
"=",
"\"quiet\""
] | Manipulate one or more Junos devices.
Purpose: The main function is the entry point for the jaide tool. Click
| handles arguments, commands and options. The parameters passed to
| this function are all potential options (required or not) that
| must come *before* the command from the group in the command line.
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator.
@type ctx: click.Context
@param host: The IP(s) or hostname(s) of the devices to connect to.
@type host: str
@param password: The string password used to connect to the device.
@type password: str
@param port: The numerical port to establish the connection to. Defauls
| to 22.
@type port: int
@param quiet: An option that the user can set to suppress all output
| from jaide.
@type quiet: bool
@param session_timeout: Sets the session timeout value. A higher value may
| be desired for long running commands, such as
| 'request system snapshot slice alternate'
@type session_timeout: int
@param connect_timeout: Sets the connection timeout value. This is how
| we'll wait when connecting before classifying
| the device unreachable.
@type connect_timeout: int
@param username: The string username used to connect to the device.
@type useranme: str
@returns: None. Functions part of click relating to the command group
| 'main' do not return anything. Click handles passing context
| between the functions and maintaing command order and chaining. | [
"Manipulate",
"one",
"or",
"more",
"Junos",
"devices",
"."
] | 8571b987a8c24c246dc09f1bcc11cb0f045ec33f | https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/cli.py#L222-L271 | train |
NetworkAutomation/jaide | jaide/cli.py | compare | def compare(ctx, commands):
""" Run 'show | compare' for set commands.
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator.
@type ctx: click.Context
@param commands: The Junos set commands that will be put into a candidate
| configuration and used to create the 'show | compare'
| against the running configuration. much like the commands
| parameter for the commit() function, this can be one of
| three things: a string containing a single command, a
| string containing a comma separated list of commands, or
| a string containing a filepath location for a file with
| commands on each line.
@type commands: str
@returns: None. Functions part of click relating to the command group
| 'main' do not return anything. Click handles passing context
| between the functions and maintaing command order and chaining.
"""
mp_pool = multiprocessing.Pool(multiprocessing.cpu_count() * 2)
for ip in ctx.obj['hosts']:
mp_pool.apply_async(wrap.open_connection, args=(ip,
ctx.obj['conn']['username'],
ctx.obj['conn']['password'],
wrap.compare, [commands],
ctx.obj['out'],
ctx.obj['conn']['connect_timeout'],
ctx.obj['conn']['session_timeout'],
ctx.obj['conn']['port']), callback=write_out)
mp_pool.close()
mp_pool.join() | python | def compare(ctx, commands):
""" Run 'show | compare' for set commands.
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator.
@type ctx: click.Context
@param commands: The Junos set commands that will be put into a candidate
| configuration and used to create the 'show | compare'
| against the running configuration. much like the commands
| parameter for the commit() function, this can be one of
| three things: a string containing a single command, a
| string containing a comma separated list of commands, or
| a string containing a filepath location for a file with
| commands on each line.
@type commands: str
@returns: None. Functions part of click relating to the command group
| 'main' do not return anything. Click handles passing context
| between the functions and maintaing command order and chaining.
"""
mp_pool = multiprocessing.Pool(multiprocessing.cpu_count() * 2)
for ip in ctx.obj['hosts']:
mp_pool.apply_async(wrap.open_connection, args=(ip,
ctx.obj['conn']['username'],
ctx.obj['conn']['password'],
wrap.compare, [commands],
ctx.obj['out'],
ctx.obj['conn']['connect_timeout'],
ctx.obj['conn']['session_timeout'],
ctx.obj['conn']['port']), callback=write_out)
mp_pool.close()
mp_pool.join() | [
"def",
"compare",
"(",
"ctx",
",",
"commands",
")",
":",
"mp_pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"*",
"2",
")",
"for",
"ip",
"in",
"ctx",
".",
"obj",
"[",
"'hosts'",
"]",
":",
"mp_pool",
".",
"apply_async",
"(",
"wrap",
".",
"open_connection",
",",
"args",
"=",
"(",
"ip",
",",
"ctx",
".",
"obj",
"[",
"'conn'",
"]",
"[",
"'username'",
"]",
",",
"ctx",
".",
"obj",
"[",
"'conn'",
"]",
"[",
"'password'",
"]",
",",
"wrap",
".",
"compare",
",",
"[",
"commands",
"]",
",",
"ctx",
".",
"obj",
"[",
"'out'",
"]",
",",
"ctx",
".",
"obj",
"[",
"'conn'",
"]",
"[",
"'connect_timeout'",
"]",
",",
"ctx",
".",
"obj",
"[",
"'conn'",
"]",
"[",
"'session_timeout'",
"]",
",",
"ctx",
".",
"obj",
"[",
"'conn'",
"]",
"[",
"'port'",
"]",
")",
",",
"callback",
"=",
"write_out",
")",
"mp_pool",
".",
"close",
"(",
")",
"mp_pool",
".",
"join",
"(",
")"
] | Run 'show | compare' for set commands.
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator.
@type ctx: click.Context
@param commands: The Junos set commands that will be put into a candidate
| configuration and used to create the 'show | compare'
| against the running configuration. much like the commands
| parameter for the commit() function, this can be one of
| three things: a string containing a single command, a
| string containing a comma separated list of commands, or
| a string containing a filepath location for a file with
| commands on each line.
@type commands: str
@returns: None. Functions part of click relating to the command group
| 'main' do not return anything. Click handles passing context
| between the functions and maintaing command order and chaining. | [
"Run",
"show",
"|",
"compare",
"for",
"set",
"commands",
"."
] | 8571b987a8c24c246dc09f1bcc11cb0f045ec33f | https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/cli.py#L376-L408 | train |
NetworkAutomation/jaide | jaide/cli.py | diff_config | def diff_config(ctx, second_host, mode):
""" Config comparison between two devices.
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator.
@type ctx: click.Context
@param second_host: The IP/hostname of the second device to pull from
@type second_host: str
@param mode: The mode in which we are retrieving the config ('set' or
| 'stanza')
@type mode: str
@returns: None. Functions part of click relating to the command group
| 'main' do not return anything. Click handles passing context
| between the functions and maintaing command order and chaining.
"""
mp_pool = multiprocessing.Pool(multiprocessing.cpu_count() * 2)
for ip in ctx.obj['hosts']:
mp_pool.apply_async(wrap.open_connection, args=(ip,
ctx.obj['conn']['username'],
ctx.obj['conn']['password'],
wrap.diff_config, [second_host, mode],
ctx.obj['out'],
ctx.obj['conn']['connect_timeout'],
ctx.obj['conn']['session_timeout'],
ctx.obj['conn']['port']), callback=write_out)
mp_pool.close()
mp_pool.join() | python | def diff_config(ctx, second_host, mode):
""" Config comparison between two devices.
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator.
@type ctx: click.Context
@param second_host: The IP/hostname of the second device to pull from
@type second_host: str
@param mode: The mode in which we are retrieving the config ('set' or
| 'stanza')
@type mode: str
@returns: None. Functions part of click relating to the command group
| 'main' do not return anything. Click handles passing context
| between the functions and maintaing command order and chaining.
"""
mp_pool = multiprocessing.Pool(multiprocessing.cpu_count() * 2)
for ip in ctx.obj['hosts']:
mp_pool.apply_async(wrap.open_connection, args=(ip,
ctx.obj['conn']['username'],
ctx.obj['conn']['password'],
wrap.diff_config, [second_host, mode],
ctx.obj['out'],
ctx.obj['conn']['connect_timeout'],
ctx.obj['conn']['session_timeout'],
ctx.obj['conn']['port']), callback=write_out)
mp_pool.close()
mp_pool.join() | [
"def",
"diff_config",
"(",
"ctx",
",",
"second_host",
",",
"mode",
")",
":",
"mp_pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"*",
"2",
")",
"for",
"ip",
"in",
"ctx",
".",
"obj",
"[",
"'hosts'",
"]",
":",
"mp_pool",
".",
"apply_async",
"(",
"wrap",
".",
"open_connection",
",",
"args",
"=",
"(",
"ip",
",",
"ctx",
".",
"obj",
"[",
"'conn'",
"]",
"[",
"'username'",
"]",
",",
"ctx",
".",
"obj",
"[",
"'conn'",
"]",
"[",
"'password'",
"]",
",",
"wrap",
".",
"diff_config",
",",
"[",
"second_host",
",",
"mode",
"]",
",",
"ctx",
".",
"obj",
"[",
"'out'",
"]",
",",
"ctx",
".",
"obj",
"[",
"'conn'",
"]",
"[",
"'connect_timeout'",
"]",
",",
"ctx",
".",
"obj",
"[",
"'conn'",
"]",
"[",
"'session_timeout'",
"]",
",",
"ctx",
".",
"obj",
"[",
"'conn'",
"]",
"[",
"'port'",
"]",
")",
",",
"callback",
"=",
"write_out",
")",
"mp_pool",
".",
"close",
"(",
")",
"mp_pool",
".",
"join",
"(",
")"
] | Config comparison between two devices.
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorator.
@type ctx: click.Context
@param second_host: The IP/hostname of the second device to pull from
@type second_host: str
@param mode: The mode in which we are retrieving the config ('set' or
| 'stanza')
@type mode: str
@returns: None. Functions part of click relating to the command group
| 'main' do not return anything. Click handles passing context
| between the functions and maintaing command order and chaining. | [
"Config",
"comparison",
"between",
"two",
"devices",
"."
] | 8571b987a8c24c246dc09f1bcc11cb0f045ec33f | https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/cli.py#L593-L621 | train |
NetworkAutomation/jaide | jaide/cli.py | AliasedGroup.get_command | def get_command(self, ctx, cmd_name):
""" Allow for partial commands. """
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
matches = [x for x in self.list_commands(ctx)
if x.startswith(cmd_name)]
if not matches:
return None
elif len(matches) == 1:
return click.Group.get_command(self, ctx, matches[0])
ctx.fail('Command ambiguous, could be: %s' %
', '.join(sorted(matches))) | python | def get_command(self, ctx, cmd_name):
""" Allow for partial commands. """
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
matches = [x for x in self.list_commands(ctx)
if x.startswith(cmd_name)]
if not matches:
return None
elif len(matches) == 1:
return click.Group.get_command(self, ctx, matches[0])
ctx.fail('Command ambiguous, could be: %s' %
', '.join(sorted(matches))) | [
"def",
"get_command",
"(",
"self",
",",
"ctx",
",",
"cmd_name",
")",
":",
"rv",
"=",
"click",
".",
"Group",
".",
"get_command",
"(",
"self",
",",
"ctx",
",",
"cmd_name",
")",
"if",
"rv",
"is",
"not",
"None",
":",
"return",
"rv",
"matches",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"list_commands",
"(",
"ctx",
")",
"if",
"x",
".",
"startswith",
"(",
"cmd_name",
")",
"]",
"if",
"not",
"matches",
":",
"return",
"None",
"elif",
"len",
"(",
"matches",
")",
"==",
"1",
":",
"return",
"click",
".",
"Group",
".",
"get_command",
"(",
"self",
",",
"ctx",
",",
"matches",
"[",
"0",
"]",
")",
"ctx",
".",
"fail",
"(",
"'Command ambiguous, could be: %s'",
"%",
"', '",
".",
"join",
"(",
"sorted",
"(",
"matches",
")",
")",
")"
] | Allow for partial commands. | [
"Allow",
"for",
"partial",
"commands",
"."
] | 8571b987a8c24c246dc09f1bcc11cb0f045ec33f | https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/cli.py#L39-L51 | train |
dourvaris/nano-python | src/nano/conversion.py | convert | def convert(value, from_unit, to_unit):
"""
Converts a value from `from_unit` units to `to_unit` units
:param value: value to convert
:type value: int or str or decimal.Decimal
:param from_unit: unit to convert from
:type from_unit: str
:param to_unit: unit to convert to
:type to_unit: str
>>> convert(value='1.5', from_unit='xrb', to_unit='krai')
Decimal('0.0015')
"""
if isinstance(value, float):
raise ValueError(
"float values can lead to unexpected precision loss, please use a"
" Decimal or string eg."
" convert('%s', %r, %r)" % (value, from_unit, to_unit)
)
if from_unit not in UNITS_TO_RAW:
raise ValueError('unknown unit: %r' % from_unit)
if to_unit not in UNITS_TO_RAW:
raise ValueError('unknown unit: %r' % to_unit)
try:
value = Decimal(value)
except Exception:
raise ValueError('not a number: %r' % value)
from_value_in_base = UNITS_TO_RAW[from_unit]
to_value_in_base = UNITS_TO_RAW[to_unit]
result = value * (from_value_in_base / to_value_in_base)
return result.normalize() | python | def convert(value, from_unit, to_unit):
"""
Converts a value from `from_unit` units to `to_unit` units
:param value: value to convert
:type value: int or str or decimal.Decimal
:param from_unit: unit to convert from
:type from_unit: str
:param to_unit: unit to convert to
:type to_unit: str
>>> convert(value='1.5', from_unit='xrb', to_unit='krai')
Decimal('0.0015')
"""
if isinstance(value, float):
raise ValueError(
"float values can lead to unexpected precision loss, please use a"
" Decimal or string eg."
" convert('%s', %r, %r)" % (value, from_unit, to_unit)
)
if from_unit not in UNITS_TO_RAW:
raise ValueError('unknown unit: %r' % from_unit)
if to_unit not in UNITS_TO_RAW:
raise ValueError('unknown unit: %r' % to_unit)
try:
value = Decimal(value)
except Exception:
raise ValueError('not a number: %r' % value)
from_value_in_base = UNITS_TO_RAW[from_unit]
to_value_in_base = UNITS_TO_RAW[to_unit]
result = value * (from_value_in_base / to_value_in_base)
return result.normalize() | [
"def",
"convert",
"(",
"value",
",",
"from_unit",
",",
"to_unit",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"float",
")",
":",
"raise",
"ValueError",
"(",
"\"float values can lead to unexpected precision loss, please use a\"",
"\" Decimal or string eg.\"",
"\" convert('%s', %r, %r)\"",
"%",
"(",
"value",
",",
"from_unit",
",",
"to_unit",
")",
")",
"if",
"from_unit",
"not",
"in",
"UNITS_TO_RAW",
":",
"raise",
"ValueError",
"(",
"'unknown unit: %r'",
"%",
"from_unit",
")",
"if",
"to_unit",
"not",
"in",
"UNITS_TO_RAW",
":",
"raise",
"ValueError",
"(",
"'unknown unit: %r'",
"%",
"to_unit",
")",
"try",
":",
"value",
"=",
"Decimal",
"(",
"value",
")",
"except",
"Exception",
":",
"raise",
"ValueError",
"(",
"'not a number: %r'",
"%",
"value",
")",
"from_value_in_base",
"=",
"UNITS_TO_RAW",
"[",
"from_unit",
"]",
"to_value_in_base",
"=",
"UNITS_TO_RAW",
"[",
"to_unit",
"]",
"result",
"=",
"value",
"*",
"(",
"from_value_in_base",
"/",
"to_value_in_base",
")",
"return",
"result",
".",
"normalize",
"(",
")"
] | Converts a value from `from_unit` units to `to_unit` units
:param value: value to convert
:type value: int or str or decimal.Decimal
:param from_unit: unit to convert from
:type from_unit: str
:param to_unit: unit to convert to
:type to_unit: str
>>> convert(value='1.5', from_unit='xrb', to_unit='krai')
Decimal('0.0015') | [
"Converts",
"a",
"value",
"from",
"from_unit",
"units",
"to",
"to_unit",
"units"
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/conversion.py#L45-L85 | train |
ofa/django-bouncy | django_bouncy/views.py | endpoint | def endpoint(request):
"""Endpoint that SNS accesses. Includes logic verifying request"""
# pylint: disable=too-many-return-statements,too-many-branches
# In order to 'hide' the endpoint, all non-POST requests should return
# the site's default HTTP404
if request.method != 'POST':
raise Http404
# If necessary, check that the topic is correct
if hasattr(settings, 'BOUNCY_TOPIC_ARN'):
# Confirm that the proper topic header was sent
if 'HTTP_X_AMZ_SNS_TOPIC_ARN' not in request.META:
return HttpResponseBadRequest('No TopicArn Header')
# Check to see if the topic is in the settings
# Because you can have bounces and complaints coming from multiple
# topics, BOUNCY_TOPIC_ARN is a list
if (not request.META['HTTP_X_AMZ_SNS_TOPIC_ARN']
in settings.BOUNCY_TOPIC_ARN):
return HttpResponseBadRequest('Bad Topic')
# Load the JSON POST Body
if isinstance(request.body, str):
# requests return str in python 2.7
request_body = request.body
else:
# and return bytes in python 3.4
request_body = request.body.decode()
try:
data = json.loads(request_body)
except ValueError:
logger.warning('Notification Not Valid JSON: {}'.format(request_body))
return HttpResponseBadRequest('Not Valid JSON')
# Ensure that the JSON we're provided contains all the keys we expect
# Comparison code from http://stackoverflow.com/questions/1285911/
if not set(VITAL_NOTIFICATION_FIELDS) <= set(data):
logger.warning('Request Missing Necessary Keys')
return HttpResponseBadRequest('Request Missing Necessary Keys')
# Ensure that the type of notification is one we'll accept
if not data['Type'] in ALLOWED_TYPES:
logger.info('Notification Type Not Known %s', data['Type'])
return HttpResponseBadRequest('Unknown Notification Type')
# Confirm that the signing certificate is hosted on a correct domain
# AWS by default uses sns.{region}.amazonaws.com
# On the off chance you need this to be a different domain, allow the
# regex to be overridden in settings
domain = urlparse(data['SigningCertURL']).netloc
pattern = getattr(
settings, 'BOUNCY_CERT_DOMAIN_REGEX', r"sns.[a-z0-9\-]+.amazonaws.com$"
)
if not re.search(pattern, domain):
logger.warning(
'Improper Certificate Location %s', data['SigningCertURL'])
return HttpResponseBadRequest('Improper Certificate Location')
# Verify that the notification is signed by Amazon
if (getattr(settings, 'BOUNCY_VERIFY_CERTIFICATE', True)
and not verify_notification(data)):
logger.error('Verification Failure %s', )
return HttpResponseBadRequest('Improper Signature')
# Send a signal to say a valid notification has been received
signals.notification.send(
sender='bouncy_endpoint', notification=data, request=request)
# Handle subscription-based messages.
if data['Type'] == 'SubscriptionConfirmation':
# Allow the disabling of the auto-subscription feature
if not getattr(settings, 'BOUNCY_AUTO_SUBSCRIBE', True):
raise Http404
return approve_subscription(data)
elif data['Type'] == 'UnsubscribeConfirmation':
# We won't handle unsubscribe requests here. Return a 200 status code
# so Amazon won't redeliver the request. If you want to remove this
# endpoint, remove it either via the API or the AWS Console
logger.info('UnsubscribeConfirmation Not Handled')
return HttpResponse('UnsubscribeConfirmation Not Handled')
try:
message = json.loads(data['Message'])
except ValueError:
# This message is not JSON. But we need to return a 200 status code
# so that Amazon doesn't attempt to deliver the message again
logger.info('Non-Valid JSON Message Received')
return HttpResponse('Message is not valid JSON')
return process_message(message, data) | python | def endpoint(request):
"""Endpoint that SNS accesses. Includes logic verifying request"""
# pylint: disable=too-many-return-statements,too-many-branches
# In order to 'hide' the endpoint, all non-POST requests should return
# the site's default HTTP404
if request.method != 'POST':
raise Http404
# If necessary, check that the topic is correct
if hasattr(settings, 'BOUNCY_TOPIC_ARN'):
# Confirm that the proper topic header was sent
if 'HTTP_X_AMZ_SNS_TOPIC_ARN' not in request.META:
return HttpResponseBadRequest('No TopicArn Header')
# Check to see if the topic is in the settings
# Because you can have bounces and complaints coming from multiple
# topics, BOUNCY_TOPIC_ARN is a list
if (not request.META['HTTP_X_AMZ_SNS_TOPIC_ARN']
in settings.BOUNCY_TOPIC_ARN):
return HttpResponseBadRequest('Bad Topic')
# Load the JSON POST Body
if isinstance(request.body, str):
# requests return str in python 2.7
request_body = request.body
else:
# and return bytes in python 3.4
request_body = request.body.decode()
try:
data = json.loads(request_body)
except ValueError:
logger.warning('Notification Not Valid JSON: {}'.format(request_body))
return HttpResponseBadRequest('Not Valid JSON')
# Ensure that the JSON we're provided contains all the keys we expect
# Comparison code from http://stackoverflow.com/questions/1285911/
if not set(VITAL_NOTIFICATION_FIELDS) <= set(data):
logger.warning('Request Missing Necessary Keys')
return HttpResponseBadRequest('Request Missing Necessary Keys')
# Ensure that the type of notification is one we'll accept
if not data['Type'] in ALLOWED_TYPES:
logger.info('Notification Type Not Known %s', data['Type'])
return HttpResponseBadRequest('Unknown Notification Type')
# Confirm that the signing certificate is hosted on a correct domain
# AWS by default uses sns.{region}.amazonaws.com
# On the off chance you need this to be a different domain, allow the
# regex to be overridden in settings
domain = urlparse(data['SigningCertURL']).netloc
pattern = getattr(
settings, 'BOUNCY_CERT_DOMAIN_REGEX', r"sns.[a-z0-9\-]+.amazonaws.com$"
)
if not re.search(pattern, domain):
logger.warning(
'Improper Certificate Location %s', data['SigningCertURL'])
return HttpResponseBadRequest('Improper Certificate Location')
# Verify that the notification is signed by Amazon
if (getattr(settings, 'BOUNCY_VERIFY_CERTIFICATE', True)
and not verify_notification(data)):
logger.error('Verification Failure %s', )
return HttpResponseBadRequest('Improper Signature')
# Send a signal to say a valid notification has been received
signals.notification.send(
sender='bouncy_endpoint', notification=data, request=request)
# Handle subscription-based messages.
if data['Type'] == 'SubscriptionConfirmation':
# Allow the disabling of the auto-subscription feature
if not getattr(settings, 'BOUNCY_AUTO_SUBSCRIBE', True):
raise Http404
return approve_subscription(data)
elif data['Type'] == 'UnsubscribeConfirmation':
# We won't handle unsubscribe requests here. Return a 200 status code
# so Amazon won't redeliver the request. If you want to remove this
# endpoint, remove it either via the API or the AWS Console
logger.info('UnsubscribeConfirmation Not Handled')
return HttpResponse('UnsubscribeConfirmation Not Handled')
try:
message = json.loads(data['Message'])
except ValueError:
# This message is not JSON. But we need to return a 200 status code
# so that Amazon doesn't attempt to deliver the message again
logger.info('Non-Valid JSON Message Received')
return HttpResponse('Message is not valid JSON')
return process_message(message, data) | [
"def",
"endpoint",
"(",
"request",
")",
":",
"# pylint: disable=too-many-return-statements,too-many-branches",
"# In order to 'hide' the endpoint, all non-POST requests should return",
"# the site's default HTTP404",
"if",
"request",
".",
"method",
"!=",
"'POST'",
":",
"raise",
"Http404",
"# If necessary, check that the topic is correct",
"if",
"hasattr",
"(",
"settings",
",",
"'BOUNCY_TOPIC_ARN'",
")",
":",
"# Confirm that the proper topic header was sent",
"if",
"'HTTP_X_AMZ_SNS_TOPIC_ARN'",
"not",
"in",
"request",
".",
"META",
":",
"return",
"HttpResponseBadRequest",
"(",
"'No TopicArn Header'",
")",
"# Check to see if the topic is in the settings",
"# Because you can have bounces and complaints coming from multiple",
"# topics, BOUNCY_TOPIC_ARN is a list",
"if",
"(",
"not",
"request",
".",
"META",
"[",
"'HTTP_X_AMZ_SNS_TOPIC_ARN'",
"]",
"in",
"settings",
".",
"BOUNCY_TOPIC_ARN",
")",
":",
"return",
"HttpResponseBadRequest",
"(",
"'Bad Topic'",
")",
"# Load the JSON POST Body",
"if",
"isinstance",
"(",
"request",
".",
"body",
",",
"str",
")",
":",
"# requests return str in python 2.7",
"request_body",
"=",
"request",
".",
"body",
"else",
":",
"# and return bytes in python 3.4",
"request_body",
"=",
"request",
".",
"body",
".",
"decode",
"(",
")",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"request_body",
")",
"except",
"ValueError",
":",
"logger",
".",
"warning",
"(",
"'Notification Not Valid JSON: {}'",
".",
"format",
"(",
"request_body",
")",
")",
"return",
"HttpResponseBadRequest",
"(",
"'Not Valid JSON'",
")",
"# Ensure that the JSON we're provided contains all the keys we expect",
"# Comparison code from http://stackoverflow.com/questions/1285911/",
"if",
"not",
"set",
"(",
"VITAL_NOTIFICATION_FIELDS",
")",
"<=",
"set",
"(",
"data",
")",
":",
"logger",
".",
"warning",
"(",
"'Request Missing Necessary Keys'",
")",
"return",
"HttpResponseBadRequest",
"(",
"'Request Missing Necessary Keys'",
")",
"# Ensure that the type of notification is one we'll accept",
"if",
"not",
"data",
"[",
"'Type'",
"]",
"in",
"ALLOWED_TYPES",
":",
"logger",
".",
"info",
"(",
"'Notification Type Not Known %s'",
",",
"data",
"[",
"'Type'",
"]",
")",
"return",
"HttpResponseBadRequest",
"(",
"'Unknown Notification Type'",
")",
"# Confirm that the signing certificate is hosted on a correct domain",
"# AWS by default uses sns.{region}.amazonaws.com",
"# On the off chance you need this to be a different domain, allow the",
"# regex to be overridden in settings",
"domain",
"=",
"urlparse",
"(",
"data",
"[",
"'SigningCertURL'",
"]",
")",
".",
"netloc",
"pattern",
"=",
"getattr",
"(",
"settings",
",",
"'BOUNCY_CERT_DOMAIN_REGEX'",
",",
"r\"sns.[a-z0-9\\-]+.amazonaws.com$\"",
")",
"if",
"not",
"re",
".",
"search",
"(",
"pattern",
",",
"domain",
")",
":",
"logger",
".",
"warning",
"(",
"'Improper Certificate Location %s'",
",",
"data",
"[",
"'SigningCertURL'",
"]",
")",
"return",
"HttpResponseBadRequest",
"(",
"'Improper Certificate Location'",
")",
"# Verify that the notification is signed by Amazon",
"if",
"(",
"getattr",
"(",
"settings",
",",
"'BOUNCY_VERIFY_CERTIFICATE'",
",",
"True",
")",
"and",
"not",
"verify_notification",
"(",
"data",
")",
")",
":",
"logger",
".",
"error",
"(",
"'Verification Failure %s'",
",",
")",
"return",
"HttpResponseBadRequest",
"(",
"'Improper Signature'",
")",
"# Send a signal to say a valid notification has been received",
"signals",
".",
"notification",
".",
"send",
"(",
"sender",
"=",
"'bouncy_endpoint'",
",",
"notification",
"=",
"data",
",",
"request",
"=",
"request",
")",
"# Handle subscription-based messages.",
"if",
"data",
"[",
"'Type'",
"]",
"==",
"'SubscriptionConfirmation'",
":",
"# Allow the disabling of the auto-subscription feature",
"if",
"not",
"getattr",
"(",
"settings",
",",
"'BOUNCY_AUTO_SUBSCRIBE'",
",",
"True",
")",
":",
"raise",
"Http404",
"return",
"approve_subscription",
"(",
"data",
")",
"elif",
"data",
"[",
"'Type'",
"]",
"==",
"'UnsubscribeConfirmation'",
":",
"# We won't handle unsubscribe requests here. Return a 200 status code",
"# so Amazon won't redeliver the request. If you want to remove this",
"# endpoint, remove it either via the API or the AWS Console",
"logger",
".",
"info",
"(",
"'UnsubscribeConfirmation Not Handled'",
")",
"return",
"HttpResponse",
"(",
"'UnsubscribeConfirmation Not Handled'",
")",
"try",
":",
"message",
"=",
"json",
".",
"loads",
"(",
"data",
"[",
"'Message'",
"]",
")",
"except",
"ValueError",
":",
"# This message is not JSON. But we need to return a 200 status code",
"# so that Amazon doesn't attempt to deliver the message again",
"logger",
".",
"info",
"(",
"'Non-Valid JSON Message Received'",
")",
"return",
"HttpResponse",
"(",
"'Message is not valid JSON'",
")",
"return",
"process_message",
"(",
"message",
",",
"data",
")"
] | Endpoint that SNS accesses. Includes logic verifying request | [
"Endpoint",
"that",
"SNS",
"accesses",
".",
"Includes",
"logic",
"verifying",
"request"
] | a386dfa8c4ce59bd18978a3537c03cd6ad07bf06 | https://github.com/ofa/django-bouncy/blob/a386dfa8c4ce59bd18978a3537c03cd6ad07bf06/django_bouncy/views.py#L38-L128 | train |
ofa/django-bouncy | django_bouncy/views.py | process_message | def process_message(message, notification):
"""
Function to process a JSON message delivered from Amazon
"""
# Confirm that there are 'notificationType' and 'mail' fields in our
# message
if not set(VITAL_MESSAGE_FIELDS) <= set(message):
# At this point we're sure that it's Amazon sending the message
# If we don't return a 200 status code, Amazon will attempt to send us
# this same message a few seconds later.
logger.info('JSON Message Missing Vital Fields')
return HttpResponse('Missing Vital Fields')
if message['notificationType'] == 'Complaint':
return process_complaint(message, notification)
if message['notificationType'] == 'Bounce':
return process_bounce(message, notification)
if message['notificationType'] == 'Delivery':
return process_delivery(message, notification)
else:
return HttpResponse('Unknown Notification Type') | python | def process_message(message, notification):
"""
Function to process a JSON message delivered from Amazon
"""
# Confirm that there are 'notificationType' and 'mail' fields in our
# message
if not set(VITAL_MESSAGE_FIELDS) <= set(message):
# At this point we're sure that it's Amazon sending the message
# If we don't return a 200 status code, Amazon will attempt to send us
# this same message a few seconds later.
logger.info('JSON Message Missing Vital Fields')
return HttpResponse('Missing Vital Fields')
if message['notificationType'] == 'Complaint':
return process_complaint(message, notification)
if message['notificationType'] == 'Bounce':
return process_bounce(message, notification)
if message['notificationType'] == 'Delivery':
return process_delivery(message, notification)
else:
return HttpResponse('Unknown Notification Type') | [
"def",
"process_message",
"(",
"message",
",",
"notification",
")",
":",
"# Confirm that there are 'notificationType' and 'mail' fields in our",
"# message",
"if",
"not",
"set",
"(",
"VITAL_MESSAGE_FIELDS",
")",
"<=",
"set",
"(",
"message",
")",
":",
"# At this point we're sure that it's Amazon sending the message",
"# If we don't return a 200 status code, Amazon will attempt to send us",
"# this same message a few seconds later.",
"logger",
".",
"info",
"(",
"'JSON Message Missing Vital Fields'",
")",
"return",
"HttpResponse",
"(",
"'Missing Vital Fields'",
")",
"if",
"message",
"[",
"'notificationType'",
"]",
"==",
"'Complaint'",
":",
"return",
"process_complaint",
"(",
"message",
",",
"notification",
")",
"if",
"message",
"[",
"'notificationType'",
"]",
"==",
"'Bounce'",
":",
"return",
"process_bounce",
"(",
"message",
",",
"notification",
")",
"if",
"message",
"[",
"'notificationType'",
"]",
"==",
"'Delivery'",
":",
"return",
"process_delivery",
"(",
"message",
",",
"notification",
")",
"else",
":",
"return",
"HttpResponse",
"(",
"'Unknown Notification Type'",
")"
] | Function to process a JSON message delivered from Amazon | [
"Function",
"to",
"process",
"a",
"JSON",
"message",
"delivered",
"from",
"Amazon"
] | a386dfa8c4ce59bd18978a3537c03cd6ad07bf06 | https://github.com/ofa/django-bouncy/blob/a386dfa8c4ce59bd18978a3537c03cd6ad07bf06/django_bouncy/views.py#L131-L151 | train |
ofa/django-bouncy | django_bouncy/views.py | process_bounce | def process_bounce(message, notification):
"""Function to process a bounce notification"""
mail = message['mail']
bounce = message['bounce']
bounces = []
for recipient in bounce['bouncedRecipients']:
# Create each bounce record. Add to a list for reference later.
bounces += [Bounce.objects.create(
sns_topic=notification['TopicArn'],
sns_messageid=notification['MessageId'],
mail_timestamp=clean_time(mail['timestamp']),
mail_id=mail['messageId'],
mail_from=mail['source'],
address=recipient['emailAddress'],
feedback_id=bounce['feedbackId'],
feedback_timestamp=clean_time(bounce['timestamp']),
hard=bool(bounce['bounceType'] == 'Permanent'),
bounce_type=bounce['bounceType'],
bounce_subtype=bounce['bounceSubType'],
reporting_mta=bounce.get('reportingMTA'),
action=recipient.get('action'),
status=recipient.get('status'),
diagnostic_code=recipient.get('diagnosticCode')
)]
# Send signals for each bounce.
for bounce in bounces:
signals.feedback.send(
sender=Bounce,
instance=bounce,
message=message,
notification=notification
)
logger.info('Logged %s Bounce(s)', str(len(bounces)))
return HttpResponse('Bounce Processed') | python | def process_bounce(message, notification):
"""Function to process a bounce notification"""
mail = message['mail']
bounce = message['bounce']
bounces = []
for recipient in bounce['bouncedRecipients']:
# Create each bounce record. Add to a list for reference later.
bounces += [Bounce.objects.create(
sns_topic=notification['TopicArn'],
sns_messageid=notification['MessageId'],
mail_timestamp=clean_time(mail['timestamp']),
mail_id=mail['messageId'],
mail_from=mail['source'],
address=recipient['emailAddress'],
feedback_id=bounce['feedbackId'],
feedback_timestamp=clean_time(bounce['timestamp']),
hard=bool(bounce['bounceType'] == 'Permanent'),
bounce_type=bounce['bounceType'],
bounce_subtype=bounce['bounceSubType'],
reporting_mta=bounce.get('reportingMTA'),
action=recipient.get('action'),
status=recipient.get('status'),
diagnostic_code=recipient.get('diagnosticCode')
)]
# Send signals for each bounce.
for bounce in bounces:
signals.feedback.send(
sender=Bounce,
instance=bounce,
message=message,
notification=notification
)
logger.info('Logged %s Bounce(s)', str(len(bounces)))
return HttpResponse('Bounce Processed') | [
"def",
"process_bounce",
"(",
"message",
",",
"notification",
")",
":",
"mail",
"=",
"message",
"[",
"'mail'",
"]",
"bounce",
"=",
"message",
"[",
"'bounce'",
"]",
"bounces",
"=",
"[",
"]",
"for",
"recipient",
"in",
"bounce",
"[",
"'bouncedRecipients'",
"]",
":",
"# Create each bounce record. Add to a list for reference later.",
"bounces",
"+=",
"[",
"Bounce",
".",
"objects",
".",
"create",
"(",
"sns_topic",
"=",
"notification",
"[",
"'TopicArn'",
"]",
",",
"sns_messageid",
"=",
"notification",
"[",
"'MessageId'",
"]",
",",
"mail_timestamp",
"=",
"clean_time",
"(",
"mail",
"[",
"'timestamp'",
"]",
")",
",",
"mail_id",
"=",
"mail",
"[",
"'messageId'",
"]",
",",
"mail_from",
"=",
"mail",
"[",
"'source'",
"]",
",",
"address",
"=",
"recipient",
"[",
"'emailAddress'",
"]",
",",
"feedback_id",
"=",
"bounce",
"[",
"'feedbackId'",
"]",
",",
"feedback_timestamp",
"=",
"clean_time",
"(",
"bounce",
"[",
"'timestamp'",
"]",
")",
",",
"hard",
"=",
"bool",
"(",
"bounce",
"[",
"'bounceType'",
"]",
"==",
"'Permanent'",
")",
",",
"bounce_type",
"=",
"bounce",
"[",
"'bounceType'",
"]",
",",
"bounce_subtype",
"=",
"bounce",
"[",
"'bounceSubType'",
"]",
",",
"reporting_mta",
"=",
"bounce",
".",
"get",
"(",
"'reportingMTA'",
")",
",",
"action",
"=",
"recipient",
".",
"get",
"(",
"'action'",
")",
",",
"status",
"=",
"recipient",
".",
"get",
"(",
"'status'",
")",
",",
"diagnostic_code",
"=",
"recipient",
".",
"get",
"(",
"'diagnosticCode'",
")",
")",
"]",
"# Send signals for each bounce.",
"for",
"bounce",
"in",
"bounces",
":",
"signals",
".",
"feedback",
".",
"send",
"(",
"sender",
"=",
"Bounce",
",",
"instance",
"=",
"bounce",
",",
"message",
"=",
"message",
",",
"notification",
"=",
"notification",
")",
"logger",
".",
"info",
"(",
"'Logged %s Bounce(s)'",
",",
"str",
"(",
"len",
"(",
"bounces",
")",
")",
")",
"return",
"HttpResponse",
"(",
"'Bounce Processed'",
")"
] | Function to process a bounce notification | [
"Function",
"to",
"process",
"a",
"bounce",
"notification"
] | a386dfa8c4ce59bd18978a3537c03cd6ad07bf06 | https://github.com/ofa/django-bouncy/blob/a386dfa8c4ce59bd18978a3537c03cd6ad07bf06/django_bouncy/views.py#L154-L191 | train |
ofa/django-bouncy | django_bouncy/views.py | process_complaint | def process_complaint(message, notification):
"""Function to process a complaint notification"""
mail = message['mail']
complaint = message['complaint']
if 'arrivalDate' in complaint:
arrival_date = clean_time(complaint['arrivalDate'])
else:
arrival_date = None
complaints = []
for recipient in complaint['complainedRecipients']:
# Create each Complaint. Save in a list for reference later.
complaints += [Complaint.objects.create(
sns_topic=notification['TopicArn'],
sns_messageid=notification['MessageId'],
mail_timestamp=clean_time(mail['timestamp']),
mail_id=mail['messageId'],
mail_from=mail['source'],
address=recipient['emailAddress'],
feedback_id=complaint['feedbackId'],
feedback_timestamp=clean_time(complaint['timestamp']),
useragent=complaint.get('userAgent'),
feedback_type=complaint.get('complaintFeedbackType'),
arrival_date=arrival_date
)]
# Send signals for each complaint.
for complaint in complaints:
signals.feedback.send(
sender=Complaint,
instance=complaint,
message=message,
notification=notification
)
logger.info('Logged %s Complaint(s)', str(len(complaints)))
return HttpResponse('Complaint Processed') | python | def process_complaint(message, notification):
"""Function to process a complaint notification"""
mail = message['mail']
complaint = message['complaint']
if 'arrivalDate' in complaint:
arrival_date = clean_time(complaint['arrivalDate'])
else:
arrival_date = None
complaints = []
for recipient in complaint['complainedRecipients']:
# Create each Complaint. Save in a list for reference later.
complaints += [Complaint.objects.create(
sns_topic=notification['TopicArn'],
sns_messageid=notification['MessageId'],
mail_timestamp=clean_time(mail['timestamp']),
mail_id=mail['messageId'],
mail_from=mail['source'],
address=recipient['emailAddress'],
feedback_id=complaint['feedbackId'],
feedback_timestamp=clean_time(complaint['timestamp']),
useragent=complaint.get('userAgent'),
feedback_type=complaint.get('complaintFeedbackType'),
arrival_date=arrival_date
)]
# Send signals for each complaint.
for complaint in complaints:
signals.feedback.send(
sender=Complaint,
instance=complaint,
message=message,
notification=notification
)
logger.info('Logged %s Complaint(s)', str(len(complaints)))
return HttpResponse('Complaint Processed') | [
"def",
"process_complaint",
"(",
"message",
",",
"notification",
")",
":",
"mail",
"=",
"message",
"[",
"'mail'",
"]",
"complaint",
"=",
"message",
"[",
"'complaint'",
"]",
"if",
"'arrivalDate'",
"in",
"complaint",
":",
"arrival_date",
"=",
"clean_time",
"(",
"complaint",
"[",
"'arrivalDate'",
"]",
")",
"else",
":",
"arrival_date",
"=",
"None",
"complaints",
"=",
"[",
"]",
"for",
"recipient",
"in",
"complaint",
"[",
"'complainedRecipients'",
"]",
":",
"# Create each Complaint. Save in a list for reference later.",
"complaints",
"+=",
"[",
"Complaint",
".",
"objects",
".",
"create",
"(",
"sns_topic",
"=",
"notification",
"[",
"'TopicArn'",
"]",
",",
"sns_messageid",
"=",
"notification",
"[",
"'MessageId'",
"]",
",",
"mail_timestamp",
"=",
"clean_time",
"(",
"mail",
"[",
"'timestamp'",
"]",
")",
",",
"mail_id",
"=",
"mail",
"[",
"'messageId'",
"]",
",",
"mail_from",
"=",
"mail",
"[",
"'source'",
"]",
",",
"address",
"=",
"recipient",
"[",
"'emailAddress'",
"]",
",",
"feedback_id",
"=",
"complaint",
"[",
"'feedbackId'",
"]",
",",
"feedback_timestamp",
"=",
"clean_time",
"(",
"complaint",
"[",
"'timestamp'",
"]",
")",
",",
"useragent",
"=",
"complaint",
".",
"get",
"(",
"'userAgent'",
")",
",",
"feedback_type",
"=",
"complaint",
".",
"get",
"(",
"'complaintFeedbackType'",
")",
",",
"arrival_date",
"=",
"arrival_date",
")",
"]",
"# Send signals for each complaint.",
"for",
"complaint",
"in",
"complaints",
":",
"signals",
".",
"feedback",
".",
"send",
"(",
"sender",
"=",
"Complaint",
",",
"instance",
"=",
"complaint",
",",
"message",
"=",
"message",
",",
"notification",
"=",
"notification",
")",
"logger",
".",
"info",
"(",
"'Logged %s Complaint(s)'",
",",
"str",
"(",
"len",
"(",
"complaints",
")",
")",
")",
"return",
"HttpResponse",
"(",
"'Complaint Processed'",
")"
] | Function to process a complaint notification | [
"Function",
"to",
"process",
"a",
"complaint",
"notification"
] | a386dfa8c4ce59bd18978a3537c03cd6ad07bf06 | https://github.com/ofa/django-bouncy/blob/a386dfa8c4ce59bd18978a3537c03cd6ad07bf06/django_bouncy/views.py#L194-L232 | train |
ofa/django-bouncy | django_bouncy/views.py | process_delivery | def process_delivery(message, notification):
"""Function to process a delivery notification"""
mail = message['mail']
delivery = message['delivery']
if 'timestamp' in delivery:
delivered_datetime = clean_time(delivery['timestamp'])
else:
delivered_datetime = None
deliveries = []
for eachrecipient in delivery['recipients']:
# Create each delivery
deliveries += [Delivery.objects.create(
sns_topic=notification['TopicArn'],
sns_messageid=notification['MessageId'],
mail_timestamp=clean_time(mail['timestamp']),
mail_id=mail['messageId'],
mail_from=mail['source'],
address=eachrecipient,
# delivery
delivered_time=delivered_datetime,
processing_time=int(delivery['processingTimeMillis']),
smtp_response=delivery['smtpResponse']
)]
# Send signals for each delivery.
for eachdelivery in deliveries:
signals.feedback.send(
sender=Delivery,
instance=eachdelivery,
message=message,
notification=notification
)
logger.info('Logged %s Deliveries(s)', str(len(deliveries)))
return HttpResponse('Delivery Processed') | python | def process_delivery(message, notification):
"""Function to process a delivery notification"""
mail = message['mail']
delivery = message['delivery']
if 'timestamp' in delivery:
delivered_datetime = clean_time(delivery['timestamp'])
else:
delivered_datetime = None
deliveries = []
for eachrecipient in delivery['recipients']:
# Create each delivery
deliveries += [Delivery.objects.create(
sns_topic=notification['TopicArn'],
sns_messageid=notification['MessageId'],
mail_timestamp=clean_time(mail['timestamp']),
mail_id=mail['messageId'],
mail_from=mail['source'],
address=eachrecipient,
# delivery
delivered_time=delivered_datetime,
processing_time=int(delivery['processingTimeMillis']),
smtp_response=delivery['smtpResponse']
)]
# Send signals for each delivery.
for eachdelivery in deliveries:
signals.feedback.send(
sender=Delivery,
instance=eachdelivery,
message=message,
notification=notification
)
logger.info('Logged %s Deliveries(s)', str(len(deliveries)))
return HttpResponse('Delivery Processed') | [
"def",
"process_delivery",
"(",
"message",
",",
"notification",
")",
":",
"mail",
"=",
"message",
"[",
"'mail'",
"]",
"delivery",
"=",
"message",
"[",
"'delivery'",
"]",
"if",
"'timestamp'",
"in",
"delivery",
":",
"delivered_datetime",
"=",
"clean_time",
"(",
"delivery",
"[",
"'timestamp'",
"]",
")",
"else",
":",
"delivered_datetime",
"=",
"None",
"deliveries",
"=",
"[",
"]",
"for",
"eachrecipient",
"in",
"delivery",
"[",
"'recipients'",
"]",
":",
"# Create each delivery ",
"deliveries",
"+=",
"[",
"Delivery",
".",
"objects",
".",
"create",
"(",
"sns_topic",
"=",
"notification",
"[",
"'TopicArn'",
"]",
",",
"sns_messageid",
"=",
"notification",
"[",
"'MessageId'",
"]",
",",
"mail_timestamp",
"=",
"clean_time",
"(",
"mail",
"[",
"'timestamp'",
"]",
")",
",",
"mail_id",
"=",
"mail",
"[",
"'messageId'",
"]",
",",
"mail_from",
"=",
"mail",
"[",
"'source'",
"]",
",",
"address",
"=",
"eachrecipient",
",",
"# delivery",
"delivered_time",
"=",
"delivered_datetime",
",",
"processing_time",
"=",
"int",
"(",
"delivery",
"[",
"'processingTimeMillis'",
"]",
")",
",",
"smtp_response",
"=",
"delivery",
"[",
"'smtpResponse'",
"]",
")",
"]",
"# Send signals for each delivery.",
"for",
"eachdelivery",
"in",
"deliveries",
":",
"signals",
".",
"feedback",
".",
"send",
"(",
"sender",
"=",
"Delivery",
",",
"instance",
"=",
"eachdelivery",
",",
"message",
"=",
"message",
",",
"notification",
"=",
"notification",
")",
"logger",
".",
"info",
"(",
"'Logged %s Deliveries(s)'",
",",
"str",
"(",
"len",
"(",
"deliveries",
")",
")",
")",
"return",
"HttpResponse",
"(",
"'Delivery Processed'",
")"
] | Function to process a delivery notification | [
"Function",
"to",
"process",
"a",
"delivery",
"notification"
] | a386dfa8c4ce59bd18978a3537c03cd6ad07bf06 | https://github.com/ofa/django-bouncy/blob/a386dfa8c4ce59bd18978a3537c03cd6ad07bf06/django_bouncy/views.py#L235-L272 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/webdriver.py | click_on_label | def click_on_label(step, label):
"""
Click on a label
"""
with AssertContextManager(step):
elem = world.browser.find_element_by_xpath(str(
'//label[normalize-space(text()) = "%s"]' % label))
elem.click() | python | def click_on_label(step, label):
"""
Click on a label
"""
with AssertContextManager(step):
elem = world.browser.find_element_by_xpath(str(
'//label[normalize-space(text()) = "%s"]' % label))
elem.click() | [
"def",
"click_on_label",
"(",
"step",
",",
"label",
")",
":",
"with",
"AssertContextManager",
"(",
"step",
")",
":",
"elem",
"=",
"world",
".",
"browser",
".",
"find_element_by_xpath",
"(",
"str",
"(",
"'//label[normalize-space(text()) = \"%s\"]'",
"%",
"label",
")",
")",
"elem",
".",
"click",
"(",
")"
] | Click on a label | [
"Click",
"on",
"a",
"label"
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/webdriver.py#L258-L266 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/webdriver.py | element_focused | def element_focused(step, id):
"""
Check if the element is focused
"""
elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id)))
focused = world.browser.switch_to_active_element()
assert_true(step, elem == focused) | python | def element_focused(step, id):
"""
Check if the element is focused
"""
elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id)))
focused = world.browser.switch_to_active_element()
assert_true(step, elem == focused) | [
"def",
"element_focused",
"(",
"step",
",",
"id",
")",
":",
"elem",
"=",
"world",
".",
"browser",
".",
"find_element_by_xpath",
"(",
"str",
"(",
"'id(\"{id}\")'",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
")",
"focused",
"=",
"world",
".",
"browser",
".",
"switch_to_active_element",
"(",
")",
"assert_true",
"(",
"step",
",",
"elem",
"==",
"focused",
")"
] | Check if the element is focused | [
"Check",
"if",
"the",
"element",
"is",
"focused"
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/webdriver.py#L270-L278 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/webdriver.py | element_not_focused | def element_not_focused(step, id):
"""
Check if the element is not focused
"""
elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id)))
focused = world.browser.switch_to_active_element()
assert_false(step, elem == focused) | python | def element_not_focused(step, id):
"""
Check if the element is not focused
"""
elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id)))
focused = world.browser.switch_to_active_element()
assert_false(step, elem == focused) | [
"def",
"element_not_focused",
"(",
"step",
",",
"id",
")",
":",
"elem",
"=",
"world",
".",
"browser",
".",
"find_element_by_xpath",
"(",
"str",
"(",
"'id(\"{id}\")'",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
")",
"focused",
"=",
"world",
".",
"browser",
".",
"switch_to_active_element",
"(",
")",
"assert_false",
"(",
"step",
",",
"elem",
"==",
"focused",
")"
] | Check if the element is not focused | [
"Check",
"if",
"the",
"element",
"is",
"not",
"focused"
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/webdriver.py#L282-L290 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/webdriver.py | input_has_value | def input_has_value(step, field_name, value):
"""
Check that the form input element has given value.
"""
with AssertContextManager(step):
text_field = find_any_field(world.browser,
DATE_FIELDS + TEXT_FIELDS,
field_name)
assert_false(step, text_field is False,
'Can not find a field named "%s"' % field_name)
assert_equals(text_field.get_attribute('value'), value) | python | def input_has_value(step, field_name, value):
"""
Check that the form input element has given value.
"""
with AssertContextManager(step):
text_field = find_any_field(world.browser,
DATE_FIELDS + TEXT_FIELDS,
field_name)
assert_false(step, text_field is False,
'Can not find a field named "%s"' % field_name)
assert_equals(text_field.get_attribute('value'), value) | [
"def",
"input_has_value",
"(",
"step",
",",
"field_name",
",",
"value",
")",
":",
"with",
"AssertContextManager",
"(",
"step",
")",
":",
"text_field",
"=",
"find_any_field",
"(",
"world",
".",
"browser",
",",
"DATE_FIELDS",
"+",
"TEXT_FIELDS",
",",
"field_name",
")",
"assert_false",
"(",
"step",
",",
"text_field",
"is",
"False",
",",
"'Can not find a field named \"%s\"'",
"%",
"field_name",
")",
"assert_equals",
"(",
"text_field",
".",
"get_attribute",
"(",
"'value'",
")",
",",
"value",
")"
] | Check that the form input element has given value. | [
"Check",
"that",
"the",
"form",
"input",
"element",
"has",
"given",
"value",
"."
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/webdriver.py#L294-L304 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/webdriver.py | submit_form_id | def submit_form_id(step, id):
"""
Submit the form having given id.
"""
form = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id)))
form.submit() | python | def submit_form_id(step, id):
"""
Submit the form having given id.
"""
form = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id)))
form.submit() | [
"def",
"submit_form_id",
"(",
"step",
",",
"id",
")",
":",
"form",
"=",
"world",
".",
"browser",
".",
"find_element_by_xpath",
"(",
"str",
"(",
"'id(\"{id}\")'",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
")",
"form",
".",
"submit",
"(",
")"
] | Submit the form having given id. | [
"Submit",
"the",
"form",
"having",
"given",
"id",
"."
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/webdriver.py#L317-L322 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/webdriver.py | submit_form_action | def submit_form_action(step, url):
"""
Submit the form having given action URL.
"""
form = world.browser.find_element_by_xpath(str('//form[@action="%s"]' %
url))
form.submit() | python | def submit_form_action(step, url):
"""
Submit the form having given action URL.
"""
form = world.browser.find_element_by_xpath(str('//form[@action="%s"]' %
url))
form.submit() | [
"def",
"submit_form_action",
"(",
"step",
",",
"url",
")",
":",
"form",
"=",
"world",
".",
"browser",
".",
"find_element_by_xpath",
"(",
"str",
"(",
"'//form[@action=\"%s\"]'",
"%",
"url",
")",
")",
"form",
".",
"submit",
"(",
")"
] | Submit the form having given action URL. | [
"Submit",
"the",
"form",
"having",
"given",
"action",
"URL",
"."
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/webdriver.py#L326-L332 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/webdriver.py | check_alert | def check_alert(step, text):
"""
Check the alert text
"""
try:
alert = Alert(world.browser)
assert_equals(alert.text, text)
except WebDriverException:
# PhantomJS is kinda poor
pass | python | def check_alert(step, text):
"""
Check the alert text
"""
try:
alert = Alert(world.browser)
assert_equals(alert.text, text)
except WebDriverException:
# PhantomJS is kinda poor
pass | [
"def",
"check_alert",
"(",
"step",
",",
"text",
")",
":",
"try",
":",
"alert",
"=",
"Alert",
"(",
"world",
".",
"browser",
")",
"assert_equals",
"(",
"alert",
".",
"text",
",",
"text",
")",
"except",
"WebDriverException",
":",
"# PhantomJS is kinda poor",
"pass"
] | Check the alert text | [
"Check",
"the",
"alert",
"text"
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/webdriver.py#L472-L482 | train |
bbangert/lettuce_webdriver | lettuce_webdriver/webdriver.py | page_title | def page_title(step, title):
"""
Check that the page title matches the given one.
"""
with AssertContextManager(step):
assert_equals(world.browser.title, title) | python | def page_title(step, title):
"""
Check that the page title matches the given one.
"""
with AssertContextManager(step):
assert_equals(world.browser.title, title) | [
"def",
"page_title",
"(",
"step",
",",
"title",
")",
":",
"with",
"AssertContextManager",
"(",
"step",
")",
":",
"assert_equals",
"(",
"world",
".",
"browser",
".",
"title",
",",
"title",
")"
] | Check that the page title matches the given one. | [
"Check",
"that",
"the",
"page",
"title",
"matches",
"the",
"given",
"one",
"."
] | d11f8531c43bb7150c316e0dc4ccd083617becf7 | https://github.com/bbangert/lettuce_webdriver/blob/d11f8531c43bb7150c316e0dc4ccd083617becf7/lettuce_webdriver/webdriver.py#L544-L550 | train |
qacafe/cdrouter.py | cdrouter/tags.py | TagsService.get | def get(self, name):
"""Get a tag.
:param name: Tag name as string.
:return: :class:`tags.Tag <tags.Tag>` object
:rtype: tags.Tag
"""
schema = TagSchema()
resp = self.service.get_id(self.base, name)
return self.service.decode(schema, resp) | python | def get(self, name):
"""Get a tag.
:param name: Tag name as string.
:return: :class:`tags.Tag <tags.Tag>` object
:rtype: tags.Tag
"""
schema = TagSchema()
resp = self.service.get_id(self.base, name)
return self.service.decode(schema, resp) | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"schema",
"=",
"TagSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"get_id",
"(",
"self",
".",
"base",
",",
"name",
")",
"return",
"self",
".",
"service",
".",
"decode",
"(",
"schema",
",",
"resp",
")"
] | Get a tag.
:param name: Tag name as string.
:return: :class:`tags.Tag <tags.Tag>` object
:rtype: tags.Tag | [
"Get",
"a",
"tag",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/tags.py#L93-L102 | train |
qacafe/cdrouter.py | cdrouter/tags.py | TagsService.edit | def edit(self, resource):
"""Edit a tag.
:param resource: :class:`tags.Tag <tags.Tag>` object
:return: :class:`tags.Tag <tags.Tag>` object
:rtype: tags.Tag
"""
schema = TagSchema(only=('name', 'configs', 'devices', 'packages', 'results'))
json = self.service.encode(schema, resource)
schema = TagSchema()
resp = self.service.edit(self.base, resource.name, json)
return self.service.decode(schema, resp) | python | def edit(self, resource):
"""Edit a tag.
:param resource: :class:`tags.Tag <tags.Tag>` object
:return: :class:`tags.Tag <tags.Tag>` object
:rtype: tags.Tag
"""
schema = TagSchema(only=('name', 'configs', 'devices', 'packages', 'results'))
json = self.service.encode(schema, resource)
schema = TagSchema()
resp = self.service.edit(self.base, resource.name, json)
return self.service.decode(schema, resp) | [
"def",
"edit",
"(",
"self",
",",
"resource",
")",
":",
"schema",
"=",
"TagSchema",
"(",
"only",
"=",
"(",
"'name'",
",",
"'configs'",
",",
"'devices'",
",",
"'packages'",
",",
"'results'",
")",
")",
"json",
"=",
"self",
".",
"service",
".",
"encode",
"(",
"schema",
",",
"resource",
")",
"schema",
"=",
"TagSchema",
"(",
")",
"resp",
"=",
"self",
".",
"service",
".",
"edit",
"(",
"self",
".",
"base",
",",
"resource",
".",
"name",
",",
"json",
")",
"return",
"self",
".",
"service",
".",
"decode",
"(",
"schema",
",",
"resp",
")"
] | Edit a tag.
:param resource: :class:`tags.Tag <tags.Tag>` object
:return: :class:`tags.Tag <tags.Tag>` object
:rtype: tags.Tag | [
"Edit",
"a",
"tag",
"."
] | aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5 | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/tags.py#L104-L116 | train |
crossbario/txaio-etcd | txaioetcd/_lease.py | Lease.remaining | def remaining(self):
"""
Get the remaining time-to-live of this lease.
:returns: TTL in seconds.
:rtype: int
"""
if self._expired:
raise Expired()
obj = {
u'ID': self.lease_id,
}
data = json.dumps(obj).encode('utf8')
url = u'{}/v3alpha/kv/lease/timetolive'.format(self._client._url).encode()
response = yield treq.post(url, data, headers=self._client._REQ_HEADERS)
obj = yield treq.json_content(response)
ttl = obj.get(u'TTL', None)
if not ttl:
self._expired = True
raise Expired()
# grantedTTL = int(obj[u'grantedTTL'])
# header = Header._parse(obj[u'header']) if u'header' in obj else None
returnValue(ttl) | python | def remaining(self):
"""
Get the remaining time-to-live of this lease.
:returns: TTL in seconds.
:rtype: int
"""
if self._expired:
raise Expired()
obj = {
u'ID': self.lease_id,
}
data = json.dumps(obj).encode('utf8')
url = u'{}/v3alpha/kv/lease/timetolive'.format(self._client._url).encode()
response = yield treq.post(url, data, headers=self._client._REQ_HEADERS)
obj = yield treq.json_content(response)
ttl = obj.get(u'TTL', None)
if not ttl:
self._expired = True
raise Expired()
# grantedTTL = int(obj[u'grantedTTL'])
# header = Header._parse(obj[u'header']) if u'header' in obj else None
returnValue(ttl) | [
"def",
"remaining",
"(",
"self",
")",
":",
"if",
"self",
".",
"_expired",
":",
"raise",
"Expired",
"(",
")",
"obj",
"=",
"{",
"u'ID'",
":",
"self",
".",
"lease_id",
",",
"}",
"data",
"=",
"json",
".",
"dumps",
"(",
"obj",
")",
".",
"encode",
"(",
"'utf8'",
")",
"url",
"=",
"u'{}/v3alpha/kv/lease/timetolive'",
".",
"format",
"(",
"self",
".",
"_client",
".",
"_url",
")",
".",
"encode",
"(",
")",
"response",
"=",
"yield",
"treq",
".",
"post",
"(",
"url",
",",
"data",
",",
"headers",
"=",
"self",
".",
"_client",
".",
"_REQ_HEADERS",
")",
"obj",
"=",
"yield",
"treq",
".",
"json_content",
"(",
"response",
")",
"ttl",
"=",
"obj",
".",
"get",
"(",
"u'TTL'",
",",
"None",
")",
"if",
"not",
"ttl",
":",
"self",
".",
"_expired",
"=",
"True",
"raise",
"Expired",
"(",
")",
"# grantedTTL = int(obj[u'grantedTTL'])",
"# header = Header._parse(obj[u'header']) if u'header' in obj else None",
"returnValue",
"(",
"ttl",
")"
] | Get the remaining time-to-live of this lease.
:returns: TTL in seconds.
:rtype: int | [
"Get",
"the",
"remaining",
"time",
"-",
"to",
"-",
"live",
"of",
"this",
"lease",
"."
] | c9aebff7f288a0b219bffc9d2579d22cf543baa5 | https://github.com/crossbario/txaio-etcd/blob/c9aebff7f288a0b219bffc9d2579d22cf543baa5/txaioetcd/_lease.py#L85-L113 | train |
crossbario/txaio-etcd | txaioetcd/_lease.py | Lease.revoke | def revoke(self):
"""
Revokes a lease. All keys attached to the lease will expire
and be deleted.
:returns: Response header.
:rtype: instance of :class:`txaioetcd.Header`
"""
if self._expired:
raise Expired()
obj = {
# ID is the lease ID to revoke. When the ID is revoked, all
# associated keys will be deleted.
u'ID': self.lease_id,
}
data = json.dumps(obj).encode('utf8')
url = u'{}/v3alpha/kv/lease/revoke'.format(self._client._url).encode()
response = yield treq.post(url, data, headers=self._client._REQ_HEADERS)
obj = yield treq.json_content(response)
header = Header._parse(obj[u'header']) if u'header' in obj else None
self._expired = True
returnValue(header) | python | def revoke(self):
"""
Revokes a lease. All keys attached to the lease will expire
and be deleted.
:returns: Response header.
:rtype: instance of :class:`txaioetcd.Header`
"""
if self._expired:
raise Expired()
obj = {
# ID is the lease ID to revoke. When the ID is revoked, all
# associated keys will be deleted.
u'ID': self.lease_id,
}
data = json.dumps(obj).encode('utf8')
url = u'{}/v3alpha/kv/lease/revoke'.format(self._client._url).encode()
response = yield treq.post(url, data, headers=self._client._REQ_HEADERS)
obj = yield treq.json_content(response)
header = Header._parse(obj[u'header']) if u'header' in obj else None
self._expired = True
returnValue(header) | [
"def",
"revoke",
"(",
"self",
")",
":",
"if",
"self",
".",
"_expired",
":",
"raise",
"Expired",
"(",
")",
"obj",
"=",
"{",
"# ID is the lease ID to revoke. When the ID is revoked, all",
"# associated keys will be deleted.",
"u'ID'",
":",
"self",
".",
"lease_id",
",",
"}",
"data",
"=",
"json",
".",
"dumps",
"(",
"obj",
")",
".",
"encode",
"(",
"'utf8'",
")",
"url",
"=",
"u'{}/v3alpha/kv/lease/revoke'",
".",
"format",
"(",
"self",
".",
"_client",
".",
"_url",
")",
".",
"encode",
"(",
")",
"response",
"=",
"yield",
"treq",
".",
"post",
"(",
"url",
",",
"data",
",",
"headers",
"=",
"self",
".",
"_client",
".",
"_REQ_HEADERS",
")",
"obj",
"=",
"yield",
"treq",
".",
"json_content",
"(",
"response",
")",
"header",
"=",
"Header",
".",
"_parse",
"(",
"obj",
"[",
"u'header'",
"]",
")",
"if",
"u'header'",
"in",
"obj",
"else",
"None",
"self",
".",
"_expired",
"=",
"True",
"returnValue",
"(",
"header",
")"
] | Revokes a lease. All keys attached to the lease will expire
and be deleted.
:returns: Response header.
:rtype: instance of :class:`txaioetcd.Header` | [
"Revokes",
"a",
"lease",
".",
"All",
"keys",
"attached",
"to",
"the",
"lease",
"will",
"expire",
"and",
"be",
"deleted",
"."
] | c9aebff7f288a0b219bffc9d2579d22cf543baa5 | https://github.com/crossbario/txaio-etcd/blob/c9aebff7f288a0b219bffc9d2579d22cf543baa5/txaioetcd/_lease.py#L146-L173 | train |
crossbario/txaio-etcd | txaioetcd/_lease.py | Lease.refresh | def refresh(self):
"""
Keeps the lease alive by streaming keep alive requests from the client
to the server and streaming keep alive responses from the server to
the client.
:returns: Response header.
:rtype: instance of :class:`txaioetcd.Header`
"""
if self._expired:
raise Expired()
obj = {
# ID is the lease ID for the lease to keep alive.
u'ID': self.lease_id,
}
data = json.dumps(obj).encode('utf8')
url = u'{}/v3alpha/lease/keepalive'.format(self._client._url).encode()
response = yield treq.post(url, data, headers=self._client._REQ_HEADERS)
obj = yield treq.json_content(response)
if u'result' not in obj:
raise Exception('bogus lease refresh response (missing "result") in {}'.format(obj))
ttl = obj[u'result'].get(u'TTL', None)
if not ttl:
self._expired = True
raise Expired()
header = Header._parse(obj[u'result'][u'header']) if u'header' in obj[u'result'] else None
self._expired = False
returnValue(header) | python | def refresh(self):
"""
Keeps the lease alive by streaming keep alive requests from the client
to the server and streaming keep alive responses from the server to
the client.
:returns: Response header.
:rtype: instance of :class:`txaioetcd.Header`
"""
if self._expired:
raise Expired()
obj = {
# ID is the lease ID for the lease to keep alive.
u'ID': self.lease_id,
}
data = json.dumps(obj).encode('utf8')
url = u'{}/v3alpha/lease/keepalive'.format(self._client._url).encode()
response = yield treq.post(url, data, headers=self._client._REQ_HEADERS)
obj = yield treq.json_content(response)
if u'result' not in obj:
raise Exception('bogus lease refresh response (missing "result") in {}'.format(obj))
ttl = obj[u'result'].get(u'TTL', None)
if not ttl:
self._expired = True
raise Expired()
header = Header._parse(obj[u'result'][u'header']) if u'header' in obj[u'result'] else None
self._expired = False
returnValue(header) | [
"def",
"refresh",
"(",
"self",
")",
":",
"if",
"self",
".",
"_expired",
":",
"raise",
"Expired",
"(",
")",
"obj",
"=",
"{",
"# ID is the lease ID for the lease to keep alive.",
"u'ID'",
":",
"self",
".",
"lease_id",
",",
"}",
"data",
"=",
"json",
".",
"dumps",
"(",
"obj",
")",
".",
"encode",
"(",
"'utf8'",
")",
"url",
"=",
"u'{}/v3alpha/lease/keepalive'",
".",
"format",
"(",
"self",
".",
"_client",
".",
"_url",
")",
".",
"encode",
"(",
")",
"response",
"=",
"yield",
"treq",
".",
"post",
"(",
"url",
",",
"data",
",",
"headers",
"=",
"self",
".",
"_client",
".",
"_REQ_HEADERS",
")",
"obj",
"=",
"yield",
"treq",
".",
"json_content",
"(",
"response",
")",
"if",
"u'result'",
"not",
"in",
"obj",
":",
"raise",
"Exception",
"(",
"'bogus lease refresh response (missing \"result\") in {}'",
".",
"format",
"(",
"obj",
")",
")",
"ttl",
"=",
"obj",
"[",
"u'result'",
"]",
".",
"get",
"(",
"u'TTL'",
",",
"None",
")",
"if",
"not",
"ttl",
":",
"self",
".",
"_expired",
"=",
"True",
"raise",
"Expired",
"(",
")",
"header",
"=",
"Header",
".",
"_parse",
"(",
"obj",
"[",
"u'result'",
"]",
"[",
"u'header'",
"]",
")",
"if",
"u'header'",
"in",
"obj",
"[",
"u'result'",
"]",
"else",
"None",
"self",
".",
"_expired",
"=",
"False",
"returnValue",
"(",
"header",
")"
] | Keeps the lease alive by streaming keep alive requests from the client
to the server and streaming keep alive responses from the server to
the client.
:returns: Response header.
:rtype: instance of :class:`txaioetcd.Header` | [
"Keeps",
"the",
"lease",
"alive",
"by",
"streaming",
"keep",
"alive",
"requests",
"from",
"the",
"client",
"to",
"the",
"server",
"and",
"streaming",
"keep",
"alive",
"responses",
"from",
"the",
"server",
"to",
"the",
"client",
"."
] | c9aebff7f288a0b219bffc9d2579d22cf543baa5 | https://github.com/crossbario/txaio-etcd/blob/c9aebff7f288a0b219bffc9d2579d22cf543baa5/txaioetcd/_lease.py#L176-L211 | train |
skillachie/news-corpus-builder | news_corpus_builder/news_corpus_generator.py | NewsCorpusGenerator.read_links_file | def read_links_file(self,file_path):
'''
Read links and associated categories for specified articles
in text file seperated by a space
Args:
file_path (str): The path to text file with news article links
and category
Returns:
articles: Array of tuples that contains article link & cateogory
ex. [('IPO','www.cs.columbia.edu')]
'''
articles = []
with open(file_path) as f:
for line in f:
line = line.strip()
#Ignore blank lines
if len(line) != 0:
link,category = line.split(' ')
articles.append((category.rstrip(),link.strip()))
return articles | python | def read_links_file(self,file_path):
'''
Read links and associated categories for specified articles
in text file seperated by a space
Args:
file_path (str): The path to text file with news article links
and category
Returns:
articles: Array of tuples that contains article link & cateogory
ex. [('IPO','www.cs.columbia.edu')]
'''
articles = []
with open(file_path) as f:
for line in f:
line = line.strip()
#Ignore blank lines
if len(line) != 0:
link,category = line.split(' ')
articles.append((category.rstrip(),link.strip()))
return articles | [
"def",
"read_links_file",
"(",
"self",
",",
"file_path",
")",
":",
"articles",
"=",
"[",
"]",
"with",
"open",
"(",
"file_path",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"#Ignore blank lines",
"if",
"len",
"(",
"line",
")",
"!=",
"0",
":",
"link",
",",
"category",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"articles",
".",
"append",
"(",
"(",
"category",
".",
"rstrip",
"(",
")",
",",
"link",
".",
"strip",
"(",
")",
")",
")",
"return",
"articles"
] | Read links and associated categories for specified articles
in text file seperated by a space
Args:
file_path (str): The path to text file with news article links
and category
Returns:
articles: Array of tuples that contains article link & cateogory
ex. [('IPO','www.cs.columbia.edu')] | [
"Read",
"links",
"and",
"associated",
"categories",
"for",
"specified",
"articles",
"in",
"text",
"file",
"seperated",
"by",
"a",
"space"
] | 7ef73c6d6a56e827ad694cdd446901590936baf9 | https://github.com/skillachie/news-corpus-builder/blob/7ef73c6d6a56e827ad694cdd446901590936baf9/news_corpus_builder/news_corpus_generator.py#L48-L71 | train |
dourvaris/nano-python | src/nano/rpc.py | Client.call | def call(self, action, params=None):
"""
Makes an RPC call to the server and returns the json response
:param action: RPC method to call
:type action: str
:param params: Dict of arguments to send with RPC call
:type params: dict
:raises: :py:exc:`nano.rpc.RPCException`
:raises: :py:exc:`requests.exceptions.RequestException`
>>> rpc.call(
... action='account_balance',
... params={
... 'account': 'xrb_3t6k35gi95xu6tergt6p69ck76ogmitsa8mnijtpxm9fkcm736xtoncuohr3'
... })
{'balance': '325586539664609129644855132177',
'pending': '2309370940000000000000000000000000'}
"""
params = params or {}
params['action'] = action
resp = self.session.post(self.host, json=params, timeout=self.timeout)
result = resp.json()
if 'error' in result:
raise RPCException(result['error'])
return result | python | def call(self, action, params=None):
"""
Makes an RPC call to the server and returns the json response
:param action: RPC method to call
:type action: str
:param params: Dict of arguments to send with RPC call
:type params: dict
:raises: :py:exc:`nano.rpc.RPCException`
:raises: :py:exc:`requests.exceptions.RequestException`
>>> rpc.call(
... action='account_balance',
... params={
... 'account': 'xrb_3t6k35gi95xu6tergt6p69ck76ogmitsa8mnijtpxm9fkcm736xtoncuohr3'
... })
{'balance': '325586539664609129644855132177',
'pending': '2309370940000000000000000000000000'}
"""
params = params or {}
params['action'] = action
resp = self.session.post(self.host, json=params, timeout=self.timeout)
result = resp.json()
if 'error' in result:
raise RPCException(result['error'])
return result | [
"def",
"call",
"(",
"self",
",",
"action",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"params",
"or",
"{",
"}",
"params",
"[",
"'action'",
"]",
"=",
"action",
"resp",
"=",
"self",
".",
"session",
".",
"post",
"(",
"self",
".",
"host",
",",
"json",
"=",
"params",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"result",
"=",
"resp",
".",
"json",
"(",
")",
"if",
"'error'",
"in",
"result",
":",
"raise",
"RPCException",
"(",
"result",
"[",
"'error'",
"]",
")",
"return",
"result"
] | Makes an RPC call to the server and returns the json response
:param action: RPC method to call
:type action: str
:param params: Dict of arguments to send with RPC call
:type params: dict
:raises: :py:exc:`nano.rpc.RPCException`
:raises: :py:exc:`requests.exceptions.RequestException`
>>> rpc.call(
... action='account_balance',
... params={
... 'account': 'xrb_3t6k35gi95xu6tergt6p69ck76ogmitsa8mnijtpxm9fkcm736xtoncuohr3'
... })
{'balance': '325586539664609129644855132177',
'pending': '2309370940000000000000000000000000'} | [
"Makes",
"an",
"RPC",
"call",
"to",
"the",
"server",
"and",
"returns",
"the",
"json",
"response"
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L57-L89 | train |
dourvaris/nano-python | src/nano/rpc.py | Client._process_value | def _process_value(self, value, type):
"""
Process a value that will be sent to backend
:param value: the value to return
:param type: hint for what sort of value this is
:type type: str
"""
if not isinstance(value, six.string_types + (list,)):
value = json.dumps(value)
return value | python | def _process_value(self, value, type):
"""
Process a value that will be sent to backend
:param value: the value to return
:param type: hint for what sort of value this is
:type type: str
"""
if not isinstance(value, six.string_types + (list,)):
value = json.dumps(value)
return value | [
"def",
"_process_value",
"(",
"self",
",",
"value",
",",
"type",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
"+",
"(",
"list",
",",
")",
")",
":",
"value",
"=",
"json",
".",
"dumps",
"(",
"value",
")",
"return",
"value"
] | Process a value that will be sent to backend
:param value: the value to return
:param type: hint for what sort of value this is
:type type: str | [
"Process",
"a",
"value",
"that",
"will",
"be",
"sent",
"to",
"backend"
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L91-L104 | train |
dourvaris/nano-python | src/nano/rpc.py | Client.block_account | def block_account(self, hash):
"""
Returns the account containing block
:param hash: Hash of the block to return account for
:type hash: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.block_account(
... hash="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F"
... )
"xrb_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpi00000000"
"""
hash = self._process_value(hash, 'block')
payload = {"hash": hash}
resp = self.call('block_account', payload)
return resp['account'] | python | def block_account(self, hash):
"""
Returns the account containing block
:param hash: Hash of the block to return account for
:type hash: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.block_account(
... hash="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F"
... )
"xrb_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpi00000000"
"""
hash = self._process_value(hash, 'block')
payload = {"hash": hash}
resp = self.call('block_account', payload)
return resp['account'] | [
"def",
"block_account",
"(",
"self",
",",
"hash",
")",
":",
"hash",
"=",
"self",
".",
"_process_value",
"(",
"hash",
",",
"'block'",
")",
"payload",
"=",
"{",
"\"hash\"",
":",
"hash",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'block_account'",
",",
"payload",
")",
"return",
"resp",
"[",
"'account'",
"]"
] | Returns the account containing block
:param hash: Hash of the block to return account for
:type hash: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.block_account(
... hash="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F"
... )
"xrb_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpi00000000" | [
"Returns",
"the",
"account",
"containing",
"block"
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L872-L894 | train |
dourvaris/nano-python | src/nano/rpc.py | Client.block_count | def block_count(self):
"""
Reports the number of blocks in the ledger and unchecked synchronizing
blocks
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.block_count()
{
"count": 1000,
"unchecked": 10
}
"""
resp = self.call('block_count')
for k, v in resp.items():
resp[k] = int(v)
return resp | python | def block_count(self):
"""
Reports the number of blocks in the ledger and unchecked synchronizing
blocks
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.block_count()
{
"count": 1000,
"unchecked": 10
}
"""
resp = self.call('block_count')
for k, v in resp.items():
resp[k] = int(v)
return resp | [
"def",
"block_count",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"call",
"(",
"'block_count'",
")",
"for",
"k",
",",
"v",
"in",
"resp",
".",
"items",
"(",
")",
":",
"resp",
"[",
"k",
"]",
"=",
"int",
"(",
"v",
")",
"return",
"resp"
] | Reports the number of blocks in the ledger and unchecked synchronizing
blocks
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.block_count()
{
"count": 1000,
"unchecked": 10
} | [
"Reports",
"the",
"number",
"of",
"blocks",
"in",
"the",
"ledger",
"and",
"unchecked",
"synchronizing",
"blocks"
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L897-L917 | train |
dourvaris/nano-python | src/nano/rpc.py | Client.mrai_from_raw | def mrai_from_raw(self, amount):
"""
Divide a raw amount down by the Mrai ratio.
:param amount: Amount in raw to convert to Mrai
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.mrai_from_raw(amount=1000000000000000000000000000000)
1
"""
amount = self._process_value(amount, 'int')
payload = {"amount": amount}
resp = self.call('mrai_from_raw', payload)
return int(resp['amount']) | python | def mrai_from_raw(self, amount):
"""
Divide a raw amount down by the Mrai ratio.
:param amount: Amount in raw to convert to Mrai
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.mrai_from_raw(amount=1000000000000000000000000000000)
1
"""
amount = self._process_value(amount, 'int')
payload = {"amount": amount}
resp = self.call('mrai_from_raw', payload)
return int(resp['amount']) | [
"def",
"mrai_from_raw",
"(",
"self",
",",
"amount",
")",
":",
"amount",
"=",
"self",
".",
"_process_value",
"(",
"amount",
",",
"'int'",
")",
"payload",
"=",
"{",
"\"amount\"",
":",
"amount",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'mrai_from_raw'",
",",
"payload",
")",
"return",
"int",
"(",
"resp",
"[",
"'amount'",
"]",
")"
] | Divide a raw amount down by the Mrai ratio.
:param amount: Amount in raw to convert to Mrai
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.mrai_from_raw(amount=1000000000000000000000000000000)
1 | [
"Divide",
"a",
"raw",
"amount",
"down",
"by",
"the",
"Mrai",
"ratio",
"."
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L1384-L1404 | train |
dourvaris/nano-python | src/nano/rpc.py | Client.mrai_to_raw | def mrai_to_raw(self, amount):
"""
Multiply an Mrai amount by the Mrai ratio.
:param amount: Amount in Mrai to convert to raw
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.mrai_to_raw(amount=1)
1000000000000000000000000000000
"""
amount = self._process_value(amount, 'int')
payload = {"amount": amount}
resp = self.call('mrai_to_raw', payload)
return int(resp['amount']) | python | def mrai_to_raw(self, amount):
"""
Multiply an Mrai amount by the Mrai ratio.
:param amount: Amount in Mrai to convert to raw
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.mrai_to_raw(amount=1)
1000000000000000000000000000000
"""
amount = self._process_value(amount, 'int')
payload = {"amount": amount}
resp = self.call('mrai_to_raw', payload)
return int(resp['amount']) | [
"def",
"mrai_to_raw",
"(",
"self",
",",
"amount",
")",
":",
"amount",
"=",
"self",
".",
"_process_value",
"(",
"amount",
",",
"'int'",
")",
"payload",
"=",
"{",
"\"amount\"",
":",
"amount",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'mrai_to_raw'",
",",
"payload",
")",
"return",
"int",
"(",
"resp",
"[",
"'amount'",
"]",
")"
] | Multiply an Mrai amount by the Mrai ratio.
:param amount: Amount in Mrai to convert to raw
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.mrai_to_raw(amount=1)
1000000000000000000000000000000 | [
"Multiply",
"an",
"Mrai",
"amount",
"by",
"the",
"Mrai",
"ratio",
"."
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L1407-L1427 | train |
dourvaris/nano-python | src/nano/rpc.py | Client.krai_from_raw | def krai_from_raw(self, amount):
"""
Divide a raw amount down by the krai ratio.
:param amount: Amount in raw to convert to krai
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.krai_from_raw(amount=1000000000000000000000000000)
1
"""
amount = self._process_value(amount, 'int')
payload = {"amount": amount}
resp = self.call('krai_from_raw', payload)
return int(resp['amount']) | python | def krai_from_raw(self, amount):
"""
Divide a raw amount down by the krai ratio.
:param amount: Amount in raw to convert to krai
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.krai_from_raw(amount=1000000000000000000000000000)
1
"""
amount = self._process_value(amount, 'int')
payload = {"amount": amount}
resp = self.call('krai_from_raw', payload)
return int(resp['amount']) | [
"def",
"krai_from_raw",
"(",
"self",
",",
"amount",
")",
":",
"amount",
"=",
"self",
".",
"_process_value",
"(",
"amount",
",",
"'int'",
")",
"payload",
"=",
"{",
"\"amount\"",
":",
"amount",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'krai_from_raw'",
",",
"payload",
")",
"return",
"int",
"(",
"resp",
"[",
"'amount'",
"]",
")"
] | Divide a raw amount down by the krai ratio.
:param amount: Amount in raw to convert to krai
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.krai_from_raw(amount=1000000000000000000000000000)
1 | [
"Divide",
"a",
"raw",
"amount",
"down",
"by",
"the",
"krai",
"ratio",
"."
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L1430-L1449 | train |
dourvaris/nano-python | src/nano/rpc.py | Client.krai_to_raw | def krai_to_raw(self, amount):
"""
Multiply an krai amount by the krai ratio.
:param amount: Amount in krai to convert to raw
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.krai_to_raw(amount=1)
1000000000000000000000000000
"""
amount = self._process_value(amount, 'int')
payload = {"amount": amount}
resp = self.call('krai_to_raw', payload)
return int(resp['amount']) | python | def krai_to_raw(self, amount):
"""
Multiply an krai amount by the krai ratio.
:param amount: Amount in krai to convert to raw
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.krai_to_raw(amount=1)
1000000000000000000000000000
"""
amount = self._process_value(amount, 'int')
payload = {"amount": amount}
resp = self.call('krai_to_raw', payload)
return int(resp['amount']) | [
"def",
"krai_to_raw",
"(",
"self",
",",
"amount",
")",
":",
"amount",
"=",
"self",
".",
"_process_value",
"(",
"amount",
",",
"'int'",
")",
"payload",
"=",
"{",
"\"amount\"",
":",
"amount",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'krai_to_raw'",
",",
"payload",
")",
"return",
"int",
"(",
"resp",
"[",
"'amount'",
"]",
")"
] | Multiply an krai amount by the krai ratio.
:param amount: Amount in krai to convert to raw
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.krai_to_raw(amount=1)
1000000000000000000000000000 | [
"Multiply",
"an",
"krai",
"amount",
"by",
"the",
"krai",
"ratio",
"."
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L1452-L1472 | train |
dourvaris/nano-python | src/nano/rpc.py | Client.rai_from_raw | def rai_from_raw(self, amount):
"""
Divide a raw amount down by the rai ratio.
:param amount: Amount in raw to convert to rai
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.rai_from_raw(amount=1000000000000000000000000)
1
"""
amount = self._process_value(amount, 'int')
payload = {"amount": amount}
resp = self.call('rai_from_raw', payload)
return int(resp['amount']) | python | def rai_from_raw(self, amount):
"""
Divide a raw amount down by the rai ratio.
:param amount: Amount in raw to convert to rai
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.rai_from_raw(amount=1000000000000000000000000)
1
"""
amount = self._process_value(amount, 'int')
payload = {"amount": amount}
resp = self.call('rai_from_raw', payload)
return int(resp['amount']) | [
"def",
"rai_from_raw",
"(",
"self",
",",
"amount",
")",
":",
"amount",
"=",
"self",
".",
"_process_value",
"(",
"amount",
",",
"'int'",
")",
"payload",
"=",
"{",
"\"amount\"",
":",
"amount",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'rai_from_raw'",
",",
"payload",
")",
"return",
"int",
"(",
"resp",
"[",
"'amount'",
"]",
")"
] | Divide a raw amount down by the rai ratio.
:param amount: Amount in raw to convert to rai
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.rai_from_raw(amount=1000000000000000000000000)
1 | [
"Divide",
"a",
"raw",
"amount",
"down",
"by",
"the",
"rai",
"ratio",
"."
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L1475-L1495 | train |
dourvaris/nano-python | src/nano/rpc.py | Client.rai_to_raw | def rai_to_raw(self, amount):
"""
Multiply an rai amount by the rai ratio.
:param amount: Amount in rai to convert to raw
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.rai_to_raw(amount=1)
1000000000000000000000000
"""
amount = self._process_value(amount, 'int')
payload = {"amount": amount}
resp = self.call('rai_to_raw', payload)
return int(resp['amount']) | python | def rai_to_raw(self, amount):
"""
Multiply an rai amount by the rai ratio.
:param amount: Amount in rai to convert to raw
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.rai_to_raw(amount=1)
1000000000000000000000000
"""
amount = self._process_value(amount, 'int')
payload = {"amount": amount}
resp = self.call('rai_to_raw', payload)
return int(resp['amount']) | [
"def",
"rai_to_raw",
"(",
"self",
",",
"amount",
")",
":",
"amount",
"=",
"self",
".",
"_process_value",
"(",
"amount",
",",
"'int'",
")",
"payload",
"=",
"{",
"\"amount\"",
":",
"amount",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'rai_to_raw'",
",",
"payload",
")",
"return",
"int",
"(",
"resp",
"[",
"'amount'",
"]",
")"
] | Multiply an rai amount by the rai ratio.
:param amount: Amount in rai to convert to raw
:type amount: int
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.rai_to_raw(amount=1)
1000000000000000000000000 | [
"Multiply",
"an",
"rai",
"amount",
"by",
"the",
"rai",
"ratio",
"."
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L1498-L1518 | train |
dourvaris/nano-python | src/nano/rpc.py | Client.payment_begin | def payment_begin(self, wallet):
"""
Begin a new payment session. Searches wallet for an account that's
marked as available and has a 0 balance. If one is found, the account
number is returned and is marked as unavailable. If no account is
found, a new account is created, placed in the wallet, and returned.
:param wallet: Wallet to begin payment in
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.payment_begin(
... wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F"
... )
"xrb_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpi00000000"
"""
wallet = self._process_value(wallet, 'wallet')
payload = {"wallet": wallet}
resp = self.call('payment_begin', payload)
return resp['account'] | python | def payment_begin(self, wallet):
"""
Begin a new payment session. Searches wallet for an account that's
marked as available and has a 0 balance. If one is found, the account
number is returned and is marked as unavailable. If no account is
found, a new account is created, placed in the wallet, and returned.
:param wallet: Wallet to begin payment in
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.payment_begin(
... wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F"
... )
"xrb_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpi00000000"
"""
wallet = self._process_value(wallet, 'wallet')
payload = {"wallet": wallet}
resp = self.call('payment_begin', payload)
return resp['account'] | [
"def",
"payment_begin",
"(",
"self",
",",
"wallet",
")",
":",
"wallet",
"=",
"self",
".",
"_process_value",
"(",
"wallet",
",",
"'wallet'",
")",
"payload",
"=",
"{",
"\"wallet\"",
":",
"wallet",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'payment_begin'",
",",
"payload",
")",
"return",
"resp",
"[",
"'account'",
"]"
] | Begin a new payment session. Searches wallet for an account that's
marked as available and has a 0 balance. If one is found, the account
number is returned and is marked as unavailable. If no account is
found, a new account is created, placed in the wallet, and returned.
:param wallet: Wallet to begin payment in
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.payment_begin(
... wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F"
... )
"xrb_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpi00000000" | [
"Begin",
"a",
"new",
"payment",
"session",
".",
"Searches",
"wallet",
"for",
"an",
"account",
"that",
"s",
"marked",
"as",
"available",
"and",
"has",
"a",
"0",
"balance",
".",
"If",
"one",
"is",
"found",
"the",
"account",
"number",
"is",
"returned",
"and",
"is",
"marked",
"as",
"unavailable",
".",
"If",
"no",
"account",
"is",
"found",
"a",
"new",
"account",
"is",
"created",
"placed",
"in",
"the",
"wallet",
"and",
"returned",
"."
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L1683-L1708 | train |
dourvaris/nano-python | src/nano/rpc.py | Client.payment_init | def payment_init(self, wallet):
"""
Marks all accounts in wallet as available for being used as a payment
session.
:param wallet: Wallet to init payment in
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.payment_init(
... wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F"
... )
True
"""
wallet = self._process_value(wallet, 'wallet')
payload = {"wallet": wallet}
resp = self.call('payment_init', payload)
return resp['status'] == 'Ready' | python | def payment_init(self, wallet):
"""
Marks all accounts in wallet as available for being used as a payment
session.
:param wallet: Wallet to init payment in
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.payment_init(
... wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F"
... )
True
"""
wallet = self._process_value(wallet, 'wallet')
payload = {"wallet": wallet}
resp = self.call('payment_init', payload)
return resp['status'] == 'Ready' | [
"def",
"payment_init",
"(",
"self",
",",
"wallet",
")",
":",
"wallet",
"=",
"self",
".",
"_process_value",
"(",
"wallet",
",",
"'wallet'",
")",
"payload",
"=",
"{",
"\"wallet\"",
":",
"wallet",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'payment_init'",
",",
"payload",
")",
"return",
"resp",
"[",
"'status'",
"]",
"==",
"'Ready'"
] | Marks all accounts in wallet as available for being used as a payment
session.
:param wallet: Wallet to init payment in
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.payment_init(
... wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F"
... )
True | [
"Marks",
"all",
"accounts",
"in",
"wallet",
"as",
"available",
"for",
"being",
"used",
"as",
"a",
"payment",
"session",
"."
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L1714-L1736 | train |
dourvaris/nano-python | src/nano/rpc.py | Client.payment_end | def payment_end(self, account, wallet):
"""
End a payment session. Marks the account as available for use in a
payment session.
:param account: Account to mark available
:type account: str
:param wallet: Wallet to end payment session for
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.payment_end(
... account="xrb_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpi00000000",
... wallet="FFFD1BAEC8EC20814BBB9059B393051AAA8380F9B5A2E6B2489A277D81789EEE"
... )
True
"""
account = self._process_value(account, 'account')
wallet = self._process_value(wallet, 'wallet')
payload = {"account": account, "wallet": wallet}
resp = self.call('payment_end', payload)
return resp == {} | python | def payment_end(self, account, wallet):
"""
End a payment session. Marks the account as available for use in a
payment session.
:param account: Account to mark available
:type account: str
:param wallet: Wallet to end payment session for
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.payment_end(
... account="xrb_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpi00000000",
... wallet="FFFD1BAEC8EC20814BBB9059B393051AAA8380F9B5A2E6B2489A277D81789EEE"
... )
True
"""
account = self._process_value(account, 'account')
wallet = self._process_value(wallet, 'wallet')
payload = {"account": account, "wallet": wallet}
resp = self.call('payment_end', payload)
return resp == {} | [
"def",
"payment_end",
"(",
"self",
",",
"account",
",",
"wallet",
")",
":",
"account",
"=",
"self",
".",
"_process_value",
"(",
"account",
",",
"'account'",
")",
"wallet",
"=",
"self",
".",
"_process_value",
"(",
"wallet",
",",
"'wallet'",
")",
"payload",
"=",
"{",
"\"account\"",
":",
"account",
",",
"\"wallet\"",
":",
"wallet",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'payment_end'",
",",
"payload",
")",
"return",
"resp",
"==",
"{",
"}"
] | End a payment session. Marks the account as available for use in a
payment session.
:param account: Account to mark available
:type account: str
:param wallet: Wallet to end payment session for
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.payment_end(
... account="xrb_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpi00000000",
... wallet="FFFD1BAEC8EC20814BBB9059B393051AAA8380F9B5A2E6B2489A277D81789EEE"
... )
True | [
"End",
"a",
"payment",
"session",
".",
"Marks",
"the",
"account",
"as",
"available",
"for",
"use",
"in",
"a",
"payment",
"session",
"."
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L1739-L1766 | train |
dourvaris/nano-python | src/nano/rpc.py | Client.representatives | def representatives(self, count=None, sorting=False):
"""
Returns a list of pairs of representative and its voting weight
:param count: Max amount of representatives to return
:type count: int
:param sorting: If true, sorts by weight
:type sorting: bool
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.representatives()
{
"xrb_1111111111111111111111111111111111111111111111111117353trpda":
3822372327060170000000000000000000000,
"xrb_1111111111111111111111111111111111111111111111111awsq94gtecn":
30999999999999999999999999000000,
"xrb_114nk4rwjctu6n6tr6g6ps61g1w3hdpjxfas4xj1tq6i8jyomc5d858xr1xi":
0
}
"""
payload = {}
if count is not None:
payload['count'] = self._process_value(count, 'int')
if sorting:
payload['sorting'] = self._process_value(sorting, 'strbool')
resp = self.call('representatives', payload)
representatives = resp.get('representatives') or {}
for k, v in representatives.items():
representatives[k] = int(v)
return representatives | python | def representatives(self, count=None, sorting=False):
"""
Returns a list of pairs of representative and its voting weight
:param count: Max amount of representatives to return
:type count: int
:param sorting: If true, sorts by weight
:type sorting: bool
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.representatives()
{
"xrb_1111111111111111111111111111111111111111111111111117353trpda":
3822372327060170000000000000000000000,
"xrb_1111111111111111111111111111111111111111111111111awsq94gtecn":
30999999999999999999999999000000,
"xrb_114nk4rwjctu6n6tr6g6ps61g1w3hdpjxfas4xj1tq6i8jyomc5d858xr1xi":
0
}
"""
payload = {}
if count is not None:
payload['count'] = self._process_value(count, 'int')
if sorting:
payload['sorting'] = self._process_value(sorting, 'strbool')
resp = self.call('representatives', payload)
representatives = resp.get('representatives') or {}
for k, v in representatives.items():
representatives[k] = int(v)
return representatives | [
"def",
"representatives",
"(",
"self",
",",
"count",
"=",
"None",
",",
"sorting",
"=",
"False",
")",
":",
"payload",
"=",
"{",
"}",
"if",
"count",
"is",
"not",
"None",
":",
"payload",
"[",
"'count'",
"]",
"=",
"self",
".",
"_process_value",
"(",
"count",
",",
"'int'",
")",
"if",
"sorting",
":",
"payload",
"[",
"'sorting'",
"]",
"=",
"self",
".",
"_process_value",
"(",
"sorting",
",",
"'strbool'",
")",
"resp",
"=",
"self",
".",
"call",
"(",
"'representatives'",
",",
"payload",
")",
"representatives",
"=",
"resp",
".",
"get",
"(",
"'representatives'",
")",
"or",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"representatives",
".",
"items",
"(",
")",
":",
"representatives",
"[",
"k",
"]",
"=",
"int",
"(",
"v",
")",
"return",
"representatives"
] | Returns a list of pairs of representative and its voting weight
:param count: Max amount of representatives to return
:type count: int
:param sorting: If true, sorts by weight
:type sorting: bool
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.representatives()
{
"xrb_1111111111111111111111111111111111111111111111111117353trpda":
3822372327060170000000000000000000000,
"xrb_1111111111111111111111111111111111111111111111111awsq94gtecn":
30999999999999999999999999000000,
"xrb_114nk4rwjctu6n6tr6g6ps61g1w3hdpjxfas4xj1tq6i8jyomc5d858xr1xi":
0
} | [
"Returns",
"a",
"list",
"of",
"pairs",
"of",
"representative",
"and",
"its",
"voting",
"weight"
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L1929-L1968 | train |
dourvaris/nano-python | src/nano/rpc.py | Client.version | def version(self):
"""
Returns the node's RPC version
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.version()
{
"rpc_version": 1,
"store_version": 10,
"node_vendor": "RaiBlocks 9.0"
}
"""
resp = self.call('version')
for key in ('rpc_version', 'store_version'):
resp[key] = int(resp[key])
return resp | python | def version(self):
"""
Returns the node's RPC version
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.version()
{
"rpc_version": 1,
"store_version": 10,
"node_vendor": "RaiBlocks 9.0"
}
"""
resp = self.call('version')
for key in ('rpc_version', 'store_version'):
resp[key] = int(resp[key])
return resp | [
"def",
"version",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"call",
"(",
"'version'",
")",
"for",
"key",
"in",
"(",
"'rpc_version'",
",",
"'store_version'",
")",
":",
"resp",
"[",
"key",
"]",
"=",
"int",
"(",
"resp",
"[",
"key",
"]",
")",
"return",
"resp"
] | Returns the node's RPC version
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.version()
{
"rpc_version": 1,
"store_version": 10,
"node_vendor": "RaiBlocks 9.0"
} | [
"Returns",
"the",
"node",
"s",
"RPC",
"version"
] | f26b8bc895b997067780f925049a70e82c0c2479 | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L3350-L3370 | train |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/contrib/github.py | _extract_email | def _extract_email(gh):
"""Get user email from github."""
return next(
(x.email for x in gh.emails() if x.verified and x.primary), None) | python | def _extract_email(gh):
"""Get user email from github."""
return next(
(x.email for x in gh.emails() if x.verified and x.primary), None) | [
"def",
"_extract_email",
"(",
"gh",
")",
":",
"return",
"next",
"(",
"(",
"x",
".",
"email",
"for",
"x",
"in",
"gh",
".",
"emails",
"(",
")",
"if",
"x",
".",
"verified",
"and",
"x",
".",
"primary",
")",
",",
"None",
")"
] | Get user email from github. | [
"Get",
"user",
"email",
"from",
"github",
"."
] | 2500dc6935738107617aeade79e050d7608004bb | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/github.py#L110-L113 | train |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/contrib/github.py | authorized | def authorized(resp, remote):
"""Authorized callback handler for GitHub.
:param resp: The response.
:param remote: The remote application.
"""
if resp and 'error' in resp:
if resp['error'] == 'bad_verification_code':
# See https://developer.github.com/v3/oauth/#bad-verification-code
# which recommends starting auth flow again.
return redirect(url_for('invenio_oauthclient.login',
remote_app='github'))
elif resp['error'] in ['incorrect_client_credentials',
'redirect_uri_mismatch']:
raise OAuthResponseError(
'Application mis-configuration in GitHub', remote, resp
)
return authorized_signup_handler(resp, remote) | python | def authorized(resp, remote):
"""Authorized callback handler for GitHub.
:param resp: The response.
:param remote: The remote application.
"""
if resp and 'error' in resp:
if resp['error'] == 'bad_verification_code':
# See https://developer.github.com/v3/oauth/#bad-verification-code
# which recommends starting auth flow again.
return redirect(url_for('invenio_oauthclient.login',
remote_app='github'))
elif resp['error'] in ['incorrect_client_credentials',
'redirect_uri_mismatch']:
raise OAuthResponseError(
'Application mis-configuration in GitHub', remote, resp
)
return authorized_signup_handler(resp, remote) | [
"def",
"authorized",
"(",
"resp",
",",
"remote",
")",
":",
"if",
"resp",
"and",
"'error'",
"in",
"resp",
":",
"if",
"resp",
"[",
"'error'",
"]",
"==",
"'bad_verification_code'",
":",
"# See https://developer.github.com/v3/oauth/#bad-verification-code",
"# which recommends starting auth flow again.",
"return",
"redirect",
"(",
"url_for",
"(",
"'invenio_oauthclient.login'",
",",
"remote_app",
"=",
"'github'",
")",
")",
"elif",
"resp",
"[",
"'error'",
"]",
"in",
"[",
"'incorrect_client_credentials'",
",",
"'redirect_uri_mismatch'",
"]",
":",
"raise",
"OAuthResponseError",
"(",
"'Application mis-configuration in GitHub'",
",",
"remote",
",",
"resp",
")",
"return",
"authorized_signup_handler",
"(",
"resp",
",",
"remote",
")"
] | Authorized callback handler for GitHub.
:param resp: The response.
:param remote: The remote application. | [
"Authorized",
"callback",
"handler",
"for",
"GitHub",
"."
] | 2500dc6935738107617aeade79e050d7608004bb | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/contrib/github.py#L180-L198 | train |
openvax/isovar | isovar/variant_sequences.py | initial_variant_sequences_from_reads | def initial_variant_sequences_from_reads(
variant_reads,
max_nucleotides_before_variant=None,
max_nucleotides_after_variant=None):
"""
Get all unique sequences from reads spanning a variant locus. This will
include partial sequences due to reads starting in the middle of the
sequence around around a variant.
"""
unique_sequence_groups = group_unique_sequences(
variant_reads,
max_prefix_size=max_nucleotides_before_variant,
max_suffix_size=max_nucleotides_after_variant)
return [
VariantSequence(
prefix=prefix,
alt=alt,
suffix=suffix,
reads=reads)
for ((prefix, alt, suffix), reads)
in unique_sequence_groups.items()
] | python | def initial_variant_sequences_from_reads(
variant_reads,
max_nucleotides_before_variant=None,
max_nucleotides_after_variant=None):
"""
Get all unique sequences from reads spanning a variant locus. This will
include partial sequences due to reads starting in the middle of the
sequence around around a variant.
"""
unique_sequence_groups = group_unique_sequences(
variant_reads,
max_prefix_size=max_nucleotides_before_variant,
max_suffix_size=max_nucleotides_after_variant)
return [
VariantSequence(
prefix=prefix,
alt=alt,
suffix=suffix,
reads=reads)
for ((prefix, alt, suffix), reads)
in unique_sequence_groups.items()
] | [
"def",
"initial_variant_sequences_from_reads",
"(",
"variant_reads",
",",
"max_nucleotides_before_variant",
"=",
"None",
",",
"max_nucleotides_after_variant",
"=",
"None",
")",
":",
"unique_sequence_groups",
"=",
"group_unique_sequences",
"(",
"variant_reads",
",",
"max_prefix_size",
"=",
"max_nucleotides_before_variant",
",",
"max_suffix_size",
"=",
"max_nucleotides_after_variant",
")",
"return",
"[",
"VariantSequence",
"(",
"prefix",
"=",
"prefix",
",",
"alt",
"=",
"alt",
",",
"suffix",
"=",
"suffix",
",",
"reads",
"=",
"reads",
")",
"for",
"(",
"(",
"prefix",
",",
"alt",
",",
"suffix",
")",
",",
"reads",
")",
"in",
"unique_sequence_groups",
".",
"items",
"(",
")",
"]"
] | Get all unique sequences from reads spanning a variant locus. This will
include partial sequences due to reads starting in the middle of the
sequence around around a variant. | [
"Get",
"all",
"unique",
"sequences",
"from",
"reads",
"spanning",
"a",
"variant",
"locus",
".",
"This",
"will",
"include",
"partial",
"sequences",
"due",
"to",
"reads",
"starting",
"in",
"the",
"middle",
"of",
"the",
"sequence",
"around",
"around",
"a",
"variant",
"."
] | b39b684920e3f6b344851d6598a1a1c67bce913b | https://github.com/openvax/isovar/blob/b39b684920e3f6b344851d6598a1a1c67bce913b/isovar/variant_sequences.py#L245-L267 | train |
openvax/isovar | isovar/variant_sequences.py | trim_variant_sequences | def trim_variant_sequences(variant_sequences, min_variant_sequence_coverage):
"""
Trim VariantSequences to desired coverage and then combine any
subsequences which get generated.
"""
n_total = len(variant_sequences)
trimmed_variant_sequences = [
variant_sequence.trim_by_coverage(min_variant_sequence_coverage)
for variant_sequence in variant_sequences
]
collapsed_variant_sequences = collapse_substrings(trimmed_variant_sequences)
n_after_trimming = len(collapsed_variant_sequences)
logger.info(
"Kept %d/%d variant sequences after read coverage trimming to >=%dx",
n_after_trimming,
n_total,
min_variant_sequence_coverage)
return collapsed_variant_sequences | python | def trim_variant_sequences(variant_sequences, min_variant_sequence_coverage):
"""
Trim VariantSequences to desired coverage and then combine any
subsequences which get generated.
"""
n_total = len(variant_sequences)
trimmed_variant_sequences = [
variant_sequence.trim_by_coverage(min_variant_sequence_coverage)
for variant_sequence in variant_sequences
]
collapsed_variant_sequences = collapse_substrings(trimmed_variant_sequences)
n_after_trimming = len(collapsed_variant_sequences)
logger.info(
"Kept %d/%d variant sequences after read coverage trimming to >=%dx",
n_after_trimming,
n_total,
min_variant_sequence_coverage)
return collapsed_variant_sequences | [
"def",
"trim_variant_sequences",
"(",
"variant_sequences",
",",
"min_variant_sequence_coverage",
")",
":",
"n_total",
"=",
"len",
"(",
"variant_sequences",
")",
"trimmed_variant_sequences",
"=",
"[",
"variant_sequence",
".",
"trim_by_coverage",
"(",
"min_variant_sequence_coverage",
")",
"for",
"variant_sequence",
"in",
"variant_sequences",
"]",
"collapsed_variant_sequences",
"=",
"collapse_substrings",
"(",
"trimmed_variant_sequences",
")",
"n_after_trimming",
"=",
"len",
"(",
"collapsed_variant_sequences",
")",
"logger",
".",
"info",
"(",
"\"Kept %d/%d variant sequences after read coverage trimming to >=%dx\"",
",",
"n_after_trimming",
",",
"n_total",
",",
"min_variant_sequence_coverage",
")",
"return",
"collapsed_variant_sequences"
] | Trim VariantSequences to desired coverage and then combine any
subsequences which get generated. | [
"Trim",
"VariantSequences",
"to",
"desired",
"coverage",
"and",
"then",
"combine",
"any",
"subsequences",
"which",
"get",
"generated",
"."
] | b39b684920e3f6b344851d6598a1a1c67bce913b | https://github.com/openvax/isovar/blob/b39b684920e3f6b344851d6598a1a1c67bce913b/isovar/variant_sequences.py#L319-L336 | train |