repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
cmutel/constructive_geometries | constructive_geometries/geomatcher.py | Geomatcher._actual_key | def _actual_key(self, key):
"""Translate provided key into the key used in the topology. Tries the unmodified key, the key with the default namespace, and the country converter. Raises a ``KeyError`` if none of these finds a suitable definition in ``self.topology``."""
if key in self or key in ("RoW", "... | python | def _actual_key(self, key):
"""Translate provided key into the key used in the topology. Tries the unmodified key, the key with the default namespace, and the country converter. Raises a ``KeyError`` if none of these finds a suitable definition in ``self.topology``."""
if key in self or key in ("RoW", "... | [
"def",
"_actual_key",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
"or",
"key",
"in",
"(",
"\"RoW\"",
",",
"\"GLO\"",
")",
":",
"return",
"key",
"elif",
"(",
"self",
".",
"default_namespace",
",",
"key",
")",
"in",
"self",
":",
"re... | Translate provided key into the key used in the topology. Tries the unmodified key, the key with the default namespace, and the country converter. Raises a ``KeyError`` if none of these finds a suitable definition in ``self.topology``. | [
"Translate",
"provided",
"key",
"into",
"the",
"key",
"used",
"in",
"the",
"topology",
".",
"Tries",
"the",
"unmodified",
"key",
"the",
"key",
"with",
"the",
"default",
"namespace",
"and",
"the",
"country",
"converter",
".",
"Raises",
"a",
"KeyError",
"if",
... | train | https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L87-L102 |
cmutel/constructive_geometries | constructive_geometries/geomatcher.py | Geomatcher._finish_filter | def _finish_filter(self, lst, key, include_self, exclusive, biggest_first):
"""Finish filtering a GIS operation. Can optionally exclude the input key, sort results, and exclude overlapping results. Internal function, not normally called directly."""
key = self._actual_key(key)
locations = [x[0] ... | python | def _finish_filter(self, lst, key, include_self, exclusive, biggest_first):
"""Finish filtering a GIS operation. Can optionally exclude the input key, sort results, and exclude overlapping results. Internal function, not normally called directly."""
key = self._actual_key(key)
locations = [x[0] ... | [
"def",
"_finish_filter",
"(",
"self",
",",
"lst",
",",
"key",
",",
"include_self",
",",
"exclusive",
",",
"biggest_first",
")",
":",
"key",
"=",
"self",
".",
"_actual_key",
"(",
"key",
")",
"locations",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",... | Finish filtering a GIS operation. Can optionally exclude the input key, sort results, and exclude overlapping results. Internal function, not normally called directly. | [
"Finish",
"filtering",
"a",
"GIS",
"operation",
".",
"Can",
"optionally",
"exclude",
"the",
"input",
"key",
"sort",
"results",
"and",
"exclude",
"overlapping",
"results",
".",
"Internal",
"function",
"not",
"normally",
"called",
"directly",
"."
] | train | https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L104-L132 |
cmutel/constructive_geometries | constructive_geometries/geomatcher.py | Geomatcher.intersects | def intersects(self, key, include_self=False, exclusive=False, biggest_first=True, only=None):
"""Get all locations that intersect this location.
Note that sorting is done by first by number of faces intersecting ``key``; the total number of faces in the intersected region is only used to break sorting... | python | def intersects(self, key, include_self=False, exclusive=False, biggest_first=True, only=None):
"""Get all locations that intersect this location.
Note that sorting is done by first by number of faces intersecting ``key``; the total number of faces in the intersected region is only used to break sorting... | [
"def",
"intersects",
"(",
"self",
",",
"key",
",",
"include_self",
"=",
"False",
",",
"exclusive",
"=",
"False",
",",
"biggest_first",
"=",
"True",
",",
"only",
"=",
"None",
")",
":",
"possibles",
"=",
"self",
".",
"topology",
"if",
"only",
"is",
"None... | Get all locations that intersect this location.
Note that sorting is done by first by number of faces intersecting ``key``; the total number of faces in the intersected region is only used to break sorting ties.
If the ``resolved_row`` context manager is not used, ``RoW`` doesn't have a spatial defini... | [
"Get",
"all",
"locations",
"that",
"intersect",
"this",
"location",
"."
] | train | https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L134-L153 |
cmutel/constructive_geometries | constructive_geometries/geomatcher.py | Geomatcher.contained | def contained(self, key, include_self=True, exclusive=False, biggest_first=True, only=None):
"""Get all locations that are completely within this location.
If the ``resolved_row`` context manager is not used, ``RoW`` doesn't have a spatial definition. Therefore, ``.contained("RoW")`` returns a list wit... | python | def contained(self, key, include_self=True, exclusive=False, biggest_first=True, only=None):
"""Get all locations that are completely within this location.
If the ``resolved_row`` context manager is not used, ``RoW`` doesn't have a spatial definition. Therefore, ``.contained("RoW")`` returns a list wit... | [
"def",
"contained",
"(",
"self",
",",
"key",
",",
"include_self",
"=",
"True",
",",
"exclusive",
"=",
"False",
",",
"biggest_first",
"=",
"True",
",",
"only",
"=",
"None",
")",
":",
"if",
"'RoW'",
"not",
"in",
"self",
":",
"if",
"key",
"==",
"'RoW'",... | Get all locations that are completely within this location.
If the ``resolved_row`` context manager is not used, ``RoW`` doesn't have a spatial definition. Therefore, ``.contained("RoW")`` returns a list with either ``RoW`` or nothing. | [
"Get",
"all",
"locations",
"that",
"are",
"completely",
"within",
"this",
"location",
"."
] | train | https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L155-L175 |
cmutel/constructive_geometries | constructive_geometries/geomatcher.py | Geomatcher.within | def within(self, key, include_self=True, exclusive=False, biggest_first=True, only=None):
"""Get all locations that completely contain this location.
If the ``resolved_row`` context manager is not used, ``RoW`` doesn't have a spatial definition. Therefore, ``RoW`` can only be contained by ``GLO`` and `... | python | def within(self, key, include_self=True, exclusive=False, biggest_first=True, only=None):
"""Get all locations that completely contain this location.
If the ``resolved_row`` context manager is not used, ``RoW`` doesn't have a spatial definition. Therefore, ``RoW`` can only be contained by ``GLO`` and `... | [
"def",
"within",
"(",
"self",
",",
"key",
",",
"include_self",
"=",
"True",
",",
"exclusive",
"=",
"False",
",",
"biggest_first",
"=",
"True",
",",
"only",
"=",
"None",
")",
":",
"possibles",
"=",
"self",
".",
"topology",
"if",
"only",
"is",
"None",
... | Get all locations that completely contain this location.
If the ``resolved_row`` context manager is not used, ``RoW`` doesn't have a spatial definition. Therefore, ``RoW`` can only be contained by ``GLO`` and ``RoW``. | [
"Get",
"all",
"locations",
"that",
"completely",
"contain",
"this",
"location",
"."
] | train | https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L177-L195 |
cmutel/constructive_geometries | constructive_geometries/geomatcher.py | Geomatcher.split_face | def split_face(self, face, number=None, ids=None):
"""Split a topological face into a number of small faces.
* ``face``: The face to split. Must be in the topology.
* ``number``: Number of new faces to create. Optional, can be inferred from ``ids``. Default is 2 new faces.
* ``ids``: It... | python | def split_face(self, face, number=None, ids=None):
"""Split a topological face into a number of small faces.
* ``face``: The face to split. Must be in the topology.
* ``number``: Number of new faces to create. Optional, can be inferred from ``ids``. Default is 2 new faces.
* ``ids``: It... | [
"def",
"split_face",
"(",
"self",
",",
"face",
",",
"number",
"=",
"None",
",",
"ids",
"=",
"None",
")",
":",
"assert",
"face",
"in",
"self",
".",
"faces",
"if",
"ids",
":",
"ids",
"=",
"set",
"(",
"ids",
")",
"else",
":",
"max_int",
"=",
"max",
... | Split a topological face into a number of small faces.
* ``face``: The face to split. Must be in the topology.
* ``number``: Number of new faces to create. Optional, can be inferred from ``ids``. Default is 2 new faces.
* ``ids``: Iterable of new face ids. Optional, default is the maximum integ... | [
"Split",
"a",
"topological",
"face",
"into",
"a",
"number",
"of",
"small",
"faces",
"."
] | train | https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L197-L223 |
cmutel/constructive_geometries | constructive_geometries/geomatcher.py | Geomatcher.add_definitions | def add_definitions(self, data, namespace, relative=True):
"""Add new topological definitions to ``self.topology``.
If ``relative`` is true, then ``data`` is defined relative to the existing locations already in ``self.topology``, e.g. IMAGE:
.. code-block:: python
{"Russia Region... | python | def add_definitions(self, data, namespace, relative=True):
"""Add new topological definitions to ``self.topology``.
If ``relative`` is true, then ``data`` is defined relative to the existing locations already in ``self.topology``, e.g. IMAGE:
.. code-block:: python
{"Russia Region... | [
"def",
"add_definitions",
"(",
"self",
",",
"data",
",",
"namespace",
",",
"relative",
"=",
"True",
")",
":",
"if",
"not",
"relative",
":",
"self",
".",
"topology",
".",
"update",
"(",
"{",
"(",
"namespace",
",",
"k",
")",
":",
"v",
"for",
"k",
","... | Add new topological definitions to ``self.topology``.
If ``relative`` is true, then ``data`` is defined relative to the existing locations already in ``self.topology``, e.g. IMAGE:
.. code-block:: python
{"Russia Region": [
"AM",
"AZ",
"GE",... | [
"Add",
"new",
"topological",
"definitions",
"to",
"self",
".",
"topology",
"."
] | train | https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L225-L256 |
maxfischer2781/include | include/mount/__init__.py | MountLoader.load_module | def load_module(self, name):
"""Load and return a module"""
if name in sys.modules:
return sys.modules[name]
# load the actual import hook module
module_name = self.mount2name(name)
__import__(module_name)
# alias the import hook module to the mount, so both c... | python | def load_module(self, name):
"""Load and return a module"""
if name in sys.modules:
return sys.modules[name]
# load the actual import hook module
module_name = self.mount2name(name)
__import__(module_name)
# alias the import hook module to the mount, so both c... | [
"def",
"load_module",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"sys",
".",
"modules",
":",
"return",
"sys",
".",
"modules",
"[",
"name",
"]",
"# load the actual import hook module",
"module_name",
"=",
"self",
".",
"mount2name",
"(",
"name",
... | Load and return a module | [
"Load",
"and",
"return",
"a",
"module"
] | train | https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/mount/__init__.py#L9-L19 |
maxfischer2781/include | include/mount/__init__.py | MountLoader.is_module | def is_module(self, name):
"""Test that `name` is a module name"""
if self.module_prefix.startswith(self.mount_prefix):
return name.startswith(self.module_prefix)
return name.startswith(self.module_prefix) and not name.startswith(self.mount_prefix) | python | def is_module(self, name):
"""Test that `name` is a module name"""
if self.module_prefix.startswith(self.mount_prefix):
return name.startswith(self.module_prefix)
return name.startswith(self.module_prefix) and not name.startswith(self.mount_prefix) | [
"def",
"is_module",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"module_prefix",
".",
"startswith",
"(",
"self",
".",
"mount_prefix",
")",
":",
"return",
"name",
".",
"startswith",
"(",
"self",
".",
"module_prefix",
")",
"return",
"name",
".",... | Test that `name` is a module name | [
"Test",
"that",
"name",
"is",
"a",
"module",
"name"
] | train | https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/mount/__init__.py#L26-L30 |
maxfischer2781/include | include/mount/__init__.py | MountLoader.is_mount | def is_mount(self, name):
"""Test that `name` is a mount name"""
if self.mount_prefix.startswith(self.module_prefix):
return name.startswith(self.mount_prefix)
return name.startswith(self.mount_prefix) and not name.startswith(self.module_prefix) | python | def is_mount(self, name):
"""Test that `name` is a mount name"""
if self.mount_prefix.startswith(self.module_prefix):
return name.startswith(self.mount_prefix)
return name.startswith(self.mount_prefix) and not name.startswith(self.module_prefix) | [
"def",
"is_mount",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"mount_prefix",
".",
"startswith",
"(",
"self",
".",
"module_prefix",
")",
":",
"return",
"name",
".",
"startswith",
"(",
"self",
".",
"mount_prefix",
")",
"return",
"name",
".",
... | Test that `name` is a mount name | [
"Test",
"that",
"name",
"is",
"a",
"mount",
"name"
] | train | https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/mount/__init__.py#L32-L36 |
maxfischer2781/include | include/mount/__init__.py | MountLoader.name2mount | def name2mount(self, name):
"""Convert a module name to a mount name"""
if not self.is_module(name):
raise ValueError('%r is not a supported module name' % (name, ))
return name.replace(self.module_prefix, self.mount_prefix) | python | def name2mount(self, name):
"""Convert a module name to a mount name"""
if not self.is_module(name):
raise ValueError('%r is not a supported module name' % (name, ))
return name.replace(self.module_prefix, self.mount_prefix) | [
"def",
"name2mount",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"self",
".",
"is_module",
"(",
"name",
")",
":",
"raise",
"ValueError",
"(",
"'%r is not a supported module name'",
"%",
"(",
"name",
",",
")",
")",
"return",
"name",
".",
"replace",
"... | Convert a module name to a mount name | [
"Convert",
"a",
"module",
"name",
"to",
"a",
"mount",
"name"
] | train | https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/mount/__init__.py#L38-L42 |
maxfischer2781/include | include/mount/__init__.py | MountLoader.mount2name | def mount2name(self, mount):
"""Convert a mount name to a module name"""
if not self.is_mount(mount):
raise ValueError('%r is not a supported mount name' % (mount,))
return mount.replace(self.mount_prefix, self.module_prefix) | python | def mount2name(self, mount):
"""Convert a mount name to a module name"""
if not self.is_mount(mount):
raise ValueError('%r is not a supported mount name' % (mount,))
return mount.replace(self.mount_prefix, self.module_prefix) | [
"def",
"mount2name",
"(",
"self",
",",
"mount",
")",
":",
"if",
"not",
"self",
".",
"is_mount",
"(",
"mount",
")",
":",
"raise",
"ValueError",
"(",
"'%r is not a supported mount name'",
"%",
"(",
"mount",
",",
")",
")",
"return",
"mount",
".",
"replace",
... | Convert a mount name to a module name | [
"Convert",
"a",
"mount",
"name",
"to",
"a",
"module",
"name"
] | train | https://github.com/maxfischer2781/include/blob/d8b0404f4996b6abcd39fdebf282b31fad8bb6f5/include/mount/__init__.py#L44-L48 |
ppo/django-guitar | guitar/templatetags/guitar_tags.py | body_class_tag | def body_class_tag(context):
"""
Return CSS "class" attributes for <body>.
Allows to provide a CSS namespace using urlpatterns namespace (as ``.ns-*``) and view name (as ``.vw-*``).
Usage: ``{% body_class %}``
Example: ``ns-my-app vw-my-view`` or ``ns-contacts vw-list``
Requires: ``apps.core.m... | python | def body_class_tag(context):
"""
Return CSS "class" attributes for <body>.
Allows to provide a CSS namespace using urlpatterns namespace (as ``.ns-*``) and view name (as ``.vw-*``).
Usage: ``{% body_class %}``
Example: ``ns-my-app vw-my-view`` or ``ns-contacts vw-list``
Requires: ``apps.core.m... | [
"def",
"body_class_tag",
"(",
"context",
")",
":",
"request",
"=",
"context",
".",
"get",
"(",
"\"request\"",
")",
"if",
"not",
"hasattr",
"(",
"request",
",",
"\"ROUTE\"",
")",
":",
"return",
"\"\"",
"css_classes",
"=",
"[",
"]",
"namespace",
"=",
"requ... | Return CSS "class" attributes for <body>.
Allows to provide a CSS namespace using urlpatterns namespace (as ``.ns-*``) and view name (as ``.vw-*``).
Usage: ``{% body_class %}``
Example: ``ns-my-app vw-my-view`` or ``ns-contacts vw-list``
Requires: ``apps.core.middlewares.CoreMiddleware``. | [
"Return",
"CSS",
"class",
"attributes",
"for",
"<body",
">",
"."
] | train | https://github.com/ppo/django-guitar/blob/857282219c0c4ff5907c3ad04ef012281d245348/guitar/templatetags/guitar_tags.py#L39-L65 |
ppo/django-guitar | guitar/templatetags/guitar_tags.py | static_absolute_tag | def static_absolute_tag(context, path):
"""
Return the absolute URL of a static file.
Usage: ``{% %}``
"""
request = context.get("request")
return urljoin(request.ABSOLUTE_ROOT, static_url(path)) | python | def static_absolute_tag(context, path):
"""
Return the absolute URL of a static file.
Usage: ``{% %}``
"""
request = context.get("request")
return urljoin(request.ABSOLUTE_ROOT, static_url(path)) | [
"def",
"static_absolute_tag",
"(",
"context",
",",
"path",
")",
":",
"request",
"=",
"context",
".",
"get",
"(",
"\"request\"",
")",
"return",
"urljoin",
"(",
"request",
".",
"ABSOLUTE_ROOT",
",",
"static_url",
"(",
"path",
")",
")"
] | Return the absolute URL of a static file.
Usage: ``{% %}`` | [
"Return",
"the",
"absolute",
"URL",
"of",
"a",
"static",
"file",
"."
] | train | https://github.com/ppo/django-guitar/blob/857282219c0c4ff5907c3ad04ef012281d245348/guitar/templatetags/guitar_tags.py#L91-L98 |
ppo/django-guitar | guitar/templatetags/guitar_tags.py | static_cdn_tag | def static_cdn_tag(path, cdn, cdn_only=False):
"""
Return the URL of a static file, with handling of offline mode.
Usage: ``{% %}``
"""
clean_path = path.lstrip("/")
if getattr(settings, "OFFLINE", False):
return static_url(join("vendor", clean_path))
elif cdn_only:
return ... | python | def static_cdn_tag(path, cdn, cdn_only=False):
"""
Return the URL of a static file, with handling of offline mode.
Usage: ``{% %}``
"""
clean_path = path.lstrip("/")
if getattr(settings, "OFFLINE", False):
return static_url(join("vendor", clean_path))
elif cdn_only:
return ... | [
"def",
"static_cdn_tag",
"(",
"path",
",",
"cdn",
",",
"cdn_only",
"=",
"False",
")",
":",
"clean_path",
"=",
"path",
".",
"lstrip",
"(",
"\"/\"",
")",
"if",
"getattr",
"(",
"settings",
",",
"\"OFFLINE\"",
",",
"False",
")",
":",
"return",
"static_url",
... | Return the URL of a static file, with handling of offline mode.
Usage: ``{% %}`` | [
"Return",
"the",
"URL",
"of",
"a",
"static",
"file",
"with",
"handling",
"of",
"offline",
"mode",
"."
] | train | https://github.com/ppo/django-guitar/blob/857282219c0c4ff5907c3ad04ef012281d245348/guitar/templatetags/guitar_tags.py#L102-L113 |
sassoo/goldman | goldman/resources/models.py | on_get | def on_get(resc, req, resp):
""" Get the models identified by query parameters
We return an empty list if no models are found.
"""
signals.pre_req.send(resc.model)
signals.pre_req_search.send(resc.model)
models = goldman.sess.store.search(resc.rtype, **{
'filters': req.filters,
... | python | def on_get(resc, req, resp):
""" Get the models identified by query parameters
We return an empty list if no models are found.
"""
signals.pre_req.send(resc.model)
signals.pre_req_search.send(resc.model)
models = goldman.sess.store.search(resc.rtype, **{
'filters': req.filters,
... | [
"def",
"on_get",
"(",
"resc",
",",
"req",
",",
"resp",
")",
":",
"signals",
".",
"pre_req",
".",
"send",
"(",
"resc",
".",
"model",
")",
"signals",
".",
"pre_req_search",
".",
"send",
"(",
"resc",
".",
"model",
")",
"models",
"=",
"goldman",
".",
"... | Get the models identified by query parameters
We return an empty list if no models are found. | [
"Get",
"the",
"models",
"identified",
"by",
"query",
"parameters"
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/resources/models.py#L20-L39 |
sassoo/goldman | goldman/resources/models.py | on_post | def on_post(resc, req, resp):
""" Deserialize the payload & create the new single item """
signals.pre_req.send(resc.model)
signals.pre_req_create.send(resc.model)
props = req.deserialize()
model = resc.model()
from_rest(model, props)
goldman.sess.store.create(model)
props = to_rest_... | python | def on_post(resc, req, resp):
""" Deserialize the payload & create the new single item """
signals.pre_req.send(resc.model)
signals.pre_req_create.send(resc.model)
props = req.deserialize()
model = resc.model()
from_rest(model, props)
goldman.sess.store.create(model)
props = to_rest_... | [
"def",
"on_post",
"(",
"resc",
",",
"req",
",",
"resp",
")",
":",
"signals",
".",
"pre_req",
".",
"send",
"(",
"resc",
".",
"model",
")",
"signals",
".",
"pre_req_create",
".",
"send",
"(",
"resc",
".",
"model",
")",
"props",
"=",
"req",
".",
"dese... | Deserialize the payload & create the new single item | [
"Deserialize",
"the",
"payload",
"&",
"create",
"the",
"new",
"single",
"item"
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/resources/models.py#L42-L61 |
pip-services3-python/pip-services3-components-python | pip_services3_components/auth/MemoryCredentialStore.py | MemoryCredentialStore.read_credentials | def read_credentials(self, credentials):
"""
Reads credentials from configuration parameters.
Each section represents an individual CredentialParams
:param credentials: configuration parameters to be read
"""
self._items.clear()
for key in credentials.get_key_nam... | python | def read_credentials(self, credentials):
"""
Reads credentials from configuration parameters.
Each section represents an individual CredentialParams
:param credentials: configuration parameters to be read
"""
self._items.clear()
for key in credentials.get_key_nam... | [
"def",
"read_credentials",
"(",
"self",
",",
"credentials",
")",
":",
"self",
".",
"_items",
".",
"clear",
"(",
")",
"for",
"key",
"in",
"credentials",
".",
"get_key_names",
"(",
")",
":",
"value",
"=",
"credentials",
".",
"get_as_nullable_string",
"(",
"k... | Reads credentials from configuration parameters.
Each section represents an individual CredentialParams
:param credentials: configuration parameters to be read | [
"Reads",
"credentials",
"from",
"configuration",
"parameters",
".",
"Each",
"section",
"represents",
"an",
"individual",
"CredentialParams"
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/auth/MemoryCredentialStore.py#L60-L70 |
pip-services3-python/pip-services3-components-python | pip_services3_components/auth/MemoryCredentialStore.py | MemoryCredentialStore.store | def store(self, correlation_id, key, credential):
"""
Stores credential parameters into the store.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param key: a key to uniquely identify the credential parameters.
:param credential: a cre... | python | def store(self, correlation_id, key, credential):
"""
Stores credential parameters into the store.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param key: a key to uniquely identify the credential parameters.
:param credential: a cre... | [
"def",
"store",
"(",
"self",
",",
"correlation_id",
",",
"key",
",",
"credential",
")",
":",
"if",
"credential",
"!=",
"None",
":",
"self",
".",
"_items",
".",
"put",
"(",
"key",
",",
"credential",
")",
"else",
":",
"self",
".",
"_items",
".",
"remov... | Stores credential parameters into the store.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param key: a key to uniquely identify the credential parameters.
:param credential: a credential parameters to be stored. | [
"Stores",
"credential",
"parameters",
"into",
"the",
"store",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/auth/MemoryCredentialStore.py#L72-L85 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/twisted/interfaces.py | CheckInputArgs | def CheckInputArgs(*interfaces):
"""Must provide at least one interface, the last one may be repeated.
"""
l = len(interfaces)
def wrapper(func):
def check_args(self, *args, **kw):
for i in range(len(args)):
if (l > i and interfaces[i].providedBy(args[i])) or interfac... | python | def CheckInputArgs(*interfaces):
"""Must provide at least one interface, the last one may be repeated.
"""
l = len(interfaces)
def wrapper(func):
def check_args(self, *args, **kw):
for i in range(len(args)):
if (l > i and interfaces[i].providedBy(args[i])) or interfac... | [
"def",
"CheckInputArgs",
"(",
"*",
"interfaces",
")",
":",
"l",
"=",
"len",
"(",
"interfaces",
")",
"def",
"wrapper",
"(",
"func",
")",
":",
"def",
"check_args",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"for",
"i",
"in",
"ran... | Must provide at least one interface, the last one may be repeated. | [
"Must",
"provide",
"at",
"least",
"one",
"interface",
"the",
"last",
"one",
"may",
"be",
"repeated",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/twisted/interfaces.py#L20-L33 |
alexmojaki/littleutils | littleutils/__init__.py | helpful_error_list_get | def helpful_error_list_get(lst, index):
"""
>>> helpful_error_list_get([1, 2, 3], 1)
2
>>> helpful_error_list_get([1, 2, 3], 4)
Traceback (most recent call last):
...
IndexError: Tried to access 4, length is only 3
"""
try:
return lst[index]
except IndexError:
rai... | python | def helpful_error_list_get(lst, index):
"""
>>> helpful_error_list_get([1, 2, 3], 1)
2
>>> helpful_error_list_get([1, 2, 3], 4)
Traceback (most recent call last):
...
IndexError: Tried to access 4, length is only 3
"""
try:
return lst[index]
except IndexError:
rai... | [
"def",
"helpful_error_list_get",
"(",
"lst",
",",
"index",
")",
":",
"try",
":",
"return",
"lst",
"[",
"index",
"]",
"except",
"IndexError",
":",
"raise",
"IndexError",
"(",
"'Tried to access %r, length is only %r'",
"%",
"(",
"index",
",",
"len",
"(",
"lst",
... | >>> helpful_error_list_get([1, 2, 3], 1)
2
>>> helpful_error_list_get([1, 2, 3], 4)
Traceback (most recent call last):
...
IndexError: Tried to access 4, length is only 3 | [
">>>",
"helpful_error_list_get",
"(",
"[",
"1",
"2",
"3",
"]",
"1",
")",
"2",
">>>",
"helpful_error_list_get",
"(",
"[",
"1",
"2",
"3",
"]",
"4",
")",
"Traceback",
"(",
"most",
"recent",
"call",
"last",
")",
":",
"...",
"IndexError",
":",
"Tried",
"t... | train | https://github.com/alexmojaki/littleutils/blob/1132d2d2782b05741a907d1281cd8c001f1d1d9d/littleutils/__init__.py#L94-L106 |
alexmojaki/littleutils | littleutils/__init__.py | only | def only(it):
"""
>>> only([7])
7
>>> only([1, 2])
Traceback (most recent call last):
...
AssertionError: Expected one value, found 2
>>> only([])
Traceback (most recent call last):
...
AssertionError: Expected one value, found 0
>>> from itertools import repeat
>>> o... | python | def only(it):
"""
>>> only([7])
7
>>> only([1, 2])
Traceback (most recent call last):
...
AssertionError: Expected one value, found 2
>>> only([])
Traceback (most recent call last):
...
AssertionError: Expected one value, found 0
>>> from itertools import repeat
>>> o... | [
"def",
"only",
"(",
"it",
")",
":",
"if",
"isinstance",
"(",
"it",
",",
"Sized",
")",
":",
"if",
"len",
"(",
"it",
")",
"!=",
"1",
":",
"raise",
"AssertionError",
"(",
"'Expected one value, found %s'",
"%",
"len",
"(",
"it",
")",
")",
"# noinspection P... | >>> only([7])
7
>>> only([1, 2])
Traceback (most recent call last):
...
AssertionError: Expected one value, found 2
>>> only([])
Traceback (most recent call last):
...
AssertionError: Expected one value, found 0
>>> from itertools import repeat
>>> only(repeat(5))
Traceba... | [
">>>",
"only",
"(",
"[",
"7",
"]",
")",
"7",
">>>",
"only",
"(",
"[",
"1",
"2",
"]",
")",
"Traceback",
"(",
"most",
"recent",
"call",
"last",
")",
":",
"...",
"AssertionError",
":",
"Expected",
"one",
"value",
"found",
"2",
">>>",
"only",
"(",
"[... | train | https://github.com/alexmojaki/littleutils/blob/1132d2d2782b05741a907d1281cd8c001f1d1d9d/littleutils/__init__.py#L124-L158 |
alexmojaki/littleutils | littleutils/__init__.py | retry | def retry(num_attempts=3, exception_class=Exception, log=None, sleeptime=1):
"""
>>> def fail():
... runs[0] += 1
... raise ValueError()
>>> runs = [0]; retry(sleeptime=0)(fail)()
Traceback (most recent call last):
...
ValueError
>>> runs
[3]
>>> runs = [0]; retry(2, ... | python | def retry(num_attempts=3, exception_class=Exception, log=None, sleeptime=1):
"""
>>> def fail():
... runs[0] += 1
... raise ValueError()
>>> runs = [0]; retry(sleeptime=0)(fail)()
Traceback (most recent call last):
...
ValueError
>>> runs
[3]
>>> runs = [0]; retry(2, ... | [
"def",
"retry",
"(",
"num_attempts",
"=",
"3",
",",
"exception_class",
"=",
"Exception",
",",
"log",
"=",
"None",
",",
"sleeptime",
"=",
"1",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def"... | >>> def fail():
... runs[0] += 1
... raise ValueError()
>>> runs = [0]; retry(sleeptime=0)(fail)()
Traceback (most recent call last):
...
ValueError
>>> runs
[3]
>>> runs = [0]; retry(2, sleeptime=0)(fail)()
Traceback (most recent call last):
...
ValueError
>>... | [
">>>",
"def",
"fail",
"()",
":",
"...",
"runs",
"[",
"0",
"]",
"+",
"=",
"1",
"...",
"raise",
"ValueError",
"()",
">>>",
"runs",
"=",
"[",
"0",
"]",
";",
"retry",
"(",
"sleeptime",
"=",
"0",
")",
"(",
"fail",
")",
"()",
"Traceback",
"(",
"most"... | train | https://github.com/alexmojaki/littleutils/blob/1132d2d2782b05741a907d1281cd8c001f1d1d9d/littleutils/__init__.py#L187-L238 |
alexmojaki/littleutils | littleutils/__init__.py | strip_optional_prefix | def strip_optional_prefix(string, prefix, log=None):
"""
>>> strip_optional_prefix('abcdef', 'abc')
'def'
>>> strip_optional_prefix('abcdef', '123')
'abcdef'
>>> strip_optional_prefix('abcdef', '123', PrintingLogger())
String starts with 'abc', not '123'
'abcdef'
"""
if string.st... | python | def strip_optional_prefix(string, prefix, log=None):
"""
>>> strip_optional_prefix('abcdef', 'abc')
'def'
>>> strip_optional_prefix('abcdef', '123')
'abcdef'
>>> strip_optional_prefix('abcdef', '123', PrintingLogger())
String starts with 'abc', not '123'
'abcdef'
"""
if string.st... | [
"def",
"strip_optional_prefix",
"(",
"string",
",",
"prefix",
",",
"log",
"=",
"None",
")",
":",
"if",
"string",
".",
"startswith",
"(",
"prefix",
")",
":",
"return",
"string",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"if",
"log",
":",
"log",
".",
... | >>> strip_optional_prefix('abcdef', 'abc')
'def'
>>> strip_optional_prefix('abcdef', '123')
'abcdef'
>>> strip_optional_prefix('abcdef', '123', PrintingLogger())
String starts with 'abc', not '123'
'abcdef' | [
">>>",
"strip_optional_prefix",
"(",
"abcdef",
"abc",
")",
"def",
">>>",
"strip_optional_prefix",
"(",
"abcdef",
"123",
")",
"abcdef",
">>>",
"strip_optional_prefix",
"(",
"abcdef",
"123",
"PrintingLogger",
"()",
")",
"String",
"starts",
"with",
"abc",
"not",
"1... | train | https://github.com/alexmojaki/littleutils/blob/1132d2d2782b05741a907d1281cd8c001f1d1d9d/littleutils/__init__.py#L241-L255 |
alexmojaki/littleutils | littleutils/__init__.py | strip_required_prefix | def strip_required_prefix(string, prefix):
"""
>>> strip_required_prefix('abcdef', 'abc')
'def'
>>> strip_required_prefix('abcdef', '123')
Traceback (most recent call last):
...
AssertionError: String starts with 'abc', not '123'
"""
if string.startswith(prefix):
return strin... | python | def strip_required_prefix(string, prefix):
"""
>>> strip_required_prefix('abcdef', 'abc')
'def'
>>> strip_required_prefix('abcdef', '123')
Traceback (most recent call last):
...
AssertionError: String starts with 'abc', not '123'
"""
if string.startswith(prefix):
return strin... | [
"def",
"strip_required_prefix",
"(",
"string",
",",
"prefix",
")",
":",
"if",
"string",
".",
"startswith",
"(",
"prefix",
")",
":",
"return",
"string",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"raise",
"AssertionError",
"(",
"'String starts with %r, not %r'",... | >>> strip_required_prefix('abcdef', 'abc')
'def'
>>> strip_required_prefix('abcdef', '123')
Traceback (most recent call last):
...
AssertionError: String starts with 'abc', not '123' | [
">>>",
"strip_required_prefix",
"(",
"abcdef",
"abc",
")",
"def",
">>>",
"strip_required_prefix",
"(",
"abcdef",
"123",
")",
"Traceback",
"(",
"most",
"recent",
"call",
"last",
")",
":",
"...",
"AssertionError",
":",
"String",
"starts",
"with",
"abc",
"not",
... | train | https://github.com/alexmojaki/littleutils/blob/1132d2d2782b05741a907d1281cd8c001f1d1d9d/littleutils/__init__.py#L258-L269 |
alexmojaki/littleutils | littleutils/__init__.py | strip_optional_suffix | def strip_optional_suffix(string, suffix, log=None):
"""
>>> strip_optional_suffix('abcdef', 'def')
'abc'
>>> strip_optional_suffix('abcdef', '123')
'abcdef'
>>> strip_optional_suffix('abcdef', '123', PrintingLogger())
String ends with 'def', not '123'
'abcdef'
"""
if string.ends... | python | def strip_optional_suffix(string, suffix, log=None):
"""
>>> strip_optional_suffix('abcdef', 'def')
'abc'
>>> strip_optional_suffix('abcdef', '123')
'abcdef'
>>> strip_optional_suffix('abcdef', '123', PrintingLogger())
String ends with 'def', not '123'
'abcdef'
"""
if string.ends... | [
"def",
"strip_optional_suffix",
"(",
"string",
",",
"suffix",
",",
"log",
"=",
"None",
")",
":",
"if",
"string",
".",
"endswith",
"(",
"suffix",
")",
":",
"return",
"string",
"[",
":",
"-",
"len",
"(",
"suffix",
")",
"]",
"if",
"log",
":",
"log",
"... | >>> strip_optional_suffix('abcdef', 'def')
'abc'
>>> strip_optional_suffix('abcdef', '123')
'abcdef'
>>> strip_optional_suffix('abcdef', '123', PrintingLogger())
String ends with 'def', not '123'
'abcdef' | [
">>>",
"strip_optional_suffix",
"(",
"abcdef",
"def",
")",
"abc",
">>>",
"strip_optional_suffix",
"(",
"abcdef",
"123",
")",
"abcdef",
">>>",
"strip_optional_suffix",
"(",
"abcdef",
"123",
"PrintingLogger",
"()",
")",
"String",
"ends",
"with",
"def",
"not",
"123... | train | https://github.com/alexmojaki/littleutils/blob/1132d2d2782b05741a907d1281cd8c001f1d1d9d/littleutils/__init__.py#L272-L286 |
alexmojaki/littleutils | littleutils/__init__.py | strip_required_suffix | def strip_required_suffix(string, suffix):
"""
>>> strip_required_suffix('abcdef', 'def')
'abc'
>>> strip_required_suffix('abcdef', '123')
Traceback (most recent call last):
...
AssertionError: String ends with 'def', not '123'
"""
if string.endswith(suffix):
return string[:-... | python | def strip_required_suffix(string, suffix):
"""
>>> strip_required_suffix('abcdef', 'def')
'abc'
>>> strip_required_suffix('abcdef', '123')
Traceback (most recent call last):
...
AssertionError: String ends with 'def', not '123'
"""
if string.endswith(suffix):
return string[:-... | [
"def",
"strip_required_suffix",
"(",
"string",
",",
"suffix",
")",
":",
"if",
"string",
".",
"endswith",
"(",
"suffix",
")",
":",
"return",
"string",
"[",
":",
"-",
"len",
"(",
"suffix",
")",
"]",
"raise",
"AssertionError",
"(",
"'String ends with %r, not %r... | >>> strip_required_suffix('abcdef', 'def')
'abc'
>>> strip_required_suffix('abcdef', '123')
Traceback (most recent call last):
...
AssertionError: String ends with 'def', not '123' | [
">>>",
"strip_required_suffix",
"(",
"abcdef",
"def",
")",
"abc",
">>>",
"strip_required_suffix",
"(",
"abcdef",
"123",
")",
"Traceback",
"(",
"most",
"recent",
"call",
"last",
")",
":",
"...",
"AssertionError",
":",
"String",
"ends",
"with",
"def",
"not",
"... | train | https://github.com/alexmojaki/littleutils/blob/1132d2d2782b05741a907d1281cd8c001f1d1d9d/littleutils/__init__.py#L289-L300 |
alexmojaki/littleutils | littleutils/__init__.py | ensure_list_if_string | def ensure_list_if_string(x):
"""
Allows an argument to be passed either as a list of strings or a single string delimited
by spaces and/or commas.
>>> assert (ensure_list_if_string(['abc', 'def', '123']) ==
... ensure_list_if_string('abc,def,123') ==
... ensure_list_if_string('a... | python | def ensure_list_if_string(x):
"""
Allows an argument to be passed either as a list of strings or a single string delimited
by spaces and/or commas.
>>> assert (ensure_list_if_string(['abc', 'def', '123']) ==
... ensure_list_if_string('abc,def,123') ==
... ensure_list_if_string('a... | [
"def",
"ensure_list_if_string",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"basestring",
")",
":",
"x",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"re",
".",
"split",
"(",
"'[,\\s]+'",
",",
"x",
")",
")",
")",
"return",
"x"
] | Allows an argument to be passed either as a list of strings or a single string delimited
by spaces and/or commas.
>>> assert (ensure_list_if_string(['abc', 'def', '123']) ==
... ensure_list_if_string('abc,def,123') ==
... ensure_list_if_string('abc def 123') ==
... ensure_lis... | [
"Allows",
"an",
"argument",
"to",
"be",
"passed",
"either",
"as",
"a",
"list",
"of",
"strings",
"or",
"a",
"single",
"string",
"delimited",
"by",
"spaces",
"and",
"/",
"or",
"commas",
".",
">>>",
"assert",
"(",
"ensure_list_if_string",
"(",
"[",
"abc",
"... | train | https://github.com/alexmojaki/littleutils/blob/1132d2d2782b05741a907d1281cd8c001f1d1d9d/littleutils/__init__.py#L303-L317 |
alexmojaki/littleutils | littleutils/__init__.py | select_keys | def select_keys(d, keys, helpful_error=True):
"""
>>> d = dict(a=1, b=2, c=3)
>>> print(json.dumps(select_keys(d, 'a c'), sort_keys=True))
{"a": 1, "c": 3}
>>> select_keys(d, 'a d')
Traceback (most recent call last):
...
KeyError: "Tried to access 'd', only keys are: ['a', 'b', 'c']"
... | python | def select_keys(d, keys, helpful_error=True):
"""
>>> d = dict(a=1, b=2, c=3)
>>> print(json.dumps(select_keys(d, 'a c'), sort_keys=True))
{"a": 1, "c": 3}
>>> select_keys(d, 'a d')
Traceback (most recent call last):
...
KeyError: "Tried to access 'd', only keys are: ['a', 'b', 'c']"
... | [
"def",
"select_keys",
"(",
"d",
",",
"keys",
",",
"helpful_error",
"=",
"True",
")",
":",
"keys",
"=",
"ensure_list_if_string",
"(",
"keys",
")",
"if",
"helpful_error",
":",
"return",
"{",
"k",
":",
"helpful_error_dict_get",
"(",
"d",
",",
"k",
")",
"for... | >>> d = dict(a=1, b=2, c=3)
>>> print(json.dumps(select_keys(d, 'a c'), sort_keys=True))
{"a": 1, "c": 3}
>>> select_keys(d, 'a d')
Traceback (most recent call last):
...
KeyError: "Tried to access 'd', only keys are: ['a', 'b', 'c']"
>>> select_keys(d, 'a d', helpful_error=False)
Traceb... | [
">>>",
"d",
"=",
"dict",
"(",
"a",
"=",
"1",
"b",
"=",
"2",
"c",
"=",
"3",
")",
">>>",
"print",
"(",
"json",
".",
"dumps",
"(",
"select_keys",
"(",
"d",
"a",
"c",
")",
"sort_keys",
"=",
"True",
"))",
"{",
"a",
":",
"1",
"c",
":",
"3",
"}"... | train | https://github.com/alexmojaki/littleutils/blob/1132d2d2782b05741a907d1281cd8c001f1d1d9d/littleutils/__init__.py#L345-L363 |
alexmojaki/littleutils | littleutils/__init__.py | group_by_key_func | def group_by_key_func(iterable, key_func):
"""
Create a dictionary from an iterable such that the keys are the result of evaluating a key function on elements
of the iterable and the values are lists of elements all of which correspond to the key.
>>> def si(d): return sorted(d.items())
>>> si(grou... | python | def group_by_key_func(iterable, key_func):
"""
Create a dictionary from an iterable such that the keys are the result of evaluating a key function on elements
of the iterable and the values are lists of elements all of which correspond to the key.
>>> def si(d): return sorted(d.items())
>>> si(grou... | [
"def",
"group_by_key_func",
"(",
"iterable",
",",
"key_func",
")",
":",
"result",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"item",
"in",
"iterable",
":",
"result",
"[",
"key_func",
"(",
"item",
")",
"]",
".",
"append",
"(",
"item",
")",
"return",
"... | Create a dictionary from an iterable such that the keys are the result of evaluating a key function on elements
of the iterable and the values are lists of elements all of which correspond to the key.
>>> def si(d): return sorted(d.items())
>>> si(group_by_key_func("a bb ccc d ee fff".split(), len))
[(... | [
"Create",
"a",
"dictionary",
"from",
"an",
"iterable",
"such",
"that",
"the",
"keys",
"are",
"the",
"result",
"of",
"evaluating",
"a",
"key",
"function",
"on",
"elements",
"of",
"the",
"iterable",
"and",
"the",
"values",
"are",
"lists",
"of",
"elements",
"... | train | https://github.com/alexmojaki/littleutils/blob/1132d2d2782b05741a907d1281cd8c001f1d1d9d/littleutils/__init__.py#L437-L451 |
alexmojaki/littleutils | littleutils/__init__.py | setattrs | def setattrs(obj, **kwargs):
"""
>>> data = SimpleNamespace()
>>> setattrs(data, a=1, b=2) # doctest:+ELLIPSIS
namespace(a=1, b=2)
"""
for key, value in kwargs.items():
setattr(obj, key, value)
return obj | python | def setattrs(obj, **kwargs):
"""
>>> data = SimpleNamespace()
>>> setattrs(data, a=1, b=2) # doctest:+ELLIPSIS
namespace(a=1, b=2)
"""
for key, value in kwargs.items():
setattr(obj, key, value)
return obj | [
"def",
"setattrs",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"obj",
",",
"key",
",",
"value",
")",
"return",
"obj"
] | >>> data = SimpleNamespace()
>>> setattrs(data, a=1, b=2) # doctest:+ELLIPSIS
namespace(a=1, b=2) | [
">>>",
"data",
"=",
"SimpleNamespace",
"()",
">>>",
"setattrs",
"(",
"data",
"a",
"=",
"1",
"b",
"=",
"2",
")",
"#",
"doctest",
":",
"+",
"ELLIPSIS",
"namespace",
"(",
"a",
"=",
"1",
"b",
"=",
"2",
")"
] | train | https://github.com/alexmojaki/littleutils/blob/1132d2d2782b05741a907d1281cd8c001f1d1d9d/littleutils/__init__.py#L462-L470 |
alexmojaki/littleutils | littleutils/__init__.py | pretty_table | def pretty_table(rows, header=None):
"""
Returns a string with a simple pretty table representing the given rows.
Rows can be:
- Sequences such as lists or tuples
- Mappings such as dicts
- Any object with a __dict__ attribute (most plain python objects) which is
equivalent to passing ... | python | def pretty_table(rows, header=None):
"""
Returns a string with a simple pretty table representing the given rows.
Rows can be:
- Sequences such as lists or tuples
- Mappings such as dicts
- Any object with a __dict__ attribute (most plain python objects) which is
equivalent to passing ... | [
"def",
"pretty_table",
"(",
"rows",
",",
"header",
"=",
"None",
")",
":",
"rows2",
"=",
"[",
"]",
"if",
"header",
":",
"header",
"=",
"ensure_list_if_string",
"(",
"header",
")",
"rows2",
".",
"insert",
"(",
"0",
",",
"header",
")",
"row_type",
"=",
... | Returns a string with a simple pretty table representing the given rows.
Rows can be:
- Sequences such as lists or tuples
- Mappings such as dicts
- Any object with a __dict__ attribute (most plain python objects) which is
equivalent to passing the __dict__ directly.
If no header is given ... | [
"Returns",
"a",
"string",
"with",
"a",
"simple",
"pretty",
"table",
"representing",
"the",
"given",
"rows",
".",
"Rows",
"can",
"be",
":",
"-",
"Sequences",
"such",
"as",
"lists",
"or",
"tuples",
"-",
"Mappings",
"such",
"as",
"dicts",
"-",
"Any",
"objec... | train | https://github.com/alexmojaki/littleutils/blob/1132d2d2782b05741a907d1281cd8c001f1d1d9d/littleutils/__init__.py#L494-L589 |
alexmojaki/littleutils | littleutils/__init__.py | date_to_datetime | def date_to_datetime(d):
"""
>>> date_to_datetime(date(2000, 1, 2))
datetime.datetime(2000, 1, 2, 0, 0)
>>> date_to_datetime(datetime(2000, 1, 2, 3, 4, 5))
datetime.datetime(2000, 1, 2, 3, 4, 5)
"""
if not isinstance(d, datetime):
d = datetime.combine(d, datetime.min.time())
retu... | python | def date_to_datetime(d):
"""
>>> date_to_datetime(date(2000, 1, 2))
datetime.datetime(2000, 1, 2, 0, 0)
>>> date_to_datetime(datetime(2000, 1, 2, 3, 4, 5))
datetime.datetime(2000, 1, 2, 3, 4, 5)
"""
if not isinstance(d, datetime):
d = datetime.combine(d, datetime.min.time())
retu... | [
"def",
"date_to_datetime",
"(",
"d",
")",
":",
"if",
"not",
"isinstance",
"(",
"d",
",",
"datetime",
")",
":",
"d",
"=",
"datetime",
".",
"combine",
"(",
"d",
",",
"datetime",
".",
"min",
".",
"time",
"(",
")",
")",
"return",
"d"
] | >>> date_to_datetime(date(2000, 1, 2))
datetime.datetime(2000, 1, 2, 0, 0)
>>> date_to_datetime(datetime(2000, 1, 2, 3, 4, 5))
datetime.datetime(2000, 1, 2, 3, 4, 5) | [
">>>",
"date_to_datetime",
"(",
"date",
"(",
"2000",
"1",
"2",
"))",
"datetime",
".",
"datetime",
"(",
"2000",
"1",
"2",
"0",
"0",
")",
">>>",
"date_to_datetime",
"(",
"datetime",
"(",
"2000",
"1",
"2",
"3",
"4",
"5",
"))",
"datetime",
".",
"datetime... | train | https://github.com/alexmojaki/littleutils/blob/1132d2d2782b05741a907d1281cd8c001f1d1d9d/littleutils/__init__.py#L592-L601 |
alexmojaki/littleutils | littleutils/__init__.py | timer | def timer(description='Operation', log=None):
"""
Simple context manager which logs (if log is provided)
or prints the time taken in seconds for the block to complete.
>>> with timer():
... sleep(0.1) # doctest:+ELLIPSIS
Operation took 0.1... seconds
>>> with timer('Sleepi... | python | def timer(description='Operation', log=None):
"""
Simple context manager which logs (if log is provided)
or prints the time taken in seconds for the block to complete.
>>> with timer():
... sleep(0.1) # doctest:+ELLIPSIS
Operation took 0.1... seconds
>>> with timer('Sleepi... | [
"def",
"timer",
"(",
"description",
"=",
"'Operation'",
",",
"log",
"=",
"None",
")",
":",
"start",
"=",
"time",
"(",
")",
"yield",
"elapsed",
"=",
"time",
"(",
")",
"-",
"start",
"message",
"=",
"'%s took %s seconds'",
"%",
"(",
"description",
",",
"e... | Simple context manager which logs (if log is provided)
or prints the time taken in seconds for the block to complete.
>>> with timer():
... sleep(0.1) # doctest:+ELLIPSIS
Operation took 0.1... seconds
>>> with timer('Sleeping'):
... sleep(0.2) # doctest:+ELLIP... | [
"Simple",
"context",
"manager",
"which",
"logs",
"(",
"if",
"log",
"is",
"provided",
")",
"or",
"prints",
"the",
"time",
"taken",
"in",
"seconds",
"for",
"the",
"block",
"to",
"complete",
"."
] | train | https://github.com/alexmojaki/littleutils/blob/1132d2d2782b05741a907d1281cd8c001f1d1d9d/littleutils/__init__.py#L716-L739 |
MinchinWeb/colourettu | tasks.py | other_dependancies | def other_dependancies(server, environment):
"""
Installs things that need to be in place before installing the main package
"""
print(' ** Other Dependancides, based on server', server, '**')
server = server.lower()
# Pillow is not on TestPyPI
if server is "local":
pass
elif se... | python | def other_dependancies(server, environment):
"""
Installs things that need to be in place before installing the main package
"""
print(' ** Other Dependancides, based on server', server, '**')
server = server.lower()
# Pillow is not on TestPyPI
if server is "local":
pass
elif se... | [
"def",
"other_dependancies",
"(",
"server",
",",
"environment",
")",
":",
"print",
"(",
"' ** Other Dependancides, based on server'",
",",
"server",
",",
"'**'",
")",
"server",
"=",
"server",
".",
"lower",
"(",
")",
"# Pillow is not on TestPyPI",
"if",
"server",
... | Installs things that need to be in place before installing the main package | [
"Installs",
"things",
"that",
"need",
"to",
"be",
"in",
"place",
"before",
"installing",
"the",
"main",
"package"
] | train | https://github.com/MinchinWeb/colourettu/blob/f0b2f6b1d44055f3ccee62ac2759829f1e16a252/tasks.py#L143-L161 |
MinchinWeb/colourettu | tasks.py | make_release | def make_release(cts):
'''Make and upload the release.
Changelog:
- v0.2.1 -- 2016-11-18 -- specify downloading of non-cached version of the
package for multiple formats can be properly and
individually tested.
- 0.2.2 -- 2016-11028 -- mov... | python | def make_release(cts):
'''Make and upload the release.
Changelog:
- v0.2.1 -- 2016-11-18 -- specify downloading of non-cached version of the
package for multiple formats can be properly and
individually tested.
- 0.2.2 -- 2016-11028 -- mov... | [
"def",
"make_release",
"(",
"cts",
")",
":",
"make_release_version",
"=",
"__version__",
"colorama",
".",
"init",
"(",
")",
"text",
".",
"title",
"(",
"\"Minchin 'Make Release' for Python v{}\"",
".",
"format",
"(",
"make_release_version",
")",
")",
"print",
"(",
... | Make and upload the release.
Changelog:
- v0.2.1 -- 2016-11-18 -- specify downloading of non-cached version of the
package for multiple formats can be properly and
individually tested.
- 0.2.2 -- 2016-11028 -- move configuration to top of file | [
"Make",
"and",
"upload",
"the",
"release",
"."
] | train | https://github.com/MinchinWeb/colourettu/blob/f0b2f6b1d44055f3ccee62ac2759829f1e16a252/tasks.py#L199-L246 |
radjkarl/fancyTools | fancytools/utils/formatedTime.py | formatedTime | def formatedTime(ms):
"""
convert milliseconds in a human readable time
>>> formatedTime(60e3)
'1m'
>>> formatedTime(1000e3)
'16m 40s'
>>> formatedTime(200000123)
'2d 7h 33m 20.123s'
"""
if ms:
s = ms / 1000.0
m, s = divmod(s, 60)
h, m = divmod(m, 60)
... | python | def formatedTime(ms):
"""
convert milliseconds in a human readable time
>>> formatedTime(60e3)
'1m'
>>> formatedTime(1000e3)
'16m 40s'
>>> formatedTime(200000123)
'2d 7h 33m 20.123s'
"""
if ms:
s = ms / 1000.0
m, s = divmod(s, 60)
h, m = divmod(m, 60)
... | [
"def",
"formatedTime",
"(",
"ms",
")",
":",
"if",
"ms",
":",
"s",
"=",
"ms",
"/",
"1000.0",
"m",
",",
"s",
"=",
"divmod",
"(",
"s",
",",
"60",
")",
"h",
",",
"m",
"=",
"divmod",
"(",
"m",
",",
"60",
")",
"d",
",",
"h",
"=",
"divmod",
"(",... | convert milliseconds in a human readable time
>>> formatedTime(60e3)
'1m'
>>> formatedTime(1000e3)
'16m 40s'
>>> formatedTime(200000123)
'2d 7h 33m 20.123s' | [
"convert",
"milliseconds",
"in",
"a",
"human",
"readable",
"time"
] | train | https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/utils/formatedTime.py#L5-L32 |
collectiveacuity/labPack | labpack/handlers/requests.py | requestsHandler._handle_command | def _handle_command(self, sys_command, pipe=False, interactive=None, print_pipe=False, handle_error=False):
'''
a method to handle system commands which require connectivity
:param sys_command: string with shell command to run in subprocess
:param pipe: boolean t... | python | def _handle_command(self, sys_command, pipe=False, interactive=None, print_pipe=False, handle_error=False):
'''
a method to handle system commands which require connectivity
:param sys_command: string with shell command to run in subprocess
:param pipe: boolean t... | [
"def",
"_handle_command",
"(",
"self",
",",
"sys_command",
",",
"pipe",
"=",
"False",
",",
"interactive",
"=",
"None",
",",
"print_pipe",
"=",
"False",
",",
"handle_error",
"=",
"False",
")",
":",
"import",
"sys",
"from",
"subprocess",
"import",
"Popen",
"... | a method to handle system commands which require connectivity
:param sys_command: string with shell command to run in subprocess
:param pipe: boolean to return a Popen object
:param interactive: [optional] callable object that accepts (string, Popen object)
:param prin... | [
"a",
"method",
"to",
"handle",
"system",
"commands",
"which",
"require",
"connectivity",
":",
"param",
"sys_command",
":",
"string",
"with",
"shell",
"command",
"to",
"run",
"in",
"subprocess",
":",
"param",
"pipe",
":",
"boolean",
"to",
"return",
"a",
"Pope... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/handlers/requests.py#L83-L146 |
collectiveacuity/labPack | labpack/handlers/requests.py | requestsHandler._check_connectivity | def _check_connectivity(self, err):
''' a method to check connectivity as source of error '''
try:
import requests
requests.get(self.uptime_ssl)
except:
from requests import Request
request_object = Request(method='GET', url=self... | python | def _check_connectivity(self, err):
''' a method to check connectivity as source of error '''
try:
import requests
requests.get(self.uptime_ssl)
except:
from requests import Request
request_object = Request(method='GET', url=self... | [
"def",
"_check_connectivity",
"(",
"self",
",",
"err",
")",
":",
"try",
":",
"import",
"requests",
"requests",
".",
"get",
"(",
"self",
".",
"uptime_ssl",
")",
"except",
":",
"from",
"requests",
"import",
"Request",
"request_object",
"=",
"Request",
"(",
"... | a method to check connectivity as source of error | [
"a",
"method",
"to",
"check",
"connectivity",
"as",
"source",
"of",
"error"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/handlers/requests.py#L148-L162 |
collectiveacuity/labPack | labpack/handlers/requests.py | requestsHandler._request | def _request(self, **kwargs):
''' a helper method for processing all request types '''
response = None
error = ''
code = 0
# send request
from requests import request
try:
response = request(**kwargs)
# handle... | python | def _request(self, **kwargs):
''' a helper method for processing all request types '''
response = None
error = ''
code = 0
# send request
from requests import request
try:
response = request(**kwargs)
# handle... | [
"def",
"_request",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"None",
"error",
"=",
"''",
"code",
"=",
"0",
"# send request\r",
"from",
"requests",
"import",
"request",
"try",
":",
"response",
"=",
"request",
"(",
"*",
"*",
"kwarg... | a helper method for processing all request types | [
"a",
"helper",
"method",
"for",
"processing",
"all",
"request",
"types"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/handlers/requests.py#L164-L191 |
collectiveacuity/labPack | labpack/handlers/requests.py | requestsHandler._get_request | def _get_request(self, url, params=None, **kwargs):
''' a method to catch and report http get request connectivity errors '''
# construct request kwargs
request_kwargs = {
'method': 'GET',
'url': url,
'params': params
}
... | python | def _get_request(self, url, params=None, **kwargs):
''' a method to catch and report http get request connectivity errors '''
# construct request kwargs
request_kwargs = {
'method': 'GET',
'url': url,
'params': params
}
... | [
"def",
"_get_request",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# construct request kwargs\r",
"request_kwargs",
"=",
"{",
"'method'",
":",
"'GET'",
",",
"'url'",
":",
"url",
",",
"'params'",
":",
"params",
... | a method to catch and report http get request connectivity errors | [
"a",
"method",
"to",
"catch",
"and",
"report",
"http",
"get",
"request",
"connectivity",
"errors"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/handlers/requests.py#L193-L207 |
collectiveacuity/labPack | labpack/handlers/requests.py | requestsHandler._post_request | def _post_request(self, url, data=None, json=None, **kwargs):
''' a method to catch and report http post request connectivity errors '''
# construct request kwargs
request_kwargs = {
'method': 'POST',
'url': url,
'data': data,
... | python | def _post_request(self, url, data=None, json=None, **kwargs):
''' a method to catch and report http post request connectivity errors '''
# construct request kwargs
request_kwargs = {
'method': 'POST',
'url': url,
'data': data,
... | [
"def",
"_post_request",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
",",
"json",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# construct request kwargs\r",
"request_kwargs",
"=",
"{",
"'method'",
":",
"'POST'",
",",
"'url'",
":",
"url",
",",
... | a method to catch and report http post request connectivity errors | [
"a",
"method",
"to",
"catch",
"and",
"report",
"http",
"post",
"request",
"connectivity",
"errors"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/handlers/requests.py#L209-L224 |
collectiveacuity/labPack | labpack/handlers/requests.py | requestsHandler._options_request | def _options_request(self, url, **kwargs):
''' a method to catch and report http options request connectivity errors '''
# construct request kwargs
request_kwargs = {
'method': 'OPTIONS',
'url': url
}
for key, value in kwargs.items()... | python | def _options_request(self, url, **kwargs):
''' a method to catch and report http options request connectivity errors '''
# construct request kwargs
request_kwargs = {
'method': 'OPTIONS',
'url': url
}
for key, value in kwargs.items()... | [
"def",
"_options_request",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"# construct request kwargs\r",
"request_kwargs",
"=",
"{",
"'method'",
":",
"'OPTIONS'",
",",
"'url'",
":",
"url",
"}",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",... | a method to catch and report http options request connectivity errors | [
"a",
"method",
"to",
"catch",
"and",
"report",
"http",
"options",
"request",
"connectivity",
"errors"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/handlers/requests.py#L275-L288 |
tripzero/python-photons | photons/lightserver.py | LightServerWss.onBinaryMessage | def onBinaryMessage(self, msg, fromClient):
data = bytearray()
data.extend(msg)
"""
self.print_debug("message length: {}".format(len(data)))
self.print_debug("message data: {}".format(hexlify(data)))
"""
try:
self.queue.put_nowait(data)
except asyncio.QueueFull:
pass | python | def onBinaryMessage(self, msg, fromClient):
data = bytearray()
data.extend(msg)
"""
self.print_debug("message length: {}".format(len(data)))
self.print_debug("message data: {}".format(hexlify(data)))
"""
try:
self.queue.put_nowait(data)
except asyncio.QueueFull:
pass | [
"def",
"onBinaryMessage",
"(",
"self",
",",
"msg",
",",
"fromClient",
")",
":",
"data",
"=",
"bytearray",
"(",
")",
"data",
".",
"extend",
"(",
"msg",
")",
"try",
":",
"self",
".",
"queue",
".",
"put_nowait",
"(",
"data",
")",
"except",
"asyncio",
".... | self.print_debug("message length: {}".format(len(data)))
self.print_debug("message data: {}".format(hexlify(data))) | [
"self",
".",
"print_debug",
"(",
"message",
"length",
":",
"{}",
".",
"format",
"(",
"len",
"(",
"data",
")))",
"self",
".",
"print_debug",
"(",
"message",
"data",
":",
"{}",
".",
"format",
"(",
"hexlify",
"(",
"data",
")))"
] | train | https://github.com/tripzero/python-photons/blob/e185bbb55881189c7deeb599384944e61cf6048d/photons/lightserver.py#L23-L35 |
kolypto/py-exdoc | exdoc/data.py | DictProxy.update | def update(self, *args, **kwargs):
""" A handy update() method which returns self :)
:rtype: DictProxy
"""
super(DictProxy, self).update(*args, **kwargs)
return self | python | def update(self, *args, **kwargs):
""" A handy update() method which returns self :)
:rtype: DictProxy
"""
super(DictProxy, self).update(*args, **kwargs)
return self | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"DictProxy",
",",
"self",
")",
".",
"update",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self"
] | A handy update() method which returns self :)
:rtype: DictProxy | [
"A",
"handy",
"update",
"()",
"method",
"which",
"returns",
"self",
":",
")"
] | train | https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/data.py#L21-L27 |
dossier/dossier.models | dossier/models/soft_selectors.py | find_soft_selectors | def find_soft_selectors(ids_and_clean_visible, start_num_tokens='10',
max_num_tokens='20', filter_punctuation='0'):
'''External interface for dossier.models.soft_selectors.
This at scans through `num_tokens` values between
`start_num_tokens` and `max_num_tokens` and calls
`find_... | python | def find_soft_selectors(ids_and_clean_visible, start_num_tokens='10',
max_num_tokens='20', filter_punctuation='0'):
'''External interface for dossier.models.soft_selectors.
This at scans through `num_tokens` values between
`start_num_tokens` and `max_num_tokens` and calls
`find_... | [
"def",
"find_soft_selectors",
"(",
"ids_and_clean_visible",
",",
"start_num_tokens",
"=",
"'10'",
",",
"max_num_tokens",
"=",
"'20'",
",",
"filter_punctuation",
"=",
"'0'",
")",
":",
"start_num_tokens",
"=",
"int",
"(",
"start_num_tokens",
")",
"max_num_tokens",
"="... | External interface for dossier.models.soft_selectors.
This at scans through `num_tokens` values between
`start_num_tokens` and `max_num_tokens` and calls
`find_soft_selectors_at_n` looking for results
All of the params can be passed from URL parameters, in which
case they can be strings and this f... | [
"External",
"interface",
"for",
"dossier",
".",
"models",
".",
"soft_selectors",
"."
] | train | https://github.com/dossier/dossier.models/blob/c9e282f690eab72963926329efe1600709e48b13/dossier/models/soft_selectors.py#L35-L131 |
dossier/dossier.models | dossier/models/soft_selectors.py | make_ngram_corpus | def make_ngram_corpus(corpus_clean_visibles, num_tokens, filter_punctuation,
zoning_rules=False):
'''takes a list of clean_visible texts, such as from StreamItems or
FCs, tokenizes all the texts, and constructs n-grams using
`num_tokens` sized windows.
``corpus_clean_visibles`` --... | python | def make_ngram_corpus(corpus_clean_visibles, num_tokens, filter_punctuation,
zoning_rules=False):
'''takes a list of clean_visible texts, such as from StreamItems or
FCs, tokenizes all the texts, and constructs n-grams using
`num_tokens` sized windows.
``corpus_clean_visibles`` --... | [
"def",
"make_ngram_corpus",
"(",
"corpus_clean_visibles",
",",
"num_tokens",
",",
"filter_punctuation",
",",
"zoning_rules",
"=",
"False",
")",
":",
"## TODO: generatlize this zoning code, so that it works on many",
"## sites in the HT domain; consider finishing streamcorpus-zoner",
... | takes a list of clean_visible texts, such as from StreamItems or
FCs, tokenizes all the texts, and constructs n-grams using
`num_tokens` sized windows.
``corpus_clean_visibles`` -- list of unicode strings
``num_tokens`` --- the n of the n-grams
``filter_punctuation`` --- if True, punctuation is fil... | [
"takes",
"a",
"list",
"of",
"clean_visible",
"texts",
"such",
"as",
"from",
"StreamItems",
"or",
"FCs",
"tokenizes",
"all",
"the",
"texts",
"and",
"constructs",
"n",
"-",
"grams",
"using",
"num_tokens",
"sized",
"windows",
"."
] | train | https://github.com/dossier/dossier.models/blob/c9e282f690eab72963926329efe1600709e48b13/dossier/models/soft_selectors.py#L184-L258 |
dossier/dossier.models | dossier/models/soft_selectors.py | ids_and_clean_visible_from_streamcorpus_chunk_path | def ids_and_clean_visible_from_streamcorpus_chunk_path(corpus_path):
'''converts a streamcorpus.Chunk file into the structure that is
passed by the search engine to find_soft_selectors
'''
ch = clean_html(clean_html.default_config)
cv = clean_visible(clean_visible.default_config)
ids_and_clean_... | python | def ids_and_clean_visible_from_streamcorpus_chunk_path(corpus_path):
'''converts a streamcorpus.Chunk file into the structure that is
passed by the search engine to find_soft_selectors
'''
ch = clean_html(clean_html.default_config)
cv = clean_visible(clean_visible.default_config)
ids_and_clean_... | [
"def",
"ids_and_clean_visible_from_streamcorpus_chunk_path",
"(",
"corpus_path",
")",
":",
"ch",
"=",
"clean_html",
"(",
"clean_html",
".",
"default_config",
")",
"cv",
"=",
"clean_visible",
"(",
"clean_visible",
".",
"default_config",
")",
"ids_and_clean_visible",
"=",... | converts a streamcorpus.Chunk file into the structure that is
passed by the search engine to find_soft_selectors | [
"converts",
"a",
"streamcorpus",
".",
"Chunk",
"file",
"into",
"the",
"structure",
"that",
"is",
"passed",
"by",
"the",
"search",
"engine",
"to",
"find_soft_selectors"
] | train | https://github.com/dossier/dossier.models/blob/c9e282f690eab72963926329efe1600709e48b13/dossier/models/soft_selectors.py#L261-L288 |
lambdalisue/maidenhair | src/maidenhair/utils/rglob.py | iglob | def iglob(pathname):
"""
Return an iterator which yields the same values as glob() without actually
storing them all simultaneously.
Parameters
----------
pathname : string
A glob pattern string which will be used for finding files
Returns
-------
iterator
An iterat... | python | def iglob(pathname):
"""
Return an iterator which yields the same values as glob() without actually
storing them all simultaneously.
Parameters
----------
pathname : string
A glob pattern string which will be used for finding files
Returns
-------
iterator
An iterat... | [
"def",
"iglob",
"(",
"pathname",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"pathname",
")",
"basename_pattern",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"pathname",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os... | Return an iterator which yields the same values as glob() without actually
storing them all simultaneously.
Parameters
----------
pathname : string
A glob pattern string which will be used for finding files
Returns
-------
iterator
An iterator instance which will yield full... | [
"Return",
"an",
"iterator",
"which",
"yields",
"the",
"same",
"values",
"as",
"glob",
"()",
"without",
"actually",
"storing",
"them",
"all",
"simultaneously",
"."
] | train | https://github.com/lambdalisue/maidenhair/blob/d5095c1087d1f4d71cc57410492151d2803a9f0d/src/maidenhair/utils/rglob.py#L13-L34 |
sassoo/goldman | goldman/models/login.py | pre_create | def pre_create(sender, model):
""" Callback before creating a new login
Without a password during create we are forced to
set the password to something random & complex.
"""
if isinstance(model, Model) and not model.password:
model.password = random_str() | python | def pre_create(sender, model):
""" Callback before creating a new login
Without a password during create we are forced to
set the password to something random & complex.
"""
if isinstance(model, Model) and not model.password:
model.password = random_str() | [
"def",
"pre_create",
"(",
"sender",
",",
"model",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"Model",
")",
"and",
"not",
"model",
".",
"password",
":",
"model",
".",
"password",
"=",
"random_str",
"(",
")"
] | Callback before creating a new login
Without a password during create we are forced to
set the password to something random & complex. | [
"Callback",
"before",
"creating",
"a",
"new",
"login"
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/models/login.py#L156-L164 |
sassoo/goldman | goldman/models/login.py | pre_save | def pre_save(sender, model):
""" Hash the password if being changed """
if isinstance(model, Model) and 'password' in model.dirty_fields:
model.salt, model.password = gen_salt_and_hash(model.password) | python | def pre_save(sender, model):
""" Hash the password if being changed """
if isinstance(model, Model) and 'password' in model.dirty_fields:
model.salt, model.password = gen_salt_and_hash(model.password) | [
"def",
"pre_save",
"(",
"sender",
",",
"model",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"Model",
")",
"and",
"'password'",
"in",
"model",
".",
"dirty_fields",
":",
"model",
".",
"salt",
",",
"model",
".",
"password",
"=",
"gen_salt_and_hash",
"(... | Hash the password if being changed | [
"Hash",
"the",
"password",
"if",
"being",
"changed"
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/models/login.py#L167-L171 |
sassoo/goldman | goldman/models/login.py | Model.auth_creds | def auth_creds(cls, username, password):
""" Validate a username & password
A token is returned if auth is successful & can be
used to authorize future requests or ignored entirely
if the authorization mechanizm does not need it.
:return: string token
"""
store... | python | def auth_creds(cls, username, password):
""" Validate a username & password
A token is returned if auth is successful & can be
used to authorize future requests or ignored entirely
if the authorization mechanizm does not need it.
:return: string token
"""
store... | [
"def",
"auth_creds",
"(",
"cls",
",",
"username",
",",
"password",
")",
":",
"store",
"=",
"goldman",
".",
"sess",
".",
"store",
"login",
"=",
"store",
".",
"find",
"(",
"cls",
".",
"RTYPE",
",",
"'username'",
",",
"username",
")",
"if",
"not",
"logi... | Validate a username & password
A token is returned if auth is successful & can be
used to authorize future requests or ignored entirely
if the authorization mechanizm does not need it.
:return: string token | [
"Validate",
"a",
"username",
"&",
"password"
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/models/login.py#L65-L91 |
sassoo/goldman | goldman/models/login.py | Model.auth_token | def auth_token(cls, token):
""" Callback method for OAuth 2.0 bearer token middleware """
store = goldman.sess.store
login = store.find(cls.RTYPE, 'token', token)
if not login:
msg = 'No login found with that token. It may have been revoked.'
raise AuthRejected(... | python | def auth_token(cls, token):
""" Callback method for OAuth 2.0 bearer token middleware """
store = goldman.sess.store
login = store.find(cls.RTYPE, 'token', token)
if not login:
msg = 'No login found with that token. It may have been revoked.'
raise AuthRejected(... | [
"def",
"auth_token",
"(",
"cls",
",",
"token",
")",
":",
"store",
"=",
"goldman",
".",
"sess",
".",
"store",
"login",
"=",
"store",
".",
"find",
"(",
"cls",
".",
"RTYPE",
",",
"'token'",
",",
"token",
")",
"if",
"not",
"login",
":",
"msg",
"=",
"... | Callback method for OAuth 2.0 bearer token middleware | [
"Callback",
"method",
"for",
"OAuth",
"2",
".",
"0",
"bearer",
"token",
"middleware"
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/models/login.py#L94-L107 |
sassoo/goldman | goldman/models/login.py | Model.post_authenticate | def post_authenticate(self):
""" Update the login_date timestamp
Initialize the thread local sess.login property with
the authenticated login model.
The login_date update will be debounced so writes don't
occur on every hit of the the API. If the login_date
was modified... | python | def post_authenticate(self):
""" Update the login_date timestamp
Initialize the thread local sess.login property with
the authenticated login model.
The login_date update will be debounced so writes don't
occur on every hit of the the API. If the login_date
was modified... | [
"def",
"post_authenticate",
"(",
"self",
")",
":",
"goldman",
".",
"sess",
".",
"login",
"=",
"self",
"now",
"=",
"dt",
".",
"now",
"(",
")",
"if",
"not",
"self",
".",
"login_date",
":",
"self",
".",
"login_date",
"=",
"now",
"else",
":",
"sec_since_... | Update the login_date timestamp
Initialize the thread local sess.login property with
the authenticated login model.
The login_date update will be debounced so writes don't
occur on every hit of the the API. If the login_date
was modified within 15 minutes then don't update it. | [
"Update",
"the",
"login_date",
"timestamp"
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/models/login.py#L109-L134 |
sassoo/goldman | goldman/models/login.py | Model.validate_username | def validate_username(self, data, value):
""" Ensure the username is unique
If the login is being created then simply check if
the username is in the store & fail.
Otherwise if the login is being updated check if the
existing rid on a username match is the same as the
l... | python | def validate_username(self, data, value):
""" Ensure the username is unique
If the login is being created then simply check if
the username is in the store & fail.
Otherwise if the login is being updated check if the
existing rid on a username match is the same as the
l... | [
"def",
"validate_username",
"(",
"self",
",",
"data",
",",
"value",
")",
":",
"store",
"=",
"goldman",
".",
"sess",
".",
"store",
"existing",
"=",
"store",
".",
"find",
"(",
"data",
"[",
"'rtype'",
"]",
",",
"'username'",
",",
"value",
")",
"if",
"ex... | Ensure the username is unique
If the login is being created then simply check if
the username is in the store & fail.
Otherwise if the login is being updated check if the
existing rid on a username match is the same as the
login being updated otherwise fail. | [
"Ensure",
"the",
"username",
"is",
"unique"
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/models/login.py#L136-L152 |
pip-services3-python/pip-services3-components-python | pip_services3_components/log/LogLevelConverter.py | LogLevelConverter.to_log_level | def to_log_level(value):
"""
Converts numbers and strings to standard log level values.
:param value: a value to be converted
:return: converted log level
"""
if value == None:
return LogLevel.Info
value = str(value).upper()
if ("0" == value... | python | def to_log_level(value):
"""
Converts numbers and strings to standard log level values.
:param value: a value to be converted
:return: converted log level
"""
if value == None:
return LogLevel.Info
value = str(value).upper()
if ("0" == value... | [
"def",
"to_log_level",
"(",
"value",
")",
":",
"if",
"value",
"==",
"None",
":",
"return",
"LogLevel",
".",
"Info",
"value",
"=",
"str",
"(",
"value",
")",
".",
"upper",
"(",
")",
"if",
"(",
"\"0\"",
"==",
"value",
")",
"or",
"(",
"\"NOTHING\"",
"=... | Converts numbers and strings to standard log level values.
:param value: a value to be converted
:return: converted log level | [
"Converts",
"numbers",
"and",
"strings",
"to",
"standard",
"log",
"level",
"values",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/log/LogLevelConverter.py#L19-L46 |
pip-services3-python/pip-services3-components-python | pip_services3_components/log/LogLevelConverter.py | LogLevelConverter.to_string | def to_string(level):
"""
Converts log level to a string.
:param level: a log level to convert
:return: log level name string.
"""
if level == LogLevel.Fatal:
return "FATAL"
if level == LogLevel.Error:
return "ERROR"
if level ==... | python | def to_string(level):
"""
Converts log level to a string.
:param level: a log level to convert
:return: log level name string.
"""
if level == LogLevel.Fatal:
return "FATAL"
if level == LogLevel.Error:
return "ERROR"
if level ==... | [
"def",
"to_string",
"(",
"level",
")",
":",
"if",
"level",
"==",
"LogLevel",
".",
"Fatal",
":",
"return",
"\"FATAL\"",
"if",
"level",
"==",
"LogLevel",
".",
"Error",
":",
"return",
"\"ERROR\"",
"if",
"level",
"==",
"LogLevel",
".",
"Warn",
":",
"return",... | Converts log level to a string.
:param level: a log level to convert
:return: log level name string. | [
"Converts",
"log",
"level",
"to",
"a",
"string",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/log/LogLevelConverter.py#L49-L69 |
stephanepechard/projy | fabfile.py | commit | def commit(message=COMMON_COMMIT_MESSAGE, capture=True):
""" git commit with common commit message when omit. """
env.warn_only = True
local(u'git commit -am"{}"'.format(message)) | python | def commit(message=COMMON_COMMIT_MESSAGE, capture=True):
""" git commit with common commit message when omit. """
env.warn_only = True
local(u'git commit -am"{}"'.format(message)) | [
"def",
"commit",
"(",
"message",
"=",
"COMMON_COMMIT_MESSAGE",
",",
"capture",
"=",
"True",
")",
":",
"env",
".",
"warn_only",
"=",
"True",
"local",
"(",
"u'git commit -am\"{}\"'",
".",
"format",
"(",
"message",
")",
")"
] | git commit with common commit message when omit. | [
"git",
"commit",
"with",
"common",
"commit",
"message",
"when",
"omit",
"."
] | train | https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/fabfile.py#L15-L18 |
collectiveacuity/labPack | labpack/authentication/ssl.py | generate_keystore | def generate_keystore(key_alias, key_folder='./', root_cert='', truststore='', password='', organization='', organization_unit='', locality='', country='', key_size=2048, verbose=True, overwrite=False):
''' a function to generate a keystore and cert files for self-signed ssl authentication '''
title = 'genera... | python | def generate_keystore(key_alias, key_folder='./', root_cert='', truststore='', password='', organization='', organization_unit='', locality='', country='', key_size=2048, verbose=True, overwrite=False):
''' a function to generate a keystore and cert files for self-signed ssl authentication '''
title = 'genera... | [
"def",
"generate_keystore",
"(",
"key_alias",
",",
"key_folder",
"=",
"'./'",
",",
"root_cert",
"=",
"''",
",",
"truststore",
"=",
"''",
",",
"password",
"=",
"''",
",",
"organization",
"=",
"''",
",",
"organization_unit",
"=",
"''",
",",
"locality",
"=",
... | a function to generate a keystore and cert files for self-signed ssl authentication | [
"a",
"function",
"to",
"generate",
"a",
"keystore",
"and",
"cert",
"files",
"for",
"self",
"-",
"signed",
"ssl",
"authentication"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/authentication/ssl.py#L6-L201 |
nefarioustim/parker | parker/store.py | get_filestore_instance | def get_filestore_instance(img_dir=None, data_dir=None):
"""Return an instance of FileStore."""
global _filestore_instances
key = "%s:%s" % (img_dir, data_dir)
try:
instance = _filestore_instances[key]
except KeyError:
instance = FileStore(
img_dir=img_dir, data_dir=dat... | python | def get_filestore_instance(img_dir=None, data_dir=None):
"""Return an instance of FileStore."""
global _filestore_instances
key = "%s:%s" % (img_dir, data_dir)
try:
instance = _filestore_instances[key]
except KeyError:
instance = FileStore(
img_dir=img_dir, data_dir=dat... | [
"def",
"get_filestore_instance",
"(",
"img_dir",
"=",
"None",
",",
"data_dir",
"=",
"None",
")",
":",
"global",
"_filestore_instances",
"key",
"=",
"\"%s:%s\"",
"%",
"(",
"img_dir",
",",
"data_dir",
")",
"try",
":",
"instance",
"=",
"_filestore_instances",
"["... | Return an instance of FileStore. | [
"Return",
"an",
"instance",
"of",
"FileStore",
"."
] | train | https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/store.py#L16-L30 |
nefarioustim/parker | parker/store.py | get_s3store_instance | def get_s3store_instance(bucket):
"""Return an instance of S3Store."""
global _s3store_instances
key = "%s" % bucket
try:
instance = _s3store_instances[key]
except KeyError:
instance = S3Store(
bucket=bucket
)
_s3store_instances[key] = instance
retu... | python | def get_s3store_instance(bucket):
"""Return an instance of S3Store."""
global _s3store_instances
key = "%s" % bucket
try:
instance = _s3store_instances[key]
except KeyError:
instance = S3Store(
bucket=bucket
)
_s3store_instances[key] = instance
retu... | [
"def",
"get_s3store_instance",
"(",
"bucket",
")",
":",
"global",
"_s3store_instances",
"key",
"=",
"\"%s\"",
"%",
"bucket",
"try",
":",
"instance",
"=",
"_s3store_instances",
"[",
"key",
"]",
"except",
"KeyError",
":",
"instance",
"=",
"S3Store",
"(",
"bucket... | Return an instance of S3Store. | [
"Return",
"an",
"instance",
"of",
"S3Store",
"."
] | train | https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/store.py#L33-L47 |
nefarioustim/parker | parker/store.py | FileStore.store_media | def store_media(self, filename, mediafile):
"""Store media files."""
filename = os.path.join(
self.img_dir,
filename
)
fileops.create_dirs(
os.path.dirname(filename)
)
mediafile.fetch_to_file(filename) | python | def store_media(self, filename, mediafile):
"""Store media files."""
filename = os.path.join(
self.img_dir,
filename
)
fileops.create_dirs(
os.path.dirname(filename)
)
mediafile.fetch_to_file(filename) | [
"def",
"store_media",
"(",
"self",
",",
"filename",
",",
"mediafile",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"img_dir",
",",
"filename",
")",
"fileops",
".",
"create_dirs",
"(",
"os",
".",
"path",
".",
"dirname",
... | Store media files. | [
"Store",
"media",
"files",
"."
] | train | https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/store.py#L80-L89 |
nefarioustim/parker | parker/store.py | FileStore.store_json | def store_json(self, filename, dict_to_store):
"""Store json files."""
filename = os.path.join(
self.data_dir,
filename + '.data'
)
fileops.dump_dict_to_file(
dict_to_store,
filename
) | python | def store_json(self, filename, dict_to_store):
"""Store json files."""
filename = os.path.join(
self.data_dir,
filename + '.data'
)
fileops.dump_dict_to_file(
dict_to_store,
filename
) | [
"def",
"store_json",
"(",
"self",
",",
"filename",
",",
"dict_to_store",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_dir",
",",
"filename",
"+",
"'.data'",
")",
"fileops",
".",
"dump_dict_to_file",
"(",
"dict_to_store... | Store json files. | [
"Store",
"json",
"files",
"."
] | train | https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/store.py#L91-L100 |
nefarioustim/parker | parker/store.py | S3Store.store_media | def store_media(self, filename, mediafile):
"""Store media files."""
temp_filename = os.path.join(
'/tmp',
filename
)
fileops.create_dirs(
os.path.dirname(temp_filename)
)
mediafile.fetch_to_file(temp_filename)
s3_key = Key(self... | python | def store_media(self, filename, mediafile):
"""Store media files."""
temp_filename = os.path.join(
'/tmp',
filename
)
fileops.create_dirs(
os.path.dirname(temp_filename)
)
mediafile.fetch_to_file(temp_filename)
s3_key = Key(self... | [
"def",
"store_media",
"(",
"self",
",",
"filename",
",",
"mediafile",
")",
":",
"temp_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'/tmp'",
",",
"filename",
")",
"fileops",
".",
"create_dirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"temp... | Store media files. | [
"Store",
"media",
"files",
"."
] | train | https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/store.py#L112-L135 |
nefarioustim/parker | parker/store.py | S3Store.store_json | def store_json(self, filename, dict_to_store):
"""Store json files."""
epoch = int(time.time() * (10 ** 6))
s3_key = Key(self.bucket)
s3_key.key = os.path.join(
'/data',
"%s_%s.json" % (filename, epoch)
)
s3_key.set_contents_from_string(
... | python | def store_json(self, filename, dict_to_store):
"""Store json files."""
epoch = int(time.time() * (10 ** 6))
s3_key = Key(self.bucket)
s3_key.key = os.path.join(
'/data',
"%s_%s.json" % (filename, epoch)
)
s3_key.set_contents_from_string(
... | [
"def",
"store_json",
"(",
"self",
",",
"filename",
",",
"dict_to_store",
")",
":",
"epoch",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"(",
"10",
"**",
"6",
")",
")",
"s3_key",
"=",
"Key",
"(",
"self",
".",
"bucket",
")",
"s3_key",
".",... | Store json files. | [
"Store",
"json",
"files",
"."
] | train | https://github.com/nefarioustim/parker/blob/ccc1de1ac6bfb5e0a8cfa4fdebb2f38f2ee027d6/parker/store.py#L137-L149 |
collectiveacuity/labPack | labpack/parsing/comparison.py | compare_records | def compare_records(new_record, old_record):
'''
a method to generate the differences between two data architectures
:param new_record: set, list or dictionary with new details of an item
:param old_record: set, list or dictionary with old details of an item
:return: list with dictiona... | python | def compare_records(new_record, old_record):
'''
a method to generate the differences between two data architectures
:param new_record: set, list or dictionary with new details of an item
:param old_record: set, list or dictionary with old details of an item
:return: list with dictiona... | [
"def",
"compare_records",
"(",
"new_record",
",",
"old_record",
")",
":",
"if",
"new_record",
".",
"__class__",
"!=",
"old_record",
".",
"__class__",
":",
"raise",
"TypeError",
"(",
"'Datatype of new and old data must match.'",
")",
"from",
"copy",
"import",
"deepco... | a method to generate the differences between two data architectures
:param new_record: set, list or dictionary with new details of an item
:param old_record: set, list or dictionary with old details of an item
:return: list with dictionary of changes between old and new records
[ {
... | [
"a",
"method",
"to",
"generate",
"the",
"differences",
"between",
"two",
"data",
"architectures",
":",
"param",
"new_record",
":",
"set",
"list",
"or",
"dictionary",
"with",
"new",
"details",
"of",
"an",
"item",
":",
"param",
"old_record",
":",
"set",
"list"... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/parsing/comparison.py#L6-L34 |
collectiveacuity/labPack | labpack/parsing/comparison.py | _compare_dict | def _compare_dict(new_dict, old_dict, change_list=None, root=None):
'''
a method for recursively listing changes made to a dictionary
:param new_dict: dictionary with new key-value pairs
:param old_dict: dictionary with old key-value pairs
:param change_list: list of differences between old an... | python | def _compare_dict(new_dict, old_dict, change_list=None, root=None):
'''
a method for recursively listing changes made to a dictionary
:param new_dict: dictionary with new key-value pairs
:param old_dict: dictionary with old key-value pairs
:param change_list: list of differences between old an... | [
"def",
"_compare_dict",
"(",
"new_dict",
",",
"old_dict",
",",
"change_list",
"=",
"None",
",",
"root",
"=",
"None",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"new_keys",
"=",
"set",
"(",
"new_dict",
".",
"keys",
"(",
")",
")",
"old_keys",
"=",
"... | a method for recursively listing changes made to a dictionary
:param new_dict: dictionary with new key-value pairs
:param old_dict: dictionary with old key-value pairs
:param change_list: list of differences between old and new
:patam root: string with record of path to the root of the main object
... | [
"a",
"method",
"for",
"recursively",
"listing",
"changes",
"made",
"to",
"a",
"dictionary"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/parsing/comparison.py#L36-L78 |
collectiveacuity/labPack | labpack/parsing/comparison.py | _compare_list | def _compare_list(new_list, old_list, change_list=None, root=None):
'''
a method for recursively listing changes made to a list
:param new_list: list with new value
:param old_list: list with old values
:param change_list: list of differences between old and new
:param root: string with re... | python | def _compare_list(new_list, old_list, change_list=None, root=None):
'''
a method for recursively listing changes made to a list
:param new_list: list with new value
:param old_list: list with old values
:param change_list: list of differences between old and new
:param root: string with re... | [
"def",
"_compare_list",
"(",
"new_list",
",",
"old_list",
",",
"change_list",
"=",
"None",
",",
"root",
"=",
"None",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"if",
"len",
"(",
"old_list",
")",
">",
"len",
"(",
"new_list",
")",
":",
"same_len",
"... | a method for recursively listing changes made to a list
:param new_list: list with new value
:param old_list: list with old values
:param change_list: list of differences between old and new
:param root: string with record of path to the root of the main object
:return: list of differences between ... | [
"a",
"method",
"for",
"recursively",
"listing",
"changes",
"made",
"to",
"a",
"list"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/parsing/comparison.py#L80-L121 |
collectiveacuity/labPack | labpack/parsing/comparison.py | _compare_set | def _compare_set(new_set, old_set, change_list, root):
'''
a method for list changes made to a set
:param new_set: set with new values
:param old_set: set with old values
:param change_list: list of differences between old and new
:patam root: string with record of path to the root of the ... | python | def _compare_set(new_set, old_set, change_list, root):
'''
a method for list changes made to a set
:param new_set: set with new values
:param old_set: set with old values
:param change_list: list of differences between old and new
:patam root: string with record of path to the root of the ... | [
"def",
"_compare_set",
"(",
"new_set",
",",
"old_set",
",",
"change_list",
",",
"root",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"path",
"=",
"deepcopy",
"(",
"root",
")",
"missing_items",
"=",
"old_set",
"-",
"new_set",
"extra_items",
"=",
"new_set",... | a method for list changes made to a set
:param new_set: set with new values
:param old_set: set with old values
:param change_list: list of differences between old and new
:patam root: string with record of path to the root of the main object
:return: list of differences between old and new | [
"a",
"method",
"for",
"list",
"changes",
"made",
"to",
"a",
"set"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/parsing/comparison.py#L123-L143 |
dangunter/smoqe | smoqe/query.py | to_mongo | def to_mongo(qry):
"""Transform a simple query with one or more filter expressions
into a MongoDB query expression.
:param qry: Filter expression(s), see function docstring for details.
:type qry: str or list
:return: MongoDB query
:rtype: dict
:raises: BadExpression, if one of the input ex... | python | def to_mongo(qry):
"""Transform a simple query with one or more filter expressions
into a MongoDB query expression.
:param qry: Filter expression(s), see function docstring for details.
:type qry: str or list
:return: MongoDB query
:rtype: dict
:raises: BadExpression, if one of the input ex... | [
"def",
"to_mongo",
"(",
"qry",
")",
":",
"rev",
"=",
"False",
"# filters, not constraints",
"# special case for empty string/list",
"if",
"qry",
"==",
"\"\"",
"or",
"qry",
"==",
"[",
"]",
":",
"return",
"{",
"}",
"# break input into groups of filters",
"unpar",
"=... | Transform a simple query with one or more filter expressions
into a MongoDB query expression.
:param qry: Filter expression(s), see function docstring for details.
:type qry: str or list
:return: MongoDB query
:rtype: dict
:raises: BadExpression, if one of the input expressions cannot be parsed... | [
"Transform",
"a",
"simple",
"query",
"with",
"one",
"or",
"more",
"filter",
"expressions",
"into",
"a",
"MongoDB",
"query",
"expression",
"."
] | train | https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L28-L126 |
dangunter/smoqe | smoqe/query.py | parse_expr | def parse_expr(e):
"""Parse a single constraint expression.
Legal expressions are defined by the regular expression `relation_re`.
:param e: Expression
:type e: str
:return: Tuple of field, operator, and value
:rtype: tuple
"""
m = relation_re.match(e)
if m is None:
raise V... | python | def parse_expr(e):
"""Parse a single constraint expression.
Legal expressions are defined by the regular expression `relation_re`.
:param e: Expression
:type e: str
:return: Tuple of field, operator, and value
:rtype: tuple
"""
m = relation_re.match(e)
if m is None:
raise V... | [
"def",
"parse_expr",
"(",
"e",
")",
":",
"m",
"=",
"relation_re",
".",
"match",
"(",
"e",
")",
"if",
"m",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"error parsing expression '{}'\"",
".",
"format",
"(",
"e",
")",
")",
"field",
",",
"op",
",",
... | Parse a single constraint expression.
Legal expressions are defined by the regular expression `relation_re`.
:param e: Expression
:type e: str
:return: Tuple of field, operator, and value
:rtype: tuple | [
"Parse",
"a",
"single",
"constraint",
"expression",
"."
] | train | https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L144-L177 |
dangunter/smoqe | smoqe/query.py | main | def main():
"""Run an interactive CLI program that
prints the output of running query() on the input string.
"""
import sys, signal
def _exit():
print("Thank you for playing Simple Mongo Query!")
sys.exit(0)
signal.signal(signal.SIGINT, lambda s, f: sys.stdout.write("\n") or _e... | python | def main():
"""Run an interactive CLI program that
prints the output of running query() on the input string.
"""
import sys, signal
def _exit():
print("Thank you for playing Simple Mongo Query!")
sys.exit(0)
signal.signal(signal.SIGINT, lambda s, f: sys.stdout.write("\n") or _e... | [
"def",
"main",
"(",
")",
":",
"import",
"sys",
",",
"signal",
"def",
"_exit",
"(",
")",
":",
"print",
"(",
"\"Thank you for playing Simple Mongo Query!\"",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
","... | Run an interactive CLI program that
prints the output of running query() on the input string. | [
"Run",
"an",
"interactive",
"CLI",
"program",
"that",
"prints",
"the",
"output",
"of",
"running",
"query",
"()",
"on",
"the",
"input",
"string",
"."
] | train | https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L752-L774 |
dangunter/smoqe | smoqe/query.py | ConstraintOperator._set_size_code | def _set_size_code(self):
"""Set the code for a size operation.
"""
if not self._op.startswith(self.SIZE):
self._size_code = None
return
if len(self._op) == len(self.SIZE):
self._size_code = self.SZ_EQ
else:
suffix = self._op[len(s... | python | def _set_size_code(self):
"""Set the code for a size operation.
"""
if not self._op.startswith(self.SIZE):
self._size_code = None
return
if len(self._op) == len(self.SIZE):
self._size_code = self.SZ_EQ
else:
suffix = self._op[len(s... | [
"def",
"_set_size_code",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_op",
".",
"startswith",
"(",
"self",
".",
"SIZE",
")",
":",
"self",
".",
"_size_code",
"=",
"None",
"return",
"if",
"len",
"(",
"self",
".",
"_op",
")",
"==",
"len",
"(",
... | Set the code for a size operation. | [
"Set",
"the",
"code",
"for",
"a",
"size",
"operation",
"."
] | train | https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L302-L315 |
dangunter/smoqe | smoqe/query.py | ConstraintOperator.compare | def compare(self, lhs_value, rhs_value):
"""Compare left- and right-size of: value <op> value.
:param lhs_value: Value to left of operator
:param rhs_value: Value to right of operator
:return: True if the comparison is valid
:rtype: bool
"""
if self.is_eq():
... | python | def compare(self, lhs_value, rhs_value):
"""Compare left- and right-size of: value <op> value.
:param lhs_value: Value to left of operator
:param rhs_value: Value to right of operator
:return: True if the comparison is valid
:rtype: bool
"""
if self.is_eq():
... | [
"def",
"compare",
"(",
"self",
",",
"lhs_value",
",",
"rhs_value",
")",
":",
"if",
"self",
".",
"is_eq",
"(",
")",
":",
"# simple {field:value}",
"return",
"lhs_value",
"is",
"not",
"None",
"and",
"lhs_value",
"==",
"rhs_value",
"if",
"self",
".",
"is_neq"... | Compare left- and right-size of: value <op> value.
:param lhs_value: Value to left of operator
:param rhs_value: Value to right of operator
:return: True if the comparison is valid
:rtype: bool | [
"Compare",
"left",
"-",
"and",
"right",
"-",
"size",
"of",
":",
"value",
"<op",
">",
"value",
"."
] | train | https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L317-L359 |
dangunter/smoqe | smoqe/query.py | Constraint.passes | def passes(self, value):
"""Does the given value pass this constraint?
:return: True,None if so; False,<expected> if not
:rtype: tuple
"""
try:
if self._op.compare(value, self.value):
return True, None
else:
return False, s... | python | def passes(self, value):
"""Does the given value pass this constraint?
:return: True,None if so; False,<expected> if not
:rtype: tuple
"""
try:
if self._op.compare(value, self.value):
return True, None
else:
return False, s... | [
"def",
"passes",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"if",
"self",
".",
"_op",
".",
"compare",
"(",
"value",
",",
"self",
".",
"value",
")",
":",
"return",
"True",
",",
"None",
"else",
":",
"return",
"False",
",",
"self",
".",
"value... | Does the given value pass this constraint?
:return: True,None if so; False,<expected> if not
:rtype: tuple | [
"Does",
"the",
"given",
"value",
"pass",
"this",
"constraint?"
] | train | https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L403-L415 |
dangunter/smoqe | smoqe/query.py | ConstraintGroup.add_constraint | def add_constraint(self, op, val):
"""Add new constraint.
:param op: Constraint operator
:type op: ConstraintOperator
:param val: Constraint value
:type val: str,Number
:raise: ValueError if combination of constraints is illegal
"""
if len(self.constraint... | python | def add_constraint(self, op, val):
"""Add new constraint.
:param op: Constraint operator
:type op: ConstraintOperator
:param val: Constraint value
:type val: str,Number
:raise: ValueError if combination of constraints is illegal
"""
if len(self.constraint... | [
"def",
"add_constraint",
"(",
"self",
",",
"op",
",",
"val",
")",
":",
"if",
"len",
"(",
"self",
".",
"constraints",
")",
">",
"0",
":",
"if",
"op",
".",
"is_equality",
"(",
")",
":",
"clist",
"=",
"', '",
".",
"join",
"(",
"map",
"(",
"str",
"... | Add new constraint.
:param op: Constraint operator
:type op: ConstraintOperator
:param val: Constraint value
:type val: str,Number
:raise: ValueError if combination of constraints is illegal | [
"Add",
"new",
"constraint",
"."
] | train | https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L445-L467 |
dangunter/smoqe | smoqe/query.py | ConstraintGroup.get_conflicts | def get_conflicts(self):
"""Get conflicts in constraints, if any.
:return: Description of each conflict, empty if none.
:rtype: list(str)
"""
conflicts = []
if self._array and self._range:
conflicts.append('cannot use range expressions on arrays')
ret... | python | def get_conflicts(self):
"""Get conflicts in constraints, if any.
:return: Description of each conflict, empty if none.
:rtype: list(str)
"""
conflicts = []
if self._array and self._range:
conflicts.append('cannot use range expressions on arrays')
ret... | [
"def",
"get_conflicts",
"(",
"self",
")",
":",
"conflicts",
"=",
"[",
"]",
"if",
"self",
".",
"_array",
"and",
"self",
".",
"_range",
":",
"conflicts",
".",
"append",
"(",
"'cannot use range expressions on arrays'",
")",
"return",
"conflicts"
] | Get conflicts in constraints, if any.
:return: Description of each conflict, empty if none.
:rtype: list(str) | [
"Get",
"conflicts",
"in",
"constraints",
"if",
"any",
"."
] | train | https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L472-L481 |
dangunter/smoqe | smoqe/query.py | ConstraintGroup.add_existence | def add_existence(self, rev):
"""Add existence constraint for the field.
This is necessary because the normal meaning of 'x > 0' is: x > 0 and is present.
Without the existence constraint, MongoDB will treat 'x > 0' as: 'x' > 0 *or* is absent.
Of course, if the constraint is already abo... | python | def add_existence(self, rev):
"""Add existence constraint for the field.
This is necessary because the normal meaning of 'x > 0' is: x > 0 and is present.
Without the existence constraint, MongoDB will treat 'x > 0' as: 'x' > 0 *or* is absent.
Of course, if the constraint is already abo... | [
"def",
"add_existence",
"(",
"self",
",",
"rev",
")",
":",
"if",
"len",
"(",
"self",
".",
"constraints",
")",
"==",
"1",
"and",
"(",
"# both 'exists' and strict equality don't require the extra clause",
"self",
".",
"constraints",
"[",
"0",
"]",
".",
"op",
"."... | Add existence constraint for the field.
This is necessary because the normal meaning of 'x > 0' is: x > 0 and is present.
Without the existence constraint, MongoDB will treat 'x > 0' as: 'x' > 0 *or* is absent.
Of course, if the constraint is already about existence, nothing is done.
:... | [
"Add",
"existence",
"constraint",
"for",
"the",
"field",
"."
] | train | https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L483-L499 |
dangunter/smoqe | smoqe/query.py | MongoClause._create | def _create(self, constraint, exists_main):
"""Create MongoDB query clause for a constraint.
:param constraint: The constraint
:type constraint: Constraint
:param exists_main: Put exists into main clause
:type exists_main: bool
:return: New clause
:rtype: MongoCl... | python | def _create(self, constraint, exists_main):
"""Create MongoDB query clause for a constraint.
:param constraint: The constraint
:type constraint: Constraint
:param exists_main: Put exists into main clause
:type exists_main: bool
:return: New clause
:rtype: MongoCl... | [
"def",
"_create",
"(",
"self",
",",
"constraint",
",",
"exists_main",
")",
":",
"c",
"=",
"constraint",
"# alias",
"op",
"=",
"self",
".",
"_reverse_operator",
"(",
"c",
".",
"op",
")",
"if",
"self",
".",
"_rev",
"else",
"c",
".",
"op",
"mop",
"=",
... | Create MongoDB query clause for a constraint.
:param constraint: The constraint
:type constraint: Constraint
:param exists_main: Put exists into main clause
:type exists_main: bool
:return: New clause
:rtype: MongoClause
:raise: ValueError if value doesn't make s... | [
"Create",
"MongoDB",
"query",
"clause",
"for",
"a",
"constraint",
"."
] | train | https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L578-L635 |
dangunter/smoqe | smoqe/query.py | MongoClause._reverse_operator | def _reverse_operator(self, op):
"""Reverse the operation e.g. since the conditions
you provide are assertions of how things should be,
e.g. asserting (a > b) leads to a search for (a <= b)
:param op: Operator for any field/value
:type op: ConstraintOperator
"""
... | python | def _reverse_operator(self, op):
"""Reverse the operation e.g. since the conditions
you provide are assertions of how things should be,
e.g. asserting (a > b) leads to a search for (a <= b)
:param op: Operator for any field/value
:type op: ConstraintOperator
"""
... | [
"def",
"_reverse_operator",
"(",
"self",
",",
"op",
")",
":",
"op",
"=",
"copy",
".",
"copy",
"(",
"op",
")",
"op",
".",
"reverse",
"(",
")",
"# check that we can map it",
"if",
"not",
"str",
"(",
"op",
")",
"in",
"self",
".",
"MONGO_OPS",
":",
"rais... | Reverse the operation e.g. since the conditions
you provide are assertions of how things should be,
e.g. asserting (a > b) leads to a search for (a <= b)
:param op: Operator for any field/value
:type op: ConstraintOperator | [
"Reverse",
"the",
"operation",
"e",
".",
"g",
".",
"since",
"the",
"conditions",
"you",
"provide",
"are",
"assertions",
"of",
"how",
"things",
"should",
"be",
"e",
".",
"g",
".",
"asserting",
"(",
"a",
">",
"b",
")",
"leads",
"to",
"a",
"search",
"fo... | train | https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L645-L658 |
dangunter/smoqe | smoqe/query.py | MongoQuery.add_clause | def add_clause(self, clause):
"""Add a new clause to the existing query.
:param clause: The clause to add
:type clause: MongoClause
:return: None
"""
if clause.query_loc == MongoClause.LOC_MAIN:
self._main.append(clause)
elif clause.query_loc == Mongo... | python | def add_clause(self, clause):
"""Add a new clause to the existing query.
:param clause: The clause to add
:type clause: MongoClause
:return: None
"""
if clause.query_loc == MongoClause.LOC_MAIN:
self._main.append(clause)
elif clause.query_loc == Mongo... | [
"def",
"add_clause",
"(",
"self",
",",
"clause",
")",
":",
"if",
"clause",
".",
"query_loc",
"==",
"MongoClause",
".",
"LOC_MAIN",
":",
"self",
".",
"_main",
".",
"append",
"(",
"clause",
")",
"elif",
"clause",
".",
"query_loc",
"==",
"MongoClause",
".",... | Add a new clause to the existing query.
:param clause: The clause to add
:type clause: MongoClause
:return: None | [
"Add",
"a",
"new",
"clause",
"to",
"the",
"existing",
"query",
"."
] | train | https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L684-L698 |
dangunter/smoqe | smoqe/query.py | MongoQuery.to_mongo | def to_mongo(self, disjunction=True):
"""Create from current state a valid MongoDB query expression.
:return: MongoDB query expression
:rtype: dict
"""
q = {}
# add all the main clauses to `q`
clauses = [e.expr for e in self._main]
if clauses:
... | python | def to_mongo(self, disjunction=True):
"""Create from current state a valid MongoDB query expression.
:return: MongoDB query expression
:rtype: dict
"""
q = {}
# add all the main clauses to `q`
clauses = [e.expr for e in self._main]
if clauses:
... | [
"def",
"to_mongo",
"(",
"self",
",",
"disjunction",
"=",
"True",
")",
":",
"q",
"=",
"{",
"}",
"# add all the main clauses to `q`",
"clauses",
"=",
"[",
"e",
".",
"expr",
"for",
"e",
"in",
"self",
".",
"_main",
"]",
"if",
"clauses",
":",
"if",
"disjunc... | Create from current state a valid MongoDB query expression.
:return: MongoDB query expression
:rtype: dict | [
"Create",
"from",
"current",
"state",
"a",
"valid",
"MongoDB",
"query",
"expression",
"."
] | train | https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L700-L737 |
maxfischer2781/chainlet | chainlet/concurrency/thread.py | convert | def convert(element):
"""
Convert a regular :term:`chainlink` to a thread based version
:param element: the chainlink to convert
:return: a threaded version of ``element`` if possible, or the element itself
"""
element = linker.LinkPrimitives().convert(element)
if isinstance(element, link.C... | python | def convert(element):
"""
Convert a regular :term:`chainlink` to a thread based version
:param element: the chainlink to convert
:return: a threaded version of ``element`` if possible, or the element itself
"""
element = linker.LinkPrimitives().convert(element)
if isinstance(element, link.C... | [
"def",
"convert",
"(",
"element",
")",
":",
"element",
"=",
"linker",
".",
"LinkPrimitives",
"(",
")",
".",
"convert",
"(",
"element",
")",
"if",
"isinstance",
"(",
"element",
",",
"link",
".",
"ChainLink",
".",
"chain_types",
".",
"base_bundle_type",
")",... | Convert a regular :term:`chainlink` to a thread based version
:param element: the chainlink to convert
:return: a threaded version of ``element`` if possible, or the element itself | [
"Convert",
"a",
"regular",
":",
"term",
":",
"chainlink",
"to",
"a",
"thread",
"based",
"version"
] | train | https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/concurrency/thread.py#L139-L151 |
maxfischer2781/chainlet | chainlet/concurrency/thread.py | ThreadPoolExecutor.submit | def submit(self, call, *args, **kwargs):
"""
Submit a call for future execution
:return: future for the call execution
:rtype: StoredFuture
"""
future = StoredFuture(call, *args, **kwargs)
self._queue.put(future)
self._ensure_worker()
return futur... | python | def submit(self, call, *args, **kwargs):
"""
Submit a call for future execution
:return: future for the call execution
:rtype: StoredFuture
"""
future = StoredFuture(call, *args, **kwargs)
self._queue.put(future)
self._ensure_worker()
return futur... | [
"def",
"submit",
"(",
"self",
",",
"call",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"future",
"=",
"StoredFuture",
"(",
"call",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_queue",
".",
"put",
"(",
"future",
")",
"... | Submit a call for future execution
:return: future for the call execution
:rtype: StoredFuture | [
"Submit",
"a",
"call",
"for",
"future",
"execution"
] | train | https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/concurrency/thread.py#L61-L71 |
maxfischer2781/chainlet | chainlet/concurrency/thread.py | ThreadPoolExecutor._dismiss_worker | def _dismiss_worker(self, worker):
"""Dismiss ``worker`` unless it is still required"""
self._workers.remove(worker)
if len(self._workers) < self._min_workers:
self._workers.add(worker)
return False
return True | python | def _dismiss_worker(self, worker):
"""Dismiss ``worker`` unless it is still required"""
self._workers.remove(worker)
if len(self._workers) < self._min_workers:
self._workers.add(worker)
return False
return True | [
"def",
"_dismiss_worker",
"(",
"self",
",",
"worker",
")",
":",
"self",
".",
"_workers",
".",
"remove",
"(",
"worker",
")",
"if",
"len",
"(",
"self",
".",
"_workers",
")",
"<",
"self",
".",
"_min_workers",
":",
"self",
".",
"_workers",
".",
"add",
"(... | Dismiss ``worker`` unless it is still required | [
"Dismiss",
"worker",
"unless",
"it",
"is",
"still",
"required"
] | train | https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/concurrency/thread.py#L89-L95 |
maxfischer2781/chainlet | chainlet/concurrency/thread.py | ThreadPoolExecutor._ensure_worker | def _ensure_worker(self):
"""Ensure there are enough workers available"""
while len(self._workers) < self._min_workers or len(self._workers) < self._queue.qsize() < self._max_workers:
worker = threading.Thread(
target=self._execute_futures,
name=self.identifie... | python | def _ensure_worker(self):
"""Ensure there are enough workers available"""
while len(self._workers) < self._min_workers or len(self._workers) < self._queue.qsize() < self._max_workers:
worker = threading.Thread(
target=self._execute_futures,
name=self.identifie... | [
"def",
"_ensure_worker",
"(",
"self",
")",
":",
"while",
"len",
"(",
"self",
".",
"_workers",
")",
"<",
"self",
".",
"_min_workers",
"or",
"len",
"(",
"self",
".",
"_workers",
")",
"<",
"self",
".",
"_queue",
".",
"qsize",
"(",
")",
"<",
"self",
".... | Ensure there are enough workers available | [
"Ensure",
"there",
"are",
"enough",
"workers",
"available"
] | train | https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/concurrency/thread.py#L97-L106 |
sassoo/goldman | goldman/utils/s3_helpers.py | s3_upload | def s3_upload(acl, bucket, conn, content, content_type, path):
""" Store an object in our an S3 bucket.
:param acl:
S3 ACL for the object
:param bucket:
S3 bucket to upload to
:param content:
a string representation of the object to upload
:param content_type:
a stri... | python | def s3_upload(acl, bucket, conn, content, content_type, path):
""" Store an object in our an S3 bucket.
:param acl:
S3 ACL for the object
:param bucket:
S3 bucket to upload to
:param content:
a string representation of the object to upload
:param content_type:
a stri... | [
"def",
"s3_upload",
"(",
"acl",
",",
"bucket",
",",
"conn",
",",
"content",
",",
"content_type",
",",
"path",
")",
":",
"# obj is the object that will be uploaded",
"obj",
"=",
"Key",
"(",
"conn",
".",
"get_bucket",
"(",
"bucket",
")",
")",
"obj",
".",
"co... | Store an object in our an S3 bucket.
:param acl:
S3 ACL for the object
:param bucket:
S3 bucket to upload to
:param content:
a string representation of the object to upload
:param content_type:
a string MIMETYPE of the object that S3 should
be informed of
:pa... | [
"Store",
"an",
"object",
"in",
"our",
"an",
"S3",
"bucket",
"."
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/s3_helpers.py#L39-L70 |
RonenNess/Fileter | fileter/filters/extension_filter.py | FilterExtension.match | def match(self, filepath):
"""
The function to check file.
Should return True if match, False otherwise.
"""
# no extension?
if filepath.find(".") == -1:
return False
# match extension
return filepath.lower().split(".")[-1] in self.__extension... | python | def match(self, filepath):
"""
The function to check file.
Should return True if match, False otherwise.
"""
# no extension?
if filepath.find(".") == -1:
return False
# match extension
return filepath.lower().split(".")[-1] in self.__extension... | [
"def",
"match",
"(",
"self",
",",
"filepath",
")",
":",
"# no extension?",
"if",
"filepath",
".",
"find",
"(",
"\".\"",
")",
"==",
"-",
"1",
":",
"return",
"False",
"# match extension",
"return",
"filepath",
".",
"lower",
"(",
")",
".",
"split",
"(",
"... | The function to check file.
Should return True if match, False otherwise. | [
"The",
"function",
"to",
"check",
"file",
".",
"Should",
"return",
"True",
"if",
"match",
"False",
"otherwise",
"."
] | train | https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/filters/extension_filter.py#L24-L34 |
collectiveacuity/labPack | labpack/activity/moves.py | movesClient._process_dates | def _process_dates(self, timezone_offset, first_date, start, end, title, track_points=False):
''' a helper method to process datetime information for other requests
:param timezone_offset: integer with timezone offset from user profile details
:param first_date: string with ISO date from ... | python | def _process_dates(self, timezone_offset, first_date, start, end, title, track_points=False):
''' a helper method to process datetime information for other requests
:param timezone_offset: integer with timezone offset from user profile details
:param first_date: string with ISO date from ... | [
"def",
"_process_dates",
"(",
"self",
",",
"timezone_offset",
",",
"first_date",
",",
"start",
",",
"end",
",",
"title",
",",
"track_points",
"=",
"False",
")",
":",
"# validate inputs\r",
"input_fields",
"=",
"{",
"'timezone_offset'",
":",
"timezone_offset",
",... | a helper method to process datetime information for other requests
:param timezone_offset: integer with timezone offset from user profile details
:param first_date: string with ISO date from user profile details firstDate
:param start: float with starting datetime for daily summaries
... | [
"a",
"helper",
"method",
"to",
"process",
"datetime",
"information",
"for",
"other",
"requests",
":",
"param",
"timezone_offset",
":",
"integer",
"with",
"timezone",
"offset",
"from",
"user",
"profile",
"details",
":",
"param",
"first_date",
":",
"string",
"with... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/activity/moves.py#L158-L224 |
collectiveacuity/labPack | labpack/activity/moves.py | movesClient.list_activities | def list_activities(self):
''' a method to retrieve the details for all activities currently supported
:return: dictionary of response details with activities list inside json key
{
'headers': { ... },
'code': 200,
'error': '',
'url':... | python | def list_activities(self):
''' a method to retrieve the details for all activities currently supported
:return: dictionary of response details with activities list inside json key
{
'headers': { ... },
'code': 200,
'error': '',
'url':... | [
"def",
"list_activities",
"(",
"self",
")",
":",
"title",
"=",
"'%s.list_activities'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# construct request parameters\r",
"url_string",
"=",
"'%s/activities'",
"%",
"self",
".",
"endpoint",
"# send request\r",
"response... | a method to retrieve the details for all activities currently supported
:return: dictionary of response details with activities list inside json key
{
'headers': { ... },
'code': 200,
'error': '',
'url': 'https://api.moves-app.com/api/1.1/activi... | [
"a",
"method",
"to",
"retrieve",
"the",
"details",
"for",
"all",
"activities",
"currently",
"supported",
":",
"return",
":",
"dictionary",
"of",
"response",
"details",
"with",
"activities",
"list",
"inside",
"json",
"key",
"{",
"headers",
":",
"{",
"...",
"}... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/activity/moves.py#L226-L258 |
collectiveacuity/labPack | labpack/activity/moves.py | movesClient.get_summary | def get_summary(self, timezone_offset, first_date, start=0.0, end=0.0):
''' a method to retrieve summary details for a period of time
NOTE: start and end must be no more than 30 days, 1 second apart
:param timezone_offset: integer with timezone offset from user profile details
... | python | def get_summary(self, timezone_offset, first_date, start=0.0, end=0.0):
''' a method to retrieve summary details for a period of time
NOTE: start and end must be no more than 30 days, 1 second apart
:param timezone_offset: integer with timezone offset from user profile details
... | [
"def",
"get_summary",
"(",
"self",
",",
"timezone_offset",
",",
"first_date",
",",
"start",
"=",
"0.0",
",",
"end",
"=",
"0.0",
")",
":",
"title",
"=",
"'%s.get_summary'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate scope\r",
"if",
"'activity... | a method to retrieve summary details for a period of time
NOTE: start and end must be no more than 30 days, 1 second apart
:param timezone_offset: integer with timezone offset from user profile details
:param first_date: string with ISO date from user profile details firstDate
:p... | [
"a",
"method",
"to",
"retrieve",
"summary",
"details",
"for",
"a",
"period",
"of",
"time",
"NOTE",
":",
"start",
"and",
"end",
"must",
"be",
"no",
"more",
"than",
"30",
"days",
"1",
"second",
"apart",
":",
"param",
"timezone_offset",
":",
"integer",
"wit... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/activity/moves.py#L302-L336 |
collectiveacuity/labPack | labpack/activity/moves.py | movesClient.get_storyline | def get_storyline(self, timezone_offset, first_date, start=0.0, end=0.0, track_points=False):
''' a method to retrieve storyline details for a period of time
NOTE: start and end must be no more than 30 days, 1 second apart
NOTE: if track_points=True, start and end must be no more than 6... | python | def get_storyline(self, timezone_offset, first_date, start=0.0, end=0.0, track_points=False):
''' a method to retrieve storyline details for a period of time
NOTE: start and end must be no more than 30 days, 1 second apart
NOTE: if track_points=True, start and end must be no more than 6... | [
"def",
"get_storyline",
"(",
"self",
",",
"timezone_offset",
",",
"first_date",
",",
"start",
"=",
"0.0",
",",
"end",
"=",
"0.0",
",",
"track_points",
"=",
"False",
")",
":",
"title",
"=",
"'%s.get_storyline'",
"%",
"self",
".",
"__class__",
".",
"__name__... | a method to retrieve storyline details for a period of time
NOTE: start and end must be no more than 30 days, 1 second apart
NOTE: if track_points=True, start and end must be no more than 6 days, 1 second apart
:param timezone_offset: integer with timezone offset from user profile detai... | [
"a",
"method",
"to",
"retrieve",
"storyline",
"details",
"for",
"a",
"period",
"of",
"time",
"NOTE",
":",
"start",
"and",
"end",
"must",
"be",
"no",
"more",
"than",
"30",
"days",
"1",
"second",
"apart",
"NOTE",
":",
"if",
"track_points",
"=",
"True",
"... | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/activity/moves.py#L410-L449 |
MinchinWeb/colourettu | colourettu/_palette.py | Palette.from_list | def from_list(self, list_of_colours, normalized_rgb=False):
"""
Given an interable (usually a list or a tuple) containing
:py:class:`Colour` s,
this then becomes the Colours contained by the Palette.
Args:
list_of_colours(list, tuple, or other interable): a collectio... | python | def from_list(self, list_of_colours, normalized_rgb=False):
"""
Given an interable (usually a list or a tuple) containing
:py:class:`Colour` s,
this then becomes the Colours contained by the Palette.
Args:
list_of_colours(list, tuple, or other interable): a collectio... | [
"def",
"from_list",
"(",
"self",
",",
"list_of_colours",
",",
"normalized_rgb",
"=",
"False",
")",
":",
"colour_for_type",
"=",
"Colour",
"(",
")",
"self",
".",
"_colours",
"=",
"[",
"]",
"for",
"c",
"in",
"list_of_colours",
":",
"if",
"type",
"(",
"c",
... | Given an interable (usually a list or a tuple) containing
:py:class:`Colour` s,
this then becomes the Colours contained by the Palette.
Args:
list_of_colours(list, tuple, or other interable): a collection of
:py:class:`Colour` s to be loaded into the palette. If thes... | [
"Given",
"an",
"interable",
"(",
"usually",
"a",
"list",
"or",
"a",
"tuple",
")",
"containing",
":",
"py",
":",
"class",
":",
"Colour",
"s",
"this",
"then",
"becomes",
"the",
"Colours",
"contained",
"by",
"the",
"Palette",
"."
] | train | https://github.com/MinchinWeb/colourettu/blob/f0b2f6b1d44055f3ccee62ac2759829f1e16a252/colourettu/_palette.py#L129-L161 |
MinchinWeb/colourettu | colourettu/_palette.py | Palette.to_image | def to_image(self, filename='palette.png', band_width=1, length=60,
max_width=0, vertical=True, alpha_channel=False):
"""
Creates an image from the palette.
Args:
filename(Optional[string]): filename of saved file. Defaults to
``palette.png`` in the ... | python | def to_image(self, filename='palette.png', band_width=1, length=60,
max_width=0, vertical=True, alpha_channel=False):
"""
Creates an image from the palette.
Args:
filename(Optional[string]): filename of saved file. Defaults to
``palette.png`` in the ... | [
"def",
"to_image",
"(",
"self",
",",
"filename",
"=",
"'palette.png'",
",",
"band_width",
"=",
"1",
",",
"length",
"=",
"60",
",",
"max_width",
"=",
"0",
",",
"vertical",
"=",
"True",
",",
"alpha_channel",
"=",
"False",
")",
":",
"# max_width is approximat... | Creates an image from the palette.
Args:
filename(Optional[string]): filename of saved file. Defaults to
``palette.png`` in the current working directory.
band_width(optional[int]): how wide each colour band should be.
Defaults to 1 pixel.
len... | [
"Creates",
"an",
"image",
"from",
"the",
"palette",
"."
] | train | https://github.com/MinchinWeb/colourettu/blob/f0b2f6b1d44055f3ccee62ac2759829f1e16a252/colourettu/_palette.py#L163-L209 |
MinchinWeb/colourettu | colourettu/_palette.py | Palette.blend | def blend(self, cycles=1):
"""
Explands the existing Palette by inserting the blending colour
between all Colours already in the Palette.
Changes the Palette in-place.
args:
cycles(int): number of *blend* cycles to apply. (Default is 1)
Example usage:
... | python | def blend(self, cycles=1):
"""
Explands the existing Palette by inserting the blending colour
between all Colours already in the Palette.
Changes the Palette in-place.
args:
cycles(int): number of *blend* cycles to apply. (Default is 1)
Example usage:
... | [
"def",
"blend",
"(",
"self",
",",
"cycles",
"=",
"1",
")",
":",
"for",
"j",
"in",
"range",
"(",
"int",
"(",
"cycles",
")",
")",
":",
"new_colours",
"=",
"[",
"]",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"self",
".",
"_colours",
")",
":",
... | Explands the existing Palette by inserting the blending colour
between all Colours already in the Palette.
Changes the Palette in-place.
args:
cycles(int): number of *blend* cycles to apply. (Default is 1)
Example usage:
.. code-block:: python
p1.blen... | [
"Explands",
"the",
"existing",
"Palette",
"by",
"inserting",
"the",
"blending",
"colour",
"between",
"all",
"Colours",
"already",
"in",
"the",
"Palette",
"."
] | train | https://github.com/MinchinWeb/colourettu/blob/f0b2f6b1d44055f3ccee62ac2759829f1e16a252/colourettu/_palette.py#L211-L260 |
collectiveacuity/labPack | utils.py | inject_init | def inject_init(init_path, readme_path, setup_kwargs):
'''
a method to add arguments to setup.py from module init file
:param init_path: string with path to module __init__ file
:param readme_path: string with path to module README.rst file
:param setup_kwargs: dictionary with existing setup ke... | python | def inject_init(init_path, readme_path, setup_kwargs):
'''
a method to add arguments to setup.py from module init file
:param init_path: string with path to module __init__ file
:param readme_path: string with path to module README.rst file
:param setup_kwargs: dictionary with existing setup ke... | [
"def",
"inject_init",
"(",
"init_path",
",",
"readme_path",
",",
"setup_kwargs",
")",
":",
"import",
"re",
"from",
"os",
"import",
"path",
"from",
"copy",
"import",
"deepcopy",
"# retrieve init text",
"init_text",
"=",
"''",
"if",
"not",
"path",
".",
"exists",... | a method to add arguments to setup.py from module init file
:param init_path: string with path to module __init__ file
:param readme_path: string with path to module README.rst file
:param setup_kwargs: dictionary with existing setup keyword arguments
:return: dictionary with injected keyword arguments | [
"a",
"method",
"to",
"add",
"arguments",
"to",
"setup",
".",
"py",
"from",
"module",
"init",
"file"
] | train | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/utils.py#L6-L79 |
magland/vdomr | vdomr/helpers.py | _create_component | def _create_component(tag_name, allow_children=True, callbacks=[]):
"""
Create a component for an HTML Tag
Examples:
>>> marquee = _create_component('marquee')
>>> marquee('woohoo')
<marquee>woohoo</marquee>
"""
def _component(*children, **kwargs):
if 'children' in kw... | python | def _create_component(tag_name, allow_children=True, callbacks=[]):
"""
Create a component for an HTML Tag
Examples:
>>> marquee = _create_component('marquee')
>>> marquee('woohoo')
<marquee>woohoo</marquee>
"""
def _component(*children, **kwargs):
if 'children' in kw... | [
"def",
"_create_component",
"(",
"tag_name",
",",
"allow_children",
"=",
"True",
",",
"callbacks",
"=",
"[",
"]",
")",
":",
"def",
"_component",
"(",
"*",
"children",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'children'",
"in",
"kwargs",
":",
"children",... | Create a component for an HTML Tag
Examples:
>>> marquee = _create_component('marquee')
>>> marquee('woohoo')
<marquee>woohoo</marquee> | [
"Create",
"a",
"component",
"for",
"an",
"HTML",
"Tag",
"Examples",
":",
">>>",
"marquee",
"=",
"_create_component",
"(",
"marquee",
")",
">>>",
"marquee",
"(",
"woohoo",
")",
"<marquee",
">",
"woohoo<",
"/",
"marquee",
">"
] | train | https://github.com/magland/vdomr/blob/89f62611689a596ca49d9e080f3a7e9cf58b71b6/vdomr/helpers.py#L6-L60 |
RazerM/bucketcache | shovel/version.py | bump | def bump(dev=False, patch=False, minor=False, major=False, nocommit=False):
"""Bump version number and commit change."""
if sum([int(x) for x in (patch, minor, major)]) > 1:
raise ValueError('Only one of patch, minor, major can be incremented.')
if check_staged():
raise EnvironmentError('Th... | python | def bump(dev=False, patch=False, minor=False, major=False, nocommit=False):
"""Bump version number and commit change."""
if sum([int(x) for x in (patch, minor, major)]) > 1:
raise ValueError('Only one of patch, minor, major can be incremented.')
if check_staged():
raise EnvironmentError('Th... | [
"def",
"bump",
"(",
"dev",
"=",
"False",
",",
"patch",
"=",
"False",
",",
"minor",
"=",
"False",
",",
"major",
"=",
"False",
",",
"nocommit",
"=",
"False",
")",
":",
"if",
"sum",
"(",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"(",
"patch",
... | Bump version number and commit change. | [
"Bump",
"version",
"number",
"and",
"commit",
"change",
"."
] | train | https://github.com/RazerM/bucketcache/blob/8d9b163b73da8c498793cce2f22f6a7cbe524d94/shovel/version.py#L19-L71 |
RazerM/bucketcache | shovel/version.py | tag | def tag():
"""Tag current version."""
if check_unstaged():
raise EnvironmentError('There are staged changes, abort.')
with open(str(INIT_PATH)) as f:
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", f.read()))
version = metadata['version']
check_output(['git', 'tag', version, '... | python | def tag():
"""Tag current version."""
if check_unstaged():
raise EnvironmentError('There are staged changes, abort.')
with open(str(INIT_PATH)) as f:
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", f.read()))
version = metadata['version']
check_output(['git', 'tag', version, '... | [
"def",
"tag",
"(",
")",
":",
"if",
"check_unstaged",
"(",
")",
":",
"raise",
"EnvironmentError",
"(",
"'There are staged changes, abort.'",
")",
"with",
"open",
"(",
"str",
"(",
"INIT_PATH",
")",
")",
"as",
"f",
":",
"metadata",
"=",
"dict",
"(",
"re",
"... | Tag current version. | [
"Tag",
"current",
"version",
"."
] | train | https://github.com/RazerM/bucketcache/blob/8d9b163b73da8c498793cce2f22f6a7cbe524d94/shovel/version.py#L75-L82 |
RazerM/bucketcache | shovel/version.py | upload | def upload():
"""Upload source to PyPI using twine."""
try:
o = check_output(['twine', 'upload'] + glob('dist/*'))
except CalledProcessError:
call(['twine', 'upload'] + glob('dist/*'))
raise
print(o.decode('utf-8')) | python | def upload():
"""Upload source to PyPI using twine."""
try:
o = check_output(['twine', 'upload'] + glob('dist/*'))
except CalledProcessError:
call(['twine', 'upload'] + glob('dist/*'))
raise
print(o.decode('utf-8')) | [
"def",
"upload",
"(",
")",
":",
"try",
":",
"o",
"=",
"check_output",
"(",
"[",
"'twine'",
",",
"'upload'",
"]",
"+",
"glob",
"(",
"'dist/*'",
")",
")",
"except",
"CalledProcessError",
":",
"call",
"(",
"[",
"'twine'",
",",
"'upload'",
"]",
"+",
"glo... | Upload source to PyPI using twine. | [
"Upload",
"source",
"to",
"PyPI",
"using",
"twine",
"."
] | train | https://github.com/RazerM/bucketcache/blob/8d9b163b73da8c498793cce2f22f6a7cbe524d94/shovel/version.py#L94-L101 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.