repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
jf-parent/brome | brome/core/selector.py | Selector.resolve_selector_type | def resolve_selector_type(self):
"""Resolve the selector type
This make sure that all the selectors
provided are of the same type (in case of a list of selector)
"""
resolved_selector_type_list = []
for current_selector in self._effective_selector_list:
resol... | python | def resolve_selector_type(self):
"""Resolve the selector type
This make sure that all the selectors
provided are of the same type (in case of a list of selector)
"""
resolved_selector_type_list = []
for current_selector in self._effective_selector_list:
resol... | [
"def",
"resolve_selector_type",
"(",
"self",
")",
":",
"resolved_selector_type_list",
"=",
"[",
"]",
"for",
"current_selector",
"in",
"self",
".",
"_effective_selector_list",
":",
"resolved_selector_type_list",
".",
"append",
"(",
"self",
".",
"get_type",
"(",
"curr... | Resolve the selector type
This make sure that all the selectors
provided are of the same type (in case of a list of selector) | [
"Resolve",
"the",
"selector",
"type"
] | train | https://github.com/jf-parent/brome/blob/784f45d96b83b703dd2181cb59ca8ea777c2510e/brome/core/selector.py#L176-L195 |
jf-parent/brome | brome/core/selector.py | Selector.resolve_function | def resolve_function(self):
"""Resolve the selenium function that will be use to find the element
"""
selector_type = self._effective_selector_type
# NAME
if selector_type == 'name':
return ('find_elements_by_name', 'NAME')
# XPATH
elif selector_type... | python | def resolve_function(self):
"""Resolve the selenium function that will be use to find the element
"""
selector_type = self._effective_selector_type
# NAME
if selector_type == 'name':
return ('find_elements_by_name', 'NAME')
# XPATH
elif selector_type... | [
"def",
"resolve_function",
"(",
"self",
")",
":",
"selector_type",
"=",
"self",
".",
"_effective_selector_type",
"# NAME",
"if",
"selector_type",
"==",
"'name'",
":",
"return",
"(",
"'find_elements_by_name'",
",",
"'NAME'",
")",
"# XPATH",
"elif",
"selector_type",
... | Resolve the selenium function that will be use to find the element | [
"Resolve",
"the",
"selenium",
"function",
"that",
"will",
"be",
"use",
"to",
"find",
"the",
"element"
] | train | https://github.com/jf-parent/brome/blob/784f45d96b83b703dd2181cb59ca8ea777c2510e/brome/core/selector.py#L197-L232 |
thelabnyc/python-versiontag | versiontag/__init__.py | __get_git_tag | def __get_git_tag():
"""
Read the Git project version by running ``git describe --tags`` in the current-working-directory.
:return: Project version string
"""
with open(os.devnull, 'wb') as devnull:
version = subprocess.check_output(['git', 'describe', '--tags'], stderr=devnull)
ver... | python | def __get_git_tag():
"""
Read the Git project version by running ``git describe --tags`` in the current-working-directory.
:return: Project version string
"""
with open(os.devnull, 'wb') as devnull:
version = subprocess.check_output(['git', 'describe', '--tags'], stderr=devnull)
ver... | [
"def",
"__get_git_tag",
"(",
")",
":",
"with",
"open",
"(",
"os",
".",
"devnull",
",",
"'wb'",
")",
"as",
"devnull",
":",
"version",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'git'",
",",
"'describe'",
",",
"'--tags'",
"]",
",",
"stderr",
"=",... | Read the Git project version by running ``git describe --tags`` in the current-working-directory.
:return: Project version string | [
"Read",
"the",
"Git",
"project",
"version",
"by",
"running",
"git",
"describe",
"--",
"tags",
"in",
"the",
"current",
"-",
"working",
"-",
"directory",
"."
] | train | https://github.com/thelabnyc/python-versiontag/blob/9ceb225dc8d87cdc065dacf4a46f02b7dd1b9564/versiontag/__init__.py#L11-L22 |
thelabnyc/python-versiontag | versiontag/__init__.py | cache_git_tag | def cache_git_tag():
"""
Try to read the current version from git and, if read successfully, cache it into the version cache file. If
the git folder doesn't exist or if git isn't installed, this is a no-op. I.E. it won't blank out a
pre-existing version cache file upon failure.
:return: Project ver... | python | def cache_git_tag():
"""
Try to read the current version from git and, if read successfully, cache it into the version cache file. If
the git folder doesn't exist or if git isn't installed, this is a no-op. I.E. it won't blank out a
pre-existing version cache file upon failure.
:return: Project ver... | [
"def",
"cache_git_tag",
"(",
")",
":",
"try",
":",
"version",
"=",
"__get_git_tag",
"(",
")",
"with",
"__open_cache_file",
"(",
"'w'",
")",
"as",
"vf",
":",
"vf",
".",
"write",
"(",
"version",
")",
"except",
"Exception",
":",
"version",
"=",
"__default_v... | Try to read the current version from git and, if read successfully, cache it into the version cache file. If
the git folder doesn't exist or if git isn't installed, this is a no-op. I.E. it won't blank out a
pre-existing version cache file upon failure.
:return: Project version string | [
"Try",
"to",
"read",
"the",
"current",
"version",
"from",
"git",
"and",
"if",
"read",
"successfully",
"cache",
"it",
"into",
"the",
"version",
"cache",
"file",
".",
"If",
"the",
"git",
"folder",
"doesn",
"t",
"exist",
"or",
"if",
"git",
"isn",
"t",
"in... | train | https://github.com/thelabnyc/python-versiontag/blob/9ceb225dc8d87cdc065dacf4a46f02b7dd1b9564/versiontag/__init__.py#L44-L58 |
thelabnyc/python-versiontag | versiontag/__init__.py | convert_to_pypi_version | def convert_to_pypi_version(version):
"""
Convert a git tag version string into something compatible with `PEP-440 <https://www.python.org/dev/peps/pep-0440/>`_.
:param version: The input version string, normally directly out of git describe.
:return: PEP-440 version string
Usage::
>>> conv... | python | def convert_to_pypi_version(version):
"""
Convert a git tag version string into something compatible with `PEP-440 <https://www.python.org/dev/peps/pep-0440/>`_.
:param version: The input version string, normally directly out of git describe.
:return: PEP-440 version string
Usage::
>>> conv... | [
"def",
"convert_to_pypi_version",
"(",
"version",
")",
":",
"v",
"=",
"re",
".",
"search",
"(",
"'^[r,v]{0,1}(?P<final>[0-9\\.]+)(\\-(?P<pre>(a|b|rc)[0-9]+))?(\\-(?P<dev>dev[0-9]+))?(\\-(?P<post>[0-9]+))?(\\-.+)?$'",
",",
"version",
")",
"if",
"not",
"v",
":",
"return",
"__... | Convert a git tag version string into something compatible with `PEP-440 <https://www.python.org/dev/peps/pep-0440/>`_.
:param version: The input version string, normally directly out of git describe.
:return: PEP-440 version string
Usage::
>>> convert_to_pypi_version('r1.0.1') # Normal Releases
... | [
"Convert",
"a",
"git",
"tag",
"version",
"string",
"into",
"something",
"compatible",
"with",
"PEP",
"-",
"440",
"<https",
":",
"//",
"www",
".",
"python",
".",
"org",
"/",
"dev",
"/",
"peps",
"/",
"pep",
"-",
"0440",
"/",
">",
"_",
"."
] | train | https://github.com/thelabnyc/python-versiontag/blob/9ceb225dc8d87cdc065dacf4a46f02b7dd1b9564/versiontag/__init__.py#L61-L102 |
thelabnyc/python-versiontag | versiontag/__init__.py | get_version | def get_version(pypi=False):
"""
Get the project version string.
Returns the most-accurate-possible version string for the current project.
This order of preference this is:
1. The actual output of ``git describe --tags``
2. The contents of the version cache file
3. The default version, ``... | python | def get_version(pypi=False):
"""
Get the project version string.
Returns the most-accurate-possible version string for the current project.
This order of preference this is:
1. The actual output of ``git describe --tags``
2. The contents of the version cache file
3. The default version, ``... | [
"def",
"get_version",
"(",
"pypi",
"=",
"False",
")",
":",
"version",
"=",
"__default_version__",
"try",
":",
"with",
"__open_cache_file",
"(",
"'r'",
")",
"as",
"vf",
":",
"version",
"=",
"vf",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"except",
... | Get the project version string.
Returns the most-accurate-possible version string for the current project.
This order of preference this is:
1. The actual output of ``git describe --tags``
2. The contents of the version cache file
3. The default version, ``r0.0.0``
:param pypi: Default False.... | [
"Get",
"the",
"project",
"version",
"string",
"."
] | train | https://github.com/thelabnyc/python-versiontag/blob/9ceb225dc8d87cdc065dacf4a46f02b7dd1b9564/versiontag/__init__.py#L105-L138 |
KelSolaar/Foundations | foundations/decorators.py | execution_time | def execution_time(object):
"""
| Implements execution timing.
| Any method / definition decorated will have it's execution timed through information messages.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object
"""
@functools.wraps(object)
d... | python | def execution_time(object):
"""
| Implements execution timing.
| Any method / definition decorated will have it's execution timed through information messages.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object
"""
@functools.wraps(object)
d... | [
"def",
"execution_time",
"(",
"object",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"object",
")",
"def",
"execution_time_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Implements execution timing.\n\n :param \\*args: Argumen... | | Implements execution timing.
| Any method / definition decorated will have it's execution timed through information messages.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object | [
"|",
"Implements",
"execution",
"timing",
".",
"|",
"Any",
"method",
"/",
"definition",
"decorated",
"will",
"have",
"it",
"s",
"execution",
"timed",
"through",
"information",
"messages",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/decorators.py#L41-L77 |
KelSolaar/Foundations | foundations/decorators.py | memoize | def memoize(cache=None):
"""
| Implements method / definition memoization.
| Any method / definition decorated will get its return value cached and restored whenever called with the same arguments.
:param cache: Alternate cache.
:type cache: dict
:return: Object.
:rtype: object
"""
... | python | def memoize(cache=None):
"""
| Implements method / definition memoization.
| Any method / definition decorated will get its return value cached and restored whenever called with the same arguments.
:param cache: Alternate cache.
:type cache: dict
:return: Object.
:rtype: object
"""
... | [
"def",
"memoize",
"(",
"cache",
"=",
"None",
")",
":",
"if",
"cache",
"is",
"None",
":",
"cache",
"=",
"{",
"}",
"def",
"memoize_decorator",
"(",
"object",
")",
":",
"\"\"\"\n Implements method / definition memoization.\n\n :param object: Object to decorat... | | Implements method / definition memoization.
| Any method / definition decorated will get its return value cached and restored whenever called with the same arguments.
:param cache: Alternate cache.
:type cache: dict
:return: Object.
:rtype: object | [
"|",
"Implements",
"method",
"/",
"definition",
"memoization",
".",
"|",
"Any",
"method",
"/",
"definition",
"decorated",
"will",
"get",
"its",
"return",
"value",
"cached",
"and",
"restored",
"whenever",
"called",
"with",
"the",
"same",
"arguments",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/decorators.py#L80-L129 |
KelSolaar/Foundations | foundations/decorators.py | system_exit | def system_exit(object):
"""
Handles proper system exit in case of critical exception.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object
"""
@functools.wraps(object)
def system_exit_wrapper(*args, **kwargs):
"""
Handles proper s... | python | def system_exit(object):
"""
Handles proper system exit in case of critical exception.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object
"""
@functools.wraps(object)
def system_exit_wrapper(*args, **kwargs):
"""
Handles proper s... | [
"def",
"system_exit",
"(",
"object",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"object",
")",
"def",
"system_exit_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Handles proper system exit in case of critical exception.\n\n ... | Handles proper system exit in case of critical exception.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object | [
"Handles",
"proper",
"system",
"exit",
"in",
"case",
"of",
"critical",
"exception",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/decorators.py#L132-L160 |
KelSolaar/Foundations | foundations/trace.py | is_read_only | def is_read_only(object):
"""
Returns if given object is read only ( built-in or extension ).
:param object: Object.
:type object: object
:return: Is object read only.
:rtype: bool
"""
try:
attribute = "_trace__read__"
setattr(object, attribute, True)
delattr(ob... | python | def is_read_only(object):
"""
Returns if given object is read only ( built-in or extension ).
:param object: Object.
:type object: object
:return: Is object read only.
:rtype: bool
"""
try:
attribute = "_trace__read__"
setattr(object, attribute, True)
delattr(ob... | [
"def",
"is_read_only",
"(",
"object",
")",
":",
"try",
":",
"attribute",
"=",
"\"_trace__read__\"",
"setattr",
"(",
"object",
",",
"attribute",
",",
"True",
")",
"delattr",
"(",
"object",
",",
"attribute",
")",
"return",
"False",
"except",
"(",
"TypeError",
... | Returns if given object is read only ( built-in or extension ).
:param object: Object.
:type object: object
:return: Is object read only.
:rtype: bool | [
"Returns",
"if",
"given",
"object",
"is",
"read",
"only",
"(",
"built",
"-",
"in",
"or",
"extension",
")",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L91-L107 |
KelSolaar/Foundations | foundations/trace.py | trace_walker | def trace_walker(module):
"""
Defines a generator used to walk into modules.
:param module: Module to walk.
:type module: ModuleType
:return: Class / Function / Method.
:rtype: object or object
"""
for name, function in inspect.getmembers(module, inspect.isfunction):
yield None... | python | def trace_walker(module):
"""
Defines a generator used to walk into modules.
:param module: Module to walk.
:type module: ModuleType
:return: Class / Function / Method.
:rtype: object or object
"""
for name, function in inspect.getmembers(module, inspect.isfunction):
yield None... | [
"def",
"trace_walker",
"(",
"module",
")",
":",
"for",
"name",
",",
"function",
"in",
"inspect",
".",
"getmembers",
"(",
"module",
",",
"inspect",
".",
"isfunction",
")",
":",
"yield",
"None",
",",
"function",
"for",
"name",
",",
"cls",
"in",
"inspect",
... | Defines a generator used to walk into modules.
:param module: Module to walk.
:type module: ModuleType
:return: Class / Function / Method.
:rtype: object or object | [
"Defines",
"a",
"generator",
"used",
"to",
"walk",
"into",
"modules",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L225-L250 |
KelSolaar/Foundations | foundations/trace.py | get_object_name | def get_object_name(object):
"""
Returns given object name.
:param object: Object to retrieve the name.
:type object: object
:return: Object name.
:rtype: unicode
"""
if type(object) is property:
return object.fget.__name__
elif hasattr(object, "__name__"):
return o... | python | def get_object_name(object):
"""
Returns given object name.
:param object: Object to retrieve the name.
:type object: object
:return: Object name.
:rtype: unicode
"""
if type(object) is property:
return object.fget.__name__
elif hasattr(object, "__name__"):
return o... | [
"def",
"get_object_name",
"(",
"object",
")",
":",
"if",
"type",
"(",
"object",
")",
"is",
"property",
":",
"return",
"object",
".",
"fget",
".",
"__name__",
"elif",
"hasattr",
"(",
"object",
",",
"\"__name__\"",
")",
":",
"return",
"object",
".",
"__nam... | Returns given object name.
:param object: Object to retrieve the name.
:type object: object
:return: Object name.
:rtype: unicode | [
"Returns",
"given",
"object",
"name",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L253-L270 |
KelSolaar/Foundations | foundations/trace.py | get_trace_name | def get_trace_name(object):
"""
Returns given object trace name.
:param object: Object.
:type object: object
:return: Object trace name.
:rtype: unicode
"""
global TRACE_NAMES_CACHE
global TRACE_WALKER_CACHE
trace_name = TRACE_NAMES_CACHE.get(object)
if trace_name is None:... | python | def get_trace_name(object):
"""
Returns given object trace name.
:param object: Object.
:type object: object
:return: Object trace name.
:rtype: unicode
"""
global TRACE_NAMES_CACHE
global TRACE_WALKER_CACHE
trace_name = TRACE_NAMES_CACHE.get(object)
if trace_name is None:... | [
"def",
"get_trace_name",
"(",
"object",
")",
":",
"global",
"TRACE_NAMES_CACHE",
"global",
"TRACE_WALKER_CACHE",
"trace_name",
"=",
"TRACE_NAMES_CACHE",
".",
"get",
"(",
"object",
")",
"if",
"trace_name",
"is",
"None",
":",
"TRACE_NAMES_CACHE",
"[",
"object",
"]",... | Returns given object trace name.
:param object: Object.
:type object: object
:return: Object trace name.
:rtype: unicode | [
"Returns",
"given",
"object",
"trace",
"name",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L273-L308 |
KelSolaar/Foundations | foundations/trace.py | get_method_name | def get_method_name(method):
"""
Returns given method name.
:param method: Method to retrieve the name.
:type method: object
:return: Method name.
:rtype: unicode
"""
name = get_object_name(method)
if name.startswith("__") and not name.endswith("__"):
name = "_{0}{1}".forma... | python | def get_method_name(method):
"""
Returns given method name.
:param method: Method to retrieve the name.
:type method: object
:return: Method name.
:rtype: unicode
"""
name = get_object_name(method)
if name.startswith("__") and not name.endswith("__"):
name = "_{0}{1}".forma... | [
"def",
"get_method_name",
"(",
"method",
")",
":",
"name",
"=",
"get_object_name",
"(",
"method",
")",
"if",
"name",
".",
"startswith",
"(",
"\"__\"",
")",
"and",
"not",
"name",
".",
"endswith",
"(",
"\"__\"",
")",
":",
"name",
"=",
"\"_{0}{1}\"",
".",
... | Returns given method name.
:param method: Method to retrieve the name.
:type method: object
:return: Method name.
:rtype: unicode | [
"Returns",
"given",
"method",
"name",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L311-L324 |
KelSolaar/Foundations | foundations/trace.py | validate_tracer | def validate_tracer(*args):
"""
Validate and finishes a tracer by adding mandatory extra attributes.
:param \*args: Arguments.
:type \*args: \*
:return: Validated wrapped object.
:rtype: object
"""
object, wrapped = args
if is_traced(object) or is_untracable(object) or get_object_n... | python | def validate_tracer(*args):
"""
Validate and finishes a tracer by adding mandatory extra attributes.
:param \*args: Arguments.
:type \*args: \*
:return: Validated wrapped object.
:rtype: object
"""
object, wrapped = args
if is_traced(object) or is_untracable(object) or get_object_n... | [
"def",
"validate_tracer",
"(",
"*",
"args",
")",
":",
"object",
",",
"wrapped",
"=",
"args",
"if",
"is_traced",
"(",
"object",
")",
"or",
"is_untracable",
"(",
"object",
")",
"or",
"get_object_name",
"(",
"object",
")",
"in",
"UNTRACABLE_NAMES",
":",
"retu... | Validate and finishes a tracer by adding mandatory extra attributes.
:param \*args: Arguments.
:type \*args: \*
:return: Validated wrapped object.
:rtype: object | [
"Validate",
"and",
"finishes",
"a",
"tracer",
"by",
"adding",
"mandatory",
"extra",
"attributes",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L374-L391 |
KelSolaar/Foundations | foundations/trace.py | tracer | def tracer(object):
"""
| Traces execution.
| Any method / definition decorated will have it's execution traced.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object
"""
@functools.wraps(object)
@functools.partial(validate_tracer, object)
... | python | def tracer(object):
"""
| Traces execution.
| Any method / definition decorated will have it's execution traced.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object
"""
@functools.wraps(object)
@functools.partial(validate_tracer, object)
... | [
"def",
"tracer",
"(",
"object",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"object",
")",
"@",
"functools",
".",
"partial",
"(",
"validate_tracer",
",",
"object",
")",
"def",
"tracer_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
... | | Traces execution.
| Any method / definition decorated will have it's execution traced.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object | [
"|",
"Traces",
"execution",
".",
"|",
"Any",
"method",
"/",
"definition",
"decorated",
"will",
"have",
"it",
"s",
"execution",
"traced",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L394-L437 |
KelSolaar/Foundations | foundations/trace.py | untracable | def untracable(object):
"""
Marks decorated object as non tracable.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object
"""
@functools.wraps(object)
def untracable_wrapper(*args, **kwargs):
"""
Marks decorated object as non tracab... | python | def untracable(object):
"""
Marks decorated object as non tracable.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object
"""
@functools.wraps(object)
def untracable_wrapper(*args, **kwargs):
"""
Marks decorated object as non tracab... | [
"def",
"untracable",
"(",
"object",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"object",
")",
"def",
"untracable_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Marks decorated object as non tracable.\n\n :param \\*args: Argu... | Marks decorated object as non tracable.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object | [
"Marks",
"decorated",
"object",
"as",
"non",
"tracable",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L455-L482 |
KelSolaar/Foundations | foundations/trace.py | trace_function | def trace_function(module, function, tracer=tracer):
"""
Traces given module function using given tracer.
:param module: Module of the function.
:type module: object
:param function: Function to trace.
:type function: object
:param tracer: Tracer.
:type tracer: object
:return: Defin... | python | def trace_function(module, function, tracer=tracer):
"""
Traces given module function using given tracer.
:param module: Module of the function.
:type module: object
:param function: Function to trace.
:type function: object
:param tracer: Tracer.
:type tracer: object
:return: Defin... | [
"def",
"trace_function",
"(",
"module",
",",
"function",
",",
"tracer",
"=",
"tracer",
")",
":",
"if",
"is_traced",
"(",
"function",
")",
":",
"return",
"False",
"name",
"=",
"get_object_name",
"(",
"function",
")",
"if",
"is_untracable",
"(",
"function",
... | Traces given module function using given tracer.
:param module: Module of the function.
:type module: object
:param function: Function to trace.
:type function: object
:param tracer: Tracer.
:type tracer: object
:return: Definition success.
:rtype: bool | [
"Traces",
"given",
"module",
"function",
"using",
"given",
"tracer",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L485-L507 |
KelSolaar/Foundations | foundations/trace.py | untrace_function | def untrace_function(module, function):
"""
Untraces given module function.
:param module: Module of the function.
:type module: object
:param function: Function to untrace.
:type function: object
:return: Definition success.
:rtype: bool
"""
if not is_traced(function):
... | python | def untrace_function(module, function):
"""
Untraces given module function.
:param module: Module of the function.
:type module: object
:param function: Function to untrace.
:type function: object
:return: Definition success.
:rtype: bool
"""
if not is_traced(function):
... | [
"def",
"untrace_function",
"(",
"module",
",",
"function",
")",
":",
"if",
"not",
"is_traced",
"(",
"function",
")",
":",
"return",
"False",
"name",
"=",
"get_object_name",
"(",
"function",
")",
"setattr",
"(",
"module",
",",
"name",
",",
"untracer",
"(",
... | Untraces given module function.
:param module: Module of the function.
:type module: object
:param function: Function to untrace.
:type function: object
:return: Definition success.
:rtype: bool | [
"Untraces",
"given",
"module",
"function",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L510-L527 |
KelSolaar/Foundations | foundations/trace.py | trace_method | def trace_method(cls, method, tracer=tracer):
"""
Traces given class method using given tracer.
:param cls: Class of the method.
:type cls: object
:param method: Method to trace.
:type method: object
:param tracer: Tracer.
:type tracer: object
:return: Definition success.
:rtype... | python | def trace_method(cls, method, tracer=tracer):
"""
Traces given class method using given tracer.
:param cls: Class of the method.
:type cls: object
:param method: Method to trace.
:type method: object
:param tracer: Tracer.
:type tracer: object
:return: Definition success.
:rtype... | [
"def",
"trace_method",
"(",
"cls",
",",
"method",
",",
"tracer",
"=",
"tracer",
")",
":",
"if",
"is_traced",
"(",
"method",
")",
":",
"return",
"False",
"name",
"=",
"get_method_name",
"(",
"method",
")",
"if",
"is_untracable",
"(",
"method",
")",
"or",
... | Traces given class method using given tracer.
:param cls: Class of the method.
:type cls: object
:param method: Method to trace.
:type method: object
:param tracer: Tracer.
:type tracer: object
:return: Definition success.
:rtype: bool | [
"Traces",
"given",
"class",
"method",
"using",
"given",
"tracer",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L530-L557 |
KelSolaar/Foundations | foundations/trace.py | untrace_method | def untrace_method(cls, method):
"""
Untraces given class method.
:param cls: Class of the method.
:type cls: object
:param method: Method to untrace.
:type method: object
:return: Definition success.
:rtype: bool
"""
if not is_traced(method):
return False
name = g... | python | def untrace_method(cls, method):
"""
Untraces given class method.
:param cls: Class of the method.
:type cls: object
:param method: Method to untrace.
:type method: object
:return: Definition success.
:rtype: bool
"""
if not is_traced(method):
return False
name = g... | [
"def",
"untrace_method",
"(",
"cls",
",",
"method",
")",
":",
"if",
"not",
"is_traced",
"(",
"method",
")",
":",
"return",
"False",
"name",
"=",
"get_method_name",
"(",
"method",
")",
"if",
"is_class_method",
"(",
"method",
")",
":",
"setattr",
"(",
"cls... | Untraces given class method.
:param cls: Class of the method.
:type cls: object
:param method: Method to untrace.
:type method: object
:return: Definition success.
:rtype: bool | [
"Untraces",
"given",
"class",
"method",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L560-L582 |
KelSolaar/Foundations | foundations/trace.py | trace_property | def trace_property(cls, accessor, tracer=tracer):
"""
Traces given class property using given tracer.
:param cls: Class of the property.
:type cls: object
:param accessor: Property to trace.
:type accessor: property
:param tracer: Tracer.
:type tracer: object
:return: Definition suc... | python | def trace_property(cls, accessor, tracer=tracer):
"""
Traces given class property using given tracer.
:param cls: Class of the property.
:type cls: object
:param accessor: Property to trace.
:type accessor: property
:param tracer: Tracer.
:type tracer: object
:return: Definition suc... | [
"def",
"trace_property",
"(",
"cls",
",",
"accessor",
",",
"tracer",
"=",
"tracer",
")",
":",
"if",
"is_traced",
"(",
"accessor",
".",
"fget",
")",
"and",
"is_traced",
"(",
"accessor",
".",
"fset",
")",
"and",
"is_traced",
"(",
"accessor",
".",
"fdel",
... | Traces given class property using given tracer.
:param cls: Class of the property.
:type cls: object
:param accessor: Property to trace.
:type accessor: property
:param tracer: Tracer.
:type tracer: object
:return: Definition success.
:rtype: bool | [
"Traces",
"given",
"class",
"property",
"using",
"given",
"tracer",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L585-L606 |
KelSolaar/Foundations | foundations/trace.py | untrace_property | def untrace_property(cls, accessor):
"""
Untraces given class property.
:param cls: Class of the property.
:type cls: object
:param accessor: Property to untrace.
:type accessor: property
:return: Definition success.
:rtype: bool
"""
if not is_traced(accessor.fget) or not is_tr... | python | def untrace_property(cls, accessor):
"""
Untraces given class property.
:param cls: Class of the property.
:type cls: object
:param accessor: Property to untrace.
:type accessor: property
:return: Definition success.
:rtype: bool
"""
if not is_traced(accessor.fget) or not is_tr... | [
"def",
"untrace_property",
"(",
"cls",
",",
"accessor",
")",
":",
"if",
"not",
"is_traced",
"(",
"accessor",
".",
"fget",
")",
"or",
"not",
"is_traced",
"(",
"accessor",
".",
"fset",
")",
"or",
"not",
"is_traced",
"(",
"accessor",
".",
"fdel",
")",
":"... | Untraces given class property.
:param cls: Class of the property.
:type cls: object
:param accessor: Property to untrace.
:type accessor: property
:return: Definition success.
:rtype: bool | [
"Untraces",
"given",
"class",
"property",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L609-L628 |
KelSolaar/Foundations | foundations/trace.py | trace_class | def trace_class(cls, tracer=tracer, pattern=r".*", flags=0):
"""
Traces given class using given tracer.
:param cls: Class to trace.
:type cls: object
:param tracer: Tracer.
:type tracer: object
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex fla... | python | def trace_class(cls, tracer=tracer, pattern=r".*", flags=0):
"""
Traces given class using given tracer.
:param cls: Class to trace.
:type cls: object
:param tracer: Tracer.
:type tracer: object
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex fla... | [
"def",
"trace_class",
"(",
"cls",
",",
"tracer",
"=",
"tracer",
",",
"pattern",
"=",
"r\".*\"",
",",
"flags",
"=",
"0",
")",
":",
"if",
"not",
"is_base_traced",
"(",
"cls",
")",
"and",
"(",
"is_traced",
"(",
"cls",
")",
"or",
"is_read_only",
"(",
"cl... | Traces given class using given tracer.
:param cls: Class to trace.
:type cls: object
:param tracer: Tracer.
:type tracer: object
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:type flags: int
:return: Definition success.
:rtype: boo... | [
"Traces",
"given",
"class",
"using",
"given",
"tracer",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L631-L670 |
KelSolaar/Foundations | foundations/trace.py | untrace_class | def untrace_class(cls):
"""
Untraces given class.
:param cls: Class to untrace.
:type cls: object
:return: Definition success.
:rtype: bool
"""
for name, method in inspect.getmembers(cls, inspect.ismethod):
untrace_method(cls, method)
for name, function in inspect.getmembe... | python | def untrace_class(cls):
"""
Untraces given class.
:param cls: Class to untrace.
:type cls: object
:return: Definition success.
:rtype: bool
"""
for name, method in inspect.getmembers(cls, inspect.ismethod):
untrace_method(cls, method)
for name, function in inspect.getmembe... | [
"def",
"untrace_class",
"(",
"cls",
")",
":",
"for",
"name",
",",
"method",
"in",
"inspect",
".",
"getmembers",
"(",
"cls",
",",
"inspect",
".",
"ismethod",
")",
":",
"untrace_method",
"(",
"cls",
",",
"method",
")",
"for",
"name",
",",
"function",
"in... | Untraces given class.
:param cls: Class to untrace.
:type cls: object
:return: Definition success.
:rtype: bool | [
"Untraces",
"given",
"class",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L673-L694 |
KelSolaar/Foundations | foundations/trace.py | trace_module | def trace_module(module, tracer=tracer, pattern=r".*", flags=0):
"""
Traces given module members using given tracer.
:param module: Module to trace.
:type module: ModuleType
:param tracer: Tracer.
:type tracer: object
:param pattern: Matching pattern.
:type pattern: unicode
:param f... | python | def trace_module(module, tracer=tracer, pattern=r".*", flags=0):
"""
Traces given module members using given tracer.
:param module: Module to trace.
:type module: ModuleType
:param tracer: Tracer.
:type tracer: object
:param pattern: Matching pattern.
:type pattern: unicode
:param f... | [
"def",
"trace_module",
"(",
"module",
",",
"tracer",
"=",
"tracer",
",",
"pattern",
"=",
"r\".*\"",
",",
"flags",
"=",
"0",
")",
":",
"if",
"is_traced",
"(",
"module",
")",
":",
"return",
"False",
"global",
"REGISTERED_MODULES",
"for",
"name",
",",
"func... | Traces given module members using given tracer.
:param module: Module to trace.
:type module: ModuleType
:param tracer: Tracer.
:type tracer: object
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:type flags: int
:return: Definition succ... | [
"Traces",
"given",
"module",
"members",
"using",
"given",
"tracer",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L697-L736 |
KelSolaar/Foundations | foundations/trace.py | untrace_module | def untrace_module(module):
"""
Untraces given module members.
:param module: Module to untrace.
:type module: ModuleType
:return: Definition success.
:rtype: bool
"""
for name, function in inspect.getmembers(module, inspect.isfunction):
untrace_function(module, function)
... | python | def untrace_module(module):
"""
Untraces given module members.
:param module: Module to untrace.
:type module: ModuleType
:return: Definition success.
:rtype: bool
"""
for name, function in inspect.getmembers(module, inspect.isfunction):
untrace_function(module, function)
... | [
"def",
"untrace_module",
"(",
"module",
")",
":",
"for",
"name",
",",
"function",
"in",
"inspect",
".",
"getmembers",
"(",
"module",
",",
"inspect",
".",
"isfunction",
")",
":",
"untrace_function",
"(",
"module",
",",
"function",
")",
"for",
"name",
",",
... | Untraces given module members.
:param module: Module to untrace.
:type module: ModuleType
:return: Definition success.
:rtype: bool | [
"Untraces",
"given",
"module",
"members",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L739-L757 |
KelSolaar/Foundations | foundations/trace.py | register_module | def register_module(module=None):
"""
Registers given module or caller introspected module in the candidates modules for tracing.
:param module: Module to register.
:type module: ModuleType
:return: Definition success.
:rtype: bool
"""
global REGISTERED_MODULES
if module is None:
... | python | def register_module(module=None):
"""
Registers given module or caller introspected module in the candidates modules for tracing.
:param module: Module to register.
:type module: ModuleType
:return: Definition success.
:rtype: bool
"""
global REGISTERED_MODULES
if module is None:
... | [
"def",
"register_module",
"(",
"module",
"=",
"None",
")",
":",
"global",
"REGISTERED_MODULES",
"if",
"module",
"is",
"None",
":",
"# Note: inspect.getmodule() can return the wrong module if it has been imported with different relatives paths.",
"module",
"=",
"sys",
".",
"mo... | Registers given module or caller introspected module in the candidates modules for tracing.
:param module: Module to register.
:type module: ModuleType
:return: Definition success.
:rtype: bool | [
"Registers",
"given",
"module",
"or",
"caller",
"introspected",
"module",
"in",
"the",
"candidates",
"modules",
"for",
"tracing",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L760-L777 |
KelSolaar/Foundations | foundations/trace.py | install_tracer | def install_tracer(tracer=tracer, pattern=r".*", flags=0):
"""
Installs given tracer in the candidates modules for tracing matching given pattern.
:param tracer: Tracer.
:type tracer: object
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:ty... | python | def install_tracer(tracer=tracer, pattern=r".*", flags=0):
"""
Installs given tracer in the candidates modules for tracing matching given pattern.
:param tracer: Tracer.
:type tracer: object
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:ty... | [
"def",
"install_tracer",
"(",
"tracer",
"=",
"tracer",
",",
"pattern",
"=",
"r\".*\"",
",",
"flags",
"=",
"0",
")",
":",
"for",
"module",
"in",
"REGISTERED_MODULES",
":",
"if",
"not",
"re",
".",
"search",
"(",
"pattern",
",",
"module",
".",
"__name__",
... | Installs given tracer in the candidates modules for tracing matching given pattern.
:param tracer: Tracer.
:type tracer: object
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:type flags: int
:return: Definition success.
:rtype: bool | [
"Installs",
"given",
"tracer",
"in",
"the",
"candidates",
"modules",
"for",
"tracing",
"matching",
"given",
"pattern",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L780-L799 |
KelSolaar/Foundations | foundations/trace.py | uninstall_tracer | def uninstall_tracer(pattern=r".*", flags=0):
"""
Installs the tracer in the candidates modules for tracing matching given pattern.
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:type flags: int
:return: Definition success.
:rtype: bool
... | python | def uninstall_tracer(pattern=r".*", flags=0):
"""
Installs the tracer in the candidates modules for tracing matching given pattern.
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:type flags: int
:return: Definition success.
:rtype: bool
... | [
"def",
"uninstall_tracer",
"(",
"pattern",
"=",
"r\".*\"",
",",
"flags",
"=",
"0",
")",
":",
"for",
"module",
"in",
"REGISTERED_MODULES",
":",
"if",
"not",
"is_traced",
"(",
"module",
")",
":",
"continue",
"if",
"not",
"re",
".",
"search",
"(",
"pattern"... | Installs the tracer in the candidates modules for tracing matching given pattern.
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:type flags: int
:return: Definition success.
:rtype: bool | [
"Installs",
"the",
"tracer",
"in",
"the",
"candidates",
"modules",
"for",
"tracing",
"matching",
"given",
"pattern",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L802-L822 |
KelSolaar/Foundations | foundations/trace.py | evaluate_trace_request | def evaluate_trace_request(data, tracer=tracer):
"""
Evaluate given string trace request.
Usage::
Umbra -t "{'umbra.engine' : ('.*', 0), 'umbra.preferences' : (r'.*', 0)}"
Umbra -t "['umbra.engine', 'umbra.preferences']"
Umbra -t "'umbra.engine, umbra.preferences"
:param data:... | python | def evaluate_trace_request(data, tracer=tracer):
"""
Evaluate given string trace request.
Usage::
Umbra -t "{'umbra.engine' : ('.*', 0), 'umbra.preferences' : (r'.*', 0)}"
Umbra -t "['umbra.engine', 'umbra.preferences']"
Umbra -t "'umbra.engine, umbra.preferences"
:param data:... | [
"def",
"evaluate_trace_request",
"(",
"data",
",",
"tracer",
"=",
"tracer",
")",
":",
"data",
"=",
"ast",
".",
"literal_eval",
"(",
"data",
")",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"modules",
"=",
"dict",
".",
"fromkeys",
"(",
"map",... | Evaluate given string trace request.
Usage::
Umbra -t "{'umbra.engine' : ('.*', 0), 'umbra.preferences' : (r'.*', 0)}"
Umbra -t "['umbra.engine', 'umbra.preferences']"
Umbra -t "'umbra.engine, umbra.preferences"
:param data: Trace request.
:type data: unicode
:param tracer: Tr... | [
"Evaluate",
"given",
"string",
"trace",
"request",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/trace.py#L825-L857 |
TissueMAPS/TmClient | src/python/tmclient/base.py | HttpClient._init_session | def _init_session(self):
'''
Delayed initialization of Requests Session object.
This is done in order *not* to share the Session object across
a multiprocessing pool.
'''
self._real_session = requests.Session()
# FIXME: this fails when one runs HTTPS on non-stand... | python | def _init_session(self):
'''
Delayed initialization of Requests Session object.
This is done in order *not* to share the Session object across
a multiprocessing pool.
'''
self._real_session = requests.Session()
# FIXME: this fails when one runs HTTPS on non-stand... | [
"def",
"_init_session",
"(",
"self",
")",
":",
"self",
".",
"_real_session",
"=",
"requests",
".",
"Session",
"(",
")",
"# FIXME: this fails when one runs HTTPS on non-standard ports,",
"# e.g. https://tissuemaps.example.org:8443/",
"if",
"self",
".",
"_port",
"==",
"443"... | Delayed initialization of Requests Session object.
This is done in order *not* to share the Session object across
a multiprocessing pool. | [
"Delayed",
"initialization",
"of",
"Requests",
"Session",
"object",
"."
] | train | https://github.com/TissueMAPS/TmClient/blob/6fb40622af19142cb5169a64b8c2965993a25ab1/src/python/tmclient/base.py#L63-L91 |
TissueMAPS/TmClient | src/python/tmclient/base.py | HttpClient._build_url | def _build_url(self, route, params={}):
'''Builds the full URL based on the base URL (``http://<host>:<port>``)
and the provided `route`.
Parameters
----------
route: str
route used by the TissueMAPS RESTful API
params: dict, optional
optional par... | python | def _build_url(self, route, params={}):
'''Builds the full URL based on the base URL (``http://<host>:<port>``)
and the provided `route`.
Parameters
----------
route: str
route used by the TissueMAPS RESTful API
params: dict, optional
optional par... | [
"def",
"_build_url",
"(",
"self",
",",
"route",
",",
"params",
"=",
"{",
"}",
")",
":",
"url",
"=",
"self",
".",
"_base_url",
"+",
"route",
"if",
"not",
"params",
":",
"logger",
".",
"debug",
"(",
"'url: %s'",
",",
"url",
")",
"return",
"url",
"url... | Builds the full URL based on the base URL (``http://<host>:<port>``)
and the provided `route`.
Parameters
----------
route: str
route used by the TissueMAPS RESTful API
params: dict, optional
optional parameters that need to be included in the URL query s... | [
"Builds",
"the",
"full",
"URL",
"based",
"on",
"the",
"base",
"URL",
"(",
"http",
":",
"//",
"<host",
">",
":",
"<port",
">",
")",
"and",
"the",
"provided",
"route",
"."
] | train | https://github.com/TissueMAPS/TmClient/blob/6fb40622af19142cb5169a64b8c2965993a25ab1/src/python/tmclient/base.py#L115-L137 |
TissueMAPS/TmClient | src/python/tmclient/base.py | HttpClient._login | def _login(self, username, password):
'''Authenticates a TissueMAPS user.
Parameters
----------
username: str
name
password: str
password
'''
logger.debug('login in as user "%s"' % username)
url = self._build_url('/auth')
p... | python | def _login(self, username, password):
'''Authenticates a TissueMAPS user.
Parameters
----------
username: str
name
password: str
password
'''
logger.debug('login in as user "%s"' % username)
url = self._build_url('/auth')
p... | [
"def",
"_login",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"logger",
".",
"debug",
"(",
"'login in as user \"%s\"'",
"%",
"username",
")",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'/auth'",
")",
"payload",
"=",
"{",
"'username'",
":",
... | Authenticates a TissueMAPS user.
Parameters
----------
username: str
name
password: str
password | [
"Authenticates",
"a",
"TissueMAPS",
"user",
"."
] | train | https://github.com/TissueMAPS/TmClient/blob/6fb40622af19142cb5169a64b8c2965993a25ab1/src/python/tmclient/base.py#L139-L157 |
getfleety/coralillo | coralillo/hashing.py | force_bytes | def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first f... | python | def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first f... | [
"def",
"force_bytes",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"strings_only",
"=",
"False",
",",
"errors",
"=",
"'strict'",
")",
":",
"# Handle the common case first for performance reasons.",
"if",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"if",
... | Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects. | [
"Similar",
"to",
"smart_bytes",
"except",
"that",
"lazy",
"instances",
"are",
"resolved",
"to",
"strings",
"rather",
"than",
"kept",
"as",
"lazy",
"objects",
".",
"If",
"strings_only",
"is",
"True",
"don",
"t",
"convert",
"(",
"some",
")",
"non",
"-",
"str... | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/hashing.py#L49-L68 |
getfleety/coralillo | coralillo/hashing.py | get_random_string | def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Return a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit val... | python | def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Return a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit val... | [
"def",
"get_random_string",
"(",
"length",
"=",
"12",
",",
"allowed_chars",
"=",
"'abcdefghijklmnopqrstuvwxyz'",
"'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'",
")",
":",
"if",
"not",
"using_sysrandom",
":",
"# This is ugly, and a hack, but it makes things better than",
"# the alternat... | Return a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits | [
"Return",
"a",
"securely",
"generated",
"random",
"string",
".",
"The",
"default",
"length",
"of",
"12",
"with",
"the",
"a",
"-",
"z",
"A",
"-",
"Z",
"0",
"-",
"9",
"character",
"set",
"returns",
"a",
"71",
"-",
"bit",
"value",
".",
"log_2",
"((",
... | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/hashing.py#L74-L94 |
getfleety/coralillo | coralillo/hashing.py | check_password | def check_password(password, encoded, setter=None, preferred='default'):
"""
Return a boolean of whether the raw password matches the three
part encoded digest.
If setter is specified, it'll be called when you need to
regenerate the password.
"""
if password is None:
return False
... | python | def check_password(password, encoded, setter=None, preferred='default'):
"""
Return a boolean of whether the raw password matches the three
part encoded digest.
If setter is specified, it'll be called when you need to
regenerate the password.
"""
if password is None:
return False
... | [
"def",
"check_password",
"(",
"password",
",",
"encoded",
",",
"setter",
"=",
"None",
",",
"preferred",
"=",
"'default'",
")",
":",
"if",
"password",
"is",
"None",
":",
"return",
"False",
"preferred",
"=",
"bCryptPasswordHasher",
"hasher",
"=",
"bCryptPassword... | Return a boolean of whether the raw password matches the three
part encoded digest.
If setter is specified, it'll be called when you need to
regenerate the password. | [
"Return",
"a",
"boolean",
"of",
"whether",
"the",
"raw",
"password",
"matches",
"the",
"three",
"part",
"encoded",
"digest",
".",
"If",
"setter",
"is",
"specified",
"it",
"ll",
"be",
"called",
"when",
"you",
"need",
"to",
"regenerate",
"the",
"password",
"... | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/hashing.py#L99-L125 |
getfleety/coralillo | coralillo/hashing.py | make_password | def make_password(password, salt=None, hasher='default'):
"""
Turn a plain-text password into a hash for database storage
Same as encode() but generate a new random salt. If password is None then
return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string,
which disallows logins. Addition... | python | def make_password(password, salt=None, hasher='default'):
"""
Turn a plain-text password into a hash for database storage
Same as encode() but generate a new random salt. If password is None then
return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string,
which disallows logins. Addition... | [
"def",
"make_password",
"(",
"password",
",",
"salt",
"=",
"None",
",",
"hasher",
"=",
"'default'",
")",
":",
"if",
"password",
"is",
"None",
":",
"return",
"UNUSABLE_PASSWORD_PREFIX",
"+",
"get_random_string",
"(",
"UNUSABLE_PASSWORD_SUFFIX_LENGTH",
")",
"hasher"... | Turn a plain-text password into a hash for database storage
Same as encode() but generate a new random salt. If password is None then
return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string,
which disallows logins. Additional random string reduces chances of gaining
access to staff or sup... | [
"Turn",
"a",
"plain",
"-",
"text",
"password",
"into",
"a",
"hash",
"for",
"database",
"storage",
"Same",
"as",
"encode",
"()",
"but",
"generate",
"a",
"new",
"random",
"salt",
".",
"If",
"password",
"is",
"None",
"then",
"return",
"a",
"concatenation",
... | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/hashing.py#L128-L143 |
getfleety/coralillo | coralillo/hashing.py | mask_hash | def mask_hash(hash, show=6, char="*"):
"""
Return the given hash, with only the first ``show`` number shown. The
rest are masked with ``char`` for security reasons.
"""
masked = hash[:show]
masked += char * len(hash[show:])
return masked | python | def mask_hash(hash, show=6, char="*"):
"""
Return the given hash, with only the first ``show`` number shown. The
rest are masked with ``char`` for security reasons.
"""
masked = hash[:show]
masked += char * len(hash[show:])
return masked | [
"def",
"mask_hash",
"(",
"hash",
",",
"show",
"=",
"6",
",",
"char",
"=",
"\"*\"",
")",
":",
"masked",
"=",
"hash",
"[",
":",
"show",
"]",
"masked",
"+=",
"char",
"*",
"len",
"(",
"hash",
"[",
"show",
":",
"]",
")",
"return",
"masked"
] | Return the given hash, with only the first ``show`` number shown. The
rest are masked with ``char`` for security reasons. | [
"Return",
"the",
"given",
"hash",
"with",
"only",
"the",
"first",
"show",
"number",
"shown",
".",
"The",
"rest",
"are",
"masked",
"with",
"char",
"for",
"security",
"reasons",
"."
] | train | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/hashing.py#L146-L153 |
PMBio/limix-backup | limix/scripts/limix_runner.py | LIMIX_runner.load_data | def load_data(self):
"""
Run the job specified in data_script
"""
options=self.options
command = open(self.options.data_script).read()
self.result["data_script"]=command
t0=time.time()
data=None #fallback data
exec(command) #creates variabl... | python | def load_data(self):
"""
Run the job specified in data_script
"""
options=self.options
command = open(self.options.data_script).read()
self.result["data_script"]=command
t0=time.time()
data=None #fallback data
exec(command) #creates variabl... | [
"def",
"load_data",
"(",
"self",
")",
":",
"options",
"=",
"self",
".",
"options",
"command",
"=",
"open",
"(",
"self",
".",
"options",
".",
"data_script",
")",
".",
"read",
"(",
")",
"self",
".",
"result",
"[",
"\"data_script\"",
"]",
"=",
"command",
... | Run the job specified in data_script | [
"Run",
"the",
"job",
"specified",
"in",
"data_script"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/scripts/limix_runner.py#L51-L64 |
PMBio/limix-backup | limix/scripts/limix_runner.py | LIMIX_runner.run_experiment | def run_experiment(self):
"""
Run the job specified in experiment_script
"""
data=self.data
options=self.options
result=self.result
command = open(self.options.experiment_script).read()
result["experiment_script"]=command
t0=time.time()
ex... | python | def run_experiment(self):
"""
Run the job specified in experiment_script
"""
data=self.data
options=self.options
result=self.result
command = open(self.options.experiment_script).read()
result["experiment_script"]=command
t0=time.time()
ex... | [
"def",
"run_experiment",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"data",
"options",
"=",
"self",
".",
"options",
"result",
"=",
"self",
".",
"result",
"command",
"=",
"open",
"(",
"self",
".",
"options",
".",
"experiment_script",
")",
".",
"re... | Run the job specified in experiment_script | [
"Run",
"the",
"job",
"specified",
"in",
"experiment_script"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/scripts/limix_runner.py#L66-L81 |
PMBio/limix-backup | limix/scripts/limix_runner.py | LIMIX_runner.write_resultfiles | def write_resultfiles(self):
"""
Write the output to disk
"""
t0=time.time()
writer = ow.output_writer(output_dictionary=self.result)
if len(self.options.outpath)>=3 and self.options.outpath[-3:]==".h5":
writer.write_hdf5(filename=self.options.outpath,timestam... | python | def write_resultfiles(self):
"""
Write the output to disk
"""
t0=time.time()
writer = ow.output_writer(output_dictionary=self.result)
if len(self.options.outpath)>=3 and self.options.outpath[-3:]==".h5":
writer.write_hdf5(filename=self.options.outpath,timestam... | [
"def",
"write_resultfiles",
"(",
"self",
")",
":",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"writer",
"=",
"ow",
".",
"output_writer",
"(",
"output_dictionary",
"=",
"self",
".",
"result",
")",
"if",
"len",
"(",
"self",
".",
"options",
".",
"outpath",... | Write the output to disk | [
"Write",
"the",
"output",
"to",
"disk"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/scripts/limix_runner.py#L83-L94 |
TAPPGuild/sqlalchemy-models | sqlalchemy_models/__init__.py | generate_signature_class | def generate_signature_class(cls):
"""
Generate a declarative model for storing signatures related to the given
cls parameter.
:param class cls: The declarative model to generate a signature class for.
:return: The signature class, as a declarative derived from Base.
"""
return type("%sSigs... | python | def generate_signature_class(cls):
"""
Generate a declarative model for storing signatures related to the given
cls parameter.
:param class cls: The declarative model to generate a signature class for.
:return: The signature class, as a declarative derived from Base.
"""
return type("%sSigs... | [
"def",
"generate_signature_class",
"(",
"cls",
")",
":",
"return",
"type",
"(",
"\"%sSigs\"",
"%",
"cls",
".",
"__name__",
",",
"(",
"Base",
",",
")",
",",
"{",
"'__tablename__'",
":",
"\"%s_sigs\"",
"%",
"cls",
".",
"__tablename__",
",",
"'id'",
":",
"s... | Generate a declarative model for storing signatures related to the given
cls parameter.
:param class cls: The declarative model to generate a signature class for.
:return: The signature class, as a declarative derived from Base. | [
"Generate",
"a",
"declarative",
"model",
"for",
"storing",
"signatures",
"related",
"to",
"the",
"given",
"cls",
"parameter",
"."
] | train | https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/__init__.py#L65-L83 |
TAPPGuild/sqlalchemy-models | sqlalchemy_models/__init__.py | create_session_engine | def create_session_engine(uri=None, cfg=None):
"""
Create an sqlalchemy session and engine.
:param str uri: The database URI to connect to
:param cfg: The configuration object with database URI info.
:return: The session and the engine as a list (in that order)
"""
if uri is not None:
... | python | def create_session_engine(uri=None, cfg=None):
"""
Create an sqlalchemy session and engine.
:param str uri: The database URI to connect to
:param cfg: The configuration object with database URI info.
:return: The session and the engine as a list (in that order)
"""
if uri is not None:
... | [
"def",
"create_session_engine",
"(",
"uri",
"=",
"None",
",",
"cfg",
"=",
"None",
")",
":",
"if",
"uri",
"is",
"not",
"None",
":",
"eng",
"=",
"sa",
".",
"create_engine",
"(",
"uri",
")",
"elif",
"cfg",
"is",
"not",
"None",
":",
"eng",
"=",
"sa",
... | Create an sqlalchemy session and engine.
:param str uri: The database URI to connect to
:param cfg: The configuration object with database URI info.
:return: The session and the engine as a list (in that order) | [
"Create",
"an",
"sqlalchemy",
"session",
"and",
"engine",
"."
] | train | https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/__init__.py#L86-L101 |
TAPPGuild/sqlalchemy-models | sqlalchemy_models/__init__.py | setup_database | def setup_database(eng, modules=None, models=None):
"""
Set up databases using create_all().
:param eng: The sqlalchemy engine to use.
:param list modules: A list of modules with models inside.
:param list models: A list of models to setup.
"""
if modules is not None:
for modu in m... | python | def setup_database(eng, modules=None, models=None):
"""
Set up databases using create_all().
:param eng: The sqlalchemy engine to use.
:param list modules: A list of modules with models inside.
:param list models: A list of models to setup.
"""
if modules is not None:
for modu in m... | [
"def",
"setup_database",
"(",
"eng",
",",
"modules",
"=",
"None",
",",
"models",
"=",
"None",
")",
":",
"if",
"modules",
"is",
"not",
"None",
":",
"for",
"modu",
"in",
"modules",
":",
"for",
"m",
"in",
"modu",
".",
"__all__",
":",
"getattr",
"(",
"... | Set up databases using create_all().
:param eng: The sqlalchemy engine to use.
:param list modules: A list of modules with models inside.
:param list models: A list of models to setup. | [
"Set",
"up",
"databases",
"using",
"create_all",
"()",
"."
] | train | https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/__init__.py#L104-L118 |
20c/munge | munge/util.py | recursive_update | def recursive_update(a, b, **kwargs):
"""
recursive dict a.update(b), merges dicts and lists
Note: will clobber non dict keys if b has a dict with same key
options:
copy: deepcopy instead of reference (default False)
merge_lists: merge lists as well (default True)
"""
copy = kwar... | python | def recursive_update(a, b, **kwargs):
"""
recursive dict a.update(b), merges dicts and lists
Note: will clobber non dict keys if b has a dict with same key
options:
copy: deepcopy instead of reference (default False)
merge_lists: merge lists as well (default True)
"""
copy = kwar... | [
"def",
"recursive_update",
"(",
"a",
",",
"b",
",",
"*",
"*",
"kwargs",
")",
":",
"copy",
"=",
"kwargs",
".",
"get",
"(",
"'copy'",
",",
"False",
")",
"merge_lists",
"=",
"kwargs",
".",
"get",
"(",
"'merge_lists'",
",",
"True",
")",
"for",
"k",
","... | recursive dict a.update(b), merges dicts and lists
Note: will clobber non dict keys if b has a dict with same key
options:
copy: deepcopy instead of reference (default False)
merge_lists: merge lists as well (default True) | [
"recursive",
"dict",
"a",
".",
"update",
"(",
"b",
")",
"merges",
"dicts",
"and",
"lists",
"Note",
":",
"will",
"clobber",
"non",
"dict",
"keys",
"if",
"b",
"has",
"a",
"dict",
"with",
"same",
"key",
"options",
":",
"copy",
":",
"deepcopy",
"instead",
... | train | https://github.com/20c/munge/blob/e20fef8c24e48d4b0a5c387820fbb2b7bebb0af0/munge/util.py#L6-L37 |
goshuirc/irc | girc/events.py | ctcp_unpack_message | def ctcp_unpack_message(info):
"""Given a an input message (privmsg/pubmsg/notice), return events."""
verb = info['verb']
message = info['params'][1]
# NOTE: full CTCP dequoting and unpacking is not done here, only a subset
# this is because doing the full thing breaks legitimate messages
# ... | python | def ctcp_unpack_message(info):
"""Given a an input message (privmsg/pubmsg/notice), return events."""
verb = info['verb']
message = info['params'][1]
# NOTE: full CTCP dequoting and unpacking is not done here, only a subset
# this is because doing the full thing breaks legitimate messages
# ... | [
"def",
"ctcp_unpack_message",
"(",
"info",
")",
":",
"verb",
"=",
"info",
"[",
"'verb'",
"]",
"message",
"=",
"info",
"[",
"'params'",
"]",
"[",
"1",
"]",
"# NOTE: full CTCP dequoting and unpacking is not done here, only a subset",
"# this is because doing the full thin... | Given a an input message (privmsg/pubmsg/notice), return events. | [
"Given",
"a",
"an",
"input",
"message",
"(",
"privmsg",
"/",
"pubmsg",
"/",
"notice",
")",
"return",
"events",
"."
] | train | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/events.py#L101-L183 |
goshuirc/irc | girc/events.py | message_to_event | def message_to_event(direction, message):
"""Prepare an ``RFC1459Message`` for event dispatch.
We do this because we have to handle special things as well, such as CTCP
and deconstructing verbs properly.
"""
server = message.server
# change numerics into nice names
if message.verb in numer... | python | def message_to_event(direction, message):
"""Prepare an ``RFC1459Message`` for event dispatch.
We do this because we have to handle special things as well, such as CTCP
and deconstructing verbs properly.
"""
server = message.server
# change numerics into nice names
if message.verb in numer... | [
"def",
"message_to_event",
"(",
"direction",
",",
"message",
")",
":",
"server",
"=",
"message",
".",
"server",
"# change numerics into nice names",
"if",
"message",
".",
"verb",
"in",
"numerics",
":",
"message",
".",
"verb",
"=",
"numerics",
"[",
"message",
"... | Prepare an ``RFC1459Message`` for event dispatch.
We do this because we have to handle special things as well, such as CTCP
and deconstructing verbs properly. | [
"Prepare",
"an",
"RFC1459Message",
"for",
"event",
"dispatch",
"."
] | train | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/events.py#L186-L386 |
PMBio/limix-backup | limix/stats/power.py | power | def power(maf=0.5,beta=0.1, N=100, cutoff=5e-8):
"""
estimate power for a given allele frequency, effect size beta and sample size N
Assumption:
z-score = beta_ML distributed as p(0) = N(0,1.0(maf*(1-maf)*N))) under the null hypothesis
the actual beta_ML is distributed as p(alt) = N( beta , 1.0/(maf*(1-maf)N) )... | python | def power(maf=0.5,beta=0.1, N=100, cutoff=5e-8):
"""
estimate power for a given allele frequency, effect size beta and sample size N
Assumption:
z-score = beta_ML distributed as p(0) = N(0,1.0(maf*(1-maf)*N))) under the null hypothesis
the actual beta_ML is distributed as p(alt) = N( beta , 1.0/(maf*(1-maf)N) )... | [
"def",
"power",
"(",
"maf",
"=",
"0.5",
",",
"beta",
"=",
"0.1",
",",
"N",
"=",
"100",
",",
"cutoff",
"=",
"5e-8",
")",
":",
"\"\"\"\n\tstd(snp)=sqrt(2.0*maf*(1-maf)) \n\tpower = \\int \n\n\tbeta_ML = (snp^T*snp)^{-1}*snp^T*Y = cov(snp,Y)/var(snp) \n\tE[beta_ML]\t= (snp^T*s... | estimate power for a given allele frequency, effect size beta and sample size N
Assumption:
z-score = beta_ML distributed as p(0) = N(0,1.0(maf*(1-maf)*N))) under the null hypothesis
the actual beta_ML is distributed as p(alt) = N( beta , 1.0/(maf*(1-maf)N) )
Arguments:
maf: minor allele frequency of the ... | [
"estimate",
"power",
"for",
"a",
"given",
"allele",
"frequency",
"effect",
"size",
"beta",
"and",
"sample",
"size",
"N"
] | train | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/stats/power.py#L18-L62 |
jic-dtool/dtool-irods | dtool_irods/__init__.py | CommandWrapper._call_cmd_line | def _call_cmd_line(self):
"""Run the command line tool."""
try:
logging.info("Calling Popen with: {}".format(self.args))
p = Popen(self.args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
except OSError:
raise(RuntimeError("No such command found in PATH"))
# ... | python | def _call_cmd_line(self):
"""Run the command line tool."""
try:
logging.info("Calling Popen with: {}".format(self.args))
p = Popen(self.args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
except OSError:
raise(RuntimeError("No such command found in PATH"))
# ... | [
"def",
"_call_cmd_line",
"(",
"self",
")",
":",
"try",
":",
"logging",
".",
"info",
"(",
"\"Calling Popen with: {}\"",
".",
"format",
"(",
"self",
".",
"args",
")",
")",
"p",
"=",
"Popen",
"(",
"self",
".",
"args",
",",
"stdin",
"=",
"PIPE",
",",
"st... | Run the command line tool. | [
"Run",
"the",
"command",
"line",
"tool",
"."
] | train | https://github.com/jic-dtool/dtool-irods/blob/65da4ebc7f71dc04e93698c154fdaa89064e17e8/dtool_irods/__init__.py#L24-L38 |
basilfx/flask-daapserver | examples/SoundcloudServer.py | download_file | def download_file(url, file_name):
"""
Helper for downloading a remote file to disk.
"""
logger.info("Downloading URL: %s", url)
file_size = 0
if not os.path.isfile(file_name):
response = requests.get(url, stream=True)
with open(file_name, "wb") as fp:
if not respo... | python | def download_file(url, file_name):
"""
Helper for downloading a remote file to disk.
"""
logger.info("Downloading URL: %s", url)
file_size = 0
if not os.path.isfile(file_name):
response = requests.get(url, stream=True)
with open(file_name, "wb") as fp:
if not respo... | [
"def",
"download_file",
"(",
"url",
",",
"file_name",
")",
":",
"logger",
".",
"info",
"(",
"\"Downloading URL: %s\"",
",",
"url",
")",
"file_size",
"=",
"0",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file_name",
")",
":",
"response",
"=",
"... | Helper for downloading a remote file to disk. | [
"Helper",
"for",
"downloading",
"a",
"remote",
"file",
"to",
"disk",
"."
] | train | https://github.com/basilfx/flask-daapserver/blob/ca595fcbc5b657cba826eccd3be5cebba0a1db0e/examples/SoundcloudServer.py#L129-L153 |
StyXman/ayrton | ayrton/parser/astcompiler/tools/asdl.py | check | def check(mod):
"""Check the parsed ASDL tree for correctness.
Return True if success. For failure, the errors are printed out and False
is returned.
"""
v = Check()
v.visit(mod)
for t in v.types:
if t not in mod.types and not t in builtin_types:
v.errors += 1
... | python | def check(mod):
"""Check the parsed ASDL tree for correctness.
Return True if success. For failure, the errors are printed out and False
is returned.
"""
v = Check()
v.visit(mod)
for t in v.types:
if t not in mod.types and not t in builtin_types:
v.errors += 1
... | [
"def",
"check",
"(",
"mod",
")",
":",
"v",
"=",
"Check",
"(",
")",
"v",
".",
"visit",
"(",
"mod",
")",
"for",
"t",
"in",
"v",
".",
"types",
":",
"if",
"t",
"not",
"in",
"mod",
".",
"types",
"and",
"not",
"t",
"in",
"builtin_types",
":",
"v",
... | Check the parsed ASDL tree for correctness.
Return True if success. For failure, the errors are printed out and False
is returned. | [
"Check",
"the",
"parsed",
"ASDL",
"tree",
"for",
"correctness",
"."
] | train | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/astcompiler/tools/asdl.py#L177-L191 |
StyXman/ayrton | ayrton/parser/astcompiler/tools/asdl.py | parse | def parse(filename):
"""Parse ASDL from the given file and return a Module node describing it."""
with open(filename) as f:
parser = ASDLParser()
return parser.parse(f.read()) | python | def parse(filename):
"""Parse ASDL from the given file and return a Module node describing it."""
with open(filename) as f:
parser = ASDLParser()
return parser.parse(f.read()) | [
"def",
"parse",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"parser",
"=",
"ASDLParser",
"(",
")",
"return",
"parser",
".",
"parse",
"(",
"f",
".",
"read",
"(",
")",
")"
] | Parse ASDL from the given file and return a Module node describing it. | [
"Parse",
"ASDL",
"from",
"the",
"given",
"file",
"and",
"return",
"a",
"Module",
"node",
"describing",
"it",
"."
] | train | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/astcompiler/tools/asdl.py#L196-L200 |
StyXman/ayrton | ayrton/parser/astcompiler/tools/asdl.py | tokenize_asdl | def tokenize_asdl(buf):
"""Tokenize the given buffer. Yield Token objects."""
for lineno, line in enumerate(buf.splitlines(), 1):
for m in re.finditer(r'\s*(\w+|--.*|.)', line.strip()):
c = m.group(1)
if c[0].isalpha():
# Some kind of identifier
if... | python | def tokenize_asdl(buf):
"""Tokenize the given buffer. Yield Token objects."""
for lineno, line in enumerate(buf.splitlines(), 1):
for m in re.finditer(r'\s*(\w+|--.*|.)', line.strip()):
c = m.group(1)
if c[0].isalpha():
# Some kind of identifier
if... | [
"def",
"tokenize_asdl",
"(",
"buf",
")",
":",
"for",
"lineno",
",",
"line",
"in",
"enumerate",
"(",
"buf",
".",
"splitlines",
"(",
")",
",",
"1",
")",
":",
"for",
"m",
"in",
"re",
".",
"finditer",
"(",
"r'\\s*(\\w+|--.*|.)'",
",",
"line",
".",
"strip... | Tokenize the given buffer. Yield Token objects. | [
"Tokenize",
"the",
"given",
"buffer",
".",
"Yield",
"Token",
"objects",
"."
] | train | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/astcompiler/tools/asdl.py#L222-L242 |
StyXman/ayrton | ayrton/parser/astcompiler/tools/asdl.py | ASDLParser.parse | def parse(self, buf):
"""Parse the ASDL in the buffer and return an AST with a Module root.
"""
self._tokenizer = tokenize_asdl(buf)
self._advance()
return self._parse_module() | python | def parse(self, buf):
"""Parse the ASDL in the buffer and return an AST with a Module root.
"""
self._tokenizer = tokenize_asdl(buf)
self._advance()
return self._parse_module() | [
"def",
"parse",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"_tokenizer",
"=",
"tokenize_asdl",
"(",
"buf",
")",
"self",
".",
"_advance",
"(",
")",
"return",
"self",
".",
"_parse_module",
"(",
")"
] | Parse the ASDL in the buffer and return an AST with a Module root. | [
"Parse",
"the",
"ASDL",
"in",
"the",
"buffer",
"and",
"return",
"an",
"AST",
"with",
"a",
"Module",
"root",
"."
] | train | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/astcompiler/tools/asdl.py#L255-L260 |
StyXman/ayrton | ayrton/parser/astcompiler/tools/asdl.py | ASDLParser._advance | def _advance(self):
""" Return the value of the current token and read the next one into
self.cur_token.
"""
cur_val = None if self.cur_token is None else self.cur_token.value
try:
self.cur_token = next(self._tokenizer)
except StopIteration:
se... | python | def _advance(self):
""" Return the value of the current token and read the next one into
self.cur_token.
"""
cur_val = None if self.cur_token is None else self.cur_token.value
try:
self.cur_token = next(self._tokenizer)
except StopIteration:
se... | [
"def",
"_advance",
"(",
"self",
")",
":",
"cur_val",
"=",
"None",
"if",
"self",
".",
"cur_token",
"is",
"None",
"else",
"self",
".",
"cur_token",
".",
"value",
"try",
":",
"self",
".",
"cur_token",
"=",
"next",
"(",
"self",
".",
"_tokenizer",
")",
"e... | Return the value of the current token and read the next one into
self.cur_token. | [
"Return",
"the",
"value",
"of",
"the",
"current",
"token",
"and",
"read",
"the",
"next",
"one",
"into",
"self",
".",
"cur_token",
"."
] | train | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/astcompiler/tools/asdl.py#L342-L351 |
StyXman/ayrton | ayrton/parser/astcompiler/tools/asdl.py | ASDLParser._match | def _match(self, kind):
"""The 'match' primitive of RD parsers.
* Verifies that the current token is of the given kind (kind can
be a tuple, in which the kind must match one of its members).
* Returns the value of the current token
* Reads in the next token
"""
... | python | def _match(self, kind):
"""The 'match' primitive of RD parsers.
* Verifies that the current token is of the given kind (kind can
be a tuple, in which the kind must match one of its members).
* Returns the value of the current token
* Reads in the next token
"""
... | [
"def",
"_match",
"(",
"self",
",",
"kind",
")",
":",
"if",
"(",
"isinstance",
"(",
"kind",
",",
"tuple",
")",
"and",
"self",
".",
"cur_token",
".",
"kind",
"in",
"kind",
"or",
"self",
".",
"cur_token",
".",
"kind",
"==",
"kind",
")",
":",
"value",
... | The 'match' primitive of RD parsers.
* Verifies that the current token is of the given kind (kind can
be a tuple, in which the kind must match one of its members).
* Returns the value of the current token
* Reads in the next token | [
"The",
"match",
"primitive",
"of",
"RD",
"parsers",
"."
] | train | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/astcompiler/tools/asdl.py#L355-L372 |
jhermann/rudiments | src/rudiments/humanize.py | bytes2iec | def bytes2iec(size, compact=False):
""" Convert a size value in bytes to its equivalent in IEC notation.
See `<http://physics.nist.gov/cuu/Units/binary.html>`_.
Parameters:
size (int): Number of bytes.
compact (bool): If ``True``, the result contains no spaces.
Ret... | python | def bytes2iec(size, compact=False):
""" Convert a size value in bytes to its equivalent in IEC notation.
See `<http://physics.nist.gov/cuu/Units/binary.html>`_.
Parameters:
size (int): Number of bytes.
compact (bool): If ``True``, the result contains no spaces.
Ret... | [
"def",
"bytes2iec",
"(",
"size",
",",
"compact",
"=",
"False",
")",
":",
"postfn",
"=",
"lambda",
"text",
":",
"text",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"if",
"compact",
"else",
"text",
"if",
"size",
"<",
"0",
":",
"raise",
"ValueError",
... | Convert a size value in bytes to its equivalent in IEC notation.
See `<http://physics.nist.gov/cuu/Units/binary.html>`_.
Parameters:
size (int): Number of bytes.
compact (bool): If ``True``, the result contains no spaces.
Return:
String representation of ``... | [
"Convert",
"a",
"size",
"value",
"in",
"bytes",
"to",
"its",
"equivalent",
"in",
"IEC",
"notation",
"."
] | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/humanize.py#L24-L51 |
jhermann/rudiments | src/rudiments/humanize.py | iec2bytes | def iec2bytes(size_spec, only_positive=True):
""" Convert a size specification, optionally containing a scaling
unit in IEC notation, to a number of bytes.
Parameters:
size_spec (str): Number, optionally followed by a unit.
only_positive (bool): Allow only positive values?
... | python | def iec2bytes(size_spec, only_positive=True):
""" Convert a size specification, optionally containing a scaling
unit in IEC notation, to a number of bytes.
Parameters:
size_spec (str): Number, optionally followed by a unit.
only_positive (bool): Allow only positive values?
... | [
"def",
"iec2bytes",
"(",
"size_spec",
",",
"only_positive",
"=",
"True",
")",
":",
"scale",
"=",
"1",
"try",
":",
"size",
"=",
"int",
"(",
"0",
"+",
"size_spec",
")",
"# return numeric values as-is",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",... | Convert a size specification, optionally containing a scaling
unit in IEC notation, to a number of bytes.
Parameters:
size_spec (str): Number, optionally followed by a unit.
only_positive (bool): Allow only positive values?
Return:
Numeric bytes size.
... | [
"Convert",
"a",
"size",
"specification",
"optionally",
"containing",
"a",
"scaling",
"unit",
"in",
"IEC",
"notation",
"to",
"a",
"number",
"of",
"bytes",
"."
] | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/humanize.py#L54-L99 |
jhermann/rudiments | src/rudiments/humanize.py | merge_adjacent | def merge_adjacent(numbers, indicator='..', base=0):
""" Merge adjacent numbers in an iterable of numbers.
Parameters:
numbers (list): List of integers or numeric strings.
indicator (str): Delimiter to indicate generated ranges.
base (int): Passed to the `int()` conversi... | python | def merge_adjacent(numbers, indicator='..', base=0):
""" Merge adjacent numbers in an iterable of numbers.
Parameters:
numbers (list): List of integers or numeric strings.
indicator (str): Delimiter to indicate generated ranges.
base (int): Passed to the `int()` conversi... | [
"def",
"merge_adjacent",
"(",
"numbers",
",",
"indicator",
"=",
"'..'",
",",
"base",
"=",
"0",
")",
":",
"integers",
"=",
"list",
"(",
"sorted",
"(",
"[",
"(",
"int",
"(",
"\"%s\"",
"%",
"i",
",",
"base",
")",
",",
"i",
")",
"for",
"i",
"in",
"... | Merge adjacent numbers in an iterable of numbers.
Parameters:
numbers (list): List of integers or numeric strings.
indicator (str): Delimiter to indicate generated ranges.
base (int): Passed to the `int()` conversion when comparing numbers.
Return:
list ... | [
"Merge",
"adjacent",
"numbers",
"in",
"an",
"iterable",
"of",
"numbers",
"."
] | train | https://github.com/jhermann/rudiments/blob/028ec7237946115c7b18e50557cbc5f6b824653e/src/rudiments/humanize.py#L102-L125 |
wilzbach/smarkov | smarkov/hmm.py | HMM._compute_emissions | def _compute_emissions(self, corpus, order=1):
""" Computes the emissions and transitions probabilities of a corpus
based on word types
Args:
corpus: the given corpus (a corpus_entry needs to be iterable)
order: the maximal Markov chain order
Computes:
... | python | def _compute_emissions(self, corpus, order=1):
""" Computes the emissions and transitions probabilities of a corpus
based on word types
Args:
corpus: the given corpus (a corpus_entry needs to be iterable)
order: the maximal Markov chain order
Computes:
... | [
"def",
"_compute_emissions",
"(",
"self",
",",
"corpus",
",",
"order",
"=",
"1",
")",
":",
"self",
".",
"emissions",
"=",
"defaultdict",
"(",
"lambda",
":",
"defaultdict",
"(",
"int",
")",
")",
"self",
".",
"transitions_hmm",
"=",
"defaultdict",
"(",
"la... | Computes the emissions and transitions probabilities of a corpus
based on word types
Args:
corpus: the given corpus (a corpus_entry needs to be iterable)
order: the maximal Markov chain order
Computes:
self.emissions: Probabilities to emit word (token_valu... | [
"Computes",
"the",
"emissions",
"and",
"transitions",
"probabilities",
"of",
"a",
"corpus",
"based",
"on",
"word",
"types",
"Args",
":",
"corpus",
":",
"the",
"given",
"corpus",
"(",
"a",
"corpus_entry",
"needs",
"to",
"be",
"iterable",
")",
"order",
":",
... | train | https://github.com/wilzbach/smarkov/blob/c98c08cc432e18c5c87fb9a6e013b1b8eaa54d37/smarkov/hmm.py#L29-L72 |
wilzbach/smarkov | smarkov/hmm.py | HMM.generate_text | def generate_text(self, generation_type='markov'):
""" Generates sentences from a given corpus
Args:
generation_type: 'markov' | 'hmm' | 'hmm_past'
Returns:
Properly formatted string of generated sentences
"""
assert generation_type in ['markov', 'hmm', 'h... | python | def generate_text(self, generation_type='markov'):
""" Generates sentences from a given corpus
Args:
generation_type: 'markov' | 'hmm' | 'hmm_past'
Returns:
Properly formatted string of generated sentences
"""
assert generation_type in ['markov', 'hmm', 'h... | [
"def",
"generate_text",
"(",
"self",
",",
"generation_type",
"=",
"'markov'",
")",
":",
"assert",
"generation_type",
"in",
"[",
"'markov'",
",",
"'hmm'",
",",
"'hmm_past'",
"]",
"if",
"generation_type",
"==",
"\"markov\"",
":",
"return",
"self",
".",
"_text_ge... | Generates sentences from a given corpus
Args:
generation_type: 'markov' | 'hmm' | 'hmm_past'
Returns:
Properly formatted string of generated sentences | [
"Generates",
"sentences",
"from",
"a",
"given",
"corpus",
"Args",
":",
"generation_type",
":",
"markov",
"|",
"hmm",
"|",
"hmm_past",
"Returns",
":",
"Properly",
"formatted",
"string",
"of",
"generated",
"sentences"
] | train | https://github.com/wilzbach/smarkov/blob/c98c08cc432e18c5c87fb9a6e013b1b8eaa54d37/smarkov/hmm.py#L74-L87 |
wilzbach/smarkov | smarkov/hmm.py | HMM._emitHMM | def _emitHMM(self, token_type, past_states, past_emissions):
""" emits a word based on previous tokens """
assert token_type in self.emissions
return utils.weighted_choice(self.emissions[token_type].items()) | python | def _emitHMM(self, token_type, past_states, past_emissions):
""" emits a word based on previous tokens """
assert token_type in self.emissions
return utils.weighted_choice(self.emissions[token_type].items()) | [
"def",
"_emitHMM",
"(",
"self",
",",
"token_type",
",",
"past_states",
",",
"past_emissions",
")",
":",
"assert",
"token_type",
"in",
"self",
".",
"emissions",
"return",
"utils",
".",
"weighted_choice",
"(",
"self",
".",
"emissions",
"[",
"token_type",
"]",
... | emits a word based on previous tokens | [
"emits",
"a",
"word",
"based",
"on",
"previous",
"tokens"
] | train | https://github.com/wilzbach/smarkov/blob/c98c08cc432e18c5c87fb9a6e013b1b8eaa54d37/smarkov/hmm.py#L93-L96 |
wilzbach/smarkov | smarkov/hmm.py | HMM._emitHMM_with_past | def _emitHMM_with_past(self, token_type, past_states, past_emissions):
""" emits a word based on previous states (=token) and previous emissions (=words)
The states and emissions are weighted according to their defined probabilities
self.prob_hmm_states and self.prob_hmm_emissions"""
... | python | def _emitHMM_with_past(self, token_type, past_states, past_emissions):
""" emits a word based on previous states (=token) and previous emissions (=words)
The states and emissions are weighted according to their defined probabilities
self.prob_hmm_states and self.prob_hmm_emissions"""
... | [
"def",
"_emitHMM_with_past",
"(",
"self",
",",
"token_type",
",",
"past_states",
",",
"past_emissions",
")",
":",
"assert",
"token_type",
"in",
"self",
".",
"emissions",
"states_items",
"=",
"[",
"(",
"x",
"[",
"0",
"]",
",",
"x",
"[",
"1",
"]",
"*",
"... | emits a word based on previous states (=token) and previous emissions (=words)
The states and emissions are weighted according to their defined probabilities
self.prob_hmm_states and self.prob_hmm_emissions | [
"emits",
"a",
"word",
"based",
"on",
"previous",
"states",
"(",
"=",
"token",
")",
"and",
"previous",
"emissions",
"(",
"=",
"words",
")",
"The",
"states",
"and",
"emissions",
"are",
"weighted",
"according",
"to",
"their",
"defined",
"probabilities",
"self",... | train | https://github.com/wilzbach/smarkov/blob/c98c08cc432e18c5c87fb9a6e013b1b8eaa54d37/smarkov/hmm.py#L98-L110 |
geopython/geolinks | geolinks/__init__.py | inurl | def inurl(needles, haystack, position='any'):
"""convenience function to make string.find return bool"""
count = 0
# lowercase everything to do case-insensitive search
haystack2 = haystack.lower()
for needle in needles:
needle2 = needle.lower()
if position == 'any':
if... | python | def inurl(needles, haystack, position='any'):
"""convenience function to make string.find return bool"""
count = 0
# lowercase everything to do case-insensitive search
haystack2 = haystack.lower()
for needle in needles:
needle2 = needle.lower()
if position == 'any':
if... | [
"def",
"inurl",
"(",
"needles",
",",
"haystack",
",",
"position",
"=",
"'any'",
")",
":",
"count",
"=",
"0",
"# lowercase everything to do case-insensitive search",
"haystack2",
"=",
"haystack",
".",
"lower",
"(",
")",
"for",
"needle",
"in",
"needles",
":",
"n... | convenience function to make string.find return bool | [
"convenience",
"function",
"to",
"make",
"string",
".",
"find",
"return",
"bool"
] | train | https://github.com/geopython/geolinks/blob/134608c81e6b31323a17d05fb5e62e3119de81da/geolinks/__init__.py#L37-L60 |
geopython/geolinks | geolinks/__init__.py | sniff_link | def sniff_link(url):
"""performs basic heuristics to detect what the URL is"""
protocol = None
link = url.strip()
# heuristics begin
if inurl(['service=CSW', 'request=GetRecords'], link):
protocol = 'OGC:CSW'
elif inurl(['service=SOS', 'request=GetObservation'], link):
protocol... | python | def sniff_link(url):
"""performs basic heuristics to detect what the URL is"""
protocol = None
link = url.strip()
# heuristics begin
if inurl(['service=CSW', 'request=GetRecords'], link):
protocol = 'OGC:CSW'
elif inurl(['service=SOS', 'request=GetObservation'], link):
protocol... | [
"def",
"sniff_link",
"(",
"url",
")",
":",
"protocol",
"=",
"None",
"link",
"=",
"url",
".",
"strip",
"(",
")",
"# heuristics begin",
"if",
"inurl",
"(",
"[",
"'service=CSW'",
",",
"'request=GetRecords'",
"]",
",",
"link",
")",
":",
"protocol",
"=",
"'OG... | performs basic heuristics to detect what the URL is | [
"performs",
"basic",
"heuristics",
"to",
"detect",
"what",
"the",
"URL",
"is"
] | train | https://github.com/geopython/geolinks/blob/134608c81e6b31323a17d05fb5e62e3119de81da/geolinks/__init__.py#L63-L110 |
jf-parent/brome | brome/runner/localhost_instance.py | LocalhostInstance.startup | def startup(self):
"""Start the instance
This is mainly use to start the proxy
"""
self.runner.info_log("Startup")
if self.browser_config.config.get('enable_proxy'):
self.start_proxy() | python | def startup(self):
"""Start the instance
This is mainly use to start the proxy
"""
self.runner.info_log("Startup")
if self.browser_config.config.get('enable_proxy'):
self.start_proxy() | [
"def",
"startup",
"(",
"self",
")",
":",
"self",
".",
"runner",
".",
"info_log",
"(",
"\"Startup\"",
")",
"if",
"self",
".",
"browser_config",
".",
"config",
".",
"get",
"(",
"'enable_proxy'",
")",
":",
"self",
".",
"start_proxy",
"(",
")"
] | Start the instance
This is mainly use to start the proxy | [
"Start",
"the",
"instance"
] | train | https://github.com/jf-parent/brome/blob/784f45d96b83b703dd2181cb59ca8ea777c2510e/brome/runner/localhost_instance.py#L29-L37 |
jf-parent/brome | brome/runner/localhost_instance.py | LocalhostInstance.tear_down | def tear_down(self):
"""Tear down the instance
This is mainly use to stop the proxy
"""
self.runner.info_log("Tear down")
if self.browser_config.config.get('enable_proxy'):
self.stop_proxy() | python | def tear_down(self):
"""Tear down the instance
This is mainly use to stop the proxy
"""
self.runner.info_log("Tear down")
if self.browser_config.config.get('enable_proxy'):
self.stop_proxy() | [
"def",
"tear_down",
"(",
"self",
")",
":",
"self",
".",
"runner",
".",
"info_log",
"(",
"\"Tear down\"",
")",
"if",
"self",
".",
"browser_config",
".",
"config",
".",
"get",
"(",
"'enable_proxy'",
")",
":",
"self",
".",
"stop_proxy",
"(",
")"
] | Tear down the instance
This is mainly use to stop the proxy | [
"Tear",
"down",
"the",
"instance"
] | train | https://github.com/jf-parent/brome/blob/784f45d96b83b703dd2181cb59ca8ea777c2510e/brome/runner/localhost_instance.py#L39-L47 |
jf-parent/brome | brome/runner/localhost_instance.py | LocalhostInstance.execute_command | def execute_command(self, command):
"""Execute a command
Args:
command (str)
Returns:
process (object)
"""
self.runner.info_log("Executing command: %s" % command)
process = Popen(
command,
stdout=open(os.devnull,... | python | def execute_command(self, command):
"""Execute a command
Args:
command (str)
Returns:
process (object)
"""
self.runner.info_log("Executing command: %s" % command)
process = Popen(
command,
stdout=open(os.devnull,... | [
"def",
"execute_command",
"(",
"self",
",",
"command",
")",
":",
"self",
".",
"runner",
".",
"info_log",
"(",
"\"Executing command: %s\"",
"%",
"command",
")",
"process",
"=",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"open",
"(",
"os",
".",
"devnull",
... | Execute a command
Args:
command (str)
Returns:
process (object) | [
"Execute",
"a",
"command"
] | train | https://github.com/jf-parent/brome/blob/784f45d96b83b703dd2181cb59ca8ea777c2510e/brome/runner/localhost_instance.py#L49-L67 |
jf-parent/brome | brome/runner/localhost_instance.py | LocalhostInstance.start_proxy | def start_proxy(self, port=None):
"""Start the mitmproxy
"""
self.runner.info_log("Starting proxy...")
# Get a random port that is available
if not port:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('0.0.0.0', 0))
sock.... | python | def start_proxy(self, port=None):
"""Start the mitmproxy
"""
self.runner.info_log("Starting proxy...")
# Get a random port that is available
if not port:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('0.0.0.0', 0))
sock.... | [
"def",
"start_proxy",
"(",
"self",
",",
"port",
"=",
"None",
")",
":",
"self",
".",
"runner",
".",
"info_log",
"(",
"\"Starting proxy...\"",
")",
"# Get a random port that is available",
"if",
"not",
"port",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"s... | Start the mitmproxy | [
"Start",
"the",
"mitmproxy"
] | train | https://github.com/jf-parent/brome/blob/784f45d96b83b703dd2181cb59ca8ea777c2510e/brome/runner/localhost_instance.py#L69-L118 |
jf-parent/brome | brome/runner/localhost_instance.py | LocalhostInstance.stop_proxy | def stop_proxy(self):
"""Stop the mitmproxy
"""
self.runner.info_log("Stopping proxy...")
if hasattr(self, 'proxy_pid'):
try:
kill_by_pid(self.proxy_pid)
except psutil.NoSuchProcess:
pass | python | def stop_proxy(self):
"""Stop the mitmproxy
"""
self.runner.info_log("Stopping proxy...")
if hasattr(self, 'proxy_pid'):
try:
kill_by_pid(self.proxy_pid)
except psutil.NoSuchProcess:
pass | [
"def",
"stop_proxy",
"(",
"self",
")",
":",
"self",
".",
"runner",
".",
"info_log",
"(",
"\"Stopping proxy...\"",
")",
"if",
"hasattr",
"(",
"self",
",",
"'proxy_pid'",
")",
":",
"try",
":",
"kill_by_pid",
"(",
"self",
".",
"proxy_pid",
")",
"except",
"p... | Stop the mitmproxy | [
"Stop",
"the",
"mitmproxy"
] | train | https://github.com/jf-parent/brome/blob/784f45d96b83b703dd2181cb59ca8ea777c2510e/brome/runner/localhost_instance.py#L120-L130 |
ssato/python-anytemplate | anytemplate/engines/tenjin.py | Engine.renders_impl | def renders_impl(self, template_content, context,
at_encoding=anytemplate.compat.ENCODING, **kwargs):
"""
Render given template string and return the result.
:param template_content: Template content
:param context: A dict or dict-like object to instantiate given
... | python | def renders_impl(self, template_content, context,
at_encoding=anytemplate.compat.ENCODING, **kwargs):
"""
Render given template string and return the result.
:param template_content: Template content
:param context: A dict or dict-like object to instantiate given
... | [
"def",
"renders_impl",
"(",
"self",
",",
"template_content",
",",
"context",
",",
"at_encoding",
"=",
"anytemplate",
".",
"compat",
".",
"ENCODING",
",",
"*",
"*",
"kwargs",
")",
":",
"tmpdir",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"TMPDIR\"",
",... | Render given template string and return the result.
:param template_content: Template content
:param context: A dict or dict-like object to instantiate given
template file
:param at_encoding: Template encoding
:param kwargs: Keyword arguments such as:
- at_paths:... | [
"Render",
"given",
"template",
"string",
"and",
"return",
"the",
"result",
"."
] | train | https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/engines/tenjin.py#L84-L120 |
ssato/python-anytemplate | anytemplate/engines/tenjin.py | Engine.render_impl | def render_impl(self, template, context, at_paths=None, **kwargs):
"""
Render given template file and return the result.
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param at_paths: Template search... | python | def render_impl(self, template, context, at_paths=None, **kwargs):
"""
Render given template file and return the result.
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param at_paths: Template search... | [
"def",
"render_impl",
"(",
"self",
",",
"template",
",",
"context",
",",
"at_paths",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Override the path to pass it to tenjin.Engine.",
"if",
"at_paths",
"is",
"not",
"None",
":",
"paths",
"=",
"at_paths",
"+",
... | Render given template file and return the result.
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param at_paths: Template search paths
:param kwargs: Keyword arguments passed to the template engine to
... | [
"Render",
"given",
"template",
"file",
"and",
"return",
"the",
"result",
"."
] | train | https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/engines/tenjin.py#L122-L144 |
jhshi/wltrace | wltrace/utils.py | calc_padding | def calc_padding(fmt, align):
"""Calculate how many padding bytes needed for ``fmt`` to be aligned to
``align``.
Args:
fmt (str): :mod:`struct` format.
align (int): alignment (2, 4, 8, etc.)
Returns:
str: padding format (e.g., various number of 'x').
>>> calc_padding('b', ... | python | def calc_padding(fmt, align):
"""Calculate how many padding bytes needed for ``fmt`` to be aligned to
``align``.
Args:
fmt (str): :mod:`struct` format.
align (int): alignment (2, 4, 8, etc.)
Returns:
str: padding format (e.g., various number of 'x').
>>> calc_padding('b', ... | [
"def",
"calc_padding",
"(",
"fmt",
",",
"align",
")",
":",
"remain",
"=",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"%",
"align",
"if",
"remain",
"==",
"0",
":",
"return",
"\"\"",
"return",
"'x'",
"*",
"(",
"align",
"-",
"remain",
")"
] | Calculate how many padding bytes needed for ``fmt`` to be aligned to
``align``.
Args:
fmt (str): :mod:`struct` format.
align (int): alignment (2, 4, 8, etc.)
Returns:
str: padding format (e.g., various number of 'x').
>>> calc_padding('b', 2)
'x'
>>> calc_padding('b',... | [
"Calculate",
"how",
"many",
"padding",
"bytes",
"needed",
"for",
"fmt",
"to",
"be",
"aligned",
"to",
"align",
"."
] | train | https://github.com/jhshi/wltrace/blob/4c8441162f7cddd47375da2effc52c95b97dc81d/wltrace/utils.py#L23-L43 |
jhshi/wltrace | wltrace/utils.py | align_up | def align_up(offset, align):
"""Align ``offset`` up to ``align`` boundary.
Args:
offset (int): value to be aligned.
align (int): alignment boundary.
Returns:
int: aligned offset.
>>> align_up(3, 2)
4
>>> align_up(3, 1)
3
"""
remain = offset % align
if ... | python | def align_up(offset, align):
"""Align ``offset`` up to ``align`` boundary.
Args:
offset (int): value to be aligned.
align (int): alignment boundary.
Returns:
int: aligned offset.
>>> align_up(3, 2)
4
>>> align_up(3, 1)
3
"""
remain = offset % align
if ... | [
"def",
"align_up",
"(",
"offset",
",",
"align",
")",
":",
"remain",
"=",
"offset",
"%",
"align",
"if",
"remain",
"==",
"0",
":",
"return",
"offset",
"else",
":",
"return",
"offset",
"+",
"(",
"align",
"-",
"remain",
")"
] | Align ``offset`` up to ``align`` boundary.
Args:
offset (int): value to be aligned.
align (int): alignment boundary.
Returns:
int: aligned offset.
>>> align_up(3, 2)
4
>>> align_up(3, 1)
3 | [
"Align",
"offset",
"up",
"to",
"align",
"boundary",
"."
] | train | https://github.com/jhshi/wltrace/blob/4c8441162f7cddd47375da2effc52c95b97dc81d/wltrace/utils.py#L46-L66 |
jhshi/wltrace | wltrace/utils.py | bin_to_mac | def bin_to_mac(bin, size=6):
"""Convert 6 bytes into a MAC string.
Args:
bin (str): hex string of lenth 6.
Returns:
str: String representation of the MAC address in lower case.
Raises:
Exception: if ``len(bin)`` is not 6.
"""
if len(bin) != size:
raise Exceptio... | python | def bin_to_mac(bin, size=6):
"""Convert 6 bytes into a MAC string.
Args:
bin (str): hex string of lenth 6.
Returns:
str: String representation of the MAC address in lower case.
Raises:
Exception: if ``len(bin)`` is not 6.
"""
if len(bin) != size:
raise Exceptio... | [
"def",
"bin_to_mac",
"(",
"bin",
",",
"size",
"=",
"6",
")",
":",
"if",
"len",
"(",
"bin",
")",
"!=",
"size",
":",
"raise",
"Exception",
"(",
"\"Invalid MAC address: %s\"",
"%",
"(",
"bin",
")",
")",
"return",
"':'",
".",
"join",
"(",
"[",
"binascii"... | Convert 6 bytes into a MAC string.
Args:
bin (str): hex string of lenth 6.
Returns:
str: String representation of the MAC address in lower case.
Raises:
Exception: if ``len(bin)`` is not 6. | [
"Convert",
"6",
"bytes",
"into",
"a",
"MAC",
"string",
"."
] | train | https://github.com/jhshi/wltrace/blob/4c8441162f7cddd47375da2effc52c95b97dc81d/wltrace/utils.py#L100-L114 |
TAPPGuild/sqlalchemy-models | sqlalchemy_models/exchange.py | LimitOrder.load_commodities | def load_commodities(self):
"""
Load the commodities for Amounts in this object.
"""
base, quote = self.market.split("_")
if isinstance(self.price, Amount):
self.price = Amount("{0:.8f} {1}".format(self.price.to_double(), quote))
else:
self.price =... | python | def load_commodities(self):
"""
Load the commodities for Amounts in this object.
"""
base, quote = self.market.split("_")
if isinstance(self.price, Amount):
self.price = Amount("{0:.8f} {1}".format(self.price.to_double(), quote))
else:
self.price =... | [
"def",
"load_commodities",
"(",
"self",
")",
":",
"base",
",",
"quote",
"=",
"self",
".",
"market",
".",
"split",
"(",
"\"_\"",
")",
"if",
"isinstance",
"(",
"self",
".",
"price",
",",
"Amount",
")",
":",
"self",
".",
"price",
"=",
"Amount",
"(",
"... | Load the commodities for Amounts in this object. | [
"Load",
"the",
"commodities",
"for",
"Amounts",
"in",
"this",
"object",
"."
] | train | https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/exchange.py#L58-L74 |
TAPPGuild/sqlalchemy-models | sqlalchemy_models/exchange.py | Ticker.load_commodities | def load_commodities(self):
"""
Load the commodities for Amounts in this object.
"""
base, quote = self.market.split("_")
if isinstance(self.bid, Amount):
self.bid = Amount("{0:.8f} {1}".format(self.bid.to_double(), quote))
else:
self.bid = Amount(... | python | def load_commodities(self):
"""
Load the commodities for Amounts in this object.
"""
base, quote = self.market.split("_")
if isinstance(self.bid, Amount):
self.bid = Amount("{0:.8f} {1}".format(self.bid.to_double(), quote))
else:
self.bid = Amount(... | [
"def",
"load_commodities",
"(",
"self",
")",
":",
"base",
",",
"quote",
"=",
"self",
".",
"market",
".",
"split",
"(",
"\"_\"",
")",
"if",
"isinstance",
"(",
"self",
".",
"bid",
",",
"Amount",
")",
":",
"self",
".",
"bid",
"=",
"Amount",
"(",
"\"{0... | Load the commodities for Amounts in this object. | [
"Load",
"the",
"commodities",
"for",
"Amounts",
"in",
"this",
"object",
"."
] | train | https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/exchange.py#L108-L136 |
TAPPGuild/sqlalchemy-models | sqlalchemy_models/exchange.py | Trade.load_commodities | def load_commodities(self):
"""
Load the commodities for Amounts in this object.
"""
base, quote = self.market.split("_")
if isinstance(self.price, Amount):
self.price = Amount("{0:.8f} {1}".format(self.price.to_double(), quote))
else:
self.price =... | python | def load_commodities(self):
"""
Load the commodities for Amounts in this object.
"""
base, quote = self.market.split("_")
if isinstance(self.price, Amount):
self.price = Amount("{0:.8f} {1}".format(self.price.to_double(), quote))
else:
self.price =... | [
"def",
"load_commodities",
"(",
"self",
")",
":",
"base",
",",
"quote",
"=",
"self",
".",
"market",
".",
"split",
"(",
"\"_\"",
")",
"if",
"isinstance",
"(",
"self",
".",
"price",
",",
"Amount",
")",
":",
"self",
".",
"price",
"=",
"Amount",
"(",
"... | Load the commodities for Amounts in this object. | [
"Load",
"the",
"commodities",
"for",
"Amounts",
"in",
"this",
"object",
"."
] | train | https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/exchange.py#L188-L205 |
renskiy/django-cache | djangocache.py | cache_page | def cache_page(**kwargs):
"""
This decorator is similar to `django.views.decorators.cache.cache_page`
"""
cache_timeout = kwargs.pop('cache_timeout', None)
key_prefix = kwargs.pop('key_prefix', None)
cache_min_age = kwargs.pop('cache_min_age', None)
decorator = decorators.decorator_from_midd... | python | def cache_page(**kwargs):
"""
This decorator is similar to `django.views.decorators.cache.cache_page`
"""
cache_timeout = kwargs.pop('cache_timeout', None)
key_prefix = kwargs.pop('key_prefix', None)
cache_min_age = kwargs.pop('cache_min_age', None)
decorator = decorators.decorator_from_midd... | [
"def",
"cache_page",
"(",
"*",
"*",
"kwargs",
")",
":",
"cache_timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'cache_timeout'",
",",
"None",
")",
"key_prefix",
"=",
"kwargs",
".",
"pop",
"(",
"'key_prefix'",
",",
"None",
")",
"cache_min_age",
"=",
"kwargs",
... | This decorator is similar to `django.views.decorators.cache.cache_page` | [
"This",
"decorator",
"is",
"similar",
"to",
"django",
".",
"views",
".",
"decorators",
".",
"cache",
".",
"cache_page"
] | train | https://github.com/renskiy/django-cache/blob/8883e0f9f48f0d9473c49442475becff08101e2c/djangocache.py#L17-L30 |
vreon/figment | figment/entity.py | Entity.tell | def tell(self, message):
"""Send text to this entity."""
if self.hearing:
self.zone.send_message(self.id, json.dumps(message)) | python | def tell(self, message):
"""Send text to this entity."""
if self.hearing:
self.zone.send_message(self.id, json.dumps(message)) | [
"def",
"tell",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"hearing",
":",
"self",
".",
"zone",
".",
"send_message",
"(",
"self",
".",
"id",
",",
"json",
".",
"dumps",
"(",
"message",
")",
")"
] | Send text to this entity. | [
"Send",
"text",
"to",
"this",
"entity",
"."
] | train | https://github.com/vreon/figment/blob/78248b53d06bc525004a0f5b19c45afd1536083c/figment/entity.py#L140-L143 |
KelSolaar/Foundations | foundations/environment.py | get_system_application_data_directory | def get_system_application_data_directory():
"""
Returns the system Application data directory.
Examples directories::
- 'C:\\Users\\$USER\\AppData\\Roaming' on Windows 7.
- 'C:\\Documents and Settings\\$USER\\Application Data' on Windows XP.
- '/Users/$USER/Library/Preferences' on... | python | def get_system_application_data_directory():
"""
Returns the system Application data directory.
Examples directories::
- 'C:\\Users\\$USER\\AppData\\Roaming' on Windows 7.
- 'C:\\Documents and Settings\\$USER\\Application Data' on Windows XP.
- '/Users/$USER/Library/Preferences' on... | [
"def",
"get_system_application_data_directory",
"(",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"\"Windows\"",
"or",
"platform",
".",
"system",
"(",
")",
"==",
"\"Microsoft\"",
":",
"environment",
"=",
"Environment",
"(",
"\"APPDATA\"",
")",
"r... | Returns the system Application data directory.
Examples directories::
- 'C:\\Users\\$USER\\AppData\\Roaming' on Windows 7.
- 'C:\\Documents and Settings\\$USER\\Application Data' on Windows XP.
- '/Users/$USER/Library/Preferences' on Mac Os X.
- '/home/$USER' on Linux.
:return... | [
"Returns",
"the",
"system",
"Application",
"data",
"directory",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/environment.py#L237-L260 |
KelSolaar/Foundations | foundations/environment.py | get_user_application_data_directory | def get_user_application_data_directory():
"""
| Returns the user Application directory.
| The difference between :func:`get_user_application_data_directory`
and :func:`get_system_application_data_directory` definitions is that :func:`get_user_application_data_directory` definition
will appe... | python | def get_user_application_data_directory():
"""
| Returns the user Application directory.
| The difference between :func:`get_user_application_data_directory`
and :func:`get_system_application_data_directory` definitions is that :func:`get_user_application_data_directory` definition
will appe... | [
"def",
"get_user_application_data_directory",
"(",
")",
":",
"system_application_data_directory",
"=",
"get_system_application_data_directory",
"(",
")",
"if",
"not",
"foundations",
".",
"common",
".",
"path_exists",
"(",
"system_application_data_directory",
")",
":",
"LOGG... | | Returns the user Application directory.
| The difference between :func:`get_user_application_data_directory`
and :func:`get_system_application_data_directory` definitions is that :func:`get_user_application_data_directory` definition
will append :attr:`foundations.globals.constants.Constants.provi... | [
"|",
"Returns",
"the",
"user",
"Application",
"directory",
".",
"|",
"The",
"difference",
"between",
":",
"func",
":",
"get_user_application_data_directory",
"and",
":",
"func",
":",
"get_system_application_data_directory",
"definitions",
"is",
"that",
":",
"func",
... | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/environment.py#L263-L295 |
KelSolaar/Foundations | foundations/environment.py | Environment.variables | def variables(self, value):
"""
Setter for **self.__variables** attribute.
:param value: Attribute value.
:type value: dict
"""
if value is not None:
assert type(value) is dict, "'{0}' attribute: '{1}' type is not 'dict'!".format("variables", value)
... | python | def variables(self, value):
"""
Setter for **self.__variables** attribute.
:param value: Attribute value.
:type value: dict
"""
if value is not None:
assert type(value) is dict, "'{0}' attribute: '{1}' type is not 'dict'!".format("variables", value)
... | [
"def",
"variables",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"dict",
",",
"\"'{0}' attribute: '{1}' type is not 'dict'!\"",
".",
"format",
"(",
"\"variables\"",
",",
"value",
")"... | Setter for **self.__variables** attribute.
:param value: Attribute value.
:type value: dict | [
"Setter",
"for",
"**",
"self",
".",
"__variables",
"**",
"attribute",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/environment.py#L90-L105 |
KelSolaar/Foundations | foundations/environment.py | Environment.__add_variables | def __add_variables(self, *args, **kwargs):
"""
Adds given variables to __variables attribute.
:param \*args: Variables.
:type \*args: \*
:param \*\*kwargs: Variables : Values.
:type \*\*kwargs: \*
"""
for variable in args:
self.__variables[v... | python | def __add_variables(self, *args, **kwargs):
"""
Adds given variables to __variables attribute.
:param \*args: Variables.
:type \*args: \*
:param \*\*kwargs: Variables : Values.
:type \*\*kwargs: \*
"""
for variable in args:
self.__variables[v... | [
"def",
"__add_variables",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"variable",
"in",
"args",
":",
"self",
".",
"__variables",
"[",
"variable",
"]",
"=",
"None",
"self",
".",
"__variables",
".",
"update",
"(",
"kwargs",
... | Adds given variables to __variables attribute.
:param \*args: Variables.
:type \*args: \*
:param \*\*kwargs: Variables : Values.
:type \*\*kwargs: \* | [
"Adds",
"given",
"variables",
"to",
"__variables",
"attribute",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/environment.py#L117-L129 |
KelSolaar/Foundations | foundations/environment.py | Environment.get_values | def get_values(self, *args):
"""
Gets environment variables values.
Usage::
>>> environment = Environment("HOME")
>>> environment.get_values()
{'HOME': u'/Users/JohnDoe'}
>>> environment.get_values("USER")
{'HOME': u'/Users/JohnDoe', ... | python | def get_values(self, *args):
"""
Gets environment variables values.
Usage::
>>> environment = Environment("HOME")
>>> environment.get_values()
{'HOME': u'/Users/JohnDoe'}
>>> environment.get_values("USER")
{'HOME': u'/Users/JohnDoe', ... | [
"def",
"get_values",
"(",
"self",
",",
"*",
"args",
")",
":",
"args",
"and",
"self",
".",
"__add_variables",
"(",
"*",
"args",
")",
"LOGGER",
".",
"debug",
"(",
"\"> Object environment variables: '{0}'.\"",
".",
"format",
"(",
"\",\"",
".",
"join",
"(",
"(... | Gets environment variables values.
Usage::
>>> environment = Environment("HOME")
>>> environment.get_values()
{'HOME': u'/Users/JohnDoe'}
>>> environment.get_values("USER")
{'HOME': u'/Users/JohnDoe', 'USER': u'JohnDoe'}
:param \*args: Addit... | [
"Gets",
"environment",
"variables",
"values",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/environment.py#L131-L158 |
KelSolaar/Foundations | foundations/environment.py | Environment.set_values | def set_values(self, **kwargs):
"""
Sets environment variables values.
Usage::
>>> environment = Environment()
>>> environment.set_values(JOHN="DOE", DOE="JOHN")
True
>>> import os
>>> os.environ["JOHN"]
'DOE'
... | python | def set_values(self, **kwargs):
"""
Sets environment variables values.
Usage::
>>> environment = Environment()
>>> environment.set_values(JOHN="DOE", DOE="JOHN")
True
>>> import os
>>> os.environ["JOHN"]
'DOE'
... | [
"def",
"set_values",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__variables",
".",
"update",
"(",
"kwargs",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"__variables",
".",
"iteritems",
"(",
")",
":",
"if",
"value",
"is",
... | Sets environment variables values.
Usage::
>>> environment = Environment()
>>> environment.set_values(JOHN="DOE", DOE="JOHN")
True
>>> import os
>>> os.environ["JOHN"]
'DOE'
>>> os.environ["DOE"]
'JOHN'
:p... | [
"Sets",
"environment",
"variables",
"values",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/environment.py#L160-L190 |
KelSolaar/Foundations | foundations/environment.py | Environment.get_value | def get_value(self, variable=None):
"""
Gets given environment variable value.
:param variable: Variable to retrieve value.
:type variable: unicode
:return: Variable value.
:rtype: unicode
:note: If the **variable** argument is not given the first **self.__varia... | python | def get_value(self, variable=None):
"""
Gets given environment variable value.
:param variable: Variable to retrieve value.
:type variable: unicode
:return: Variable value.
:rtype: unicode
:note: If the **variable** argument is not given the first **self.__varia... | [
"def",
"get_value",
"(",
"self",
",",
"variable",
"=",
"None",
")",
":",
"if",
"variable",
":",
"self",
".",
"get_values",
"(",
"variable",
")",
"return",
"self",
".",
"__variables",
"[",
"variable",
"]",
"else",
":",
"self",
".",
"get_values",
"(",
")... | Gets given environment variable value.
:param variable: Variable to retrieve value.
:type variable: unicode
:return: Variable value.
:rtype: unicode
:note: If the **variable** argument is not given the first **self.__variables** attribute value will be returned. | [
"Gets",
"given",
"environment",
"variable",
"value",
"."
] | train | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/environment.py#L192-L209 |
vroomfonde1/basicmodem | basicmodem/basicmodem.py | BasicModem.read | def read(self, timeout=1.0):
"""read from modem port, return null string on timeout."""
self.ser.timeout = timeout
if self.ser is None:
return ''
return self.ser.readline() | python | def read(self, timeout=1.0):
"""read from modem port, return null string on timeout."""
self.ser.timeout = timeout
if self.ser is None:
return ''
return self.ser.readline() | [
"def",
"read",
"(",
"self",
",",
"timeout",
"=",
"1.0",
")",
":",
"self",
".",
"ser",
".",
"timeout",
"=",
"timeout",
"if",
"self",
".",
"ser",
"is",
"None",
":",
"return",
"''",
"return",
"self",
".",
"ser",
".",
"readline",
"(",
")"
] | read from modem port, return null string on timeout. | [
"read",
"from",
"modem",
"port",
"return",
"null",
"string",
"on",
"timeout",
"."
] | train | https://github.com/vroomfonde1/basicmodem/blob/ea5835b0d4a05d167456f78d2ae8c74c1d636aac/basicmodem/basicmodem.py#L73-L78 |
vroomfonde1/basicmodem | basicmodem/basicmodem.py | BasicModem.write | def write(self, cmd='AT'):
"""write string to modem, returns number of bytes written."""
self.cmd_response = ''
self.cmd_responselines = []
if self.ser is None:
return 0
cmd += '\r\n'
return self.ser.write(cmd.encode()) | python | def write(self, cmd='AT'):
"""write string to modem, returns number of bytes written."""
self.cmd_response = ''
self.cmd_responselines = []
if self.ser is None:
return 0
cmd += '\r\n'
return self.ser.write(cmd.encode()) | [
"def",
"write",
"(",
"self",
",",
"cmd",
"=",
"'AT'",
")",
":",
"self",
".",
"cmd_response",
"=",
"''",
"self",
".",
"cmd_responselines",
"=",
"[",
"]",
"if",
"self",
".",
"ser",
"is",
"None",
":",
"return",
"0",
"cmd",
"+=",
"'\\r\\n'",
"return",
... | write string to modem, returns number of bytes written. | [
"write",
"string",
"to",
"modem",
"returns",
"number",
"of",
"bytes",
"written",
"."
] | train | https://github.com/vroomfonde1/basicmodem/blob/ea5835b0d4a05d167456f78d2ae8c74c1d636aac/basicmodem/basicmodem.py#L80-L87 |
vroomfonde1/basicmodem | basicmodem/basicmodem.py | BasicModem.sendcmd | def sendcmd(self, cmd='AT', timeout=1.0):
"""send command, wait for response. returns response from modem."""
import time
if self.write(cmd):
while self.get_response() == '' and timeout > 0:
time.sleep(0.1)
timeout -= 0.1
return self.get_lines(... | python | def sendcmd(self, cmd='AT', timeout=1.0):
"""send command, wait for response. returns response from modem."""
import time
if self.write(cmd):
while self.get_response() == '' and timeout > 0:
time.sleep(0.1)
timeout -= 0.1
return self.get_lines(... | [
"def",
"sendcmd",
"(",
"self",
",",
"cmd",
"=",
"'AT'",
",",
"timeout",
"=",
"1.0",
")",
":",
"import",
"time",
"if",
"self",
".",
"write",
"(",
"cmd",
")",
":",
"while",
"self",
".",
"get_response",
"(",
")",
"==",
"''",
"and",
"timeout",
">",
"... | send command, wait for response. returns response from modem. | [
"send",
"command",
"wait",
"for",
"response",
".",
"returns",
"response",
"from",
"modem",
"."
] | train | https://github.com/vroomfonde1/basicmodem/blob/ea5835b0d4a05d167456f78d2ae8c74c1d636aac/basicmodem/basicmodem.py#L89-L96 |
vroomfonde1/basicmodem | basicmodem/basicmodem.py | BasicModem._modem_sm | def _modem_sm(self):
"""Handle modem response state machine."""
import datetime
read_timeout = READ_IDLE_TIMEOUT
while self.ser:
try:
resp = self.read(read_timeout)
except (serial.SerialException, SystemExit, TypeError):
_LOGGER.de... | python | def _modem_sm(self):
"""Handle modem response state machine."""
import datetime
read_timeout = READ_IDLE_TIMEOUT
while self.ser:
try:
resp = self.read(read_timeout)
except (serial.SerialException, SystemExit, TypeError):
_LOGGER.de... | [
"def",
"_modem_sm",
"(",
"self",
")",
":",
"import",
"datetime",
"read_timeout",
"=",
"READ_IDLE_TIMEOUT",
"while",
"self",
".",
"ser",
":",
"try",
":",
"resp",
"=",
"self",
".",
"read",
"(",
"read_timeout",
")",
"except",
"(",
"serial",
".",
"SerialExcept... | Handle modem response state machine. | [
"Handle",
"modem",
"response",
"state",
"machine",
"."
] | train | https://github.com/vroomfonde1/basicmodem/blob/ea5835b0d4a05d167456f78d2ae8c74c1d636aac/basicmodem/basicmodem.py#L144-L216 |
goshuirc/irc | girc/client.py | ServerConnection.register_event | def register_event(self, direction, verb, child_fn, priority=10):
"""Register an event with all servers.
Args:
direction (str): `in`, `out`, `both`, or `girc`.
verb (str): Event name, `all`, or `raw`.
child_fn (function): Handler function.
priority (int):... | python | def register_event(self, direction, verb, child_fn, priority=10):
"""Register an event with all servers.
Args:
direction (str): `in`, `out`, `both`, or `girc`.
verb (str): Event name, `all`, or `raw`.
child_fn (function): Handler function.
priority (int):... | [
"def",
"register_event",
"(",
"self",
",",
"direction",
",",
"verb",
",",
"child_fn",
",",
"priority",
"=",
"10",
")",
":",
"event_managers",
"=",
"[",
"]",
"if",
"direction",
"in",
"(",
"'in'",
",",
"'both'",
")",
":",
"event_managers",
".",
"append",
... | Register an event with all servers.
Args:
direction (str): `in`, `out`, `both`, or `girc`.
verb (str): Event name, `all`, or `raw`.
child_fn (function): Handler function.
priority (int): Handler priority (lower priority executes first).
Note: `all` will ... | [
"Register",
"an",
"event",
"with",
"all",
"servers",
"."
] | train | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/client.py#L98-L119 |
goshuirc/irc | girc/client.py | ServerConnection.set_user_info | def set_user_info(self, nick, user='*', real='*'):
"""Sets user info for this server, to be used before connection.
Args:
nick (str): Nickname to use.
user (str): Username to use.
real (str): Realname to use.
"""
if self.connected:
raise E... | python | def set_user_info(self, nick, user='*', real='*'):
"""Sets user info for this server, to be used before connection.
Args:
nick (str): Nickname to use.
user (str): Username to use.
real (str): Realname to use.
"""
if self.connected:
raise E... | [
"def",
"set_user_info",
"(",
"self",
",",
"nick",
",",
"user",
"=",
"'*'",
",",
"real",
"=",
"'*'",
")",
":",
"if",
"self",
".",
"connected",
":",
"raise",
"Exception",
"(",
"\"Can't set user info now, we're already connected!\"",
")",
"# server will pickup list w... | Sets user info for this server, to be used before connection.
Args:
nick (str): Nickname to use.
user (str): Username to use.
real (str): Realname to use. | [
"Sets",
"user",
"info",
"for",
"this",
"server",
"to",
"be",
"used",
"before",
"connection",
"."
] | train | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/client.py#L134-L153 |
goshuirc/irc | girc/client.py | ServerConnection.istring | def istring(self, in_string=''):
"""Return a string that uses this server's IRC casemapping.
This string's equality with other strings, ``lower()``, and ``upper()`` takes this
server's casemapping into account. This should be used for things such as nicks and
channel names, where compar... | python | def istring(self, in_string=''):
"""Return a string that uses this server's IRC casemapping.
This string's equality with other strings, ``lower()``, and ``upper()`` takes this
server's casemapping into account. This should be used for things such as nicks and
channel names, where compar... | [
"def",
"istring",
"(",
"self",
",",
"in_string",
"=",
"''",
")",
":",
"new_string",
"=",
"IString",
"(",
"in_string",
")",
"new_string",
".",
"set_std",
"(",
"self",
".",
"features",
".",
"get",
"(",
"'casemapping'",
")",
")",
"if",
"not",
"self",
".",... | Return a string that uses this server's IRC casemapping.
This string's equality with other strings, ``lower()``, and ``upper()`` takes this
server's casemapping into account. This should be used for things such as nicks and
channel names, where comparing strings using the correct casemapping ca... | [
"Return",
"a",
"string",
"that",
"uses",
"this",
"server",
"s",
"IRC",
"casemapping",
"."
] | train | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/client.py#L165-L177 |
goshuirc/irc | girc/client.py | ServerConnection.ilist | def ilist(self, in_list=[]):
"""Return a list that uses this server's IRC casemapping.
All strings in this list are lowercased using the server's casemapping before inserting
them into the list, and the ``in`` operator takes casemapping into account.
"""
new_list = IList(in_list... | python | def ilist(self, in_list=[]):
"""Return a list that uses this server's IRC casemapping.
All strings in this list are lowercased using the server's casemapping before inserting
them into the list, and the ``in`` operator takes casemapping into account.
"""
new_list = IList(in_list... | [
"def",
"ilist",
"(",
"self",
",",
"in_list",
"=",
"[",
"]",
")",
":",
"new_list",
"=",
"IList",
"(",
"in_list",
")",
"new_list",
".",
"set_std",
"(",
"self",
".",
"features",
".",
"get",
"(",
"'casemapping'",
")",
")",
"if",
"not",
"self",
".",
"_c... | Return a list that uses this server's IRC casemapping.
All strings in this list are lowercased using the server's casemapping before inserting
them into the list, and the ``in`` operator takes casemapping into account. | [
"Return",
"a",
"list",
"that",
"uses",
"this",
"server",
"s",
"IRC",
"casemapping",
"."
] | train | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/client.py#L179-L189 |
goshuirc/irc | girc/client.py | ServerConnection.idict | def idict(self, in_dict={}):
"""Return a dict that uses this server's IRC casemapping.
All keys in this dictionary are stored and compared using this server's casemapping.
"""
new_dict = IDict(in_dict)
new_dict.set_std(self.features.get('casemapping'))
if not self._casem... | python | def idict(self, in_dict={}):
"""Return a dict that uses this server's IRC casemapping.
All keys in this dictionary are stored and compared using this server's casemapping.
"""
new_dict = IDict(in_dict)
new_dict.set_std(self.features.get('casemapping'))
if not self._casem... | [
"def",
"idict",
"(",
"self",
",",
"in_dict",
"=",
"{",
"}",
")",
":",
"new_dict",
"=",
"IDict",
"(",
"in_dict",
")",
"new_dict",
".",
"set_std",
"(",
"self",
".",
"features",
".",
"get",
"(",
"'casemapping'",
")",
")",
"if",
"not",
"self",
".",
"_c... | Return a dict that uses this server's IRC casemapping.
All keys in this dictionary are stored and compared using this server's casemapping. | [
"Return",
"a",
"dict",
"that",
"uses",
"this",
"server",
"s",
"IRC",
"casemapping",
"."
] | train | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/client.py#L191-L200 |
goshuirc/irc | girc/client.py | ServerConnection.connect | def connect(self, *args, auto_reconnect=False, **kwargs):
"""Connects to the given server.
Args:
auto_reconnect (bool): Automatically reconnect on disconnection.
Other arguments to this function are as usually supplied to
:meth:`asyncio.BaseEventLoop.create_connection`.
... | python | def connect(self, *args, auto_reconnect=False, **kwargs):
"""Connects to the given server.
Args:
auto_reconnect (bool): Automatically reconnect on disconnection.
Other arguments to this function are as usually supplied to
:meth:`asyncio.BaseEventLoop.create_connection`.
... | [
"def",
"connect",
"(",
"self",
",",
"*",
"args",
",",
"auto_reconnect",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"connection_info",
"=",
"{",
"'auto_reconnect'",
":",
"auto_reconnect",
",",
"'args'",
":",
"args",
",",
"'kwargs'",
":",
"kwargs",
"... | Connects to the given server.
Args:
auto_reconnect (bool): Automatically reconnect on disconnection.
Other arguments to this function are as usually supplied to
:meth:`asyncio.BaseEventLoop.create_connection`. | [
"Connects",
"to",
"the",
"given",
"server",
"."
] | train | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/client.py#L203-L226 |
goshuirc/irc | girc/client.py | ServerConnection.quit | def quit(self, message=None):
"""Quit from the server."""
if message is None:
message = 'Quit'
if self.connected:
self.send('QUIT', params=[message]) | python | def quit(self, message=None):
"""Quit from the server."""
if message is None:
message = 'Quit'
if self.connected:
self.send('QUIT', params=[message]) | [
"def",
"quit",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"'Quit'",
"if",
"self",
".",
"connected",
":",
"self",
".",
"send",
"(",
"'QUIT'",
",",
"params",
"=",
"[",
"message",
"]",
")"
] | Quit from the server. | [
"Quit",
"from",
"the",
"server",
"."
] | train | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/client.py#L244-L250 |
goshuirc/irc | girc/client.py | ServerConnection.send | def send(self, verb, params=None, source=None, tags=None):
"""Send a generic IRC message to the server.
A message is created using the various parts of the message, then gets
assembled and sent to the server.
Args:
verb (str): Verb, such as PRIVMSG.
params (list... | python | def send(self, verb, params=None, source=None, tags=None):
"""Send a generic IRC message to the server.
A message is created using the various parts of the message, then gets
assembled and sent to the server.
Args:
verb (str): Verb, such as PRIVMSG.
params (list... | [
"def",
"send",
"(",
"self",
",",
"verb",
",",
"params",
"=",
"None",
",",
"source",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"m",
"=",
"RFC1459Message",
".",
"from_data",
"(",
"verb",
",",
"params",
"=",
"params",
",",
"source",
"=",
"sourc... | Send a generic IRC message to the server.
A message is created using the various parts of the message, then gets
assembled and sent to the server.
Args:
verb (str): Verb, such as PRIVMSG.
params (list of str): Message parameters, defaults to no params.
sourc... | [
"Send",
"a",
"generic",
"IRC",
"message",
"to",
"the",
"server",
"."
] | train | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/client.py#L263-L277 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.