repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
quikmile/trellio | trellio/services.py | publish | def publish(func):
"""
publish the return value of this function as a message from this endpoint
"""
@wraps(func)
def wrapper(self, *args, **kwargs): # outgoing
payload = func(self, *args, **kwargs)
payload.pop('self', None)
self._publish(func.__name__, payload)
return None
wrapper.is_publish = True
return wrapper | python | def publish(func):
"""
publish the return value of this function as a message from this endpoint
"""
@wraps(func)
def wrapper(self, *args, **kwargs): # outgoing
payload = func(self, *args, **kwargs)
payload.pop('self', None)
self._publish(func.__name__, payload)
return None
wrapper.is_publish = True
return wrapper | [
"def",
"publish",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# outgoing",
"payload",
"=",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"payload",
".",
"pop",
"(",
"'self'",
",",
"None",
")",
"self",
".",
"_publish",
"(",
"func",
".",
"__name__",
",",
"payload",
")",
"return",
"None",
"wrapper",
".",
"is_publish",
"=",
"True",
"return",
"wrapper"
] | publish the return value of this function as a message from this endpoint | [
"publish",
"the",
"return",
"value",
"of",
"this",
"function",
"as",
"a",
"message",
"from",
"this",
"endpoint"
] | e8b050077562acf32805fcbb9c0c162248a23c62 | https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/services.py#L26-L40 | train |
quikmile/trellio | trellio/services.py | request | def request(func=None, timeout=600):
"""
use to request an api call from a specific endpoint
"""
if func is None:
return partial(request, timeout=timeout)
@wraps(func)
def wrapper(self, *args, **kwargs):
params = func(self, *args, **kwargs)
self = params.pop('self', None)
entity = params.pop('entity', None)
app_name = params.pop('app_name', None)
request_id = unique_hex()
params['request_id'] = request_id
future = self._send_request(app_name, endpoint=func.__name__, entity=entity, params=params, timeout=timeout)
return future
wrapper.is_request = True
return wrapper | python | def request(func=None, timeout=600):
"""
use to request an api call from a specific endpoint
"""
if func is None:
return partial(request, timeout=timeout)
@wraps(func)
def wrapper(self, *args, **kwargs):
params = func(self, *args, **kwargs)
self = params.pop('self', None)
entity = params.pop('entity', None)
app_name = params.pop('app_name', None)
request_id = unique_hex()
params['request_id'] = request_id
future = self._send_request(app_name, endpoint=func.__name__, entity=entity, params=params, timeout=timeout)
return future
wrapper.is_request = True
return wrapper | [
"def",
"request",
"(",
"func",
"=",
"None",
",",
"timeout",
"=",
"600",
")",
":",
"if",
"func",
"is",
"None",
":",
"return",
"partial",
"(",
"request",
",",
"timeout",
"=",
"timeout",
")",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
"=",
"params",
".",
"pop",
"(",
"'self'",
",",
"None",
")",
"entity",
"=",
"params",
".",
"pop",
"(",
"'entity'",
",",
"None",
")",
"app_name",
"=",
"params",
".",
"pop",
"(",
"'app_name'",
",",
"None",
")",
"request_id",
"=",
"unique_hex",
"(",
")",
"params",
"[",
"'request_id'",
"]",
"=",
"request_id",
"future",
"=",
"self",
".",
"_send_request",
"(",
"app_name",
",",
"endpoint",
"=",
"func",
".",
"__name__",
",",
"entity",
"=",
"entity",
",",
"params",
"=",
"params",
",",
"timeout",
"=",
"timeout",
")",
"return",
"future",
"wrapper",
".",
"is_request",
"=",
"True",
"return",
"wrapper"
] | use to request an api call from a specific endpoint | [
"use",
"to",
"request",
"an",
"api",
"call",
"from",
"a",
"specific",
"endpoint"
] | e8b050077562acf32805fcbb9c0c162248a23c62 | https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/services.py#L83-L102 | train |
grktsh/falcon-oas | src/falcon_oas/problems.py | serialize_problem | def serialize_problem(req, resp, problem):
"""Serialize the given instance of Problem."""
preferred = req.client_prefers(
('application/json', 'application/problem+json')
)
if preferred is None:
preferred = 'application/json'
resp.data = problem.to_json().encode('utf-8')
resp.content_type = preferred
resp.append_header('Vary', 'Accept') | python | def serialize_problem(req, resp, problem):
"""Serialize the given instance of Problem."""
preferred = req.client_prefers(
('application/json', 'application/problem+json')
)
if preferred is None:
preferred = 'application/json'
resp.data = problem.to_json().encode('utf-8')
resp.content_type = preferred
resp.append_header('Vary', 'Accept') | [
"def",
"serialize_problem",
"(",
"req",
",",
"resp",
",",
"problem",
")",
":",
"preferred",
"=",
"req",
".",
"client_prefers",
"(",
"(",
"'application/json'",
",",
"'application/problem+json'",
")",
")",
"if",
"preferred",
"is",
"None",
":",
"preferred",
"=",
"'application/json'",
"resp",
".",
"data",
"=",
"problem",
".",
"to_json",
"(",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"resp",
".",
"content_type",
"=",
"preferred",
"resp",
".",
"append_header",
"(",
"'Vary'",
",",
"'Accept'",
")"
] | Serialize the given instance of Problem. | [
"Serialize",
"the",
"given",
"instance",
"of",
"Problem",
"."
] | 380921e82a50b565b3df6e494b06cc9dba961db7 | https://github.com/grktsh/falcon-oas/blob/380921e82a50b565b3df6e494b06cc9dba961db7/src/falcon_oas/problems.py#L52-L62 | train |
glormph/msstitch | src/app/actions/proteindata.py | add_psms_to_proteindata | def add_psms_to_proteindata(proteindata, p_acc, pool, psmdata):
"""Fill function for create_featuredata_map"""
seq, psm_id = psmdata[2], psmdata[3]
try:
proteindata[p_acc]['pools'][pool]['psms'].add(psm_id)
except KeyError:
emptyinfo = {'psms': set(), 'peptides': set(), 'unipeps': 0}
try:
proteindata[p_acc]['pools'][pool] = emptyinfo
except KeyError:
proteindata[p_acc].update({'pools': {pool: emptyinfo}})
proteindata[p_acc]['pools'][pool]['psms'].add(psm_id)
proteindata[p_acc]['pools'][pool]['peptides'].add(seq) | python | def add_psms_to_proteindata(proteindata, p_acc, pool, psmdata):
"""Fill function for create_featuredata_map"""
seq, psm_id = psmdata[2], psmdata[3]
try:
proteindata[p_acc]['pools'][pool]['psms'].add(psm_id)
except KeyError:
emptyinfo = {'psms': set(), 'peptides': set(), 'unipeps': 0}
try:
proteindata[p_acc]['pools'][pool] = emptyinfo
except KeyError:
proteindata[p_acc].update({'pools': {pool: emptyinfo}})
proteindata[p_acc]['pools'][pool]['psms'].add(psm_id)
proteindata[p_acc]['pools'][pool]['peptides'].add(seq) | [
"def",
"add_psms_to_proteindata",
"(",
"proteindata",
",",
"p_acc",
",",
"pool",
",",
"psmdata",
")",
":",
"seq",
",",
"psm_id",
"=",
"psmdata",
"[",
"2",
"]",
",",
"psmdata",
"[",
"3",
"]",
"try",
":",
"proteindata",
"[",
"p_acc",
"]",
"[",
"'pools'",
"]",
"[",
"pool",
"]",
"[",
"'psms'",
"]",
".",
"add",
"(",
"psm_id",
")",
"except",
"KeyError",
":",
"emptyinfo",
"=",
"{",
"'psms'",
":",
"set",
"(",
")",
",",
"'peptides'",
":",
"set",
"(",
")",
",",
"'unipeps'",
":",
"0",
"}",
"try",
":",
"proteindata",
"[",
"p_acc",
"]",
"[",
"'pools'",
"]",
"[",
"pool",
"]",
"=",
"emptyinfo",
"except",
"KeyError",
":",
"proteindata",
"[",
"p_acc",
"]",
".",
"update",
"(",
"{",
"'pools'",
":",
"{",
"pool",
":",
"emptyinfo",
"}",
"}",
")",
"proteindata",
"[",
"p_acc",
"]",
"[",
"'pools'",
"]",
"[",
"pool",
"]",
"[",
"'psms'",
"]",
".",
"add",
"(",
"psm_id",
")",
"proteindata",
"[",
"p_acc",
"]",
"[",
"'pools'",
"]",
"[",
"pool",
"]",
"[",
"'peptides'",
"]",
".",
"add",
"(",
"seq",
")"
] | Fill function for create_featuredata_map | [
"Fill",
"function",
"for",
"create_featuredata_map"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/proteindata.py#L27-L39 | train |
Erotemic/utool | utool/util_dbg.py | print_traceback | def print_traceback(with_colors=True):
"""
prints current stack
"""
#traceback.print_tb()
import traceback
stack = traceback.extract_stack()
stack_lines = traceback.format_list(stack)
tbtext = ''.join(stack_lines)
if with_colors:
try:
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter
lexer = get_lexer_by_name('pytb', stripall=True)
formatter = TerminalFormatter(bg='dark')
formatted_text = highlight(tbtext, lexer, formatter)
print(formatted_text)
except Exception:
print(tbtext)
else:
print(tbtext) | python | def print_traceback(with_colors=True):
"""
prints current stack
"""
#traceback.print_tb()
import traceback
stack = traceback.extract_stack()
stack_lines = traceback.format_list(stack)
tbtext = ''.join(stack_lines)
if with_colors:
try:
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter
lexer = get_lexer_by_name('pytb', stripall=True)
formatter = TerminalFormatter(bg='dark')
formatted_text = highlight(tbtext, lexer, formatter)
print(formatted_text)
except Exception:
print(tbtext)
else:
print(tbtext) | [
"def",
"print_traceback",
"(",
"with_colors",
"=",
"True",
")",
":",
"#traceback.print_tb()",
"import",
"traceback",
"stack",
"=",
"traceback",
".",
"extract_stack",
"(",
")",
"stack_lines",
"=",
"traceback",
".",
"format_list",
"(",
"stack",
")",
"tbtext",
"=",
"''",
".",
"join",
"(",
"stack_lines",
")",
"if",
"with_colors",
":",
"try",
":",
"from",
"pygments",
"import",
"highlight",
"from",
"pygments",
".",
"lexers",
"import",
"get_lexer_by_name",
"from",
"pygments",
".",
"formatters",
"import",
"TerminalFormatter",
"lexer",
"=",
"get_lexer_by_name",
"(",
"'pytb'",
",",
"stripall",
"=",
"True",
")",
"formatter",
"=",
"TerminalFormatter",
"(",
"bg",
"=",
"'dark'",
")",
"formatted_text",
"=",
"highlight",
"(",
"tbtext",
",",
"lexer",
",",
"formatter",
")",
"print",
"(",
"formatted_text",
")",
"except",
"Exception",
":",
"print",
"(",
"tbtext",
")",
"else",
":",
"print",
"(",
"tbtext",
")"
] | prints current stack | [
"prints",
"current",
"stack"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dbg.py#L40-L61 | train |
Erotemic/utool | utool/util_dbg.py | is_valid_varname | def is_valid_varname(varname):
""" Checks syntax and validity of a variable name """
if not isinstance(varname, six.string_types):
return False
match_obj = re.match(varname_regex, varname)
valid_syntax = match_obj is not None
valid_name = not keyword.iskeyword(varname)
isvalid = valid_syntax and valid_name
return isvalid | python | def is_valid_varname(varname):
""" Checks syntax and validity of a variable name """
if not isinstance(varname, six.string_types):
return False
match_obj = re.match(varname_regex, varname)
valid_syntax = match_obj is not None
valid_name = not keyword.iskeyword(varname)
isvalid = valid_syntax and valid_name
return isvalid | [
"def",
"is_valid_varname",
"(",
"varname",
")",
":",
"if",
"not",
"isinstance",
"(",
"varname",
",",
"six",
".",
"string_types",
")",
":",
"return",
"False",
"match_obj",
"=",
"re",
".",
"match",
"(",
"varname_regex",
",",
"varname",
")",
"valid_syntax",
"=",
"match_obj",
"is",
"not",
"None",
"valid_name",
"=",
"not",
"keyword",
".",
"iskeyword",
"(",
"varname",
")",
"isvalid",
"=",
"valid_syntax",
"and",
"valid_name",
"return",
"isvalid"
] | Checks syntax and validity of a variable name | [
"Checks",
"syntax",
"and",
"validity",
"of",
"a",
"variable",
"name"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dbg.py#L101-L109 | train |
Erotemic/utool | utool/util_dbg.py | execstr_dict | def execstr_dict(dict_, local_name=None, exclude_list=None, explicit=False):
"""
returns execable python code that declares variables using keys and values
execstr_dict
Args:
dict_ (dict):
local_name (str): optional: local name of dictionary. Specifying this
is much safer
exclude_list (list):
Returns:
str: execstr --- the executable string that will put keys from dict
into local vars
CommandLine:
python -m utool.util_dbg --test-execstr_dict
Example:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> from utool.util_dbg import * # NOQA
>>> my_dictionary = {'a': True, 'b': False}
>>> execstr = execstr_dict(my_dictionary)
>>> exec(execstr)
>>> assert 'a' in vars() and 'b' in vars(), 'execstr failed'
>>> assert b is False and a is True, 'execstr failed'
>>> result = execstr
>>> print(result)
a = my_dictionary['a']
b = my_dictionary['b']
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dbg import * # NOQA
>>> import utool as ut
>>> my_dictionary = {'a': True, 'b': False}
>>> execstr = execstr_dict(my_dictionary)
>>> locals_ = locals()
>>> exec(execstr, locals_)
>>> a, b = ut.dict_take(locals_, ['a', 'b'])
>>> assert 'a' in locals_ and 'b' in locals_, 'execstr failed'
>>> assert b is False and a is True, 'execstr failed'
>>> result = execstr
>>> print(result)
a = my_dictionary['a']
b = my_dictionary['b']
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dbg import * # NOQA
>>> import utool as ut
>>> my_dictionary = {'a': True, 'b': False}
>>> execstr = execstr_dict(my_dictionary, explicit=True)
>>> result = execstr
>>> print(result)
a = True
b = False
"""
import utool as ut
if explicit:
expr_list = []
for (key, val) in sorted(dict_.items()):
assert isinstance(key, six.string_types), 'keys must be strings'
expr_list.append('%s = %s' % (key, ut.repr2(val),))
execstr = '\n'.join(expr_list)
return execstr
else:
if local_name is None:
# Magic way of getting the local name of dict_
local_name = get_varname_from_locals(dict_, get_parent_frame().f_locals)
try:
if exclude_list is None:
exclude_list = []
assert isinstance(exclude_list, list)
exclude_list.append(local_name)
expr_list = []
assert isinstance(dict_, dict), 'incorrect type type(dict_)=%r, dict_=%r' % (type(dict), dict_)
for (key, val) in sorted(dict_.items()):
assert isinstance(key, six.string_types), 'keys must be strings'
if not is_valid_varname(key):
continue
if not any((fnmatch.fnmatch(key, pat) for pat in exclude_list)):
expr = '%s = %s[%s]' % (key, local_name, ut.repr2(key))
expr_list.append(expr)
execstr = '\n'.join(expr_list)
return execstr
except Exception as ex:
locals_ = locals()
ut.printex(ex, key_list=['locals_'])
raise | python | def execstr_dict(dict_, local_name=None, exclude_list=None, explicit=False):
"""
returns execable python code that declares variables using keys and values
execstr_dict
Args:
dict_ (dict):
local_name (str): optional: local name of dictionary. Specifying this
is much safer
exclude_list (list):
Returns:
str: execstr --- the executable string that will put keys from dict
into local vars
CommandLine:
python -m utool.util_dbg --test-execstr_dict
Example:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> from utool.util_dbg import * # NOQA
>>> my_dictionary = {'a': True, 'b': False}
>>> execstr = execstr_dict(my_dictionary)
>>> exec(execstr)
>>> assert 'a' in vars() and 'b' in vars(), 'execstr failed'
>>> assert b is False and a is True, 'execstr failed'
>>> result = execstr
>>> print(result)
a = my_dictionary['a']
b = my_dictionary['b']
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dbg import * # NOQA
>>> import utool as ut
>>> my_dictionary = {'a': True, 'b': False}
>>> execstr = execstr_dict(my_dictionary)
>>> locals_ = locals()
>>> exec(execstr, locals_)
>>> a, b = ut.dict_take(locals_, ['a', 'b'])
>>> assert 'a' in locals_ and 'b' in locals_, 'execstr failed'
>>> assert b is False and a is True, 'execstr failed'
>>> result = execstr
>>> print(result)
a = my_dictionary['a']
b = my_dictionary['b']
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dbg import * # NOQA
>>> import utool as ut
>>> my_dictionary = {'a': True, 'b': False}
>>> execstr = execstr_dict(my_dictionary, explicit=True)
>>> result = execstr
>>> print(result)
a = True
b = False
"""
import utool as ut
if explicit:
expr_list = []
for (key, val) in sorted(dict_.items()):
assert isinstance(key, six.string_types), 'keys must be strings'
expr_list.append('%s = %s' % (key, ut.repr2(val),))
execstr = '\n'.join(expr_list)
return execstr
else:
if local_name is None:
# Magic way of getting the local name of dict_
local_name = get_varname_from_locals(dict_, get_parent_frame().f_locals)
try:
if exclude_list is None:
exclude_list = []
assert isinstance(exclude_list, list)
exclude_list.append(local_name)
expr_list = []
assert isinstance(dict_, dict), 'incorrect type type(dict_)=%r, dict_=%r' % (type(dict), dict_)
for (key, val) in sorted(dict_.items()):
assert isinstance(key, six.string_types), 'keys must be strings'
if not is_valid_varname(key):
continue
if not any((fnmatch.fnmatch(key, pat) for pat in exclude_list)):
expr = '%s = %s[%s]' % (key, local_name, ut.repr2(key))
expr_list.append(expr)
execstr = '\n'.join(expr_list)
return execstr
except Exception as ex:
locals_ = locals()
ut.printex(ex, key_list=['locals_'])
raise | [
"def",
"execstr_dict",
"(",
"dict_",
",",
"local_name",
"=",
"None",
",",
"exclude_list",
"=",
"None",
",",
"explicit",
"=",
"False",
")",
":",
"import",
"utool",
"as",
"ut",
"if",
"explicit",
":",
"expr_list",
"=",
"[",
"]",
"for",
"(",
"key",
",",
"val",
")",
"in",
"sorted",
"(",
"dict_",
".",
"items",
"(",
")",
")",
":",
"assert",
"isinstance",
"(",
"key",
",",
"six",
".",
"string_types",
")",
",",
"'keys must be strings'",
"expr_list",
".",
"append",
"(",
"'%s = %s'",
"%",
"(",
"key",
",",
"ut",
".",
"repr2",
"(",
"val",
")",
",",
")",
")",
"execstr",
"=",
"'\\n'",
".",
"join",
"(",
"expr_list",
")",
"return",
"execstr",
"else",
":",
"if",
"local_name",
"is",
"None",
":",
"# Magic way of getting the local name of dict_",
"local_name",
"=",
"get_varname_from_locals",
"(",
"dict_",
",",
"get_parent_frame",
"(",
")",
".",
"f_locals",
")",
"try",
":",
"if",
"exclude_list",
"is",
"None",
":",
"exclude_list",
"=",
"[",
"]",
"assert",
"isinstance",
"(",
"exclude_list",
",",
"list",
")",
"exclude_list",
".",
"append",
"(",
"local_name",
")",
"expr_list",
"=",
"[",
"]",
"assert",
"isinstance",
"(",
"dict_",
",",
"dict",
")",
",",
"'incorrect type type(dict_)=%r, dict_=%r'",
"%",
"(",
"type",
"(",
"dict",
")",
",",
"dict_",
")",
"for",
"(",
"key",
",",
"val",
")",
"in",
"sorted",
"(",
"dict_",
".",
"items",
"(",
")",
")",
":",
"assert",
"isinstance",
"(",
"key",
",",
"six",
".",
"string_types",
")",
",",
"'keys must be strings'",
"if",
"not",
"is_valid_varname",
"(",
"key",
")",
":",
"continue",
"if",
"not",
"any",
"(",
"(",
"fnmatch",
".",
"fnmatch",
"(",
"key",
",",
"pat",
")",
"for",
"pat",
"in",
"exclude_list",
")",
")",
":",
"expr",
"=",
"'%s = %s[%s]'",
"%",
"(",
"key",
",",
"local_name",
",",
"ut",
".",
"repr2",
"(",
"key",
")",
")",
"expr_list",
".",
"append",
"(",
"expr",
")",
"execstr",
"=",
"'\\n'",
".",
"join",
"(",
"expr_list",
")",
"return",
"execstr",
"except",
"Exception",
"as",
"ex",
":",
"locals_",
"=",
"locals",
"(",
")",
"ut",
".",
"printex",
"(",
"ex",
",",
"key_list",
"=",
"[",
"'locals_'",
"]",
")",
"raise"
] | returns execable python code that declares variables using keys and values
execstr_dict
Args:
dict_ (dict):
local_name (str): optional: local name of dictionary. Specifying this
is much safer
exclude_list (list):
Returns:
str: execstr --- the executable string that will put keys from dict
into local vars
CommandLine:
python -m utool.util_dbg --test-execstr_dict
Example:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> from utool.util_dbg import * # NOQA
>>> my_dictionary = {'a': True, 'b': False}
>>> execstr = execstr_dict(my_dictionary)
>>> exec(execstr)
>>> assert 'a' in vars() and 'b' in vars(), 'execstr failed'
>>> assert b is False and a is True, 'execstr failed'
>>> result = execstr
>>> print(result)
a = my_dictionary['a']
b = my_dictionary['b']
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dbg import * # NOQA
>>> import utool as ut
>>> my_dictionary = {'a': True, 'b': False}
>>> execstr = execstr_dict(my_dictionary)
>>> locals_ = locals()
>>> exec(execstr, locals_)
>>> a, b = ut.dict_take(locals_, ['a', 'b'])
>>> assert 'a' in locals_ and 'b' in locals_, 'execstr failed'
>>> assert b is False and a is True, 'execstr failed'
>>> result = execstr
>>> print(result)
a = my_dictionary['a']
b = my_dictionary['b']
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dbg import * # NOQA
>>> import utool as ut
>>> my_dictionary = {'a': True, 'b': False}
>>> execstr = execstr_dict(my_dictionary, explicit=True)
>>> result = execstr
>>> print(result)
a = True
b = False | [
"returns",
"execable",
"python",
"code",
"that",
"declares",
"variables",
"using",
"keys",
"and",
"values"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dbg.py#L112-L203 | train |
Erotemic/utool | utool/util_dbg.py | embed2 | def embed2(**kwargs):
"""
Modified from IPython.terminal.embed.embed so I can mess with stack_depth
"""
config = kwargs.get('config')
header = kwargs.pop('header', u'')
stack_depth = kwargs.pop('stack_depth', 2)
compile_flags = kwargs.pop('compile_flags', None)
import IPython
from IPython.core.interactiveshell import InteractiveShell
from IPython.terminal.embed import InteractiveShellEmbed
if config is None:
config = IPython.terminal.ipapp.load_default_config()
config.InteractiveShellEmbed = config.TerminalInteractiveShell
kwargs['config'] = config
#save ps1/ps2 if defined
ps1 = None
ps2 = None
try:
ps1 = sys.ps1
ps2 = sys.ps2
except AttributeError:
pass
#save previous instance
saved_shell_instance = InteractiveShell._instance
if saved_shell_instance is not None:
cls = type(saved_shell_instance)
cls.clear_instance()
shell = InteractiveShellEmbed.instance(**kwargs)
shell(header=header, stack_depth=stack_depth, compile_flags=compile_flags)
InteractiveShellEmbed.clear_instance()
#restore previous instance
if saved_shell_instance is not None:
cls = type(saved_shell_instance)
cls.clear_instance()
for subclass in cls._walk_mro():
subclass._instance = saved_shell_instance
if ps1 is not None:
sys.ps1 = ps1
sys.ps2 = ps2 | python | def embed2(**kwargs):
"""
Modified from IPython.terminal.embed.embed so I can mess with stack_depth
"""
config = kwargs.get('config')
header = kwargs.pop('header', u'')
stack_depth = kwargs.pop('stack_depth', 2)
compile_flags = kwargs.pop('compile_flags', None)
import IPython
from IPython.core.interactiveshell import InteractiveShell
from IPython.terminal.embed import InteractiveShellEmbed
if config is None:
config = IPython.terminal.ipapp.load_default_config()
config.InteractiveShellEmbed = config.TerminalInteractiveShell
kwargs['config'] = config
#save ps1/ps2 if defined
ps1 = None
ps2 = None
try:
ps1 = sys.ps1
ps2 = sys.ps2
except AttributeError:
pass
#save previous instance
saved_shell_instance = InteractiveShell._instance
if saved_shell_instance is not None:
cls = type(saved_shell_instance)
cls.clear_instance()
shell = InteractiveShellEmbed.instance(**kwargs)
shell(header=header, stack_depth=stack_depth, compile_flags=compile_flags)
InteractiveShellEmbed.clear_instance()
#restore previous instance
if saved_shell_instance is not None:
cls = type(saved_shell_instance)
cls.clear_instance()
for subclass in cls._walk_mro():
subclass._instance = saved_shell_instance
if ps1 is not None:
sys.ps1 = ps1
sys.ps2 = ps2 | [
"def",
"embed2",
"(",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"kwargs",
".",
"get",
"(",
"'config'",
")",
"header",
"=",
"kwargs",
".",
"pop",
"(",
"'header'",
",",
"u''",
")",
"stack_depth",
"=",
"kwargs",
".",
"pop",
"(",
"'stack_depth'",
",",
"2",
")",
"compile_flags",
"=",
"kwargs",
".",
"pop",
"(",
"'compile_flags'",
",",
"None",
")",
"import",
"IPython",
"from",
"IPython",
".",
"core",
".",
"interactiveshell",
"import",
"InteractiveShell",
"from",
"IPython",
".",
"terminal",
".",
"embed",
"import",
"InteractiveShellEmbed",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"IPython",
".",
"terminal",
".",
"ipapp",
".",
"load_default_config",
"(",
")",
"config",
".",
"InteractiveShellEmbed",
"=",
"config",
".",
"TerminalInteractiveShell",
"kwargs",
"[",
"'config'",
"]",
"=",
"config",
"#save ps1/ps2 if defined",
"ps1",
"=",
"None",
"ps2",
"=",
"None",
"try",
":",
"ps1",
"=",
"sys",
".",
"ps1",
"ps2",
"=",
"sys",
".",
"ps2",
"except",
"AttributeError",
":",
"pass",
"#save previous instance",
"saved_shell_instance",
"=",
"InteractiveShell",
".",
"_instance",
"if",
"saved_shell_instance",
"is",
"not",
"None",
":",
"cls",
"=",
"type",
"(",
"saved_shell_instance",
")",
"cls",
".",
"clear_instance",
"(",
")",
"shell",
"=",
"InteractiveShellEmbed",
".",
"instance",
"(",
"*",
"*",
"kwargs",
")",
"shell",
"(",
"header",
"=",
"header",
",",
"stack_depth",
"=",
"stack_depth",
",",
"compile_flags",
"=",
"compile_flags",
")",
"InteractiveShellEmbed",
".",
"clear_instance",
"(",
")",
"#restore previous instance",
"if",
"saved_shell_instance",
"is",
"not",
"None",
":",
"cls",
"=",
"type",
"(",
"saved_shell_instance",
")",
"cls",
".",
"clear_instance",
"(",
")",
"for",
"subclass",
"in",
"cls",
".",
"_walk_mro",
"(",
")",
":",
"subclass",
".",
"_instance",
"=",
"saved_shell_instance",
"if",
"ps1",
"is",
"not",
"None",
":",
"sys",
".",
"ps1",
"=",
"ps1",
"sys",
".",
"ps2",
"=",
"ps2"
] | Modified from IPython.terminal.embed.embed so I can mess with stack_depth | [
"Modified",
"from",
"IPython",
".",
"terminal",
".",
"embed",
".",
"embed",
"so",
"I",
"can",
"mess",
"with",
"stack_depth"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dbg.py#L559-L598 | train |
Erotemic/utool | utool/util_dbg.py | search_stack_for_localvar | def search_stack_for_localvar(varname):
"""
Finds a local varable somewhere in the stack and returns the value
Args:
varname (str): variable name
Returns:
None if varname is not found else its value
"""
curr_frame = inspect.currentframe()
print(' * Searching parent frames for: ' + six.text_type(varname))
frame_no = 0
while curr_frame.f_back is not None:
if varname in curr_frame.f_locals.keys():
print(' * Found in frame: ' + six.text_type(frame_no))
return curr_frame.f_locals[varname]
frame_no += 1
curr_frame = curr_frame.f_back
print('... Found nothing in all ' + six.text_type(frame_no) + ' frames.')
return None | python | def search_stack_for_localvar(varname):
"""
Finds a local varable somewhere in the stack and returns the value
Args:
varname (str): variable name
Returns:
None if varname is not found else its value
"""
curr_frame = inspect.currentframe()
print(' * Searching parent frames for: ' + six.text_type(varname))
frame_no = 0
while curr_frame.f_back is not None:
if varname in curr_frame.f_locals.keys():
print(' * Found in frame: ' + six.text_type(frame_no))
return curr_frame.f_locals[varname]
frame_no += 1
curr_frame = curr_frame.f_back
print('... Found nothing in all ' + six.text_type(frame_no) + ' frames.')
return None | [
"def",
"search_stack_for_localvar",
"(",
"varname",
")",
":",
"curr_frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"print",
"(",
"' * Searching parent frames for: '",
"+",
"six",
".",
"text_type",
"(",
"varname",
")",
")",
"frame_no",
"=",
"0",
"while",
"curr_frame",
".",
"f_back",
"is",
"not",
"None",
":",
"if",
"varname",
"in",
"curr_frame",
".",
"f_locals",
".",
"keys",
"(",
")",
":",
"print",
"(",
"' * Found in frame: '",
"+",
"six",
".",
"text_type",
"(",
"frame_no",
")",
")",
"return",
"curr_frame",
".",
"f_locals",
"[",
"varname",
"]",
"frame_no",
"+=",
"1",
"curr_frame",
"=",
"curr_frame",
".",
"f_back",
"print",
"(",
"'... Found nothing in all '",
"+",
"six",
".",
"text_type",
"(",
"frame_no",
")",
"+",
"' frames.'",
")",
"return",
"None"
] | Finds a local varable somewhere in the stack and returns the value
Args:
varname (str): variable name
Returns:
None if varname is not found else its value | [
"Finds",
"a",
"local",
"varable",
"somewhere",
"in",
"the",
"stack",
"and",
"returns",
"the",
"value"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dbg.py#L684-L704 | train |
Erotemic/utool | utool/util_dbg.py | formatex | def formatex(ex, msg='[!?] Caught exception',
prefix=None, key_list=[], locals_=None, iswarning=False, tb=False,
N=0, keys=None, colored=None):
r"""
Formats an exception with relevant info
Args:
ex (Exception): exception to print
msg (unicode): a message to display to the user (default = u'[!?] Caught exception')
keys (None): a list of strings denoting variables or expressions of interest (default = [])
iswarning (bool): prints as a warning rather than an error if True (default = False)
tb (bool): if True prints the traceback in the error message (default = False)
prefix (None): (default = None)
locals_ (None): (default = None)
N (int): (default = 0)
colored (None): (default = None)
key_list (list): DEPRICATED use keys
Returns:
str: formated exception
CommandLine:
python -m utool.util_dbg --exec-formatex
Example:
>>> # ENABLE_DOCTET
>>> from utool.util_dbg import * # NOQA
>>> import utool as ut
>>> msg = 'Testing Exception'
>>> prefix = '[test]'
>>> key_list = ['N', 'foo', 'tb']
>>> locals_ = None
>>> iswarning = True
>>> keys = None
>>> colored = None
>>> def failfunc():
>>> tb = True
>>> N = 0
>>> try:
>>> raise Exception('test exception. This is not an error')
>>> except Exception as ex:
>>> result = formatex(ex, msg, prefix, key_list, locals_,
>>> iswarning, tb, N, keys, colored)
>>> return result
>>> result = failfunc().replace('\n\n', '')
>>> print(result)
<!!! WARNING !!!>
Traceback (most recent call last):
File "<string>", line 15, in failfunc
Exception: test exception. This is not an error[test] Testing Exception
<class 'Exception'>: test exception. This is not an error
[test] N = 0
[test] foo = NameError (this likely due to a misformatted printex and is not related to the exception)
[test] tb = True
</!!! WARNING !!!>
"""
# Get error prefix and local info
if prefix is None:
prefix = get_caller_prefix(aserror=True, N=N)
if locals_ is None:
locals_ = get_parent_frame(N=N).f_locals
if keys is not None:
# shorthand for key_list
key_list = keys
# build exception message
errstr_list = [] # list of exception strings
ex_tag = 'WARNING' if iswarning else 'EXCEPTION'
errstr_list.append('<!!! %s !!!>' % ex_tag)
if tb or FORCE_TB:
tbtext = traceback.format_exc()
if colored or COLORED_EXCEPTIONS:
from utool import util_str
tbtext = util_str.highlight_text(tbtext, lexer_name='pytb', stripall=True)
errstr_list.append(tbtext)
errstr_list.append(prefix + ' ' + six.text_type(msg) + '\n%r: %s' % (type(ex), six.text_type(ex)))
#errstr_list.append(prefix + ' ' + six.text_type(msg) + '\ntype(ex)=%r' % (type(ex),))
parse_locals_keylist(locals_, key_list, errstr_list, prefix)
errstr_list.append('</!!! %s !!!>' % ex_tag)
return '\n'.join(errstr_list) | python | def formatex(ex, msg='[!?] Caught exception',
prefix=None, key_list=[], locals_=None, iswarning=False, tb=False,
N=0, keys=None, colored=None):
r"""
Formats an exception with relevant info
Args:
ex (Exception): exception to print
msg (unicode): a message to display to the user (default = u'[!?] Caught exception')
keys (None): a list of strings denoting variables or expressions of interest (default = [])
iswarning (bool): prints as a warning rather than an error if True (default = False)
tb (bool): if True prints the traceback in the error message (default = False)
prefix (None): (default = None)
locals_ (None): (default = None)
N (int): (default = 0)
colored (None): (default = None)
key_list (list): DEPRICATED use keys
Returns:
str: formated exception
CommandLine:
python -m utool.util_dbg --exec-formatex
Example:
>>> # ENABLE_DOCTET
>>> from utool.util_dbg import * # NOQA
>>> import utool as ut
>>> msg = 'Testing Exception'
>>> prefix = '[test]'
>>> key_list = ['N', 'foo', 'tb']
>>> locals_ = None
>>> iswarning = True
>>> keys = None
>>> colored = None
>>> def failfunc():
>>> tb = True
>>> N = 0
>>> try:
>>> raise Exception('test exception. This is not an error')
>>> except Exception as ex:
>>> result = formatex(ex, msg, prefix, key_list, locals_,
>>> iswarning, tb, N, keys, colored)
>>> return result
>>> result = failfunc().replace('\n\n', '')
>>> print(result)
<!!! WARNING !!!>
Traceback (most recent call last):
File "<string>", line 15, in failfunc
Exception: test exception. This is not an error[test] Testing Exception
<class 'Exception'>: test exception. This is not an error
[test] N = 0
[test] foo = NameError (this likely due to a misformatted printex and is not related to the exception)
[test] tb = True
</!!! WARNING !!!>
"""
# Get error prefix and local info
if prefix is None:
prefix = get_caller_prefix(aserror=True, N=N)
if locals_ is None:
locals_ = get_parent_frame(N=N).f_locals
if keys is not None:
# shorthand for key_list
key_list = keys
# build exception message
errstr_list = [] # list of exception strings
ex_tag = 'WARNING' if iswarning else 'EXCEPTION'
errstr_list.append('<!!! %s !!!>' % ex_tag)
if tb or FORCE_TB:
tbtext = traceback.format_exc()
if colored or COLORED_EXCEPTIONS:
from utool import util_str
tbtext = util_str.highlight_text(tbtext, lexer_name='pytb', stripall=True)
errstr_list.append(tbtext)
errstr_list.append(prefix + ' ' + six.text_type(msg) + '\n%r: %s' % (type(ex), six.text_type(ex)))
#errstr_list.append(prefix + ' ' + six.text_type(msg) + '\ntype(ex)=%r' % (type(ex),))
parse_locals_keylist(locals_, key_list, errstr_list, prefix)
errstr_list.append('</!!! %s !!!>' % ex_tag)
return '\n'.join(errstr_list) | [
"def",
"formatex",
"(",
"ex",
",",
"msg",
"=",
"'[!?] Caught exception'",
",",
"prefix",
"=",
"None",
",",
"key_list",
"=",
"[",
"]",
",",
"locals_",
"=",
"None",
",",
"iswarning",
"=",
"False",
",",
"tb",
"=",
"False",
",",
"N",
"=",
"0",
",",
"keys",
"=",
"None",
",",
"colored",
"=",
"None",
")",
":",
"# Get error prefix and local info",
"if",
"prefix",
"is",
"None",
":",
"prefix",
"=",
"get_caller_prefix",
"(",
"aserror",
"=",
"True",
",",
"N",
"=",
"N",
")",
"if",
"locals_",
"is",
"None",
":",
"locals_",
"=",
"get_parent_frame",
"(",
"N",
"=",
"N",
")",
".",
"f_locals",
"if",
"keys",
"is",
"not",
"None",
":",
"# shorthand for key_list",
"key_list",
"=",
"keys",
"# build exception message",
"errstr_list",
"=",
"[",
"]",
"# list of exception strings",
"ex_tag",
"=",
"'WARNING'",
"if",
"iswarning",
"else",
"'EXCEPTION'",
"errstr_list",
".",
"append",
"(",
"'<!!! %s !!!>'",
"%",
"ex_tag",
")",
"if",
"tb",
"or",
"FORCE_TB",
":",
"tbtext",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"if",
"colored",
"or",
"COLORED_EXCEPTIONS",
":",
"from",
"utool",
"import",
"util_str",
"tbtext",
"=",
"util_str",
".",
"highlight_text",
"(",
"tbtext",
",",
"lexer_name",
"=",
"'pytb'",
",",
"stripall",
"=",
"True",
")",
"errstr_list",
".",
"append",
"(",
"tbtext",
")",
"errstr_list",
".",
"append",
"(",
"prefix",
"+",
"' '",
"+",
"six",
".",
"text_type",
"(",
"msg",
")",
"+",
"'\\n%r: %s'",
"%",
"(",
"type",
"(",
"ex",
")",
",",
"six",
".",
"text_type",
"(",
"ex",
")",
")",
")",
"#errstr_list.append(prefix + ' ' + six.text_type(msg) + '\\ntype(ex)=%r' % (type(ex),))",
"parse_locals_keylist",
"(",
"locals_",
",",
"key_list",
",",
"errstr_list",
",",
"prefix",
")",
"errstr_list",
".",
"append",
"(",
"'</!!! %s !!!>'",
"%",
"ex_tag",
")",
"return",
"'\\n'",
".",
"join",
"(",
"errstr_list",
")"
] | r"""
Formats an exception with relevant info
Args:
ex (Exception): exception to print
msg (unicode): a message to display to the user (default = u'[!?] Caught exception')
keys (None): a list of strings denoting variables or expressions of interest (default = [])
iswarning (bool): prints as a warning rather than an error if True (default = False)
tb (bool): if True prints the traceback in the error message (default = False)
prefix (None): (default = None)
locals_ (None): (default = None)
N (int): (default = 0)
colored (None): (default = None)
key_list (list): DEPRICATED use keys
Returns:
str: formated exception
CommandLine:
python -m utool.util_dbg --exec-formatex
Example:
>>> # ENABLE_DOCTET
>>> from utool.util_dbg import * # NOQA
>>> import utool as ut
>>> msg = 'Testing Exception'
>>> prefix = '[test]'
>>> key_list = ['N', 'foo', 'tb']
>>> locals_ = None
>>> iswarning = True
>>> keys = None
>>> colored = None
>>> def failfunc():
>>> tb = True
>>> N = 0
>>> try:
>>> raise Exception('test exception. This is not an error')
>>> except Exception as ex:
>>> result = formatex(ex, msg, prefix, key_list, locals_,
>>> iswarning, tb, N, keys, colored)
>>> return result
>>> result = failfunc().replace('\n\n', '')
>>> print(result)
<!!! WARNING !!!>
Traceback (most recent call last):
File "<string>", line 15, in failfunc
Exception: test exception. This is not an error[test] Testing Exception
<class 'Exception'>: test exception. This is not an error
[test] N = 0
[test] foo = NameError (this likely due to a misformatted printex and is not related to the exception)
[test] tb = True
</!!! WARNING !!!> | [
"r",
"Formats",
"an",
"exception",
"with",
"relevant",
"info"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dbg.py#L1090-L1170 | train |
Erotemic/utool | utool/util_dbg.py | parse_locals_keylist | def parse_locals_keylist(locals_, key_list, strlist_=None, prefix=''):
""" For each key in keylist, puts its value in locals into a stringlist
Args:
locals_ (?):
key_list (list):
strlist_ (list): (default = None)
prefix (unicode): (default = u'')
Returns:
list: strlist_
CommandLine:
python -m utool.util_dbg --exec-parse_locals_keylist
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dbg import * # NOQA
>>> import utool as ut
>>> locals_ = {'foo': [1, 2, 3], 'bar': 'spam', 'eggs': 4, 'num': 5}
>>> key_list = [(len, 'foo'), 'bar.lower.__name__', 'eggs', 'num', 'other']
>>> strlist_ = None
>>> prefix = u''
>>> strlist_ = parse_locals_keylist(locals_, key_list, strlist_, prefix)
>>> result = ('strlist_ = %s' % (ut.repr2(strlist_, nl=True),))
>>> print(result)
strlist_ = [
' len(foo) = 3',
" bar.lower.__name__ = 'lower'",
' eggs = 4',
' num = 5',
' other = NameError (this likely due to a misformatted printex and is not related to the exception)',
]
"""
from utool import util_str
if strlist_ is None:
strlist_ = []
for key in key_list:
try:
if key is None:
strlist_.append('')
elif isinstance(key, tuple):
# Given a tuple of information
tup = key
func, key_ = tup
val = get_varval_from_locals(key_, locals_)
funcvalstr = six.text_type(func(val))
callname = util_str.get_callable_name(func)
strlist_.append('%s %s(%s) = %s' % (prefix, callname, key_, funcvalstr))
elif isinstance(key, six.string_types):
# Try to infer print from variable name
val = get_varval_from_locals(key, locals_)
#valstr = util_str.truncate_str(repr(val), maxlen=200)
valstr = util_str.truncate_str(util_str.repr2(val), maxlen=200)
strlist_.append('%s %s = %s' % (prefix, key, valstr))
else:
# Try to infer print from variable value
val = key
typestr = repr(type(val))
namestr = get_varname_from_locals(val, locals_)
#valstr = util_str.truncate_str(repr(val), maxlen=200)
valstr = util_str.truncate_str(util_str.repr2(val), maxlen=200)
strlist_.append('%s %s %s = %s' % (prefix, typestr, namestr, valstr))
except AssertionError as ex:
strlist_.append(prefix + ' ' + six.text_type(ex) + ' (this likely due to a misformatted printex and is not related to the exception)')
return strlist_ | python | def parse_locals_keylist(locals_, key_list, strlist_=None, prefix=''):
""" For each key in keylist, puts its value in locals into a stringlist
Args:
locals_ (?):
key_list (list):
strlist_ (list): (default = None)
prefix (unicode): (default = u'')
Returns:
list: strlist_
CommandLine:
python -m utool.util_dbg --exec-parse_locals_keylist
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dbg import * # NOQA
>>> import utool as ut
>>> locals_ = {'foo': [1, 2, 3], 'bar': 'spam', 'eggs': 4, 'num': 5}
>>> key_list = [(len, 'foo'), 'bar.lower.__name__', 'eggs', 'num', 'other']
>>> strlist_ = None
>>> prefix = u''
>>> strlist_ = parse_locals_keylist(locals_, key_list, strlist_, prefix)
>>> result = ('strlist_ = %s' % (ut.repr2(strlist_, nl=True),))
>>> print(result)
strlist_ = [
' len(foo) = 3',
" bar.lower.__name__ = 'lower'",
' eggs = 4',
' num = 5',
' other = NameError (this likely due to a misformatted printex and is not related to the exception)',
]
"""
from utool import util_str
if strlist_ is None:
strlist_ = []
for key in key_list:
try:
if key is None:
strlist_.append('')
elif isinstance(key, tuple):
# Given a tuple of information
tup = key
func, key_ = tup
val = get_varval_from_locals(key_, locals_)
funcvalstr = six.text_type(func(val))
callname = util_str.get_callable_name(func)
strlist_.append('%s %s(%s) = %s' % (prefix, callname, key_, funcvalstr))
elif isinstance(key, six.string_types):
# Try to infer print from variable name
val = get_varval_from_locals(key, locals_)
#valstr = util_str.truncate_str(repr(val), maxlen=200)
valstr = util_str.truncate_str(util_str.repr2(val), maxlen=200)
strlist_.append('%s %s = %s' % (prefix, key, valstr))
else:
# Try to infer print from variable value
val = key
typestr = repr(type(val))
namestr = get_varname_from_locals(val, locals_)
#valstr = util_str.truncate_str(repr(val), maxlen=200)
valstr = util_str.truncate_str(util_str.repr2(val), maxlen=200)
strlist_.append('%s %s %s = %s' % (prefix, typestr, namestr, valstr))
except AssertionError as ex:
strlist_.append(prefix + ' ' + six.text_type(ex) + ' (this likely due to a misformatted printex and is not related to the exception)')
return strlist_ | [
"def",
"parse_locals_keylist",
"(",
"locals_",
",",
"key_list",
",",
"strlist_",
"=",
"None",
",",
"prefix",
"=",
"''",
")",
":",
"from",
"utool",
"import",
"util_str",
"if",
"strlist_",
"is",
"None",
":",
"strlist_",
"=",
"[",
"]",
"for",
"key",
"in",
"key_list",
":",
"try",
":",
"if",
"key",
"is",
"None",
":",
"strlist_",
".",
"append",
"(",
"''",
")",
"elif",
"isinstance",
"(",
"key",
",",
"tuple",
")",
":",
"# Given a tuple of information",
"tup",
"=",
"key",
"func",
",",
"key_",
"=",
"tup",
"val",
"=",
"get_varval_from_locals",
"(",
"key_",
",",
"locals_",
")",
"funcvalstr",
"=",
"six",
".",
"text_type",
"(",
"func",
"(",
"val",
")",
")",
"callname",
"=",
"util_str",
".",
"get_callable_name",
"(",
"func",
")",
"strlist_",
".",
"append",
"(",
"'%s %s(%s) = %s'",
"%",
"(",
"prefix",
",",
"callname",
",",
"key_",
",",
"funcvalstr",
")",
")",
"elif",
"isinstance",
"(",
"key",
",",
"six",
".",
"string_types",
")",
":",
"# Try to infer print from variable name",
"val",
"=",
"get_varval_from_locals",
"(",
"key",
",",
"locals_",
")",
"#valstr = util_str.truncate_str(repr(val), maxlen=200)",
"valstr",
"=",
"util_str",
".",
"truncate_str",
"(",
"util_str",
".",
"repr2",
"(",
"val",
")",
",",
"maxlen",
"=",
"200",
")",
"strlist_",
".",
"append",
"(",
"'%s %s = %s'",
"%",
"(",
"prefix",
",",
"key",
",",
"valstr",
")",
")",
"else",
":",
"# Try to infer print from variable value",
"val",
"=",
"key",
"typestr",
"=",
"repr",
"(",
"type",
"(",
"val",
")",
")",
"namestr",
"=",
"get_varname_from_locals",
"(",
"val",
",",
"locals_",
")",
"#valstr = util_str.truncate_str(repr(val), maxlen=200)",
"valstr",
"=",
"util_str",
".",
"truncate_str",
"(",
"util_str",
".",
"repr2",
"(",
"val",
")",
",",
"maxlen",
"=",
"200",
")",
"strlist_",
".",
"append",
"(",
"'%s %s %s = %s'",
"%",
"(",
"prefix",
",",
"typestr",
",",
"namestr",
",",
"valstr",
")",
")",
"except",
"AssertionError",
"as",
"ex",
":",
"strlist_",
".",
"append",
"(",
"prefix",
"+",
"' '",
"+",
"six",
".",
"text_type",
"(",
"ex",
")",
"+",
"' (this likely due to a misformatted printex and is not related to the exception)'",
")",
"return",
"strlist_"
] | For each key in keylist, puts its value in locals into a stringlist
Args:
locals_ (?):
key_list (list):
strlist_ (list): (default = None)
prefix (unicode): (default = u'')
Returns:
list: strlist_
CommandLine:
python -m utool.util_dbg --exec-parse_locals_keylist
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dbg import * # NOQA
>>> import utool as ut
>>> locals_ = {'foo': [1, 2, 3], 'bar': 'spam', 'eggs': 4, 'num': 5}
>>> key_list = [(len, 'foo'), 'bar.lower.__name__', 'eggs', 'num', 'other']
>>> strlist_ = None
>>> prefix = u''
>>> strlist_ = parse_locals_keylist(locals_, key_list, strlist_, prefix)
>>> result = ('strlist_ = %s' % (ut.repr2(strlist_, nl=True),))
>>> print(result)
strlist_ = [
' len(foo) = 3',
" bar.lower.__name__ = 'lower'",
' eggs = 4',
' num = 5',
' other = NameError (this likely due to a misformatted printex and is not related to the exception)',
] | [
"For",
"each",
"key",
"in",
"keylist",
"puts",
"its",
"value",
"in",
"locals",
"into",
"a",
"stringlist"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dbg.py#L1265-L1331 | train |
dsoprea/NsqSpinner | nsq/consumer.py | ConsumerCallbacks.__send_rdy | def __send_rdy(self, connection, command):
"""Determine the RDY value, and set it. It can either be a static value
a callback, or None. If it's None, we'll calculate the value based on
our limits and connection counts.
The documentation recommends starting with (1), but since we are always
dealing directly with *nsqd* servers by now, we'll always have a valid
count to work with. Since we derive this count off a set of servers
that will always be up-to-date, we have everything we need, here, going
forward.
"""
if self.__consumer.original_rdy is None:
node_count = self.__consumer.get_node_count_for_topic(
connection.context.topic)
self.__logger_rdy.debug("Calculating RDY: max_in_flight=(%d) "
"node_count=(%d)",
self.__consumer.max_in_flight, node_count)
if self.__consumer.max_in_flight >= node_count:
# Calculate the RDY based on the max_in_flight and total number
# of servers. We always round up, or else we'd run the risk of
# not facilitating some servers.
rdy_this = int(math.ceil(
float(self.__consumer.max_in_flight) /
float(node_count)))
self.__logger_rdy.debug("Assigning RDY based on max_in_flight "
"(%d) and node count (%d) (optimal): "
"(%d)",
self.__consumer.max_in_flight,
node_count, rdy_this)
else:
# We have two possible scenarios:
# (1) The client is starting up, and the total RDY count is
# already accounted for.
# (2) The client is already started, and another connection has
# a (0) RDY count.
#
# In the case of (1), we'll take an RDY of (0). In the case of
# (2) We'll send an RDY of (1) on their behalf, before we
# assume a (0) for ourself.
# Look for existing connections that have a (0) RDY (which
# would've only been set to (0) intentionally).
self.__logger_rdy.debug("(max_in_flight > nodes). Doing RDY "
"election.")
sleeping_connections = [
c \
for (c, info) \
in self.__consumer.connection_context.items() \
if info['rdy_count'] == 0]
self.__logger_rdy.debug("Current sleeping_connections: %s",
sleeping_connections)
if sleeping_connections:
elected_connection = random.choice(sleeping_connections)
self.__logger_rdy.debug("Sending RDY of (1) on: [%s]",
elected_connection)
command_elected = nsq.command.Command(elected_connection)
command_elected.rdy(1)
else:
self.__logger.debug("No sleeping connections. We got the "
"short stick: [%s]", connection)
rdy_this = 0
else:
try:
rdy_this = self.__consumer.original_rdy(
connection.node,
self.__consumer.connection_count,
self.__consumer)
self.__logger_rdy.debug("Using RDY from callback: (%d)",
rdy_this)
except TypeError:
rdy_this = self.__consumer.original_rdy
self.__logger_rdy.debug("Using static RDY: (%d)", rdy_this)
# Make sure that the aggregate set of RDY counts doesn't exceed the
# max. This constrains the previous value, above.
rdy_this = min(rdy_this + \
self.__get_total_rdy_count(),
self.__consumer.max_in_flight)
# Make sure we don't exceed the maximum specified by the server. This
# only works because we're running greenlets, not threads. At any given
# time, only one greenlet is running, and we can make sure to
# distribute the remainder of (max_in_flight / nodes) across a subset
# of the nodes (they don't all have to have an even slice of
# max_in_flight).
server_features = self.__consumer.identify.server_features
max_rdy_count = server_features['max_rdy_count']
rdy_this = min(max_rdy_count, rdy_this)
self.__logger_rdy.debug("Final RDY (max_in_flight=(%d) "
"max_rdy_count=(%d)): (%d)",
self.__consumer.max_in_flight, max_rdy_count,
rdy_this)
if rdy_this > 0:
command.rdy(rdy_this)
else:
self.__logger_rdy.info("This connection will go to sleep (not "
"enough RDY to go around).")
return rdy_this | python | def __send_rdy(self, connection, command):
"""Determine the RDY value, and set it. It can either be a static value
a callback, or None. If it's None, we'll calculate the value based on
our limits and connection counts.
The documentation recommends starting with (1), but since we are always
dealing directly with *nsqd* servers by now, we'll always have a valid
count to work with. Since we derive this count off a set of servers
that will always be up-to-date, we have everything we need, here, going
forward.
"""
if self.__consumer.original_rdy is None:
node_count = self.__consumer.get_node_count_for_topic(
connection.context.topic)
self.__logger_rdy.debug("Calculating RDY: max_in_flight=(%d) "
"node_count=(%d)",
self.__consumer.max_in_flight, node_count)
if self.__consumer.max_in_flight >= node_count:
# Calculate the RDY based on the max_in_flight and total number
# of servers. We always round up, or else we'd run the risk of
# not facilitating some servers.
rdy_this = int(math.ceil(
float(self.__consumer.max_in_flight) /
float(node_count)))
self.__logger_rdy.debug("Assigning RDY based on max_in_flight "
"(%d) and node count (%d) (optimal): "
"(%d)",
self.__consumer.max_in_flight,
node_count, rdy_this)
else:
# We have two possible scenarios:
# (1) The client is starting up, and the total RDY count is
# already accounted for.
# (2) The client is already started, and another connection has
# a (0) RDY count.
#
# In the case of (1), we'll take an RDY of (0). In the case of
# (2) We'll send an RDY of (1) on their behalf, before we
# assume a (0) for ourself.
# Look for existing connections that have a (0) RDY (which
# would've only been set to (0) intentionally).
self.__logger_rdy.debug("(max_in_flight > nodes). Doing RDY "
"election.")
sleeping_connections = [
c \
for (c, info) \
in self.__consumer.connection_context.items() \
if info['rdy_count'] == 0]
self.__logger_rdy.debug("Current sleeping_connections: %s",
sleeping_connections)
if sleeping_connections:
elected_connection = random.choice(sleeping_connections)
self.__logger_rdy.debug("Sending RDY of (1) on: [%s]",
elected_connection)
command_elected = nsq.command.Command(elected_connection)
command_elected.rdy(1)
else:
self.__logger.debug("No sleeping connections. We got the "
"short stick: [%s]", connection)
rdy_this = 0
else:
try:
rdy_this = self.__consumer.original_rdy(
connection.node,
self.__consumer.connection_count,
self.__consumer)
self.__logger_rdy.debug("Using RDY from callback: (%d)",
rdy_this)
except TypeError:
rdy_this = self.__consumer.original_rdy
self.__logger_rdy.debug("Using static RDY: (%d)", rdy_this)
# Make sure that the aggregate set of RDY counts doesn't exceed the
# max. This constrains the previous value, above.
rdy_this = min(rdy_this + \
self.__get_total_rdy_count(),
self.__consumer.max_in_flight)
# Make sure we don't exceed the maximum specified by the server. This
# only works because we're running greenlets, not threads. At any given
# time, only one greenlet is running, and we can make sure to
# distribute the remainder of (max_in_flight / nodes) across a subset
# of the nodes (they don't all have to have an even slice of
# max_in_flight).
server_features = self.__consumer.identify.server_features
max_rdy_count = server_features['max_rdy_count']
rdy_this = min(max_rdy_count, rdy_this)
self.__logger_rdy.debug("Final RDY (max_in_flight=(%d) "
"max_rdy_count=(%d)): (%d)",
self.__consumer.max_in_flight, max_rdy_count,
rdy_this)
if rdy_this > 0:
command.rdy(rdy_this)
else:
self.__logger_rdy.info("This connection will go to sleep (not "
"enough RDY to go around).")
return rdy_this | [
"def",
"__send_rdy",
"(",
"self",
",",
"connection",
",",
"command",
")",
":",
"if",
"self",
".",
"__consumer",
".",
"original_rdy",
"is",
"None",
":",
"node_count",
"=",
"self",
".",
"__consumer",
".",
"get_node_count_for_topic",
"(",
"connection",
".",
"context",
".",
"topic",
")",
"self",
".",
"__logger_rdy",
".",
"debug",
"(",
"\"Calculating RDY: max_in_flight=(%d) \"",
"\"node_count=(%d)\"",
",",
"self",
".",
"__consumer",
".",
"max_in_flight",
",",
"node_count",
")",
"if",
"self",
".",
"__consumer",
".",
"max_in_flight",
">=",
"node_count",
":",
"# Calculate the RDY based on the max_in_flight and total number ",
"# of servers. We always round up, or else we'd run the risk of ",
"# not facilitating some servers.",
"rdy_this",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"float",
"(",
"self",
".",
"__consumer",
".",
"max_in_flight",
")",
"/",
"float",
"(",
"node_count",
")",
")",
")",
"self",
".",
"__logger_rdy",
".",
"debug",
"(",
"\"Assigning RDY based on max_in_flight \"",
"\"(%d) and node count (%d) (optimal): \"",
"\"(%d)\"",
",",
"self",
".",
"__consumer",
".",
"max_in_flight",
",",
"node_count",
",",
"rdy_this",
")",
"else",
":",
"# We have two possible scenarios:",
"# (1) The client is starting up, and the total RDY count is ",
"# already accounted for.",
"# (2) The client is already started, and another connection has",
"# a (0) RDY count.",
"#",
"# In the case of (1), we'll take an RDY of (0). In the case of",
"# (2) We'll send an RDY of (1) on their behalf, before we ",
"# assume a (0) for ourself.",
"# Look for existing connections that have a (0) RDY (which ",
"# would've only been set to (0) intentionally).",
"self",
".",
"__logger_rdy",
".",
"debug",
"(",
"\"(max_in_flight > nodes). Doing RDY \"",
"\"election.\"",
")",
"sleeping_connections",
"=",
"[",
"c",
"for",
"(",
"c",
",",
"info",
")",
"in",
"self",
".",
"__consumer",
".",
"connection_context",
".",
"items",
"(",
")",
"if",
"info",
"[",
"'rdy_count'",
"]",
"==",
"0",
"]",
"self",
".",
"__logger_rdy",
".",
"debug",
"(",
"\"Current sleeping_connections: %s\"",
",",
"sleeping_connections",
")",
"if",
"sleeping_connections",
":",
"elected_connection",
"=",
"random",
".",
"choice",
"(",
"sleeping_connections",
")",
"self",
".",
"__logger_rdy",
".",
"debug",
"(",
"\"Sending RDY of (1) on: [%s]\"",
",",
"elected_connection",
")",
"command_elected",
"=",
"nsq",
".",
"command",
".",
"Command",
"(",
"elected_connection",
")",
"command_elected",
".",
"rdy",
"(",
"1",
")",
"else",
":",
"self",
".",
"__logger",
".",
"debug",
"(",
"\"No sleeping connections. We got the \"",
"\"short stick: [%s]\"",
",",
"connection",
")",
"rdy_this",
"=",
"0",
"else",
":",
"try",
":",
"rdy_this",
"=",
"self",
".",
"__consumer",
".",
"original_rdy",
"(",
"connection",
".",
"node",
",",
"self",
".",
"__consumer",
".",
"connection_count",
",",
"self",
".",
"__consumer",
")",
"self",
".",
"__logger_rdy",
".",
"debug",
"(",
"\"Using RDY from callback: (%d)\"",
",",
"rdy_this",
")",
"except",
"TypeError",
":",
"rdy_this",
"=",
"self",
".",
"__consumer",
".",
"original_rdy",
"self",
".",
"__logger_rdy",
".",
"debug",
"(",
"\"Using static RDY: (%d)\"",
",",
"rdy_this",
")",
"# Make sure that the aggregate set of RDY counts doesn't exceed the ",
"# max. This constrains the previous value, above.",
"rdy_this",
"=",
"min",
"(",
"rdy_this",
"+",
"self",
".",
"__get_total_rdy_count",
"(",
")",
",",
"self",
".",
"__consumer",
".",
"max_in_flight",
")",
"# Make sure we don't exceed the maximum specified by the server. This ",
"# only works because we're running greenlets, not threads. At any given ",
"# time, only one greenlet is running, and we can make sure to ",
"# distribute the remainder of (max_in_flight / nodes) across a subset ",
"# of the nodes (they don't all have to have an even slice of ",
"# max_in_flight).",
"server_features",
"=",
"self",
".",
"__consumer",
".",
"identify",
".",
"server_features",
"max_rdy_count",
"=",
"server_features",
"[",
"'max_rdy_count'",
"]",
"rdy_this",
"=",
"min",
"(",
"max_rdy_count",
",",
"rdy_this",
")",
"self",
".",
"__logger_rdy",
".",
"debug",
"(",
"\"Final RDY (max_in_flight=(%d) \"",
"\"max_rdy_count=(%d)): (%d)\"",
",",
"self",
".",
"__consumer",
".",
"max_in_flight",
",",
"max_rdy_count",
",",
"rdy_this",
")",
"if",
"rdy_this",
">",
"0",
":",
"command",
".",
"rdy",
"(",
"rdy_this",
")",
"else",
":",
"self",
".",
"__logger_rdy",
".",
"info",
"(",
"\"This connection will go to sleep (not \"",
"\"enough RDY to go around).\"",
")",
"return",
"rdy_this"
] | Determine the RDY value, and set it. It can either be a static value
a callback, or None. If it's None, we'll calculate the value based on
our limits and connection counts.
The documentation recommends starting with (1), but since we are always
dealing directly with *nsqd* servers by now, we'll always have a valid
count to work with. Since we derive this count off a set of servers
that will always be up-to-date, we have everything we need, here, going
forward. | [
"Determine",
"the",
"RDY",
"value",
"and",
"set",
"it",
".",
"It",
"can",
"either",
"be",
"a",
"static",
"value",
"a",
"callback",
"or",
"None",
".",
"If",
"it",
"s",
"None",
"we",
"ll",
"calculate",
"the",
"value",
"based",
"on",
"our",
"limits",
"and",
"connection",
"counts",
"."
] | 972237b8ddce737983bfed001fde52e5236be695 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/consumer.py#L41-L153 | train |
glormph/msstitch | src/app/actions/headers/peptable.py | switch_psm_to_peptable_fields | def switch_psm_to_peptable_fields(oldheader):
"""Returns a dict map with old to new header fields"""
return {old: new for old, new in zip([mzidtsvdata.HEADER_PEPTIDE,
mzidtsvdata.HEADER_PROTEIN,
mzidtsvdata.HEADER_PEPTIDE_Q,
mzidtsvdata.HEADER_PEPTIDE_PEP],
[peptabledata.HEADER_PEPTIDE,
peptabledata.HEADER_PROTEINS,
peptabledata.HEADER_QVAL,
peptabledata.HEADER_PEP])} | python | def switch_psm_to_peptable_fields(oldheader):
"""Returns a dict map with old to new header fields"""
return {old: new for old, new in zip([mzidtsvdata.HEADER_PEPTIDE,
mzidtsvdata.HEADER_PROTEIN,
mzidtsvdata.HEADER_PEPTIDE_Q,
mzidtsvdata.HEADER_PEPTIDE_PEP],
[peptabledata.HEADER_PEPTIDE,
peptabledata.HEADER_PROTEINS,
peptabledata.HEADER_QVAL,
peptabledata.HEADER_PEP])} | [
"def",
"switch_psm_to_peptable_fields",
"(",
"oldheader",
")",
":",
"return",
"{",
"old",
":",
"new",
"for",
"old",
",",
"new",
"in",
"zip",
"(",
"[",
"mzidtsvdata",
".",
"HEADER_PEPTIDE",
",",
"mzidtsvdata",
".",
"HEADER_PROTEIN",
",",
"mzidtsvdata",
".",
"HEADER_PEPTIDE_Q",
",",
"mzidtsvdata",
".",
"HEADER_PEPTIDE_PEP",
"]",
",",
"[",
"peptabledata",
".",
"HEADER_PEPTIDE",
",",
"peptabledata",
".",
"HEADER_PROTEINS",
",",
"peptabledata",
".",
"HEADER_QVAL",
",",
"peptabledata",
".",
"HEADER_PEP",
"]",
")",
"}"
] | Returns a dict map with old to new header fields | [
"Returns",
"a",
"dict",
"map",
"with",
"old",
"to",
"new",
"header",
"fields"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/headers/peptable.py#L11-L20 | train |
anayjoshi/platypus | platypus/cfg/cfg.py | BasicBlock.add_instruction | def add_instruction (self, instr):
"""
Adds the argument instruction in the list of instructions of this basic block.
Also updates the variable lists (used_variables, defined_variables)
"""
assert(isinstance(instr, Instruction))
self.instruction_list.append(instr)
if instr.lhs not in self.defined_variables:
if isinstance(instr.lhs, Variable):
self.defined_variables.append(instr.lhs)
if isinstance(instr, EqInstruction):
if isinstance(instr.rhs, Variable):
if instr.rhs not in self.used_variables:
self.used_variables.append(instr.rhs)
else:
if isinstance(instr.rhs_1, Variable):
if instr.rhs_1 not in self.used_variables:
self.used_variables.append(instr.rhs_1)
if isinstance(instr.rhs_2, Variable):
if instr.rhs_2 not in self.used_variables:
self.used_variables.append(instr.rhs_2) | python | def add_instruction (self, instr):
"""
Adds the argument instruction in the list of instructions of this basic block.
Also updates the variable lists (used_variables, defined_variables)
"""
assert(isinstance(instr, Instruction))
self.instruction_list.append(instr)
if instr.lhs not in self.defined_variables:
if isinstance(instr.lhs, Variable):
self.defined_variables.append(instr.lhs)
if isinstance(instr, EqInstruction):
if isinstance(instr.rhs, Variable):
if instr.rhs not in self.used_variables:
self.used_variables.append(instr.rhs)
else:
if isinstance(instr.rhs_1, Variable):
if instr.rhs_1 not in self.used_variables:
self.used_variables.append(instr.rhs_1)
if isinstance(instr.rhs_2, Variable):
if instr.rhs_2 not in self.used_variables:
self.used_variables.append(instr.rhs_2) | [
"def",
"add_instruction",
"(",
"self",
",",
"instr",
")",
":",
"assert",
"(",
"isinstance",
"(",
"instr",
",",
"Instruction",
")",
")",
"self",
".",
"instruction_list",
".",
"append",
"(",
"instr",
")",
"if",
"instr",
".",
"lhs",
"not",
"in",
"self",
".",
"defined_variables",
":",
"if",
"isinstance",
"(",
"instr",
".",
"lhs",
",",
"Variable",
")",
":",
"self",
".",
"defined_variables",
".",
"append",
"(",
"instr",
".",
"lhs",
")",
"if",
"isinstance",
"(",
"instr",
",",
"EqInstruction",
")",
":",
"if",
"isinstance",
"(",
"instr",
".",
"rhs",
",",
"Variable",
")",
":",
"if",
"instr",
".",
"rhs",
"not",
"in",
"self",
".",
"used_variables",
":",
"self",
".",
"used_variables",
".",
"append",
"(",
"instr",
".",
"rhs",
")",
"else",
":",
"if",
"isinstance",
"(",
"instr",
".",
"rhs_1",
",",
"Variable",
")",
":",
"if",
"instr",
".",
"rhs_1",
"not",
"in",
"self",
".",
"used_variables",
":",
"self",
".",
"used_variables",
".",
"append",
"(",
"instr",
".",
"rhs_1",
")",
"if",
"isinstance",
"(",
"instr",
".",
"rhs_2",
",",
"Variable",
")",
":",
"if",
"instr",
".",
"rhs_2",
"not",
"in",
"self",
".",
"used_variables",
":",
"self",
".",
"used_variables",
".",
"append",
"(",
"instr",
".",
"rhs_2",
")"
] | Adds the argument instruction in the list of instructions of this basic block.
Also updates the variable lists (used_variables, defined_variables) | [
"Adds",
"the",
"argument",
"instruction",
"in",
"the",
"list",
"of",
"instructions",
"of",
"this",
"basic",
"block",
"."
] | 71712f58c99651efbd2e6dfd75a9b1228d42e9ef | https://github.com/anayjoshi/platypus/blob/71712f58c99651efbd2e6dfd75a9b1228d42e9ef/platypus/cfg/cfg.py#L169-L190 | train |
anayjoshi/platypus | platypus/cfg/cfg.py | BasicBlock.set_condition | def set_condition(self, condition, condition_instr=None):
"""
Defines the condition which decides how the basic block exits
:param condition:
:type condition:
:param condition_instr: If the 'condition' argument is a Variable, then\
condition_instr is None, else, condition_instr should be\
of type CmpInstruction
:type condition_instr: CmpInstruction
"""
assert(isinstance(condition, Numeric))
if condition_instr is not None:
assert(isinstance(condition_instr, CmpInstruction))
self.condition = condition
self.condition_instr = condition_instr
if condition_instr is not None:
if condition_instr.lhs not in self.defined_variables:
if isinstance(condition_instr.lhs, Variable):
self.defined_variables.append(condition_instr.lhs)
if isinstance(condition_instr.rhs_1, Variable):
if condition_instr.rhs_1 not in self.used_variables:
self.used_variables.append(condition_instr.rhs_1)
if isinstance(condition_instr.rhs_2, Variable):
if condition_instr.rhs_2 not in self.used_variables:
self.used_variables.append(condition_instr.rhs_2) | python | def set_condition(self, condition, condition_instr=None):
"""
Defines the condition which decides how the basic block exits
:param condition:
:type condition:
:param condition_instr: If the 'condition' argument is a Variable, then\
condition_instr is None, else, condition_instr should be\
of type CmpInstruction
:type condition_instr: CmpInstruction
"""
assert(isinstance(condition, Numeric))
if condition_instr is not None:
assert(isinstance(condition_instr, CmpInstruction))
self.condition = condition
self.condition_instr = condition_instr
if condition_instr is not None:
if condition_instr.lhs not in self.defined_variables:
if isinstance(condition_instr.lhs, Variable):
self.defined_variables.append(condition_instr.lhs)
if isinstance(condition_instr.rhs_1, Variable):
if condition_instr.rhs_1 not in self.used_variables:
self.used_variables.append(condition_instr.rhs_1)
if isinstance(condition_instr.rhs_2, Variable):
if condition_instr.rhs_2 not in self.used_variables:
self.used_variables.append(condition_instr.rhs_2) | [
"def",
"set_condition",
"(",
"self",
",",
"condition",
",",
"condition_instr",
"=",
"None",
")",
":",
"assert",
"(",
"isinstance",
"(",
"condition",
",",
"Numeric",
")",
")",
"if",
"condition_instr",
"is",
"not",
"None",
":",
"assert",
"(",
"isinstance",
"(",
"condition_instr",
",",
"CmpInstruction",
")",
")",
"self",
".",
"condition",
"=",
"condition",
"self",
".",
"condition_instr",
"=",
"condition_instr",
"if",
"condition_instr",
"is",
"not",
"None",
":",
"if",
"condition_instr",
".",
"lhs",
"not",
"in",
"self",
".",
"defined_variables",
":",
"if",
"isinstance",
"(",
"condition_instr",
".",
"lhs",
",",
"Variable",
")",
":",
"self",
".",
"defined_variables",
".",
"append",
"(",
"condition_instr",
".",
"lhs",
")",
"if",
"isinstance",
"(",
"condition_instr",
".",
"rhs_1",
",",
"Variable",
")",
":",
"if",
"condition_instr",
".",
"rhs_1",
"not",
"in",
"self",
".",
"used_variables",
":",
"self",
".",
"used_variables",
".",
"append",
"(",
"condition_instr",
".",
"rhs_1",
")",
"if",
"isinstance",
"(",
"condition_instr",
".",
"rhs_2",
",",
"Variable",
")",
":",
"if",
"condition_instr",
".",
"rhs_2",
"not",
"in",
"self",
".",
"used_variables",
":",
"self",
".",
"used_variables",
".",
"append",
"(",
"condition_instr",
".",
"rhs_2",
")"
] | Defines the condition which decides how the basic block exits
:param condition:
:type condition:
:param condition_instr: If the 'condition' argument is a Variable, then\
condition_instr is None, else, condition_instr should be\
of type CmpInstruction
:type condition_instr: CmpInstruction | [
"Defines",
"the",
"condition",
"which",
"decides",
"how",
"the",
"basic",
"block",
"exits"
] | 71712f58c99651efbd2e6dfd75a9b1228d42e9ef | https://github.com/anayjoshi/platypus/blob/71712f58c99651efbd2e6dfd75a9b1228d42e9ef/platypus/cfg/cfg.py#L193-L219 | train |
anayjoshi/platypus | platypus/cfg/cfg.py | Function.add_basic_block | def add_basic_block(self, basic_block):
"""Adds the given basic block in the function"""
assert(isinstance(basic_block, BasicBlock))
self.basic_block_list.append(basic_block) | python | def add_basic_block(self, basic_block):
"""Adds the given basic block in the function"""
assert(isinstance(basic_block, BasicBlock))
self.basic_block_list.append(basic_block) | [
"def",
"add_basic_block",
"(",
"self",
",",
"basic_block",
")",
":",
"assert",
"(",
"isinstance",
"(",
"basic_block",
",",
"BasicBlock",
")",
")",
"self",
".",
"basic_block_list",
".",
"append",
"(",
"basic_block",
")"
] | Adds the given basic block in the function | [
"Adds",
"the",
"given",
"basic",
"block",
"in",
"the",
"function"
] | 71712f58c99651efbd2e6dfd75a9b1228d42e9ef | https://github.com/anayjoshi/platypus/blob/71712f58c99651efbd2e6dfd75a9b1228d42e9ef/platypus/cfg/cfg.py#L256-L259 | train |
anayjoshi/platypus | platypus/cfg/cfg.py | Function.get_variable | def get_variable(self, var_name):
"""
If a variable with the name var_name exists in this function's variable list, \
then that variable object is returned; else a new variable is created\
with the given name and added to the variable list of this function\
and returned back
:returns: A variable which has the its name as var_name
:rype: Variable
"""
assert(isinstance(var_name, str))
if isinstance(var_name, str):
for var in self.variable_list:
if var.name == var_name:
return var
new_var = Variable(var_name)
self.variable_list.append(new_var)
return new_var | python | def get_variable(self, var_name):
"""
If a variable with the name var_name exists in this function's variable list, \
then that variable object is returned; else a new variable is created\
with the given name and added to the variable list of this function\
and returned back
:returns: A variable which has the its name as var_name
:rype: Variable
"""
assert(isinstance(var_name, str))
if isinstance(var_name, str):
for var in self.variable_list:
if var.name == var_name:
return var
new_var = Variable(var_name)
self.variable_list.append(new_var)
return new_var | [
"def",
"get_variable",
"(",
"self",
",",
"var_name",
")",
":",
"assert",
"(",
"isinstance",
"(",
"var_name",
",",
"str",
")",
")",
"if",
"isinstance",
"(",
"var_name",
",",
"str",
")",
":",
"for",
"var",
"in",
"self",
".",
"variable_list",
":",
"if",
"var",
".",
"name",
"==",
"var_name",
":",
"return",
"var",
"new_var",
"=",
"Variable",
"(",
"var_name",
")",
"self",
".",
"variable_list",
".",
"append",
"(",
"new_var",
")",
"return",
"new_var"
] | If a variable with the name var_name exists in this function's variable list, \
then that variable object is returned; else a new variable is created\
with the given name and added to the variable list of this function\
and returned back
:returns: A variable which has the its name as var_name
:rype: Variable | [
"If",
"a",
"variable",
"with",
"the",
"name",
"var_name",
"exists",
"in",
"this",
"function",
"s",
"variable",
"list",
"\\",
"then",
"that",
"variable",
"object",
"is",
"returned",
";",
"else",
"a",
"new",
"variable",
"is",
"created",
"\\",
"with",
"the",
"given",
"name",
"and",
"added",
"to",
"the",
"variable",
"list",
"of",
"this",
"function",
"\\",
"and",
"returned",
"back"
] | 71712f58c99651efbd2e6dfd75a9b1228d42e9ef | https://github.com/anayjoshi/platypus/blob/71712f58c99651efbd2e6dfd75a9b1228d42e9ef/platypus/cfg/cfg.py#L268-L285 | train |
anayjoshi/platypus | platypus/cfg/cfg.py | Function.add_input_variable | def add_input_variable(self, var):
"""Adds the argument variable as one of the input variable"""
assert(isinstance(var, Variable))
self.input_variable_list.append(var) | python | def add_input_variable(self, var):
"""Adds the argument variable as one of the input variable"""
assert(isinstance(var, Variable))
self.input_variable_list.append(var) | [
"def",
"add_input_variable",
"(",
"self",
",",
"var",
")",
":",
"assert",
"(",
"isinstance",
"(",
"var",
",",
"Variable",
")",
")",
"self",
".",
"input_variable_list",
".",
"append",
"(",
"var",
")"
] | Adds the argument variable as one of the input variable | [
"Adds",
"the",
"argument",
"variable",
"as",
"one",
"of",
"the",
"input",
"variable"
] | 71712f58c99651efbd2e6dfd75a9b1228d42e9ef | https://github.com/anayjoshi/platypus/blob/71712f58c99651efbd2e6dfd75a9b1228d42e9ef/platypus/cfg/cfg.py#L287-L290 | train |
anayjoshi/platypus | platypus/cfg/cfg.py | Function.add_output_variable | def add_output_variable(self, var):
"""Adds the argument variable as one of the output variable"""
assert(isinstance(var, Variable))
self.output_variable_list.append(var) | python | def add_output_variable(self, var):
"""Adds the argument variable as one of the output variable"""
assert(isinstance(var, Variable))
self.output_variable_list.append(var) | [
"def",
"add_output_variable",
"(",
"self",
",",
"var",
")",
":",
"assert",
"(",
"isinstance",
"(",
"var",
",",
"Variable",
")",
")",
"self",
".",
"output_variable_list",
".",
"append",
"(",
"var",
")"
] | Adds the argument variable as one of the output variable | [
"Adds",
"the",
"argument",
"variable",
"as",
"one",
"of",
"the",
"output",
"variable"
] | 71712f58c99651efbd2e6dfd75a9b1228d42e9ef | https://github.com/anayjoshi/platypus/blob/71712f58c99651efbd2e6dfd75a9b1228d42e9ef/platypus/cfg/cfg.py#L292-L295 | train |
LEMS/pylems | lems/parser/expr.py | ExprParser.tokenize | def tokenize(self):
"""
Tokenizes the string stored in the parser object into a list
of tokens.
"""
self.token_list = []
ps = self.parse_string.strip()
i = 0
last_token = None
while i < len(ps) and ps[i].isspace():
i += 1
while i < len(ps):
token = ''
if ps[i].isalpha():
while i < len(ps) and (ps[i].isalnum() or ps[i] == '_'):
token += ps[i]
i += 1
elif ps[i].isdigit():
while i < len(ps) and (ps[i].isdigit() or
ps[i] == '.' or
ps[i] == 'e' or
ps[i] == 'E' or
(ps[i] == '+' and (ps[i-1] == 'e' or ps[i-1] == 'E')) or
(ps[i] == '-' and (ps[i-1] == 'e' or ps[i-1] == 'E'))):
token += ps[i]
i += 1
elif ps[i] == '.':
if ps[i+1].isdigit():
while i < len(ps) and (ps[i].isdigit() or ps[i] == '.'):
token += ps[i]
i += 1
else:
while i < len(ps) and (ps[i].isalpha() or ps[i] == '.'):
token += ps[i]
i += 1
else:
token += ps[i]
i += 1
if token == '-' and \
(last_token == None or last_token == '(' or self.is_op(last_token)):
token = '~'
self.token_list += [token]
last_token = token
while i < len(ps) and ps[i].isspace():
i += 1 | python | def tokenize(self):
"""
Tokenizes the string stored in the parser object into a list
of tokens.
"""
self.token_list = []
ps = self.parse_string.strip()
i = 0
last_token = None
while i < len(ps) and ps[i].isspace():
i += 1
while i < len(ps):
token = ''
if ps[i].isalpha():
while i < len(ps) and (ps[i].isalnum() or ps[i] == '_'):
token += ps[i]
i += 1
elif ps[i].isdigit():
while i < len(ps) and (ps[i].isdigit() or
ps[i] == '.' or
ps[i] == 'e' or
ps[i] == 'E' or
(ps[i] == '+' and (ps[i-1] == 'e' or ps[i-1] == 'E')) or
(ps[i] == '-' and (ps[i-1] == 'e' or ps[i-1] == 'E'))):
token += ps[i]
i += 1
elif ps[i] == '.':
if ps[i+1].isdigit():
while i < len(ps) and (ps[i].isdigit() or ps[i] == '.'):
token += ps[i]
i += 1
else:
while i < len(ps) and (ps[i].isalpha() or ps[i] == '.'):
token += ps[i]
i += 1
else:
token += ps[i]
i += 1
if token == '-' and \
(last_token == None or last_token == '(' or self.is_op(last_token)):
token = '~'
self.token_list += [token]
last_token = token
while i < len(ps) and ps[i].isspace():
i += 1 | [
"def",
"tokenize",
"(",
"self",
")",
":",
"self",
".",
"token_list",
"=",
"[",
"]",
"ps",
"=",
"self",
".",
"parse_string",
".",
"strip",
"(",
")",
"i",
"=",
"0",
"last_token",
"=",
"None",
"while",
"i",
"<",
"len",
"(",
"ps",
")",
"and",
"ps",
"[",
"i",
"]",
".",
"isspace",
"(",
")",
":",
"i",
"+=",
"1",
"while",
"i",
"<",
"len",
"(",
"ps",
")",
":",
"token",
"=",
"''",
"if",
"ps",
"[",
"i",
"]",
".",
"isalpha",
"(",
")",
":",
"while",
"i",
"<",
"len",
"(",
"ps",
")",
"and",
"(",
"ps",
"[",
"i",
"]",
".",
"isalnum",
"(",
")",
"or",
"ps",
"[",
"i",
"]",
"==",
"'_'",
")",
":",
"token",
"+=",
"ps",
"[",
"i",
"]",
"i",
"+=",
"1",
"elif",
"ps",
"[",
"i",
"]",
".",
"isdigit",
"(",
")",
":",
"while",
"i",
"<",
"len",
"(",
"ps",
")",
"and",
"(",
"ps",
"[",
"i",
"]",
".",
"isdigit",
"(",
")",
"or",
"ps",
"[",
"i",
"]",
"==",
"'.'",
"or",
"ps",
"[",
"i",
"]",
"==",
"'e'",
"or",
"ps",
"[",
"i",
"]",
"==",
"'E'",
"or",
"(",
"ps",
"[",
"i",
"]",
"==",
"'+'",
"and",
"(",
"ps",
"[",
"i",
"-",
"1",
"]",
"==",
"'e'",
"or",
"ps",
"[",
"i",
"-",
"1",
"]",
"==",
"'E'",
")",
")",
"or",
"(",
"ps",
"[",
"i",
"]",
"==",
"'-'",
"and",
"(",
"ps",
"[",
"i",
"-",
"1",
"]",
"==",
"'e'",
"or",
"ps",
"[",
"i",
"-",
"1",
"]",
"==",
"'E'",
")",
")",
")",
":",
"token",
"+=",
"ps",
"[",
"i",
"]",
"i",
"+=",
"1",
"elif",
"ps",
"[",
"i",
"]",
"==",
"'.'",
":",
"if",
"ps",
"[",
"i",
"+",
"1",
"]",
".",
"isdigit",
"(",
")",
":",
"while",
"i",
"<",
"len",
"(",
"ps",
")",
"and",
"(",
"ps",
"[",
"i",
"]",
".",
"isdigit",
"(",
")",
"or",
"ps",
"[",
"i",
"]",
"==",
"'.'",
")",
":",
"token",
"+=",
"ps",
"[",
"i",
"]",
"i",
"+=",
"1",
"else",
":",
"while",
"i",
"<",
"len",
"(",
"ps",
")",
"and",
"(",
"ps",
"[",
"i",
"]",
".",
"isalpha",
"(",
")",
"or",
"ps",
"[",
"i",
"]",
"==",
"'.'",
")",
":",
"token",
"+=",
"ps",
"[",
"i",
"]",
"i",
"+=",
"1",
"else",
":",
"token",
"+=",
"ps",
"[",
"i",
"]",
"i",
"+=",
"1",
"if",
"token",
"==",
"'-'",
"and",
"(",
"last_token",
"==",
"None",
"or",
"last_token",
"==",
"'('",
"or",
"self",
".",
"is_op",
"(",
"last_token",
")",
")",
":",
"token",
"=",
"'~'",
"self",
".",
"token_list",
"+=",
"[",
"token",
"]",
"last_token",
"=",
"token",
"while",
"i",
"<",
"len",
"(",
"ps",
")",
"and",
"ps",
"[",
"i",
"]",
".",
"isspace",
"(",
")",
":",
"i",
"+=",
"1"
] | Tokenizes the string stored in the parser object into a list
of tokens. | [
"Tokenizes",
"the",
"string",
"stored",
"in",
"the",
"parser",
"object",
"into",
"a",
"list",
"of",
"tokens",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/parser/expr.py#L263-L315 | train |
LEMS/pylems | lems/parser/expr.py | ExprParser.parse | def parse(self):
"""
Tokenizes and parses an arithmetic expression into a parse tree.
@return: Returns a token string.
@rtype: lems.parser.expr.ExprNode
"""
#print("Parsing: %s"%self.parse_string)
self.tokenize()
if self.debug: print("Tokens found: %s"%self.token_list)
try:
parse_tree = self.parse2()
except Exception as e:
raise e
return parse_tree | python | def parse(self):
"""
Tokenizes and parses an arithmetic expression into a parse tree.
@return: Returns a token string.
@rtype: lems.parser.expr.ExprNode
"""
#print("Parsing: %s"%self.parse_string)
self.tokenize()
if self.debug: print("Tokens found: %s"%self.token_list)
try:
parse_tree = self.parse2()
except Exception as e:
raise e
return parse_tree | [
"def",
"parse",
"(",
"self",
")",
":",
"#print(\"Parsing: %s\"%self.parse_string)",
"self",
".",
"tokenize",
"(",
")",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Tokens found: %s\"",
"%",
"self",
".",
"token_list",
")",
"try",
":",
"parse_tree",
"=",
"self",
".",
"parse2",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"e",
"return",
"parse_tree"
] | Tokenizes and parses an arithmetic expression into a parse tree.
@return: Returns a token string.
@rtype: lems.parser.expr.ExprNode | [
"Tokenizes",
"and",
"parses",
"an",
"arithmetic",
"expression",
"into",
"a",
"parse",
"tree",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/parser/expr.py#L478-L493 | train |
chriso/gauged | gauged/drivers/mysql.py | MySQLDriver.insert_keys | def insert_keys(self, keys):
"""Insert keys into a table which assigns an ID"""
start = 0
bulk_insert = self.bulk_insert
keys_len = len(keys)
query = 'INSERT IGNORE INTO gauged_keys (namespace, `key`) VALUES '
execute = self.cursor.execute
while start < keys_len:
rows = keys[start:start+bulk_insert]
params = [param for params in rows for param in params]
insert = '(%s,%s),' * (len(rows) - 1) + '(%s,%s)'
execute(query + insert, params)
start += bulk_insert | python | def insert_keys(self, keys):
"""Insert keys into a table which assigns an ID"""
start = 0
bulk_insert = self.bulk_insert
keys_len = len(keys)
query = 'INSERT IGNORE INTO gauged_keys (namespace, `key`) VALUES '
execute = self.cursor.execute
while start < keys_len:
rows = keys[start:start+bulk_insert]
params = [param for params in rows for param in params]
insert = '(%s,%s),' * (len(rows) - 1) + '(%s,%s)'
execute(query + insert, params)
start += bulk_insert | [
"def",
"insert_keys",
"(",
"self",
",",
"keys",
")",
":",
"start",
"=",
"0",
"bulk_insert",
"=",
"self",
".",
"bulk_insert",
"keys_len",
"=",
"len",
"(",
"keys",
")",
"query",
"=",
"'INSERT IGNORE INTO gauged_keys (namespace, `key`) VALUES '",
"execute",
"=",
"self",
".",
"cursor",
".",
"execute",
"while",
"start",
"<",
"keys_len",
":",
"rows",
"=",
"keys",
"[",
"start",
":",
"start",
"+",
"bulk_insert",
"]",
"params",
"=",
"[",
"param",
"for",
"params",
"in",
"rows",
"for",
"param",
"in",
"params",
"]",
"insert",
"=",
"'(%s,%s),'",
"*",
"(",
"len",
"(",
"rows",
")",
"-",
"1",
")",
"+",
"'(%s,%s)'",
"execute",
"(",
"query",
"+",
"insert",
",",
"params",
")",
"start",
"+=",
"bulk_insert"
] | Insert keys into a table which assigns an ID | [
"Insert",
"keys",
"into",
"a",
"table",
"which",
"assigns",
"an",
"ID"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/mysql.py#L81-L93 | train |
chriso/gauged | gauged/drivers/mysql.py | MySQLDriver.get_writer_position | def get_writer_position(self, name):
"""Get the current writer position"""
cursor = self.cursor
cursor.execute('SELECT timestamp FROM gauged_writer_history '
'WHERE id = %s', (name,))
result = cursor.fetchone()
return result[0] if result else 0 | python | def get_writer_position(self, name):
"""Get the current writer position"""
cursor = self.cursor
cursor.execute('SELECT timestamp FROM gauged_writer_history '
'WHERE id = %s', (name,))
result = cursor.fetchone()
return result[0] if result else 0 | [
"def",
"get_writer_position",
"(",
"self",
",",
"name",
")",
":",
"cursor",
"=",
"self",
".",
"cursor",
"cursor",
".",
"execute",
"(",
"'SELECT timestamp FROM gauged_writer_history '",
"'WHERE id = %s'",
",",
"(",
"name",
",",
")",
")",
"result",
"=",
"cursor",
".",
"fetchone",
"(",
")",
"return",
"result",
"[",
"0",
"]",
"if",
"result",
"else",
"0"
] | Get the current writer position | [
"Get",
"the",
"current",
"writer",
"position"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/mysql.py#L174-L180 | train |
chriso/gauged | gauged/drivers/mysql.py | MySQLDriver.get_namespaces | def get_namespaces(self):
"""Get a list of namespaces"""
cursor = self.cursor
cursor.execute('SELECT DISTINCT namespace FROM gauged_statistics')
return [namespace for namespace, in cursor] | python | def get_namespaces(self):
"""Get a list of namespaces"""
cursor = self.cursor
cursor.execute('SELECT DISTINCT namespace FROM gauged_statistics')
return [namespace for namespace, in cursor] | [
"def",
"get_namespaces",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"cursor",
"cursor",
".",
"execute",
"(",
"'SELECT DISTINCT namespace FROM gauged_statistics'",
")",
"return",
"[",
"namespace",
"for",
"namespace",
",",
"in",
"cursor",
"]"
] | Get a list of namespaces | [
"Get",
"a",
"list",
"of",
"namespaces"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/mysql.py#L182-L186 | train |
chriso/gauged | gauged/drivers/mysql.py | MySQLDriver.remove_namespace | def remove_namespace(self, namespace):
"""Remove all data associated with the current namespace"""
params = (namespace, )
execute = self.cursor.execute
execute('DELETE FROM gauged_data WHERE namespace = %s', params)
execute('DELETE FROM gauged_statistics WHERE namespace = %s', params)
execute('DELETE FROM gauged_keys WHERE namespace = %s', params)
self.remove_cache(namespace) | python | def remove_namespace(self, namespace):
"""Remove all data associated with the current namespace"""
params = (namespace, )
execute = self.cursor.execute
execute('DELETE FROM gauged_data WHERE namespace = %s', params)
execute('DELETE FROM gauged_statistics WHERE namespace = %s', params)
execute('DELETE FROM gauged_keys WHERE namespace = %s', params)
self.remove_cache(namespace) | [
"def",
"remove_namespace",
"(",
"self",
",",
"namespace",
")",
":",
"params",
"=",
"(",
"namespace",
",",
")",
"execute",
"=",
"self",
".",
"cursor",
".",
"execute",
"execute",
"(",
"'DELETE FROM gauged_data WHERE namespace = %s'",
",",
"params",
")",
"execute",
"(",
"'DELETE FROM gauged_statistics WHERE namespace = %s'",
",",
"params",
")",
"execute",
"(",
"'DELETE FROM gauged_keys WHERE namespace = %s'",
",",
"params",
")",
"self",
".",
"remove_cache",
"(",
"namespace",
")"
] | Remove all data associated with the current namespace | [
"Remove",
"all",
"data",
"associated",
"with",
"the",
"current",
"namespace"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/mysql.py#L188-L195 | train |
chriso/gauged | gauged/drivers/mysql.py | MySQLDriver.remove_cache | def remove_cache(self, namespace, key=None):
"""Remove all cached values for the specified namespace,
optionally specifying a key"""
if key is None:
self.cursor.execute('DELETE FROM gauged_cache '
'WHERE namespace = %s', (namespace,))
else:
self.cursor.execute('DELETE FROM gauged_cache '
'WHERE namespace = %s and `key` = %s',
(namespace, key)) | python | def remove_cache(self, namespace, key=None):
"""Remove all cached values for the specified namespace,
optionally specifying a key"""
if key is None:
self.cursor.execute('DELETE FROM gauged_cache '
'WHERE namespace = %s', (namespace,))
else:
self.cursor.execute('DELETE FROM gauged_cache '
'WHERE namespace = %s and `key` = %s',
(namespace, key)) | [
"def",
"remove_cache",
"(",
"self",
",",
"namespace",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"'DELETE FROM gauged_cache '",
"'WHERE namespace = %s'",
",",
"(",
"namespace",
",",
")",
")",
"else",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"'DELETE FROM gauged_cache '",
"'WHERE namespace = %s and `key` = %s'",
",",
"(",
"namespace",
",",
"key",
")",
")"
] | Remove all cached values for the specified namespace,
optionally specifying a key | [
"Remove",
"all",
"cached",
"values",
"for",
"the",
"specified",
"namespace",
"optionally",
"specifying",
"a",
"key"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/mysql.py#L274-L283 | train |
chriso/gauged | gauged/drivers/mysql.py | MySQLDriver.clear_schema | def clear_schema(self):
"""Clear all gauged data"""
execute = self.cursor.execute
execute('TRUNCATE TABLE gauged_data')
execute('TRUNCATE TABLE gauged_keys')
execute('TRUNCATE TABLE gauged_writer_history')
execute('TRUNCATE TABLE gauged_cache')
execute('TRUNCATE TABLE gauged_statistics')
self.db.commit() | python | def clear_schema(self):
"""Clear all gauged data"""
execute = self.cursor.execute
execute('TRUNCATE TABLE gauged_data')
execute('TRUNCATE TABLE gauged_keys')
execute('TRUNCATE TABLE gauged_writer_history')
execute('TRUNCATE TABLE gauged_cache')
execute('TRUNCATE TABLE gauged_statistics')
self.db.commit() | [
"def",
"clear_schema",
"(",
"self",
")",
":",
"execute",
"=",
"self",
".",
"cursor",
".",
"execute",
"execute",
"(",
"'TRUNCATE TABLE gauged_data'",
")",
"execute",
"(",
"'TRUNCATE TABLE gauged_keys'",
")",
"execute",
"(",
"'TRUNCATE TABLE gauged_writer_history'",
")",
"execute",
"(",
"'TRUNCATE TABLE gauged_cache'",
")",
"execute",
"(",
"'TRUNCATE TABLE gauged_statistics'",
")",
"self",
".",
"db",
".",
"commit",
"(",
")"
] | Clear all gauged data | [
"Clear",
"all",
"gauged",
"data"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/mysql.py#L355-L363 | train |
Erotemic/utool | utool/util_numpy.py | quantum_random | def quantum_random():
""" returns a 32 bit unsigned integer quantum random number """
import quantumrandom
data16 = quantumrandom.uint16(array_length=2)
assert data16.flags['C_CONTIGUOUS']
data32 = data16.view(np.dtype('uint32'))[0]
return data32 | python | def quantum_random():
""" returns a 32 bit unsigned integer quantum random number """
import quantumrandom
data16 = quantumrandom.uint16(array_length=2)
assert data16.flags['C_CONTIGUOUS']
data32 = data16.view(np.dtype('uint32'))[0]
return data32 | [
"def",
"quantum_random",
"(",
")",
":",
"import",
"quantumrandom",
"data16",
"=",
"quantumrandom",
".",
"uint16",
"(",
"array_length",
"=",
"2",
")",
"assert",
"data16",
".",
"flags",
"[",
"'C_CONTIGUOUS'",
"]",
"data32",
"=",
"data16",
".",
"view",
"(",
"np",
".",
"dtype",
"(",
"'uint32'",
")",
")",
"[",
"0",
"]",
"return",
"data32"
] | returns a 32 bit unsigned integer quantum random number | [
"returns",
"a",
"32",
"bit",
"unsigned",
"integer",
"quantum",
"random",
"number"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_numpy.py#L19-L25 | train |
Erotemic/utool | utool/util_numpy.py | _npstate_to_pystate | def _npstate_to_pystate(npstate):
"""
Convert state of a NumPy RandomState object to a state
that can be used by Python's Random.
References:
https://stackoverflow.com/questions/44313620/converting-randomstate
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> from utool.util_numpy import _npstate_to_pystate
>>> py_rng = random.Random(0)
>>> np_rng = np.random.RandomState(seed=0)
>>> npstate = np_rng.get_state()
>>> pystate = _npstate_to_pystate(npstate)
>>> py_rng.setstate(pystate)
>>> assert np_rng.rand() == py_rng.random()
"""
PY_VERSION = 3
version, keys, pos, has_gauss, cached_gaussian_ = npstate
keys_pos = tuple(map(int, keys)) + (int(pos),)
cached_gaussian_ = cached_gaussian_ if has_gauss else None
pystate = (PY_VERSION, keys_pos, cached_gaussian_)
return pystate | python | def _npstate_to_pystate(npstate):
"""
Convert state of a NumPy RandomState object to a state
that can be used by Python's Random.
References:
https://stackoverflow.com/questions/44313620/converting-randomstate
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> from utool.util_numpy import _npstate_to_pystate
>>> py_rng = random.Random(0)
>>> np_rng = np.random.RandomState(seed=0)
>>> npstate = np_rng.get_state()
>>> pystate = _npstate_to_pystate(npstate)
>>> py_rng.setstate(pystate)
>>> assert np_rng.rand() == py_rng.random()
"""
PY_VERSION = 3
version, keys, pos, has_gauss, cached_gaussian_ = npstate
keys_pos = tuple(map(int, keys)) + (int(pos),)
cached_gaussian_ = cached_gaussian_ if has_gauss else None
pystate = (PY_VERSION, keys_pos, cached_gaussian_)
return pystate | [
"def",
"_npstate_to_pystate",
"(",
"npstate",
")",
":",
"PY_VERSION",
"=",
"3",
"version",
",",
"keys",
",",
"pos",
",",
"has_gauss",
",",
"cached_gaussian_",
"=",
"npstate",
"keys_pos",
"=",
"tuple",
"(",
"map",
"(",
"int",
",",
"keys",
")",
")",
"+",
"(",
"int",
"(",
"pos",
")",
",",
")",
"cached_gaussian_",
"=",
"cached_gaussian_",
"if",
"has_gauss",
"else",
"None",
"pystate",
"=",
"(",
"PY_VERSION",
",",
"keys_pos",
",",
"cached_gaussian_",
")",
"return",
"pystate"
] | Convert state of a NumPy RandomState object to a state
that can be used by Python's Random.
References:
https://stackoverflow.com/questions/44313620/converting-randomstate
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> from utool.util_numpy import _npstate_to_pystate
>>> py_rng = random.Random(0)
>>> np_rng = np.random.RandomState(seed=0)
>>> npstate = np_rng.get_state()
>>> pystate = _npstate_to_pystate(npstate)
>>> py_rng.setstate(pystate)
>>> assert np_rng.rand() == py_rng.random() | [
"Convert",
"state",
"of",
"a",
"NumPy",
"RandomState",
"object",
"to",
"a",
"state",
"that",
"can",
"be",
"used",
"by",
"Python",
"s",
"Random",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_numpy.py#L28-L52 | train |
Erotemic/utool | utool/util_numpy.py | _pystate_to_npstate | def _pystate_to_npstate(pystate):
"""
Convert state of a Python Random object to state usable
by NumPy RandomState.
References:
https://stackoverflow.com/questions/44313620/converting-randomstate
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> from utool.util_numpy import _pystate_to_npstate
>>> py_rng = random.Random(0)
>>> np_rng = np.random.RandomState(seed=0)
>>> pystate = py_rng.getstate()
>>> npstate = _pystate_to_npstate(pystate)
>>> np_rng.set_state(npstate)
>>> assert np_rng.rand() == py_rng.random()
"""
NP_VERSION = 'MT19937'
version, keys_pos_, cached_gaussian_ = pystate
keys, pos = keys_pos_[:-1], keys_pos_[-1]
keys = np.array(keys, dtype=np.uint32)
has_gauss = cached_gaussian_ is not None
cached_gaussian = cached_gaussian_ if has_gauss else 0.0
npstate = (NP_VERSION, keys, pos, has_gauss, cached_gaussian)
return npstate | python | def _pystate_to_npstate(pystate):
"""
Convert state of a Python Random object to state usable
by NumPy RandomState.
References:
https://stackoverflow.com/questions/44313620/converting-randomstate
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> from utool.util_numpy import _pystate_to_npstate
>>> py_rng = random.Random(0)
>>> np_rng = np.random.RandomState(seed=0)
>>> pystate = py_rng.getstate()
>>> npstate = _pystate_to_npstate(pystate)
>>> np_rng.set_state(npstate)
>>> assert np_rng.rand() == py_rng.random()
"""
NP_VERSION = 'MT19937'
version, keys_pos_, cached_gaussian_ = pystate
keys, pos = keys_pos_[:-1], keys_pos_[-1]
keys = np.array(keys, dtype=np.uint32)
has_gauss = cached_gaussian_ is not None
cached_gaussian = cached_gaussian_ if has_gauss else 0.0
npstate = (NP_VERSION, keys, pos, has_gauss, cached_gaussian)
return npstate | [
"def",
"_pystate_to_npstate",
"(",
"pystate",
")",
":",
"NP_VERSION",
"=",
"'MT19937'",
"version",
",",
"keys_pos_",
",",
"cached_gaussian_",
"=",
"pystate",
"keys",
",",
"pos",
"=",
"keys_pos_",
"[",
":",
"-",
"1",
"]",
",",
"keys_pos_",
"[",
"-",
"1",
"]",
"keys",
"=",
"np",
".",
"array",
"(",
"keys",
",",
"dtype",
"=",
"np",
".",
"uint32",
")",
"has_gauss",
"=",
"cached_gaussian_",
"is",
"not",
"None",
"cached_gaussian",
"=",
"cached_gaussian_",
"if",
"has_gauss",
"else",
"0.0",
"npstate",
"=",
"(",
"NP_VERSION",
",",
"keys",
",",
"pos",
",",
"has_gauss",
",",
"cached_gaussian",
")",
"return",
"npstate"
] | Convert state of a Python Random object to state usable
by NumPy RandomState.
References:
https://stackoverflow.com/questions/44313620/converting-randomstate
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> from utool.util_numpy import _pystate_to_npstate
>>> py_rng = random.Random(0)
>>> np_rng = np.random.RandomState(seed=0)
>>> pystate = py_rng.getstate()
>>> npstate = _pystate_to_npstate(pystate)
>>> np_rng.set_state(npstate)
>>> assert np_rng.rand() == py_rng.random() | [
"Convert",
"state",
"of",
"a",
"Python",
"Random",
"object",
"to",
"state",
"usable",
"by",
"NumPy",
"RandomState",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_numpy.py#L55-L81 | train |
Erotemic/utool | utool/util_numpy.py | ensure_rng | def ensure_rng(rng, impl='numpy'):
"""
Returns a random number generator
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> import utool as ut
>>> import numpy as np
>>> num = 4
>>> print('--- Python as PYTHON ---')
>>> py_rng = random.Random(0)
>>> pp_nums = [py_rng.random() for _ in range(num)]
>>> print(pp_nums)
>>> print('--- Numpy as PYTHON ---')
>>> np_rng = ut.ensure_rng(random.Random(0), impl='numpy')
>>> np_nums = [np_rng.rand() for _ in range(num)]
>>> print(np_nums)
>>> print('--- Numpy as NUMPY---')
>>> np_rng = np.random.RandomState(seed=0)
>>> nn_nums = [np_rng.rand() for _ in range(num)]
>>> print(nn_nums)
>>> print('--- Python as NUMPY---')
>>> py_rng = ut.ensure_rng(np.random.RandomState(seed=0), impl='python')
>>> pn_nums = [py_rng.random() for _ in range(num)]
>>> print(pn_nums)
>>> assert np_nums == pp_nums
>>> assert pn_nums == nn_nums
"""
if impl == 'numpy':
if rng is None:
rng = np.random
elif isinstance(rng, int):
rng = np.random.RandomState(seed=rng)
elif isinstance(rng, random.Random):
# Convert python to numpy random state
py_rng = rng
pystate = py_rng.getstate()
npstate = _pystate_to_npstate(pystate)
rng = np_rng = np.random.RandomState(seed=0)
np_rng.set_state(npstate)
elif impl == 'python':
if rng is None:
rng = random
elif isinstance(rng, int):
rng = random.Random(rng)
elif isinstance(rng, np.random.RandomState):
# Convert numpy to python random state
np_rng = rng
npstate = np_rng.get_state()
pystate = _npstate_to_pystate(npstate)
rng = py_rng = random.Random(0)
py_rng.setstate(pystate)
else:
raise KeyError('unknown rng impl={}'.format(impl))
return rng | python | def ensure_rng(rng, impl='numpy'):
"""
Returns a random number generator
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> import utool as ut
>>> import numpy as np
>>> num = 4
>>> print('--- Python as PYTHON ---')
>>> py_rng = random.Random(0)
>>> pp_nums = [py_rng.random() for _ in range(num)]
>>> print(pp_nums)
>>> print('--- Numpy as PYTHON ---')
>>> np_rng = ut.ensure_rng(random.Random(0), impl='numpy')
>>> np_nums = [np_rng.rand() for _ in range(num)]
>>> print(np_nums)
>>> print('--- Numpy as NUMPY---')
>>> np_rng = np.random.RandomState(seed=0)
>>> nn_nums = [np_rng.rand() for _ in range(num)]
>>> print(nn_nums)
>>> print('--- Python as NUMPY---')
>>> py_rng = ut.ensure_rng(np.random.RandomState(seed=0), impl='python')
>>> pn_nums = [py_rng.random() for _ in range(num)]
>>> print(pn_nums)
>>> assert np_nums == pp_nums
>>> assert pn_nums == nn_nums
"""
if impl == 'numpy':
if rng is None:
rng = np.random
elif isinstance(rng, int):
rng = np.random.RandomState(seed=rng)
elif isinstance(rng, random.Random):
# Convert python to numpy random state
py_rng = rng
pystate = py_rng.getstate()
npstate = _pystate_to_npstate(pystate)
rng = np_rng = np.random.RandomState(seed=0)
np_rng.set_state(npstate)
elif impl == 'python':
if rng is None:
rng = random
elif isinstance(rng, int):
rng = random.Random(rng)
elif isinstance(rng, np.random.RandomState):
# Convert numpy to python random state
np_rng = rng
npstate = np_rng.get_state()
pystate = _npstate_to_pystate(npstate)
rng = py_rng = random.Random(0)
py_rng.setstate(pystate)
else:
raise KeyError('unknown rng impl={}'.format(impl))
return rng | [
"def",
"ensure_rng",
"(",
"rng",
",",
"impl",
"=",
"'numpy'",
")",
":",
"if",
"impl",
"==",
"'numpy'",
":",
"if",
"rng",
"is",
"None",
":",
"rng",
"=",
"np",
".",
"random",
"elif",
"isinstance",
"(",
"rng",
",",
"int",
")",
":",
"rng",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"seed",
"=",
"rng",
")",
"elif",
"isinstance",
"(",
"rng",
",",
"random",
".",
"Random",
")",
":",
"# Convert python to numpy random state",
"py_rng",
"=",
"rng",
"pystate",
"=",
"py_rng",
".",
"getstate",
"(",
")",
"npstate",
"=",
"_pystate_to_npstate",
"(",
"pystate",
")",
"rng",
"=",
"np_rng",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"seed",
"=",
"0",
")",
"np_rng",
".",
"set_state",
"(",
"npstate",
")",
"elif",
"impl",
"==",
"'python'",
":",
"if",
"rng",
"is",
"None",
":",
"rng",
"=",
"random",
"elif",
"isinstance",
"(",
"rng",
",",
"int",
")",
":",
"rng",
"=",
"random",
".",
"Random",
"(",
"rng",
")",
"elif",
"isinstance",
"(",
"rng",
",",
"np",
".",
"random",
".",
"RandomState",
")",
":",
"# Convert numpy to python random state",
"np_rng",
"=",
"rng",
"npstate",
"=",
"np_rng",
".",
"get_state",
"(",
")",
"pystate",
"=",
"_npstate_to_pystate",
"(",
"npstate",
")",
"rng",
"=",
"py_rng",
"=",
"random",
".",
"Random",
"(",
"0",
")",
"py_rng",
".",
"setstate",
"(",
"pystate",
")",
"else",
":",
"raise",
"KeyError",
"(",
"'unknown rng impl={}'",
".",
"format",
"(",
"impl",
")",
")",
"return",
"rng"
] | Returns a random number generator
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> import utool as ut
>>> import numpy as np
>>> num = 4
>>> print('--- Python as PYTHON ---')
>>> py_rng = random.Random(0)
>>> pp_nums = [py_rng.random() for _ in range(num)]
>>> print(pp_nums)
>>> print('--- Numpy as PYTHON ---')
>>> np_rng = ut.ensure_rng(random.Random(0), impl='numpy')
>>> np_nums = [np_rng.rand() for _ in range(num)]
>>> print(np_nums)
>>> print('--- Numpy as NUMPY---')
>>> np_rng = np.random.RandomState(seed=0)
>>> nn_nums = [np_rng.rand() for _ in range(num)]
>>> print(nn_nums)
>>> print('--- Python as NUMPY---')
>>> py_rng = ut.ensure_rng(np.random.RandomState(seed=0), impl='python')
>>> pn_nums = [py_rng.random() for _ in range(num)]
>>> print(pn_nums)
>>> assert np_nums == pp_nums
>>> assert pn_nums == nn_nums | [
"Returns",
"a",
"random",
"number",
"generator"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_numpy.py#L84-L139 | train |
Erotemic/utool | utool/util_numpy.py | random_indexes | def random_indexes(max_index, subset_size=None, seed=None, rng=None):
""" random unrepeated indicies
Args:
max_index (?):
subset_size (None): (default = None)
seed (None): (default = None)
rng (RandomState): random number generator(default = None)
Returns:
?: subst
CommandLine:
python -m utool.util_numpy --exec-random_indexes
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> max_index = 10
>>> subset_size = None
>>> seed = None
>>> rng = np.random.RandomState(0)
>>> subst = random_indexes(max_index, subset_size, seed, rng)
>>> result = ('subst = %s' % (str(subst),))
>>> print(result)
"""
subst_ = np.arange(0, max_index)
rng = ensure_rng(seed if rng is None else rng)
rng.shuffle(subst_)
if subset_size is None:
subst = subst_
else:
subst = subst_[0:min(subset_size, max_index)]
return subst | python | def random_indexes(max_index, subset_size=None, seed=None, rng=None):
""" random unrepeated indicies
Args:
max_index (?):
subset_size (None): (default = None)
seed (None): (default = None)
rng (RandomState): random number generator(default = None)
Returns:
?: subst
CommandLine:
python -m utool.util_numpy --exec-random_indexes
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> max_index = 10
>>> subset_size = None
>>> seed = None
>>> rng = np.random.RandomState(0)
>>> subst = random_indexes(max_index, subset_size, seed, rng)
>>> result = ('subst = %s' % (str(subst),))
>>> print(result)
"""
subst_ = np.arange(0, max_index)
rng = ensure_rng(seed if rng is None else rng)
rng.shuffle(subst_)
if subset_size is None:
subst = subst_
else:
subst = subst_[0:min(subset_size, max_index)]
return subst | [
"def",
"random_indexes",
"(",
"max_index",
",",
"subset_size",
"=",
"None",
",",
"seed",
"=",
"None",
",",
"rng",
"=",
"None",
")",
":",
"subst_",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"max_index",
")",
"rng",
"=",
"ensure_rng",
"(",
"seed",
"if",
"rng",
"is",
"None",
"else",
"rng",
")",
"rng",
".",
"shuffle",
"(",
"subst_",
")",
"if",
"subset_size",
"is",
"None",
":",
"subst",
"=",
"subst_",
"else",
":",
"subst",
"=",
"subst_",
"[",
"0",
":",
"min",
"(",
"subset_size",
",",
"max_index",
")",
"]",
"return",
"subst"
] | random unrepeated indicies
Args:
max_index (?):
subset_size (None): (default = None)
seed (None): (default = None)
rng (RandomState): random number generator(default = None)
Returns:
?: subst
CommandLine:
python -m utool.util_numpy --exec-random_indexes
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> max_index = 10
>>> subset_size = None
>>> seed = None
>>> rng = np.random.RandomState(0)
>>> subst = random_indexes(max_index, subset_size, seed, rng)
>>> result = ('subst = %s' % (str(subst),))
>>> print(result) | [
"random",
"unrepeated",
"indicies"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_numpy.py#L142-L175 | train |
Erotemic/utool | utool/util_numpy.py | spaced_indexes | def spaced_indexes(len_, n, trunc=False):
"""
Returns n evenly spaced indexes.
Returns as many as possible if trunc is true
"""
if n is None:
return np.arange(len_)
all_indexes = np.arange(len_)
if trunc:
n = min(len_, n)
if n == 0:
return np.empty(0)
stride = len_ // n
try:
indexes = all_indexes[0:-1:stride]
except ValueError:
raise ValueError('cannot slice list of len_=%r into n=%r parts' % (len_, n))
return indexes | python | def spaced_indexes(len_, n, trunc=False):
"""
Returns n evenly spaced indexes.
Returns as many as possible if trunc is true
"""
if n is None:
return np.arange(len_)
all_indexes = np.arange(len_)
if trunc:
n = min(len_, n)
if n == 0:
return np.empty(0)
stride = len_ // n
try:
indexes = all_indexes[0:-1:stride]
except ValueError:
raise ValueError('cannot slice list of len_=%r into n=%r parts' % (len_, n))
return indexes | [
"def",
"spaced_indexes",
"(",
"len_",
",",
"n",
",",
"trunc",
"=",
"False",
")",
":",
"if",
"n",
"is",
"None",
":",
"return",
"np",
".",
"arange",
"(",
"len_",
")",
"all_indexes",
"=",
"np",
".",
"arange",
"(",
"len_",
")",
"if",
"trunc",
":",
"n",
"=",
"min",
"(",
"len_",
",",
"n",
")",
"if",
"n",
"==",
"0",
":",
"return",
"np",
".",
"empty",
"(",
"0",
")",
"stride",
"=",
"len_",
"//",
"n",
"try",
":",
"indexes",
"=",
"all_indexes",
"[",
"0",
":",
"-",
"1",
":",
"stride",
"]",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'cannot slice list of len_=%r into n=%r parts'",
"%",
"(",
"len_",
",",
"n",
")",
")",
"return",
"indexes"
] | Returns n evenly spaced indexes.
Returns as many as possible if trunc is true | [
"Returns",
"n",
"evenly",
"spaced",
"indexes",
".",
"Returns",
"as",
"many",
"as",
"possible",
"if",
"trunc",
"is",
"true"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_numpy.py#L201-L219 | train |
Erotemic/utool | utool/util_numpy.py | random_sample | def random_sample(list_, nSample, strict=False, rng=None, seed=None):
"""
Grabs data randomly
Args:
list_ (list):
nSample (?):
strict (bool): (default = False)
rng (module): random number generator(default = numpy.random)
seed (None): (default = None)
Returns:
list: sample_list
CommandLine:
python -m utool.util_numpy --exec-random_sample
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> list_ = np.arange(10)
>>> nSample = 4
>>> strict = False
>>> rng = np.random.RandomState(0)
>>> seed = None
>>> sample_list = random_sample(list_, nSample, strict, rng, seed)
>>> result = ('sample_list = %s' % (str(sample_list),))
>>> print(result)
"""
rng = ensure_rng(seed if rng is None else rng)
if isinstance(list_, list):
list2_ = list_[:]
else:
list2_ = np.copy(list_)
if len(list2_) == 0 and not strict:
return list2_
rng.shuffle(list2_)
if nSample is None and strict is False:
return list2_
if not strict:
nSample = min(max(0, nSample), len(list2_))
sample_list = list2_[:nSample]
return sample_list | python | def random_sample(list_, nSample, strict=False, rng=None, seed=None):
"""
Grabs data randomly
Args:
list_ (list):
nSample (?):
strict (bool): (default = False)
rng (module): random number generator(default = numpy.random)
seed (None): (default = None)
Returns:
list: sample_list
CommandLine:
python -m utool.util_numpy --exec-random_sample
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> list_ = np.arange(10)
>>> nSample = 4
>>> strict = False
>>> rng = np.random.RandomState(0)
>>> seed = None
>>> sample_list = random_sample(list_, nSample, strict, rng, seed)
>>> result = ('sample_list = %s' % (str(sample_list),))
>>> print(result)
"""
rng = ensure_rng(seed if rng is None else rng)
if isinstance(list_, list):
list2_ = list_[:]
else:
list2_ = np.copy(list_)
if len(list2_) == 0 and not strict:
return list2_
rng.shuffle(list2_)
if nSample is None and strict is False:
return list2_
if not strict:
nSample = min(max(0, nSample), len(list2_))
sample_list = list2_[:nSample]
return sample_list | [
"def",
"random_sample",
"(",
"list_",
",",
"nSample",
",",
"strict",
"=",
"False",
",",
"rng",
"=",
"None",
",",
"seed",
"=",
"None",
")",
":",
"rng",
"=",
"ensure_rng",
"(",
"seed",
"if",
"rng",
"is",
"None",
"else",
"rng",
")",
"if",
"isinstance",
"(",
"list_",
",",
"list",
")",
":",
"list2_",
"=",
"list_",
"[",
":",
"]",
"else",
":",
"list2_",
"=",
"np",
".",
"copy",
"(",
"list_",
")",
"if",
"len",
"(",
"list2_",
")",
"==",
"0",
"and",
"not",
"strict",
":",
"return",
"list2_",
"rng",
".",
"shuffle",
"(",
"list2_",
")",
"if",
"nSample",
"is",
"None",
"and",
"strict",
"is",
"False",
":",
"return",
"list2_",
"if",
"not",
"strict",
":",
"nSample",
"=",
"min",
"(",
"max",
"(",
"0",
",",
"nSample",
")",
",",
"len",
"(",
"list2_",
")",
")",
"sample_list",
"=",
"list2_",
"[",
":",
"nSample",
"]",
"return",
"sample_list"
] | Grabs data randomly
Args:
list_ (list):
nSample (?):
strict (bool): (default = False)
rng (module): random number generator(default = numpy.random)
seed (None): (default = None)
Returns:
list: sample_list
CommandLine:
python -m utool.util_numpy --exec-random_sample
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> list_ = np.arange(10)
>>> nSample = 4
>>> strict = False
>>> rng = np.random.RandomState(0)
>>> seed = None
>>> sample_list = random_sample(list_, nSample, strict, rng, seed)
>>> result = ('sample_list = %s' % (str(sample_list),))
>>> print(result) | [
"Grabs",
"data",
"randomly"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_numpy.py#L323-L365 | train |
Erotemic/utool | utool/util_numpy.py | deterministic_sample | def deterministic_sample(list_, nSample, seed=0, rng=None, strict=False):
""" Grabs data randomly, but in a repeatable way """
rng = ensure_rng(seed if rng is None else rng)
sample_list = random_sample(list_, nSample, strict=strict, rng=rng)
return sample_list | python | def deterministic_sample(list_, nSample, seed=0, rng=None, strict=False):
""" Grabs data randomly, but in a repeatable way """
rng = ensure_rng(seed if rng is None else rng)
sample_list = random_sample(list_, nSample, strict=strict, rng=rng)
return sample_list | [
"def",
"deterministic_sample",
"(",
"list_",
",",
"nSample",
",",
"seed",
"=",
"0",
",",
"rng",
"=",
"None",
",",
"strict",
"=",
"False",
")",
":",
"rng",
"=",
"ensure_rng",
"(",
"seed",
"if",
"rng",
"is",
"None",
"else",
"rng",
")",
"sample_list",
"=",
"random_sample",
"(",
"list_",
",",
"nSample",
",",
"strict",
"=",
"strict",
",",
"rng",
"=",
"rng",
")",
"return",
"sample_list"
] | Grabs data randomly, but in a repeatable way | [
"Grabs",
"data",
"randomly",
"but",
"in",
"a",
"repeatable",
"way"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_numpy.py#L368-L372 | train |
Erotemic/utool | utool/util_numpy.py | spaced_items | def spaced_items(list_, n, **kwargs):
""" Returns n evenly spaced items """
indexes = spaced_indexes(len(list_), n, **kwargs)
items = list_[indexes]
return items | python | def spaced_items(list_, n, **kwargs):
""" Returns n evenly spaced items """
indexes = spaced_indexes(len(list_), n, **kwargs)
items = list_[indexes]
return items | [
"def",
"spaced_items",
"(",
"list_",
",",
"n",
",",
"*",
"*",
"kwargs",
")",
":",
"indexes",
"=",
"spaced_indexes",
"(",
"len",
"(",
"list_",
")",
",",
"n",
",",
"*",
"*",
"kwargs",
")",
"items",
"=",
"list_",
"[",
"indexes",
"]",
"return",
"items"
] | Returns n evenly spaced items | [
"Returns",
"n",
"evenly",
"spaced",
"items"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_numpy.py#L375-L379 | train |
dsoprea/NsqSpinner | nsq/node_collection.py | ServerNodes.get_servers | def get_servers(self, topic):
"""We're assuming that the static list of servers can serve the given
topic, since we have to preexisting knowledge about them.
"""
return (nsq.node.ServerNode(sh) for sh in self.__server_hosts) | python | def get_servers(self, topic):
"""We're assuming that the static list of servers can serve the given
topic, since we have to preexisting knowledge about them.
"""
return (nsq.node.ServerNode(sh) for sh in self.__server_hosts) | [
"def",
"get_servers",
"(",
"self",
",",
"topic",
")",
":",
"return",
"(",
"nsq",
".",
"node",
".",
"ServerNode",
"(",
"sh",
")",
"for",
"sh",
"in",
"self",
".",
"__server_hosts",
")"
] | We're assuming that the static list of servers can serve the given
topic, since we have to preexisting knowledge about them. | [
"We",
"re",
"assuming",
"that",
"the",
"static",
"list",
"of",
"servers",
"can",
"serve",
"the",
"given",
"topic",
"since",
"we",
"have",
"to",
"preexisting",
"knowledge",
"about",
"them",
"."
] | 972237b8ddce737983bfed001fde52e5236be695 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/node_collection.py#L14-L19 | train |
MoseleyBioinformaticsLab/ctfile | ctfile/tokenizer.py | tokenizer | def tokenizer(text):
"""A lexical analyzer for the `CTfile` formatted files.
:param str text: `CTfile` formatted text.
:return: Tuples of data.
:rtype: py:class:`~collections.namedtuple`
"""
for entry in text.split('$$$$\n'):
if entry.rstrip():
lines_stream = deque(entry.split('\n'))
else:
continue
# yield from _molfile(stream=lines_stream)
for token in _molfile(stream=lines_stream):
yield token
if len(lines_stream):
# yield from _sdfile(stream=lines_stream)
for token in _sdfile(stream=lines_stream):
yield token
yield EndOfFile() | python | def tokenizer(text):
"""A lexical analyzer for the `CTfile` formatted files.
:param str text: `CTfile` formatted text.
:return: Tuples of data.
:rtype: py:class:`~collections.namedtuple`
"""
for entry in text.split('$$$$\n'):
if entry.rstrip():
lines_stream = deque(entry.split('\n'))
else:
continue
# yield from _molfile(stream=lines_stream)
for token in _molfile(stream=lines_stream):
yield token
if len(lines_stream):
# yield from _sdfile(stream=lines_stream)
for token in _sdfile(stream=lines_stream):
yield token
yield EndOfFile() | [
"def",
"tokenizer",
"(",
"text",
")",
":",
"for",
"entry",
"in",
"text",
".",
"split",
"(",
"'$$$$\\n'",
")",
":",
"if",
"entry",
".",
"rstrip",
"(",
")",
":",
"lines_stream",
"=",
"deque",
"(",
"entry",
".",
"split",
"(",
"'\\n'",
")",
")",
"else",
":",
"continue",
"# yield from _molfile(stream=lines_stream)",
"for",
"token",
"in",
"_molfile",
"(",
"stream",
"=",
"lines_stream",
")",
":",
"yield",
"token",
"if",
"len",
"(",
"lines_stream",
")",
":",
"# yield from _sdfile(stream=lines_stream)",
"for",
"token",
"in",
"_sdfile",
"(",
"stream",
"=",
"lines_stream",
")",
":",
"yield",
"token",
"yield",
"EndOfFile",
"(",
")"
] | A lexical analyzer for the `CTfile` formatted files.
:param str text: `CTfile` formatted text.
:return: Tuples of data.
:rtype: py:class:`~collections.namedtuple` | [
"A",
"lexical",
"analyzer",
"for",
"the",
"CTfile",
"formatted",
"files",
"."
] | eae864126cd9102207df5d363a3222256a0f1396 | https://github.com/MoseleyBioinformaticsLab/ctfile/blob/eae864126cd9102207df5d363a3222256a0f1396/ctfile/tokenizer.py#L48-L70 | train |
MoseleyBioinformaticsLab/ctfile | ctfile/tokenizer.py | _ctab_atom_bond_block | def _ctab_atom_bond_block(number_of_lines, block_type, stream):
"""Process atom and bond blocks of ``Ctab``.
:param number_of_lines: Number of lines to process from stream.
:param block_type: :py:class:`collections.namedtuple` to use for data processing.
:type block_type: :class:`~ctfile.tokenizer.CtabAtomBlockLine` or :class:`~ctfile.tokenizer.CtabBondBlockLine`
:param stream: Queue containing lines of text.
:type stream: :py:class:`collections.deque`
:return: Tuples of data.
:rtype: :class:`~ctfile.tokenizer.CtabAtomBlockLine` or :class:`~ctfile.tokenizer.CtabBondBlockLine`
"""
for _ in range(int(number_of_lines)):
line = stream.popleft()
yield block_type(*line.split()) | python | def _ctab_atom_bond_block(number_of_lines, block_type, stream):
"""Process atom and bond blocks of ``Ctab``.
:param number_of_lines: Number of lines to process from stream.
:param block_type: :py:class:`collections.namedtuple` to use for data processing.
:type block_type: :class:`~ctfile.tokenizer.CtabAtomBlockLine` or :class:`~ctfile.tokenizer.CtabBondBlockLine`
:param stream: Queue containing lines of text.
:type stream: :py:class:`collections.deque`
:return: Tuples of data.
:rtype: :class:`~ctfile.tokenizer.CtabAtomBlockLine` or :class:`~ctfile.tokenizer.CtabBondBlockLine`
"""
for _ in range(int(number_of_lines)):
line = stream.popleft()
yield block_type(*line.split()) | [
"def",
"_ctab_atom_bond_block",
"(",
"number_of_lines",
",",
"block_type",
",",
"stream",
")",
":",
"for",
"_",
"in",
"range",
"(",
"int",
"(",
"number_of_lines",
")",
")",
":",
"line",
"=",
"stream",
".",
"popleft",
"(",
")",
"yield",
"block_type",
"(",
"*",
"line",
".",
"split",
"(",
")",
")"
] | Process atom and bond blocks of ``Ctab``.
:param number_of_lines: Number of lines to process from stream.
:param block_type: :py:class:`collections.namedtuple` to use for data processing.
:type block_type: :class:`~ctfile.tokenizer.CtabAtomBlockLine` or :class:`~ctfile.tokenizer.CtabBondBlockLine`
:param stream: Queue containing lines of text.
:type stream: :py:class:`collections.deque`
:return: Tuples of data.
:rtype: :class:`~ctfile.tokenizer.CtabAtomBlockLine` or :class:`~ctfile.tokenizer.CtabBondBlockLine` | [
"Process",
"atom",
"and",
"bond",
"blocks",
"of",
"Ctab",
"."
] | eae864126cd9102207df5d363a3222256a0f1396 | https://github.com/MoseleyBioinformaticsLab/ctfile/blob/eae864126cd9102207df5d363a3222256a0f1396/ctfile/tokenizer.py#L134-L147 | train |
MoseleyBioinformaticsLab/ctfile | ctfile/tokenizer.py | _ctab_property_block | def _ctab_property_block(stream):
"""Process properties block of ``Ctab``.
:param stream: Queue containing lines of text.
:type stream: :py:class:`collections.deque`
:return: Tuples of data.
:rtype: :class:`~ctfile.tokenizer.CtabPropertiesBlockLine`
"""
line = stream.popleft()
while line != 'M END':
name = line.split()[1]
yield CtabPropertiesBlockLine(name, line)
line = stream.popleft() | python | def _ctab_property_block(stream):
"""Process properties block of ``Ctab``.
:param stream: Queue containing lines of text.
:type stream: :py:class:`collections.deque`
:return: Tuples of data.
:rtype: :class:`~ctfile.tokenizer.CtabPropertiesBlockLine`
"""
line = stream.popleft()
while line != 'M END':
name = line.split()[1]
yield CtabPropertiesBlockLine(name, line)
line = stream.popleft() | [
"def",
"_ctab_property_block",
"(",
"stream",
")",
":",
"line",
"=",
"stream",
".",
"popleft",
"(",
")",
"while",
"line",
"!=",
"'M END'",
":",
"name",
"=",
"line",
".",
"split",
"(",
")",
"[",
"1",
"]",
"yield",
"CtabPropertiesBlockLine",
"(",
"name",
",",
"line",
")",
"line",
"=",
"stream",
".",
"popleft",
"(",
")"
] | Process properties block of ``Ctab``.
:param stream: Queue containing lines of text.
:type stream: :py:class:`collections.deque`
:return: Tuples of data.
:rtype: :class:`~ctfile.tokenizer.CtabPropertiesBlockLine` | [
"Process",
"properties",
"block",
"of",
"Ctab",
"."
] | eae864126cd9102207df5d363a3222256a0f1396 | https://github.com/MoseleyBioinformaticsLab/ctfile/blob/eae864126cd9102207df5d363a3222256a0f1396/ctfile/tokenizer.py#L150-L162 | train |
glormph/msstitch | src/app/drivers/pycolator/qvality.py | QvalityDriver.set_features | def set_features(self):
"""Creates scorefiles for qvality's target and decoy distributions"""
self.scores = {}
for t_or_d, feats in zip(['target', 'decoy'], [self.target,
self.decoy]):
self.scores[t_or_d] = {}
self.scores[t_or_d]['scores'] = self.score_get_fun(
feats, self.featuretype, self.prepare_percolator_output)
self.scores[t_or_d]['fn'] = '{}_qvality_input.txt'.format(t_or_d)
writers.write_qvality_input(self.scores[t_or_d]['scores'],
self.scores[t_or_d]['fn']) | python | def set_features(self):
"""Creates scorefiles for qvality's target and decoy distributions"""
self.scores = {}
for t_or_d, feats in zip(['target', 'decoy'], [self.target,
self.decoy]):
self.scores[t_or_d] = {}
self.scores[t_or_d]['scores'] = self.score_get_fun(
feats, self.featuretype, self.prepare_percolator_output)
self.scores[t_or_d]['fn'] = '{}_qvality_input.txt'.format(t_or_d)
writers.write_qvality_input(self.scores[t_or_d]['scores'],
self.scores[t_or_d]['fn']) | [
"def",
"set_features",
"(",
"self",
")",
":",
"self",
".",
"scores",
"=",
"{",
"}",
"for",
"t_or_d",
",",
"feats",
"in",
"zip",
"(",
"[",
"'target'",
",",
"'decoy'",
"]",
",",
"[",
"self",
".",
"target",
",",
"self",
".",
"decoy",
"]",
")",
":",
"self",
".",
"scores",
"[",
"t_or_d",
"]",
"=",
"{",
"}",
"self",
".",
"scores",
"[",
"t_or_d",
"]",
"[",
"'scores'",
"]",
"=",
"self",
".",
"score_get_fun",
"(",
"feats",
",",
"self",
".",
"featuretype",
",",
"self",
".",
"prepare_percolator_output",
")",
"self",
".",
"scores",
"[",
"t_or_d",
"]",
"[",
"'fn'",
"]",
"=",
"'{}_qvality_input.txt'",
".",
"format",
"(",
"t_or_d",
")",
"writers",
".",
"write_qvality_input",
"(",
"self",
".",
"scores",
"[",
"t_or_d",
"]",
"[",
"'scores'",
"]",
",",
"self",
".",
"scores",
"[",
"t_or_d",
"]",
"[",
"'fn'",
"]",
")"
] | Creates scorefiles for qvality's target and decoy distributions | [
"Creates",
"scorefiles",
"for",
"qvality",
"s",
"target",
"and",
"decoy",
"distributions"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/drivers/pycolator/qvality.py#L41-L51 | train |
glormph/msstitch | src/app/drivers/pycolator/qvality.py | QvalityDriver.write | def write(self):
"""This actually runs the qvality program from PATH."""
outfn = self.create_outfilepath(self.fn, self.outsuffix)
command = ['qvality']
command.extend(self.qvalityoptions)
command.extend([self.scores['target']['fn'], self.scores['decoy']['fn'],
'-o', outfn])
subprocess.call(command) | python | def write(self):
"""This actually runs the qvality program from PATH."""
outfn = self.create_outfilepath(self.fn, self.outsuffix)
command = ['qvality']
command.extend(self.qvalityoptions)
command.extend([self.scores['target']['fn'], self.scores['decoy']['fn'],
'-o', outfn])
subprocess.call(command) | [
"def",
"write",
"(",
"self",
")",
":",
"outfn",
"=",
"self",
".",
"create_outfilepath",
"(",
"self",
".",
"fn",
",",
"self",
".",
"outsuffix",
")",
"command",
"=",
"[",
"'qvality'",
"]",
"command",
".",
"extend",
"(",
"self",
".",
"qvalityoptions",
")",
"command",
".",
"extend",
"(",
"[",
"self",
".",
"scores",
"[",
"'target'",
"]",
"[",
"'fn'",
"]",
",",
"self",
".",
"scores",
"[",
"'decoy'",
"]",
"[",
"'fn'",
"]",
",",
"'-o'",
",",
"outfn",
"]",
")",
"subprocess",
".",
"call",
"(",
"command",
")"
] | This actually runs the qvality program from PATH. | [
"This",
"actually",
"runs",
"the",
"qvality",
"program",
"from",
"PATH",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/drivers/pycolator/qvality.py#L53-L60 | train |
Erotemic/utool | utool/util_project.py | setup_repo | def setup_repo():
r"""
Creates default structure for a new repo
CommandLine:
python -m utool setup_repo --repo=dtool --codedir=~/code
python -m utool setup_repo --repo=dtool --codedir=~/code
python -m utool setup_repo --repo=ibeis-flukematch-module --codedir=~/code --modname=ibeis_flukematch
python -m utool setup_repo --repo=mtgmonte --codedir=~/code --modname=mtgmonte
python -m utool setup_repo --repo=pydarknet --codedir=~/code --modname=pydarknet
python -m utool setup_repo --repo=sandbox_utools --codedir=~/code --modname=sandbox_utools
python -m utool setup_repo --repo=ubelt --codedir=~/code --modname=ubelt -w
python -m utool setup_repo
Python:
ipython
import utool as ut
ut.rrrr(0); ut.setup_repo()
Example:
>>> # DISABLE_DOCTEST
>>> # SCRIPT
>>> from utool.util_project import * # NOQA
>>> import utool as ut
>>> result = setup_repo()
>>> print(result)
"""
print('\n [setup_repo]!')
# import os
from functools import partial
import utool as ut
# import os
code_dpath = ut.truepath(ut.get_argval('--code-dir', default='~/code'))
_code_dpath = ut.unexpanduser(code_dpath)
repo_fname = (ut.get_argval(('--repo', '--repo-name'), type_=str))
repo_dpath = join(code_dpath, repo_fname)
modname = ut.get_argval('--modname', default=repo_fname)
ut.ensuredir(repo_dpath, verbose=True)
_regencmd = 'python -m utool --tf setup_repo --repo={repo_fname} --codedir={_code_dpath} --modname={modname}'
flake8_noqacmd = 'flake8' + ':noqa'
regencmd = _regencmd.format(**locals())
with ut.ChdirContext(repo_dpath):
# os.chdir(repo_fname)
locals_ = locals()
force = True
_ensure_text = partial(ensure_text, repo_dpath='.', force=None, locals_=locals_)
_ensure_text(
fname='todo.md',
text=ut.codeblock(
r'''
# STARTBLOCK
# {modname} TODO File
* Add TODOS!
# ENDBLOCK
''')
)
_ensure_text(
fname='README.md',
text=ut.codeblock(
r'''
# STARTBLOCK
# {modname} README FILE
# ENDBLOCK
''')
)
_ensure_text(
fname='setup.py',
chmod='+x',
text=ut.codeblock(
r'''
# STARTBLOCK
#!/usr/bin/env python
"""
Initially Generated By:
{regencmd} --force-{fname}
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from setuptools import setup
try:
from utool import util_setup
except ImportError:
print('ERROR: setup requires utool')
raise
INSTALL_REQUIRES = [
#'cython >= 0.21.1',
#'numpy >= 1.9.0',
#'scipy >= 0.16.0',
]
CLUTTER_PATTERNS = [
# Patterns removed by python setup.py clean
]
if __name__ == '__main__':
kwargs = util_setup.setuptools_setup(
setup_fpath=__file__,
name='{modname}',
packages=util_setup.find_packages(),
version=util_setup.parse_package_for_version('{modname}'),
license=util_setup.read_license('LICENSE'),
long_description=util_setup.parse_readme('README.md'),
ext_modules=util_setup.find_ext_modules(),
cmdclass=util_setup.get_cmdclass(),
#description='description of module',
#url='https://github.com/<username>/{repo_fname}.git',
#author='<author>',
#author_email='<author_email>',
keywords='',
install_requires=INSTALL_REQUIRES,
clutter_patterns=CLUTTER_PATTERNS,
#package_data={{'build': ut.get_dynamic_lib_globstrs()}},
#build_command=lambda: ut.std_build_command(dirname(__file__)),
classifiers=[],
)
setup(**kwargs)
# ENDBLOCK
'''
)
)
_ensure_text(
fname='.gitignore',
text=ut.codeblock(
r'''
# STARTBLOCK
*.py[cod]
# C extensions
*.so
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
lib
lib64
__pycache__
# Installer logs
pip-log.txt
# Print Logs
logs
# Unit test / coverage reports
.coverage
.tox
nosetests.xml
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
.DS_Store
*.dump.txt
*.sqlite3
# profiler
*.lprof
*.prof
*.flann
*.npz
# utool output
_timeings.txt
failed.txt
*.orig
_doc
timeings.txt
failed_doctests.txt
# ENDBLOCK
'''
)
)
_ensure_text(
fname=join(repo_dpath, modname, '__init__.py'),
text=ut.codeblock(
r'''
# STARTBLOCK
# -*- coding: utf-8 -*-
# {flake8_noqacmd}
"""
Initially Generated By:
{regencmd}
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
__version__ = '0.0.0'
IMPORT_TUPLES = [
# ('<modname>', None),
]
__DYNAMIC__ = '--nodyn' not in sys.argv
"""
python -c "import {modname}" --dump-{modname}-init
python -c "import {modname}" --update-{modname}-init
"""
DOELSE = False
if __DYNAMIC__:
# Dynamically import listed util libraries and their members.
from utool._internal import util_importer
ignore_endswith = []
import_execstr = util_importer.dynamic_import(
__name__, IMPORT_TUPLES, ignore_endswith=ignore_endswith)
exec(import_execstr)
DOELSE = False
else:
DOELSE = True
if DOELSE:
# <AUTOGEN_INIT>
pass
# </AUTOGEN_INIT>
# ENDBLOCK
'''
)
)
_ensure_text(
fname=join(repo_dpath, modname, '__main__.py'),
chmod='+x',
text=ut.codeblock(
r'''
# STARTBLOCK
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Initially Generated By:
{regencmd}
"""
from __future__ import absolute_import, division, print_function, unicode_literals
def {modname}_main():
ignore_prefix = []
ignore_suffix = []
import utool as ut
ut.main_function_tester('{modname}', ignore_prefix, ignore_suffix)
if __name__ == '__main__':
"""
Usage:
python -m {modname} <funcname>
"""
print('Running {modname} main')
{modname}_main()
# ENDBLOCK
'''
)
)
_ensure_text(
fname='run_tests.py',
chmod='+x',
text=ut.codeblock(
r'''
# STARTBLOCK
#!/usr/bin/env python
"""
Initially Generated By:
{regencmd} --force-{fname}
"""
from __future__ import absolute_import, division, print_function
import sys
import utool as ut
def run_tests():
# Build module list and run tests
import sys
ut.change_term_title('RUN {modname} TESTS')
exclude_doctests_fnames = set([
])
exclude_dirs = [
'_broken', 'old', 'tests', 'timeits',
'_scripts', '_timeits', '_doc', 'notebook',
]
dpath_list = ['{modname}']
doctest_modname_list = ut.find_doctestable_modnames(
dpath_list, exclude_doctests_fnames, exclude_dirs)
coverage = ut.get_argflag(('--coverage', '--cov',))
if coverage:
import coverage
cov = coverage.Coverage(source=doctest_modname_list)
cov.start()
print('Starting coverage')
exclude_lines = [
'pragma: no cover',
'def __repr__',
'if self.debug:',
'if settings.DEBUG',
'raise AssertionError',
'raise NotImplementedError',
'if 0:',
'if ut.VERBOSE',
'if _debug:',
'if __name__ == .__main__.:',
'print(.*)',
]
for line in exclude_lines:
cov.exclude(line)
for modname in doctest_modname_list:
exec('import ' + modname, globals())
module_list = [sys.modules[name] for name in doctest_modname_list]
nPass, nTotal, failed_cmd_list = ut.doctest_module_list(module_list)
if coverage:
print('Stoping coverage')
cov.stop()
print('Saving coverage')
cov.save()
print('Generating coverage html report')
cov.html_report()
if nPass != nTotal:
return 1
else:
return 0
if __name__ == '__main__':
import multiprocessing
multiprocessing.freeze_support()
retcode = run_tests()
sys.exit(retcode)
# ENDBLOCK
'''
)
)
ut.ensuredir(join(repo_dpath, modname), verbose=True) | python | def setup_repo():
r"""
Creates default structure for a new repo
CommandLine:
python -m utool setup_repo --repo=dtool --codedir=~/code
python -m utool setup_repo --repo=dtool --codedir=~/code
python -m utool setup_repo --repo=ibeis-flukematch-module --codedir=~/code --modname=ibeis_flukematch
python -m utool setup_repo --repo=mtgmonte --codedir=~/code --modname=mtgmonte
python -m utool setup_repo --repo=pydarknet --codedir=~/code --modname=pydarknet
python -m utool setup_repo --repo=sandbox_utools --codedir=~/code --modname=sandbox_utools
python -m utool setup_repo --repo=ubelt --codedir=~/code --modname=ubelt -w
python -m utool setup_repo
Python:
ipython
import utool as ut
ut.rrrr(0); ut.setup_repo()
Example:
>>> # DISABLE_DOCTEST
>>> # SCRIPT
>>> from utool.util_project import * # NOQA
>>> import utool as ut
>>> result = setup_repo()
>>> print(result)
"""
print('\n [setup_repo]!')
# import os
from functools import partial
import utool as ut
# import os
code_dpath = ut.truepath(ut.get_argval('--code-dir', default='~/code'))
_code_dpath = ut.unexpanduser(code_dpath)
repo_fname = (ut.get_argval(('--repo', '--repo-name'), type_=str))
repo_dpath = join(code_dpath, repo_fname)
modname = ut.get_argval('--modname', default=repo_fname)
ut.ensuredir(repo_dpath, verbose=True)
_regencmd = 'python -m utool --tf setup_repo --repo={repo_fname} --codedir={_code_dpath} --modname={modname}'
flake8_noqacmd = 'flake8' + ':noqa'
regencmd = _regencmd.format(**locals())
with ut.ChdirContext(repo_dpath):
# os.chdir(repo_fname)
locals_ = locals()
force = True
_ensure_text = partial(ensure_text, repo_dpath='.', force=None, locals_=locals_)
_ensure_text(
fname='todo.md',
text=ut.codeblock(
r'''
# STARTBLOCK
# {modname} TODO File
* Add TODOS!
# ENDBLOCK
''')
)
_ensure_text(
fname='README.md',
text=ut.codeblock(
r'''
# STARTBLOCK
# {modname} README FILE
# ENDBLOCK
''')
)
_ensure_text(
fname='setup.py',
chmod='+x',
text=ut.codeblock(
r'''
# STARTBLOCK
#!/usr/bin/env python
"""
Initially Generated By:
{regencmd} --force-{fname}
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from setuptools import setup
try:
from utool import util_setup
except ImportError:
print('ERROR: setup requires utool')
raise
INSTALL_REQUIRES = [
#'cython >= 0.21.1',
#'numpy >= 1.9.0',
#'scipy >= 0.16.0',
]
CLUTTER_PATTERNS = [
# Patterns removed by python setup.py clean
]
if __name__ == '__main__':
kwargs = util_setup.setuptools_setup(
setup_fpath=__file__,
name='{modname}',
packages=util_setup.find_packages(),
version=util_setup.parse_package_for_version('{modname}'),
license=util_setup.read_license('LICENSE'),
long_description=util_setup.parse_readme('README.md'),
ext_modules=util_setup.find_ext_modules(),
cmdclass=util_setup.get_cmdclass(),
#description='description of module',
#url='https://github.com/<username>/{repo_fname}.git',
#author='<author>',
#author_email='<author_email>',
keywords='',
install_requires=INSTALL_REQUIRES,
clutter_patterns=CLUTTER_PATTERNS,
#package_data={{'build': ut.get_dynamic_lib_globstrs()}},
#build_command=lambda: ut.std_build_command(dirname(__file__)),
classifiers=[],
)
setup(**kwargs)
# ENDBLOCK
'''
)
)
_ensure_text(
fname='.gitignore',
text=ut.codeblock(
r'''
# STARTBLOCK
*.py[cod]
# C extensions
*.so
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
lib
lib64
__pycache__
# Installer logs
pip-log.txt
# Print Logs
logs
# Unit test / coverage reports
.coverage
.tox
nosetests.xml
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
.DS_Store
*.dump.txt
*.sqlite3
# profiler
*.lprof
*.prof
*.flann
*.npz
# utool output
_timeings.txt
failed.txt
*.orig
_doc
timeings.txt
failed_doctests.txt
# ENDBLOCK
'''
)
)
_ensure_text(
fname=join(repo_dpath, modname, '__init__.py'),
text=ut.codeblock(
r'''
# STARTBLOCK
# -*- coding: utf-8 -*-
# {flake8_noqacmd}
"""
Initially Generated By:
{regencmd}
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
__version__ = '0.0.0'
IMPORT_TUPLES = [
# ('<modname>', None),
]
__DYNAMIC__ = '--nodyn' not in sys.argv
"""
python -c "import {modname}" --dump-{modname}-init
python -c "import {modname}" --update-{modname}-init
"""
DOELSE = False
if __DYNAMIC__:
# Dynamically import listed util libraries and their members.
from utool._internal import util_importer
ignore_endswith = []
import_execstr = util_importer.dynamic_import(
__name__, IMPORT_TUPLES, ignore_endswith=ignore_endswith)
exec(import_execstr)
DOELSE = False
else:
DOELSE = True
if DOELSE:
# <AUTOGEN_INIT>
pass
# </AUTOGEN_INIT>
# ENDBLOCK
'''
)
)
_ensure_text(
fname=join(repo_dpath, modname, '__main__.py'),
chmod='+x',
text=ut.codeblock(
r'''
# STARTBLOCK
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Initially Generated By:
{regencmd}
"""
from __future__ import absolute_import, division, print_function, unicode_literals
def {modname}_main():
ignore_prefix = []
ignore_suffix = []
import utool as ut
ut.main_function_tester('{modname}', ignore_prefix, ignore_suffix)
if __name__ == '__main__':
"""
Usage:
python -m {modname} <funcname>
"""
print('Running {modname} main')
{modname}_main()
# ENDBLOCK
'''
)
)
_ensure_text(
fname='run_tests.py',
chmod='+x',
text=ut.codeblock(
r'''
# STARTBLOCK
#!/usr/bin/env python
"""
Initially Generated By:
{regencmd} --force-{fname}
"""
from __future__ import absolute_import, division, print_function
import sys
import utool as ut
def run_tests():
# Build module list and run tests
import sys
ut.change_term_title('RUN {modname} TESTS')
exclude_doctests_fnames = set([
])
exclude_dirs = [
'_broken', 'old', 'tests', 'timeits',
'_scripts', '_timeits', '_doc', 'notebook',
]
dpath_list = ['{modname}']
doctest_modname_list = ut.find_doctestable_modnames(
dpath_list, exclude_doctests_fnames, exclude_dirs)
coverage = ut.get_argflag(('--coverage', '--cov',))
if coverage:
import coverage
cov = coverage.Coverage(source=doctest_modname_list)
cov.start()
print('Starting coverage')
exclude_lines = [
'pragma: no cover',
'def __repr__',
'if self.debug:',
'if settings.DEBUG',
'raise AssertionError',
'raise NotImplementedError',
'if 0:',
'if ut.VERBOSE',
'if _debug:',
'if __name__ == .__main__.:',
'print(.*)',
]
for line in exclude_lines:
cov.exclude(line)
for modname in doctest_modname_list:
exec('import ' + modname, globals())
module_list = [sys.modules[name] for name in doctest_modname_list]
nPass, nTotal, failed_cmd_list = ut.doctest_module_list(module_list)
if coverage:
print('Stoping coverage')
cov.stop()
print('Saving coverage')
cov.save()
print('Generating coverage html report')
cov.html_report()
if nPass != nTotal:
return 1
else:
return 0
if __name__ == '__main__':
import multiprocessing
multiprocessing.freeze_support()
retcode = run_tests()
sys.exit(retcode)
# ENDBLOCK
'''
)
)
ut.ensuredir(join(repo_dpath, modname), verbose=True) | [
"def",
"setup_repo",
"(",
")",
":",
"print",
"(",
"'\\n [setup_repo]!'",
")",
"# import os",
"from",
"functools",
"import",
"partial",
"import",
"utool",
"as",
"ut",
"# import os",
"code_dpath",
"=",
"ut",
".",
"truepath",
"(",
"ut",
".",
"get_argval",
"(",
"'--code-dir'",
",",
"default",
"=",
"'~/code'",
")",
")",
"_code_dpath",
"=",
"ut",
".",
"unexpanduser",
"(",
"code_dpath",
")",
"repo_fname",
"=",
"(",
"ut",
".",
"get_argval",
"(",
"(",
"'--repo'",
",",
"'--repo-name'",
")",
",",
"type_",
"=",
"str",
")",
")",
"repo_dpath",
"=",
"join",
"(",
"code_dpath",
",",
"repo_fname",
")",
"modname",
"=",
"ut",
".",
"get_argval",
"(",
"'--modname'",
",",
"default",
"=",
"repo_fname",
")",
"ut",
".",
"ensuredir",
"(",
"repo_dpath",
",",
"verbose",
"=",
"True",
")",
"_regencmd",
"=",
"'python -m utool --tf setup_repo --repo={repo_fname} --codedir={_code_dpath} --modname={modname}'",
"flake8_noqacmd",
"=",
"'flake8'",
"+",
"':noqa'",
"regencmd",
"=",
"_regencmd",
".",
"format",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"with",
"ut",
".",
"ChdirContext",
"(",
"repo_dpath",
")",
":",
"# os.chdir(repo_fname)",
"locals_",
"=",
"locals",
"(",
")",
"force",
"=",
"True",
"_ensure_text",
"=",
"partial",
"(",
"ensure_text",
",",
"repo_dpath",
"=",
"'.'",
",",
"force",
"=",
"None",
",",
"locals_",
"=",
"locals_",
")",
"_ensure_text",
"(",
"fname",
"=",
"'todo.md'",
",",
"text",
"=",
"ut",
".",
"codeblock",
"(",
"r'''\n # STARTBLOCK\n # {modname} TODO File\n\n * Add TODOS!\n # ENDBLOCK\n '''",
")",
")",
"_ensure_text",
"(",
"fname",
"=",
"'README.md'",
",",
"text",
"=",
"ut",
".",
"codeblock",
"(",
"r'''\n # STARTBLOCK\n # {modname} README FILE\n # ENDBLOCK\n '''",
")",
")",
"_ensure_text",
"(",
"fname",
"=",
"'setup.py'",
",",
"chmod",
"=",
"'+x'",
",",
"text",
"=",
"ut",
".",
"codeblock",
"(",
"r'''\n # STARTBLOCK\n #!/usr/bin/env python\n \"\"\"\n Initially Generated By:\n {regencmd} --force-{fname}\n \"\"\"\n from __future__ import absolute_import, division, print_function, unicode_literals\n from setuptools import setup\n try:\n from utool import util_setup\n except ImportError:\n print('ERROR: setup requires utool')\n raise\n\n INSTALL_REQUIRES = [\n #'cython >= 0.21.1',\n #'numpy >= 1.9.0',\n #'scipy >= 0.16.0',\n ]\n\n CLUTTER_PATTERNS = [\n # Patterns removed by python setup.py clean\n ]\n\n if __name__ == '__main__':\n kwargs = util_setup.setuptools_setup(\n setup_fpath=__file__,\n name='{modname}',\n packages=util_setup.find_packages(),\n version=util_setup.parse_package_for_version('{modname}'),\n license=util_setup.read_license('LICENSE'),\n long_description=util_setup.parse_readme('README.md'),\n ext_modules=util_setup.find_ext_modules(),\n cmdclass=util_setup.get_cmdclass(),\n #description='description of module',\n #url='https://github.com/<username>/{repo_fname}.git',\n #author='<author>',\n #author_email='<author_email>',\n keywords='',\n install_requires=INSTALL_REQUIRES,\n clutter_patterns=CLUTTER_PATTERNS,\n #package_data={{'build': ut.get_dynamic_lib_globstrs()}},\n #build_command=lambda: ut.std_build_command(dirname(__file__)),\n classifiers=[],\n )\n setup(**kwargs)\n # ENDBLOCK\n '''",
")",
")",
"_ensure_text",
"(",
"fname",
"=",
"'.gitignore'",
",",
"text",
"=",
"ut",
".",
"codeblock",
"(",
"r'''\n # STARTBLOCK\n *.py[cod]\n\n # C extensions\n *.so\n # Packages\n *.egg\n *.egg-info\n dist\n build\n eggs\n parts\n bin\n var\n sdist\n develop-eggs\n .installed.cfg\n lib\n lib64\n __pycache__\n\n # Installer logs\n pip-log.txt\n\n # Print Logs\n logs\n\n # Unit test / coverage reports\n .coverage\n .tox\n nosetests.xml\n\n # Translations\n *.mo\n\n # Mr Developer\n .mr.developer.cfg\n .project\n .pydevproject\n .DS_Store\n *.dump.txt\n *.sqlite3\n\n # profiler\n *.lprof\n *.prof\n\n *.flann\n *.npz\n\n # utool output\n _timeings.txt\n failed.txt\n\n *.orig\n _doc\n timeings.txt\n failed_doctests.txt\n # ENDBLOCK\n '''",
")",
")",
"_ensure_text",
"(",
"fname",
"=",
"join",
"(",
"repo_dpath",
",",
"modname",
",",
"'__init__.py'",
")",
",",
"text",
"=",
"ut",
".",
"codeblock",
"(",
"r'''\n # STARTBLOCK\n # -*- coding: utf-8 -*-\n # {flake8_noqacmd}\n \"\"\"\n Initially Generated By:\n {regencmd}\n \"\"\"\n from __future__ import absolute_import, division, print_function, unicode_literals\n import sys\n __version__ = '0.0.0'\n\n IMPORT_TUPLES = [\n # ('<modname>', None),\n ]\n __DYNAMIC__ = '--nodyn' not in sys.argv\n\n \"\"\"\n python -c \"import {modname}\" --dump-{modname}-init\n python -c \"import {modname}\" --update-{modname}-init\n \"\"\"\n\n DOELSE = False\n if __DYNAMIC__:\n # Dynamically import listed util libraries and their members.\n from utool._internal import util_importer\n ignore_endswith = []\n import_execstr = util_importer.dynamic_import(\n __name__, IMPORT_TUPLES, ignore_endswith=ignore_endswith)\n exec(import_execstr)\n DOELSE = False\n else:\n DOELSE = True\n if DOELSE:\n # <AUTOGEN_INIT>\n pass\n # </AUTOGEN_INIT>\n # ENDBLOCK\n '''",
")",
")",
"_ensure_text",
"(",
"fname",
"=",
"join",
"(",
"repo_dpath",
",",
"modname",
",",
"'__main__.py'",
")",
",",
"chmod",
"=",
"'+x'",
",",
"text",
"=",
"ut",
".",
"codeblock",
"(",
"r'''\n # STARTBLOCK\n #!/usr/bin/env python\n # -*- coding: utf-8 -*-\n \"\"\"\n Initially Generated By:\n {regencmd}\n \"\"\"\n from __future__ import absolute_import, division, print_function, unicode_literals\n\n\n def {modname}_main():\n ignore_prefix = []\n ignore_suffix = []\n import utool as ut\n ut.main_function_tester('{modname}', ignore_prefix, ignore_suffix)\n\n if __name__ == '__main__':\n \"\"\"\n Usage:\n python -m {modname} <funcname>\n \"\"\"\n print('Running {modname} main')\n {modname}_main()\n # ENDBLOCK\n '''",
")",
")",
"_ensure_text",
"(",
"fname",
"=",
"'run_tests.py'",
",",
"chmod",
"=",
"'+x'",
",",
"text",
"=",
"ut",
".",
"codeblock",
"(",
"r'''\n # STARTBLOCK\n #!/usr/bin/env python\n \"\"\"\n Initially Generated By:\n {regencmd} --force-{fname}\n \"\"\"\n from __future__ import absolute_import, division, print_function\n import sys\n import utool as ut\n\n\n def run_tests():\n # Build module list and run tests\n import sys\n ut.change_term_title('RUN {modname} TESTS')\n exclude_doctests_fnames = set([\n ])\n exclude_dirs = [\n '_broken', 'old', 'tests', 'timeits',\n '_scripts', '_timeits', '_doc', 'notebook',\n ]\n dpath_list = ['{modname}']\n doctest_modname_list = ut.find_doctestable_modnames(\n dpath_list, exclude_doctests_fnames, exclude_dirs)\n\n coverage = ut.get_argflag(('--coverage', '--cov',))\n if coverage:\n import coverage\n cov = coverage.Coverage(source=doctest_modname_list)\n cov.start()\n print('Starting coverage')\n\n exclude_lines = [\n 'pragma: no cover',\n 'def __repr__',\n 'if self.debug:',\n 'if settings.DEBUG',\n 'raise AssertionError',\n 'raise NotImplementedError',\n 'if 0:',\n 'if ut.VERBOSE',\n 'if _debug:',\n 'if __name__ == .__main__.:',\n 'print(.*)',\n ]\n for line in exclude_lines:\n cov.exclude(line)\n\n for modname in doctest_modname_list:\n exec('import ' + modname, globals())\n module_list = [sys.modules[name] for name in doctest_modname_list]\n\n nPass, nTotal, failed_cmd_list = ut.doctest_module_list(module_list)\n\n if coverage:\n print('Stoping coverage')\n cov.stop()\n print('Saving coverage')\n cov.save()\n print('Generating coverage html report')\n cov.html_report()\n\n if nPass != nTotal:\n return 1\n else:\n return 0\n\n if __name__ == '__main__':\n import multiprocessing\n multiprocessing.freeze_support()\n retcode = run_tests()\n sys.exit(retcode)\n # ENDBLOCK\n '''",
")",
")",
"ut",
".",
"ensuredir",
"(",
"join",
"(",
"repo_dpath",
",",
"modname",
")",
",",
"verbose",
"=",
"True",
")"
] | r"""
Creates default structure for a new repo
CommandLine:
python -m utool setup_repo --repo=dtool --codedir=~/code
python -m utool setup_repo --repo=dtool --codedir=~/code
python -m utool setup_repo --repo=ibeis-flukematch-module --codedir=~/code --modname=ibeis_flukematch
python -m utool setup_repo --repo=mtgmonte --codedir=~/code --modname=mtgmonte
python -m utool setup_repo --repo=pydarknet --codedir=~/code --modname=pydarknet
python -m utool setup_repo --repo=sandbox_utools --codedir=~/code --modname=sandbox_utools
python -m utool setup_repo --repo=ubelt --codedir=~/code --modname=ubelt -w
python -m utool setup_repo
Python:
ipython
import utool as ut
ut.rrrr(0); ut.setup_repo()
Example:
>>> # DISABLE_DOCTEST
>>> # SCRIPT
>>> from utool.util_project import * # NOQA
>>> import utool as ut
>>> result = setup_repo()
>>> print(result) | [
"r",
"Creates",
"default",
"structure",
"for",
"a",
"new",
"repo"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_project.py#L143-L499 | train |
Erotemic/utool | utool/util_project.py | grep_projects | def grep_projects(tofind_list, user_profile=None, verbose=True, new=False,
**kwargs):
r"""
Greps the projects defined in the current UserProfile
Args:
tofind_list (list):
user_profile (None): (default = None)
Kwargs:
user_profile
CommandLine:
python -m utool --tf grep_projects grep_projects
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_project import * # NOQA
>>> import utool as ut
>>> import sys
>>> tofind_list = ut.get_argval('--find', type_=list,
>>> default=[sys.argv[-1]])
>>> grep_projects(tofind_list)
"""
import utool as ut
user_profile = ensure_user_profile(user_profile)
print('user_profile = {!r}'.format(user_profile))
kwargs = kwargs.copy()
colored = kwargs.pop('colored', True)
grepkw = {}
grepkw['greater_exclude_dirs'] = user_profile.project_exclude_dirs
grepkw['exclude_dirs'] = user_profile.project_exclude_dirs
grepkw['dpath_list'] = user_profile.project_dpaths
grepkw['include_patterns'] = user_profile.project_include_patterns
grepkw['exclude_patterns'] = user_profile.project_exclude_patterns
grepkw.update(kwargs)
msg_list1 = []
msg_list2 = []
print_ = msg_list1.append
print_('Greping Projects')
print_('tofind_list = %s' % (ut.repr4(tofind_list, nl=True),))
#print_('grepkw = %s' % ut.repr4(grepkw, nl=True))
if verbose:
print('\n'.join(msg_list1))
#with ut.Timer('greping', verbose=True):
grep_result = ut.grep(tofind_list, **grepkw)
found_fpath_list, found_lines_list, found_lxs_list = grep_result
# HACK, duplicate behavior. TODO: write grep print result function
reflags = grepkw.get('reflags', 0)
_exprs_flags = [ut.extend_regex2(expr, reflags)
for expr in tofind_list]
extended_regex_list = ut.take_column(_exprs_flags, 0)
reflags_list = ut.take_column(_exprs_flags, 1)
# HACK
# pat = ut.util_regex.regex_or(extended_regex_list)
reflags = reflags_list[0]
# from utool import util_regex
resultstr = ut.make_grep_resultstr(grep_result, extended_regex_list,
reflags, colored=colored)
msg_list2.append(resultstr)
print_ = msg_list2.append
#for fpath, lines, lxs in zip(found_fpath_list, found_lines_list,
# found_lxs_list):
# print_('----------------------')
# print_('found %d line(s) in %r: ' % (len(lines), fpath))
# name = split(fpath)[1]
# max_line = len(lines)
# ndigits = str(len(str(max_line)))
# for (lx, line) in zip(lxs, lines):
# line = line.replace('\n', '')
# print_(('%s : %' + ndigits + 'd |%s') % (name, lx, line))
# iter_ = zip(found_fpath_list, found_lines_list, found_lxs_list)
# for fpath, lines, lxs in iter_:
# print_('----------------------')
# print_('found %d line(s) in %r: ' % (len(lines), fpath))
# name = split(fpath)[1]
# max_line = len(lines)
# ndigits = str(len(str(max_line)))
# for (lx, line) in zip(lxs, lines):
# line = line.replace('\n', '')
# colored_line = ut.highlight_regex(
# line.rstrip('\n'), pat, reflags=reflags)
# print_(('%s : %' + ndigits + 'd |%s') % (name, lx, colored_line))
print_('====================')
print_('found_fpath_list = ' + ut.repr4(found_fpath_list))
print_('')
#print_('gvim -o ' + ' '.join(found_fpath_list))
if verbose:
print('\n'.join(msg_list2))
msg_list = msg_list1 + msg_list2
if new:
return GrepResult(found_fpath_list, found_lines_list, found_lxs_list,
extended_regex_list, reflags)
else:
return msg_list | python | def grep_projects(tofind_list, user_profile=None, verbose=True, new=False,
**kwargs):
r"""
Greps the projects defined in the current UserProfile
Args:
tofind_list (list):
user_profile (None): (default = None)
Kwargs:
user_profile
CommandLine:
python -m utool --tf grep_projects grep_projects
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_project import * # NOQA
>>> import utool as ut
>>> import sys
>>> tofind_list = ut.get_argval('--find', type_=list,
>>> default=[sys.argv[-1]])
>>> grep_projects(tofind_list)
"""
import utool as ut
user_profile = ensure_user_profile(user_profile)
print('user_profile = {!r}'.format(user_profile))
kwargs = kwargs.copy()
colored = kwargs.pop('colored', True)
grepkw = {}
grepkw['greater_exclude_dirs'] = user_profile.project_exclude_dirs
grepkw['exclude_dirs'] = user_profile.project_exclude_dirs
grepkw['dpath_list'] = user_profile.project_dpaths
grepkw['include_patterns'] = user_profile.project_include_patterns
grepkw['exclude_patterns'] = user_profile.project_exclude_patterns
grepkw.update(kwargs)
msg_list1 = []
msg_list2 = []
print_ = msg_list1.append
print_('Greping Projects')
print_('tofind_list = %s' % (ut.repr4(tofind_list, nl=True),))
#print_('grepkw = %s' % ut.repr4(grepkw, nl=True))
if verbose:
print('\n'.join(msg_list1))
#with ut.Timer('greping', verbose=True):
grep_result = ut.grep(tofind_list, **grepkw)
found_fpath_list, found_lines_list, found_lxs_list = grep_result
# HACK, duplicate behavior. TODO: write grep print result function
reflags = grepkw.get('reflags', 0)
_exprs_flags = [ut.extend_regex2(expr, reflags)
for expr in tofind_list]
extended_regex_list = ut.take_column(_exprs_flags, 0)
reflags_list = ut.take_column(_exprs_flags, 1)
# HACK
# pat = ut.util_regex.regex_or(extended_regex_list)
reflags = reflags_list[0]
# from utool import util_regex
resultstr = ut.make_grep_resultstr(grep_result, extended_regex_list,
reflags, colored=colored)
msg_list2.append(resultstr)
print_ = msg_list2.append
#for fpath, lines, lxs in zip(found_fpath_list, found_lines_list,
# found_lxs_list):
# print_('----------------------')
# print_('found %d line(s) in %r: ' % (len(lines), fpath))
# name = split(fpath)[1]
# max_line = len(lines)
# ndigits = str(len(str(max_line)))
# for (lx, line) in zip(lxs, lines):
# line = line.replace('\n', '')
# print_(('%s : %' + ndigits + 'd |%s') % (name, lx, line))
# iter_ = zip(found_fpath_list, found_lines_list, found_lxs_list)
# for fpath, lines, lxs in iter_:
# print_('----------------------')
# print_('found %d line(s) in %r: ' % (len(lines), fpath))
# name = split(fpath)[1]
# max_line = len(lines)
# ndigits = str(len(str(max_line)))
# for (lx, line) in zip(lxs, lines):
# line = line.replace('\n', '')
# colored_line = ut.highlight_regex(
# line.rstrip('\n'), pat, reflags=reflags)
# print_(('%s : %' + ndigits + 'd |%s') % (name, lx, colored_line))
print_('====================')
print_('found_fpath_list = ' + ut.repr4(found_fpath_list))
print_('')
#print_('gvim -o ' + ' '.join(found_fpath_list))
if verbose:
print('\n'.join(msg_list2))
msg_list = msg_list1 + msg_list2
if new:
return GrepResult(found_fpath_list, found_lines_list, found_lxs_list,
extended_regex_list, reflags)
else:
return msg_list | [
"def",
"grep_projects",
"(",
"tofind_list",
",",
"user_profile",
"=",
"None",
",",
"verbose",
"=",
"True",
",",
"new",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"utool",
"as",
"ut",
"user_profile",
"=",
"ensure_user_profile",
"(",
"user_profile",
")",
"print",
"(",
"'user_profile = {!r}'",
".",
"format",
"(",
"user_profile",
")",
")",
"kwargs",
"=",
"kwargs",
".",
"copy",
"(",
")",
"colored",
"=",
"kwargs",
".",
"pop",
"(",
"'colored'",
",",
"True",
")",
"grepkw",
"=",
"{",
"}",
"grepkw",
"[",
"'greater_exclude_dirs'",
"]",
"=",
"user_profile",
".",
"project_exclude_dirs",
"grepkw",
"[",
"'exclude_dirs'",
"]",
"=",
"user_profile",
".",
"project_exclude_dirs",
"grepkw",
"[",
"'dpath_list'",
"]",
"=",
"user_profile",
".",
"project_dpaths",
"grepkw",
"[",
"'include_patterns'",
"]",
"=",
"user_profile",
".",
"project_include_patterns",
"grepkw",
"[",
"'exclude_patterns'",
"]",
"=",
"user_profile",
".",
"project_exclude_patterns",
"grepkw",
".",
"update",
"(",
"kwargs",
")",
"msg_list1",
"=",
"[",
"]",
"msg_list2",
"=",
"[",
"]",
"print_",
"=",
"msg_list1",
".",
"append",
"print_",
"(",
"'Greping Projects'",
")",
"print_",
"(",
"'tofind_list = %s'",
"%",
"(",
"ut",
".",
"repr4",
"(",
"tofind_list",
",",
"nl",
"=",
"True",
")",
",",
")",
")",
"#print_('grepkw = %s' % ut.repr4(grepkw, nl=True))",
"if",
"verbose",
":",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"msg_list1",
")",
")",
"#with ut.Timer('greping', verbose=True):",
"grep_result",
"=",
"ut",
".",
"grep",
"(",
"tofind_list",
",",
"*",
"*",
"grepkw",
")",
"found_fpath_list",
",",
"found_lines_list",
",",
"found_lxs_list",
"=",
"grep_result",
"# HACK, duplicate behavior. TODO: write grep print result function",
"reflags",
"=",
"grepkw",
".",
"get",
"(",
"'reflags'",
",",
"0",
")",
"_exprs_flags",
"=",
"[",
"ut",
".",
"extend_regex2",
"(",
"expr",
",",
"reflags",
")",
"for",
"expr",
"in",
"tofind_list",
"]",
"extended_regex_list",
"=",
"ut",
".",
"take_column",
"(",
"_exprs_flags",
",",
"0",
")",
"reflags_list",
"=",
"ut",
".",
"take_column",
"(",
"_exprs_flags",
",",
"1",
")",
"# HACK",
"# pat = ut.util_regex.regex_or(extended_regex_list)",
"reflags",
"=",
"reflags_list",
"[",
"0",
"]",
"# from utool import util_regex",
"resultstr",
"=",
"ut",
".",
"make_grep_resultstr",
"(",
"grep_result",
",",
"extended_regex_list",
",",
"reflags",
",",
"colored",
"=",
"colored",
")",
"msg_list2",
".",
"append",
"(",
"resultstr",
")",
"print_",
"=",
"msg_list2",
".",
"append",
"#for fpath, lines, lxs in zip(found_fpath_list, found_lines_list,",
"# found_lxs_list):",
"# print_('----------------------')",
"# print_('found %d line(s) in %r: ' % (len(lines), fpath))",
"# name = split(fpath)[1]",
"# max_line = len(lines)",
"# ndigits = str(len(str(max_line)))",
"# for (lx, line) in zip(lxs, lines):",
"# line = line.replace('\\n', '')",
"# print_(('%s : %' + ndigits + 'd |%s') % (name, lx, line))",
"# iter_ = zip(found_fpath_list, found_lines_list, found_lxs_list)",
"# for fpath, lines, lxs in iter_:",
"# print_('----------------------')",
"# print_('found %d line(s) in %r: ' % (len(lines), fpath))",
"# name = split(fpath)[1]",
"# max_line = len(lines)",
"# ndigits = str(len(str(max_line)))",
"# for (lx, line) in zip(lxs, lines):",
"# line = line.replace('\\n', '')",
"# colored_line = ut.highlight_regex(",
"# line.rstrip('\\n'), pat, reflags=reflags)",
"# print_(('%s : %' + ndigits + 'd |%s') % (name, lx, colored_line))",
"print_",
"(",
"'===================='",
")",
"print_",
"(",
"'found_fpath_list = '",
"+",
"ut",
".",
"repr4",
"(",
"found_fpath_list",
")",
")",
"print_",
"(",
"''",
")",
"#print_('gvim -o ' + ' '.join(found_fpath_list))",
"if",
"verbose",
":",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"msg_list2",
")",
")",
"msg_list",
"=",
"msg_list1",
"+",
"msg_list2",
"if",
"new",
":",
"return",
"GrepResult",
"(",
"found_fpath_list",
",",
"found_lines_list",
",",
"found_lxs_list",
",",
"extended_regex_list",
",",
"reflags",
")",
"else",
":",
"return",
"msg_list"
] | r"""
Greps the projects defined in the current UserProfile
Args:
tofind_list (list):
user_profile (None): (default = None)
Kwargs:
user_profile
CommandLine:
python -m utool --tf grep_projects grep_projects
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_project import * # NOQA
>>> import utool as ut
>>> import sys
>>> tofind_list = ut.get_argval('--find', type_=list,
>>> default=[sys.argv[-1]])
>>> grep_projects(tofind_list) | [
"r",
"Greps",
"the",
"projects",
"defined",
"in",
"the",
"current",
"UserProfile"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_project.py#L606-L708 | train |
crdoconnor/faketime | setup.py | CustomInstall.run | def run(self):
"""Compile libfaketime."""
if sys.platform == "linux" or sys.platform == "linux2":
libname = 'libfaketime.so.1'
libnamemt = 'libfaketimeMT.so.1'
elif sys.platform == "darwin":
libname = 'libfaketime.1.dylib'
libnamemt = 'libfaketimeMT.1.dylib'
else:
sys.stderr.write("WARNING : libfaketime does not support platform {}\n".format(sys.platform))
sys.stderr.flush()
return
faketime_lib = join('faketime', libname)
faketime_lib_mt = join('faketime', libnamemt)
self.my_outputs = []
setup_py_directory = dirname(realpath(__file__))
faketime_directory = join(setup_py_directory, "faketime")
os.chdir(faketime_directory)
if sys.platform == "linux" or sys.platform == "linux2":
subprocess.check_call(['make',])
else:
os.chdir(setup_py_directory)
if "10.12" in subprocess.check_output(["sw_vers", "-productVersion"]).decode('utf8'):
self.copy_file(
join('faketime', "libfaketime.c.sierra"),
join('faketime', "libfaketime.c")
)
os.chdir(faketime_directory)
subprocess.check_call(['make', '-f', 'Makefile.OSX'])
os.chdir(setup_py_directory)
dest = join(self.install_purelib, dirname(faketime_lib))
dest_mt = join(self.install_purelib, dirname(faketime_lib_mt))
try:
os.makedirs(dest)
except OSError as e:
if e.errno != 17:
raise
self.copy_file(faketime_lib, dest)
if exists(faketime_lib_mt):
self.copy_file(faketime_lib_mt, dest_mt)
self.my_outputs.append(join(dest, libname))
install.run(self) | python | def run(self):
"""Compile libfaketime."""
if sys.platform == "linux" or sys.platform == "linux2":
libname = 'libfaketime.so.1'
libnamemt = 'libfaketimeMT.so.1'
elif sys.platform == "darwin":
libname = 'libfaketime.1.dylib'
libnamemt = 'libfaketimeMT.1.dylib'
else:
sys.stderr.write("WARNING : libfaketime does not support platform {}\n".format(sys.platform))
sys.stderr.flush()
return
faketime_lib = join('faketime', libname)
faketime_lib_mt = join('faketime', libnamemt)
self.my_outputs = []
setup_py_directory = dirname(realpath(__file__))
faketime_directory = join(setup_py_directory, "faketime")
os.chdir(faketime_directory)
if sys.platform == "linux" or sys.platform == "linux2":
subprocess.check_call(['make',])
else:
os.chdir(setup_py_directory)
if "10.12" in subprocess.check_output(["sw_vers", "-productVersion"]).decode('utf8'):
self.copy_file(
join('faketime', "libfaketime.c.sierra"),
join('faketime', "libfaketime.c")
)
os.chdir(faketime_directory)
subprocess.check_call(['make', '-f', 'Makefile.OSX'])
os.chdir(setup_py_directory)
dest = join(self.install_purelib, dirname(faketime_lib))
dest_mt = join(self.install_purelib, dirname(faketime_lib_mt))
try:
os.makedirs(dest)
except OSError as e:
if e.errno != 17:
raise
self.copy_file(faketime_lib, dest)
if exists(faketime_lib_mt):
self.copy_file(faketime_lib_mt, dest_mt)
self.my_outputs.append(join(dest, libname))
install.run(self) | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"\"linux\"",
"or",
"sys",
".",
"platform",
"==",
"\"linux2\"",
":",
"libname",
"=",
"'libfaketime.so.1'",
"libnamemt",
"=",
"'libfaketimeMT.so.1'",
"elif",
"sys",
".",
"platform",
"==",
"\"darwin\"",
":",
"libname",
"=",
"'libfaketime.1.dylib'",
"libnamemt",
"=",
"'libfaketimeMT.1.dylib'",
"else",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"WARNING : libfaketime does not support platform {}\\n\"",
".",
"format",
"(",
"sys",
".",
"platform",
")",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")",
"return",
"faketime_lib",
"=",
"join",
"(",
"'faketime'",
",",
"libname",
")",
"faketime_lib_mt",
"=",
"join",
"(",
"'faketime'",
",",
"libnamemt",
")",
"self",
".",
"my_outputs",
"=",
"[",
"]",
"setup_py_directory",
"=",
"dirname",
"(",
"realpath",
"(",
"__file__",
")",
")",
"faketime_directory",
"=",
"join",
"(",
"setup_py_directory",
",",
"\"faketime\"",
")",
"os",
".",
"chdir",
"(",
"faketime_directory",
")",
"if",
"sys",
".",
"platform",
"==",
"\"linux\"",
"or",
"sys",
".",
"platform",
"==",
"\"linux2\"",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"'make'",
",",
"]",
")",
"else",
":",
"os",
".",
"chdir",
"(",
"setup_py_directory",
")",
"if",
"\"10.12\"",
"in",
"subprocess",
".",
"check_output",
"(",
"[",
"\"sw_vers\"",
",",
"\"-productVersion\"",
"]",
")",
".",
"decode",
"(",
"'utf8'",
")",
":",
"self",
".",
"copy_file",
"(",
"join",
"(",
"'faketime'",
",",
"\"libfaketime.c.sierra\"",
")",
",",
"join",
"(",
"'faketime'",
",",
"\"libfaketime.c\"",
")",
")",
"os",
".",
"chdir",
"(",
"faketime_directory",
")",
"subprocess",
".",
"check_call",
"(",
"[",
"'make'",
",",
"'-f'",
",",
"'Makefile.OSX'",
"]",
")",
"os",
".",
"chdir",
"(",
"setup_py_directory",
")",
"dest",
"=",
"join",
"(",
"self",
".",
"install_purelib",
",",
"dirname",
"(",
"faketime_lib",
")",
")",
"dest_mt",
"=",
"join",
"(",
"self",
".",
"install_purelib",
",",
"dirname",
"(",
"faketime_lib_mt",
")",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"dest",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"17",
":",
"raise",
"self",
".",
"copy_file",
"(",
"faketime_lib",
",",
"dest",
")",
"if",
"exists",
"(",
"faketime_lib_mt",
")",
":",
"self",
".",
"copy_file",
"(",
"faketime_lib_mt",
",",
"dest_mt",
")",
"self",
".",
"my_outputs",
".",
"append",
"(",
"join",
"(",
"dest",
",",
"libname",
")",
")",
"install",
".",
"run",
"(",
"self",
")"
] | Compile libfaketime. | [
"Compile",
"libfaketime",
"."
] | 6e81ca070c0e601a52507b945ed45d5d42576b21 | https://github.com/crdoconnor/faketime/blob/6e81ca070c0e601a52507b945ed45d5d42576b21/setup.py#L14-L62 | train |
Erotemic/utool | utool/util_parallel.py | generate2 | def generate2(func, args_gen, kw_gen=None, ntasks=None, ordered=True,
force_serial=False, use_pool=False, chunksize=None, nprocs=None,
progkw={}, nTasks=None, verbose=None):
r"""
Interfaces to either multiprocessing or futures.
Esentially maps ``args_gen`` onto ``func`` using pool.imap.
However, args_gen must be a tuple of args that will be unpacked and send to
the function. Thus, the function can take multiple args. Also specifing
keyword args is supported.
Useful for embarrassingly parallel loops. Currently does not work with
opencv3
CommandLine:
python -m utool.util_parallel generate2
Args:
func (function): live python function
args_gen (?):
kw_gen (None): (default = None)
ntasks (None): (default = None)
ordered (bool): (default = True)
force_serial (bool): (default = False)
verbose (bool): verbosity flag(default = None)
CommandLine:
python -m utool.util_parallel generate2
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_parallel import * # NOQA
>>> from utool.util_parallel import _kw_wrap_worker # NOQA
>>> import utool as ut
>>> args_gen = list(zip(range(10000)))
>>> kw_gen = [{}] * len(args_gen)
>>> func = ut.is_prime
>>> _ = list(generate2(func, args_gen))
>>> _ = list(generate2(func, args_gen, ordered=False))
>>> _ = list(generate2(func, args_gen, force_serial=True))
>>> _ = list(generate2(func, args_gen, use_pool=True))
>>> _ = list(generate2(func, args_gen, ordered=False, verbose=False))
Example0:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> #num = 8700 # parallel is slower for smaller numbers
>>> num = 500 # parallel has an initial (~.1 second startup overhead)
>>> print('TESTING SERIAL')
>>> func = ut.is_prime
>>> args_list = list(range(0, num))
>>> flag_generator0 = ut.generate2(ut.is_prime, zip(range(0, num)), force_serial=True)
>>> flag_list0 = list(flag_generator0)
>>> print('TESTING PARALLEL')
>>> flag_generator1 = ut.generate2(ut.is_prime, zip(range(0, num)))
>>> flag_list1 = list(flag_generator1)
>>> print('ASSERTING')
>>> assert len(flag_list1) == num
>>> assert flag_list0 == flag_list1
Example1:
>>> # ENABLE_DOCTEST
>>> # Trying to recreate the freeze seen in IBEIS
>>> import utool as ut
>>> print('TESTING SERIAL')
>>> flag_generator0 = ut.generate2(ut.is_prime, zip(range(0, 1)))
>>> flag_list0 = list(flag_generator0)
>>> flag_generator1 = ut.generate2(ut.fibonacci_recursive, zip(range(0, 1)))
>>> flag_list1 = list(flag_generator1)
>>> print('TESTING PARALLEL')
>>> flag_generator2 = ut.generate2(ut.is_prime, zip(range(0, 12)))
>>> flag_list2 = list(flag_generator2)
>>> flag_generator3 = ut.generate2(ut.fibonacci_recursive, zip(range(0, 12)))
>>> flag_list3 = list(flag_generator3)
>>> print('flag_list0 = %r' % (flag_list0,))
>>> print('flag_list1 = %r' % (flag_list1,))
>>> print('flag_list2 = %r' % (flag_list1,))
>>> print('flag_list3 = %r' % (flag_list1,))
Example2:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> # Trying to recreate the freeze seen in IBEIS
>>> import vtool as vt
>>> #def gen_chip(tup):
>>> # import vtool as vt
>>> # cfpath, gfpath, bbox, theta, new_size, filter_list = tup
>>> # chipBGR = vt.compute_chip(gfpath, bbox, theta, new_size, filter_list)
>>> # height, width = chipBGR.shape[0:2]
>>> # vt.imwrite(cfpath, chipBGR)
>>> # return cfpath, width, height
>>> import utool as ut
>>> from ibeis.algo.preproc.preproc_chip import gen_chip
>>> #from ibeis.algo.preproc.preproc_feat import gen_feat_worker
>>> key_list = ['grace.jpg', 'easy1.png', 'ada2.jpg', 'easy3.png',
>>> 'hard3.png', 'zebra.png', 'patsy.jpg', 'ada.jpg',
>>> 'carl.jpg', 'lena.png', 'easy2.png']
>>> img_fpath_list = [ut.grab_test_imgpath(key) for key in key_list]
>>> arg_list1 = [(ut.augpath(img_fpath, '_testgen'), img_fpath, (0, 0, 100, 100), 0.0, (545, 372), []) for img_fpath in img_fpath_list[0:1]]
>>> arg_list2 = [(ut.augpath(img_fpath, '_testgen'), img_fpath, (0, 0, 100, 100), 0.0, (545, 372), []) for img_fpath in img_fpath_list]
>>> #arg_list3 = [(count, fpath, {}) for count, fpath in enumerate(ut.get_list_column(arg_list1, 0))]
>>> #arg_list4 = [(count, fpath, {}) for count, fpath in enumerate(ut.get_list_column(arg_list2, 0))]
>>> ut.remove_file_list(ut.get_list_column(arg_list2, 0))
>>> chips1 = [x for x in ut.generate2(gen_chip, arg_list1)]
>>> chips2 = [y for y in ut.generate2(gen_chip, arg_list2, force_serial=True)]
>>> #feats3 = [z for z in ut.generate2(gen_feat_worker, arg_list3)]
>>> #feats4 = [w for w in ut.generate2(gen_feat_worker, arg_list4)]
Example3:
>>> # DISABLE_DOCTEST
>>> # FAILING_DOCTEST
>>> # Trying to recreate the freeze seen in IBEIS
>>> # Extremely weird case: freezes only if dsize > (313, 313) AND __testwarp was called beforehand.
>>> # otherwise the parallel loop works fine. Could be an opencv 3.0.0-dev issue.
>>> import vtool as vt
>>> import utool as ut
>>> from ibeis.algo.preproc.preproc_chip import gen_chip
>>> import cv2
>>> from utool.util_parallel import __testwarp
>>> key_list = ['grace.jpg', 'easy1.png', 'ada2.jpg', 'easy3.png',
>>> 'hard3.png', 'zebra.png', 'patsy.jpg', 'ada.jpg',
>>> 'carl.jpg', 'lena.png', 'easy2.png']
>>> img_fpath_list = [ut.grab_test_imgpath(key) for key in key_list]
>>> arg_list1 = [(vt.imread(fpath),) for fpath in img_fpath_list[0:1]]
>>> arg_list2 = [(vt.imread(fpath),) for fpath in img_fpath_list]
>>> #new1 = [x for x in ut.generate2(__testwarp, arg_list1)]
>>> new1 = __testwarp(arg_list1[0])
>>> new2 = [y for y in ut.generate2(__testwarp, arg_list2, force_serial=False)]
>>> #print('new2 = %r' % (new2,))
#Example4:
# >>> # Freakin weird. When IBEIS Runs generate it doesn't close the processes
# >>> # UNSTABLE_DOCTEST
# >>> # python -m utool.util_parallel --test-generate:4
# >>> # Trying to see if we can recreate the problem where there are
# >>> # defunct python processes
# >>> import utool as ut
# >>> #num = 8700 # parallel is slower for smaller numbers
# >>> num = 70000 # parallel has an initial (~.1 second startup overhead)
# >>> print('TESTING PARALLEL')
# >>> flag_generator1 = list(ut.generate2(ut.is_prime, range(0, num)))
# >>> flag_generator1 = list(ut.generate2(ut.is_prime, range(0, num)))
# >>> import time
# >>> time.sleep(10)
"""
if verbose is None:
verbose = 2
if ntasks is None:
ntasks = nTasks
if ntasks is None:
try:
ntasks = len(args_gen)
except TypeError:
# Cast to a list
args_gen = list(args_gen)
ntasks = len(args_gen)
if ntasks == 1 or ntasks < __MIN_PARALLEL_TASKS__:
force_serial = True
if __FORCE_SERIAL__:
force_serial = __FORCE_SERIAL__
if ntasks == 0:
if verbose:
print('[ut.generate2] submitted 0 tasks')
raise StopIteration
if nprocs is None:
nprocs = min(ntasks, get_default_numprocs())
if nprocs == 1:
force_serial = True
if kw_gen is None:
kw_gen = [{}] * ntasks
if isinstance(kw_gen, dict):
# kw_gen can be a single dict applied to everything
kw_gen = [kw_gen] * ntasks
if force_serial:
for result in _generate_serial2(func, args_gen, kw_gen,
ntasks=ntasks, progkw=progkw,
verbose=verbose):
yield result
else:
if verbose:
gentype = 'mp' if use_pool else 'futures'
fmtstr = '[generate2] executing {} {} tasks using {} {} procs'
print(fmtstr.format(ntasks, get_funcname(func), nprocs, gentype))
if verbose > 1:
lbl = '(pargen) %s: ' % (get_funcname(func),)
progkw_ = dict(freq=None, bs=True, adjust=False, freq_est='absolute')
progkw_.update(progkw)
# print('progkw_.update = {!r}'.format(progkw_.update))
progpart = util_progress.ProgPartial(length=ntasks, lbl=lbl, **progkw_)
if use_pool:
# Use multiprocessing
if chunksize is None:
chunksize = max(min(4, ntasks), min(8, ntasks // (nprocs ** 2)))
try:
pool = multiprocessing.Pool(nprocs)
if ordered:
pmap_func = pool.imap
else:
pmap_func = pool.imap_unordered
wrapped_arg_gen = zip([func] * len(args_gen), args_gen, kw_gen)
res_gen = pmap_func(_kw_wrap_worker, wrapped_arg_gen,
chunksize)
if verbose > 1:
res_gen = progpart(res_gen)
for res in res_gen:
yield res
finally:
pool.close()
pool.join()
else:
# Use futures
executor = futures.ProcessPoolExecutor(nprocs)
try:
fs_list = [executor.submit(func, *a, **k)
for a, k in zip(args_gen, kw_gen)]
fs_gen = fs_list
if not ordered:
fs_gen = futures.as_completed(fs_gen)
if verbose > 1:
fs_gen = progpart(fs_gen)
for fs in fs_gen:
yield fs.result()
finally:
executor.shutdown(wait=True) | python | def generate2(func, args_gen, kw_gen=None, ntasks=None, ordered=True,
force_serial=False, use_pool=False, chunksize=None, nprocs=None,
progkw={}, nTasks=None, verbose=None):
r"""
Interfaces to either multiprocessing or futures.
Esentially maps ``args_gen`` onto ``func`` using pool.imap.
However, args_gen must be a tuple of args that will be unpacked and send to
the function. Thus, the function can take multiple args. Also specifing
keyword args is supported.
Useful for embarrassingly parallel loops. Currently does not work with
opencv3
CommandLine:
python -m utool.util_parallel generate2
Args:
func (function): live python function
args_gen (?):
kw_gen (None): (default = None)
ntasks (None): (default = None)
ordered (bool): (default = True)
force_serial (bool): (default = False)
verbose (bool): verbosity flag(default = None)
CommandLine:
python -m utool.util_parallel generate2
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_parallel import * # NOQA
>>> from utool.util_parallel import _kw_wrap_worker # NOQA
>>> import utool as ut
>>> args_gen = list(zip(range(10000)))
>>> kw_gen = [{}] * len(args_gen)
>>> func = ut.is_prime
>>> _ = list(generate2(func, args_gen))
>>> _ = list(generate2(func, args_gen, ordered=False))
>>> _ = list(generate2(func, args_gen, force_serial=True))
>>> _ = list(generate2(func, args_gen, use_pool=True))
>>> _ = list(generate2(func, args_gen, ordered=False, verbose=False))
Example0:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> #num = 8700 # parallel is slower for smaller numbers
>>> num = 500 # parallel has an initial (~.1 second startup overhead)
>>> print('TESTING SERIAL')
>>> func = ut.is_prime
>>> args_list = list(range(0, num))
>>> flag_generator0 = ut.generate2(ut.is_prime, zip(range(0, num)), force_serial=True)
>>> flag_list0 = list(flag_generator0)
>>> print('TESTING PARALLEL')
>>> flag_generator1 = ut.generate2(ut.is_prime, zip(range(0, num)))
>>> flag_list1 = list(flag_generator1)
>>> print('ASSERTING')
>>> assert len(flag_list1) == num
>>> assert flag_list0 == flag_list1
Example1:
>>> # ENABLE_DOCTEST
>>> # Trying to recreate the freeze seen in IBEIS
>>> import utool as ut
>>> print('TESTING SERIAL')
>>> flag_generator0 = ut.generate2(ut.is_prime, zip(range(0, 1)))
>>> flag_list0 = list(flag_generator0)
>>> flag_generator1 = ut.generate2(ut.fibonacci_recursive, zip(range(0, 1)))
>>> flag_list1 = list(flag_generator1)
>>> print('TESTING PARALLEL')
>>> flag_generator2 = ut.generate2(ut.is_prime, zip(range(0, 12)))
>>> flag_list2 = list(flag_generator2)
>>> flag_generator3 = ut.generate2(ut.fibonacci_recursive, zip(range(0, 12)))
>>> flag_list3 = list(flag_generator3)
>>> print('flag_list0 = %r' % (flag_list0,))
>>> print('flag_list1 = %r' % (flag_list1,))
>>> print('flag_list2 = %r' % (flag_list1,))
>>> print('flag_list3 = %r' % (flag_list1,))
Example2:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> # Trying to recreate the freeze seen in IBEIS
>>> import vtool as vt
>>> #def gen_chip(tup):
>>> # import vtool as vt
>>> # cfpath, gfpath, bbox, theta, new_size, filter_list = tup
>>> # chipBGR = vt.compute_chip(gfpath, bbox, theta, new_size, filter_list)
>>> # height, width = chipBGR.shape[0:2]
>>> # vt.imwrite(cfpath, chipBGR)
>>> # return cfpath, width, height
>>> import utool as ut
>>> from ibeis.algo.preproc.preproc_chip import gen_chip
>>> #from ibeis.algo.preproc.preproc_feat import gen_feat_worker
>>> key_list = ['grace.jpg', 'easy1.png', 'ada2.jpg', 'easy3.png',
>>> 'hard3.png', 'zebra.png', 'patsy.jpg', 'ada.jpg',
>>> 'carl.jpg', 'lena.png', 'easy2.png']
>>> img_fpath_list = [ut.grab_test_imgpath(key) for key in key_list]
>>> arg_list1 = [(ut.augpath(img_fpath, '_testgen'), img_fpath, (0, 0, 100, 100), 0.0, (545, 372), []) for img_fpath in img_fpath_list[0:1]]
>>> arg_list2 = [(ut.augpath(img_fpath, '_testgen'), img_fpath, (0, 0, 100, 100), 0.0, (545, 372), []) for img_fpath in img_fpath_list]
>>> #arg_list3 = [(count, fpath, {}) for count, fpath in enumerate(ut.get_list_column(arg_list1, 0))]
>>> #arg_list4 = [(count, fpath, {}) for count, fpath in enumerate(ut.get_list_column(arg_list2, 0))]
>>> ut.remove_file_list(ut.get_list_column(arg_list2, 0))
>>> chips1 = [x for x in ut.generate2(gen_chip, arg_list1)]
>>> chips2 = [y for y in ut.generate2(gen_chip, arg_list2, force_serial=True)]
>>> #feats3 = [z for z in ut.generate2(gen_feat_worker, arg_list3)]
>>> #feats4 = [w for w in ut.generate2(gen_feat_worker, arg_list4)]
Example3:
>>> # DISABLE_DOCTEST
>>> # FAILING_DOCTEST
>>> # Trying to recreate the freeze seen in IBEIS
>>> # Extremely weird case: freezes only if dsize > (313, 313) AND __testwarp was called beforehand.
>>> # otherwise the parallel loop works fine. Could be an opencv 3.0.0-dev issue.
>>> import vtool as vt
>>> import utool as ut
>>> from ibeis.algo.preproc.preproc_chip import gen_chip
>>> import cv2
>>> from utool.util_parallel import __testwarp
>>> key_list = ['grace.jpg', 'easy1.png', 'ada2.jpg', 'easy3.png',
>>> 'hard3.png', 'zebra.png', 'patsy.jpg', 'ada.jpg',
>>> 'carl.jpg', 'lena.png', 'easy2.png']
>>> img_fpath_list = [ut.grab_test_imgpath(key) for key in key_list]
>>> arg_list1 = [(vt.imread(fpath),) for fpath in img_fpath_list[0:1]]
>>> arg_list2 = [(vt.imread(fpath),) for fpath in img_fpath_list]
>>> #new1 = [x for x in ut.generate2(__testwarp, arg_list1)]
>>> new1 = __testwarp(arg_list1[0])
>>> new2 = [y for y in ut.generate2(__testwarp, arg_list2, force_serial=False)]
>>> #print('new2 = %r' % (new2,))
#Example4:
# >>> # Freakin weird. When IBEIS Runs generate it doesn't close the processes
# >>> # UNSTABLE_DOCTEST
# >>> # python -m utool.util_parallel --test-generate:4
# >>> # Trying to see if we can recreate the problem where there are
# >>> # defunct python processes
# >>> import utool as ut
# >>> #num = 8700 # parallel is slower for smaller numbers
# >>> num = 70000 # parallel has an initial (~.1 second startup overhead)
# >>> print('TESTING PARALLEL')
# >>> flag_generator1 = list(ut.generate2(ut.is_prime, range(0, num)))
# >>> flag_generator1 = list(ut.generate2(ut.is_prime, range(0, num)))
# >>> import time
# >>> time.sleep(10)
"""
if verbose is None:
verbose = 2
if ntasks is None:
ntasks = nTasks
if ntasks is None:
try:
ntasks = len(args_gen)
except TypeError:
# Cast to a list
args_gen = list(args_gen)
ntasks = len(args_gen)
if ntasks == 1 or ntasks < __MIN_PARALLEL_TASKS__:
force_serial = True
if __FORCE_SERIAL__:
force_serial = __FORCE_SERIAL__
if ntasks == 0:
if verbose:
print('[ut.generate2] submitted 0 tasks')
raise StopIteration
if nprocs is None:
nprocs = min(ntasks, get_default_numprocs())
if nprocs == 1:
force_serial = True
if kw_gen is None:
kw_gen = [{}] * ntasks
if isinstance(kw_gen, dict):
# kw_gen can be a single dict applied to everything
kw_gen = [kw_gen] * ntasks
if force_serial:
for result in _generate_serial2(func, args_gen, kw_gen,
ntasks=ntasks, progkw=progkw,
verbose=verbose):
yield result
else:
if verbose:
gentype = 'mp' if use_pool else 'futures'
fmtstr = '[generate2] executing {} {} tasks using {} {} procs'
print(fmtstr.format(ntasks, get_funcname(func), nprocs, gentype))
if verbose > 1:
lbl = '(pargen) %s: ' % (get_funcname(func),)
progkw_ = dict(freq=None, bs=True, adjust=False, freq_est='absolute')
progkw_.update(progkw)
# print('progkw_.update = {!r}'.format(progkw_.update))
progpart = util_progress.ProgPartial(length=ntasks, lbl=lbl, **progkw_)
if use_pool:
# Use multiprocessing
if chunksize is None:
chunksize = max(min(4, ntasks), min(8, ntasks // (nprocs ** 2)))
try:
pool = multiprocessing.Pool(nprocs)
if ordered:
pmap_func = pool.imap
else:
pmap_func = pool.imap_unordered
wrapped_arg_gen = zip([func] * len(args_gen), args_gen, kw_gen)
res_gen = pmap_func(_kw_wrap_worker, wrapped_arg_gen,
chunksize)
if verbose > 1:
res_gen = progpart(res_gen)
for res in res_gen:
yield res
finally:
pool.close()
pool.join()
else:
# Use futures
executor = futures.ProcessPoolExecutor(nprocs)
try:
fs_list = [executor.submit(func, *a, **k)
for a, k in zip(args_gen, kw_gen)]
fs_gen = fs_list
if not ordered:
fs_gen = futures.as_completed(fs_gen)
if verbose > 1:
fs_gen = progpart(fs_gen)
for fs in fs_gen:
yield fs.result()
finally:
executor.shutdown(wait=True) | [
"def",
"generate2",
"(",
"func",
",",
"args_gen",
",",
"kw_gen",
"=",
"None",
",",
"ntasks",
"=",
"None",
",",
"ordered",
"=",
"True",
",",
"force_serial",
"=",
"False",
",",
"use_pool",
"=",
"False",
",",
"chunksize",
"=",
"None",
",",
"nprocs",
"=",
"None",
",",
"progkw",
"=",
"{",
"}",
",",
"nTasks",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"verbose",
"is",
"None",
":",
"verbose",
"=",
"2",
"if",
"ntasks",
"is",
"None",
":",
"ntasks",
"=",
"nTasks",
"if",
"ntasks",
"is",
"None",
":",
"try",
":",
"ntasks",
"=",
"len",
"(",
"args_gen",
")",
"except",
"TypeError",
":",
"# Cast to a list",
"args_gen",
"=",
"list",
"(",
"args_gen",
")",
"ntasks",
"=",
"len",
"(",
"args_gen",
")",
"if",
"ntasks",
"==",
"1",
"or",
"ntasks",
"<",
"__MIN_PARALLEL_TASKS__",
":",
"force_serial",
"=",
"True",
"if",
"__FORCE_SERIAL__",
":",
"force_serial",
"=",
"__FORCE_SERIAL__",
"if",
"ntasks",
"==",
"0",
":",
"if",
"verbose",
":",
"print",
"(",
"'[ut.generate2] submitted 0 tasks'",
")",
"raise",
"StopIteration",
"if",
"nprocs",
"is",
"None",
":",
"nprocs",
"=",
"min",
"(",
"ntasks",
",",
"get_default_numprocs",
"(",
")",
")",
"if",
"nprocs",
"==",
"1",
":",
"force_serial",
"=",
"True",
"if",
"kw_gen",
"is",
"None",
":",
"kw_gen",
"=",
"[",
"{",
"}",
"]",
"*",
"ntasks",
"if",
"isinstance",
"(",
"kw_gen",
",",
"dict",
")",
":",
"# kw_gen can be a single dict applied to everything",
"kw_gen",
"=",
"[",
"kw_gen",
"]",
"*",
"ntasks",
"if",
"force_serial",
":",
"for",
"result",
"in",
"_generate_serial2",
"(",
"func",
",",
"args_gen",
",",
"kw_gen",
",",
"ntasks",
"=",
"ntasks",
",",
"progkw",
"=",
"progkw",
",",
"verbose",
"=",
"verbose",
")",
":",
"yield",
"result",
"else",
":",
"if",
"verbose",
":",
"gentype",
"=",
"'mp'",
"if",
"use_pool",
"else",
"'futures'",
"fmtstr",
"=",
"'[generate2] executing {} {} tasks using {} {} procs'",
"print",
"(",
"fmtstr",
".",
"format",
"(",
"ntasks",
",",
"get_funcname",
"(",
"func",
")",
",",
"nprocs",
",",
"gentype",
")",
")",
"if",
"verbose",
">",
"1",
":",
"lbl",
"=",
"'(pargen) %s: '",
"%",
"(",
"get_funcname",
"(",
"func",
")",
",",
")",
"progkw_",
"=",
"dict",
"(",
"freq",
"=",
"None",
",",
"bs",
"=",
"True",
",",
"adjust",
"=",
"False",
",",
"freq_est",
"=",
"'absolute'",
")",
"progkw_",
".",
"update",
"(",
"progkw",
")",
"# print('progkw_.update = {!r}'.format(progkw_.update))",
"progpart",
"=",
"util_progress",
".",
"ProgPartial",
"(",
"length",
"=",
"ntasks",
",",
"lbl",
"=",
"lbl",
",",
"*",
"*",
"progkw_",
")",
"if",
"use_pool",
":",
"# Use multiprocessing",
"if",
"chunksize",
"is",
"None",
":",
"chunksize",
"=",
"max",
"(",
"min",
"(",
"4",
",",
"ntasks",
")",
",",
"min",
"(",
"8",
",",
"ntasks",
"//",
"(",
"nprocs",
"**",
"2",
")",
")",
")",
"try",
":",
"pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"nprocs",
")",
"if",
"ordered",
":",
"pmap_func",
"=",
"pool",
".",
"imap",
"else",
":",
"pmap_func",
"=",
"pool",
".",
"imap_unordered",
"wrapped_arg_gen",
"=",
"zip",
"(",
"[",
"func",
"]",
"*",
"len",
"(",
"args_gen",
")",
",",
"args_gen",
",",
"kw_gen",
")",
"res_gen",
"=",
"pmap_func",
"(",
"_kw_wrap_worker",
",",
"wrapped_arg_gen",
",",
"chunksize",
")",
"if",
"verbose",
">",
"1",
":",
"res_gen",
"=",
"progpart",
"(",
"res_gen",
")",
"for",
"res",
"in",
"res_gen",
":",
"yield",
"res",
"finally",
":",
"pool",
".",
"close",
"(",
")",
"pool",
".",
"join",
"(",
")",
"else",
":",
"# Use futures",
"executor",
"=",
"futures",
".",
"ProcessPoolExecutor",
"(",
"nprocs",
")",
"try",
":",
"fs_list",
"=",
"[",
"executor",
".",
"submit",
"(",
"func",
",",
"*",
"a",
",",
"*",
"*",
"k",
")",
"for",
"a",
",",
"k",
"in",
"zip",
"(",
"args_gen",
",",
"kw_gen",
")",
"]",
"fs_gen",
"=",
"fs_list",
"if",
"not",
"ordered",
":",
"fs_gen",
"=",
"futures",
".",
"as_completed",
"(",
"fs_gen",
")",
"if",
"verbose",
">",
"1",
":",
"fs_gen",
"=",
"progpart",
"(",
"fs_gen",
")",
"for",
"fs",
"in",
"fs_gen",
":",
"yield",
"fs",
".",
"result",
"(",
")",
"finally",
":",
"executor",
".",
"shutdown",
"(",
"wait",
"=",
"True",
")"
] | r"""
Interfaces to either multiprocessing or futures.
Esentially maps ``args_gen`` onto ``func`` using pool.imap.
However, args_gen must be a tuple of args that will be unpacked and send to
the function. Thus, the function can take multiple args. Also specifing
keyword args is supported.
Useful for embarrassingly parallel loops. Currently does not work with
opencv3
CommandLine:
python -m utool.util_parallel generate2
Args:
func (function): live python function
args_gen (?):
kw_gen (None): (default = None)
ntasks (None): (default = None)
ordered (bool): (default = True)
force_serial (bool): (default = False)
verbose (bool): verbosity flag(default = None)
CommandLine:
python -m utool.util_parallel generate2
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_parallel import * # NOQA
>>> from utool.util_parallel import _kw_wrap_worker # NOQA
>>> import utool as ut
>>> args_gen = list(zip(range(10000)))
>>> kw_gen = [{}] * len(args_gen)
>>> func = ut.is_prime
>>> _ = list(generate2(func, args_gen))
>>> _ = list(generate2(func, args_gen, ordered=False))
>>> _ = list(generate2(func, args_gen, force_serial=True))
>>> _ = list(generate2(func, args_gen, use_pool=True))
>>> _ = list(generate2(func, args_gen, ordered=False, verbose=False))
Example0:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> #num = 8700 # parallel is slower for smaller numbers
>>> num = 500 # parallel has an initial (~.1 second startup overhead)
>>> print('TESTING SERIAL')
>>> func = ut.is_prime
>>> args_list = list(range(0, num))
>>> flag_generator0 = ut.generate2(ut.is_prime, zip(range(0, num)), force_serial=True)
>>> flag_list0 = list(flag_generator0)
>>> print('TESTING PARALLEL')
>>> flag_generator1 = ut.generate2(ut.is_prime, zip(range(0, num)))
>>> flag_list1 = list(flag_generator1)
>>> print('ASSERTING')
>>> assert len(flag_list1) == num
>>> assert flag_list0 == flag_list1
Example1:
>>> # ENABLE_DOCTEST
>>> # Trying to recreate the freeze seen in IBEIS
>>> import utool as ut
>>> print('TESTING SERIAL')
>>> flag_generator0 = ut.generate2(ut.is_prime, zip(range(0, 1)))
>>> flag_list0 = list(flag_generator0)
>>> flag_generator1 = ut.generate2(ut.fibonacci_recursive, zip(range(0, 1)))
>>> flag_list1 = list(flag_generator1)
>>> print('TESTING PARALLEL')
>>> flag_generator2 = ut.generate2(ut.is_prime, zip(range(0, 12)))
>>> flag_list2 = list(flag_generator2)
>>> flag_generator3 = ut.generate2(ut.fibonacci_recursive, zip(range(0, 12)))
>>> flag_list3 = list(flag_generator3)
>>> print('flag_list0 = %r' % (flag_list0,))
>>> print('flag_list1 = %r' % (flag_list1,))
>>> print('flag_list2 = %r' % (flag_list1,))
>>> print('flag_list3 = %r' % (flag_list1,))
Example2:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> # Trying to recreate the freeze seen in IBEIS
>>> import vtool as vt
>>> #def gen_chip(tup):
>>> # import vtool as vt
>>> # cfpath, gfpath, bbox, theta, new_size, filter_list = tup
>>> # chipBGR = vt.compute_chip(gfpath, bbox, theta, new_size, filter_list)
>>> # height, width = chipBGR.shape[0:2]
>>> # vt.imwrite(cfpath, chipBGR)
>>> # return cfpath, width, height
>>> import utool as ut
>>> from ibeis.algo.preproc.preproc_chip import gen_chip
>>> #from ibeis.algo.preproc.preproc_feat import gen_feat_worker
>>> key_list = ['grace.jpg', 'easy1.png', 'ada2.jpg', 'easy3.png',
>>> 'hard3.png', 'zebra.png', 'patsy.jpg', 'ada.jpg',
>>> 'carl.jpg', 'lena.png', 'easy2.png']
>>> img_fpath_list = [ut.grab_test_imgpath(key) for key in key_list]
>>> arg_list1 = [(ut.augpath(img_fpath, '_testgen'), img_fpath, (0, 0, 100, 100), 0.0, (545, 372), []) for img_fpath in img_fpath_list[0:1]]
>>> arg_list2 = [(ut.augpath(img_fpath, '_testgen'), img_fpath, (0, 0, 100, 100), 0.0, (545, 372), []) for img_fpath in img_fpath_list]
>>> #arg_list3 = [(count, fpath, {}) for count, fpath in enumerate(ut.get_list_column(arg_list1, 0))]
>>> #arg_list4 = [(count, fpath, {}) for count, fpath in enumerate(ut.get_list_column(arg_list2, 0))]
>>> ut.remove_file_list(ut.get_list_column(arg_list2, 0))
>>> chips1 = [x for x in ut.generate2(gen_chip, arg_list1)]
>>> chips2 = [y for y in ut.generate2(gen_chip, arg_list2, force_serial=True)]
>>> #feats3 = [z for z in ut.generate2(gen_feat_worker, arg_list3)]
>>> #feats4 = [w for w in ut.generate2(gen_feat_worker, arg_list4)]
Example3:
>>> # DISABLE_DOCTEST
>>> # FAILING_DOCTEST
>>> # Trying to recreate the freeze seen in IBEIS
>>> # Extremely weird case: freezes only if dsize > (313, 313) AND __testwarp was called beforehand.
>>> # otherwise the parallel loop works fine. Could be an opencv 3.0.0-dev issue.
>>> import vtool as vt
>>> import utool as ut
>>> from ibeis.algo.preproc.preproc_chip import gen_chip
>>> import cv2
>>> from utool.util_parallel import __testwarp
>>> key_list = ['grace.jpg', 'easy1.png', 'ada2.jpg', 'easy3.png',
>>> 'hard3.png', 'zebra.png', 'patsy.jpg', 'ada.jpg',
>>> 'carl.jpg', 'lena.png', 'easy2.png']
>>> img_fpath_list = [ut.grab_test_imgpath(key) for key in key_list]
>>> arg_list1 = [(vt.imread(fpath),) for fpath in img_fpath_list[0:1]]
>>> arg_list2 = [(vt.imread(fpath),) for fpath in img_fpath_list]
>>> #new1 = [x for x in ut.generate2(__testwarp, arg_list1)]
>>> new1 = __testwarp(arg_list1[0])
>>> new2 = [y for y in ut.generate2(__testwarp, arg_list2, force_serial=False)]
>>> #print('new2 = %r' % (new2,))
#Example4:
# >>> # Freakin weird. When IBEIS Runs generate it doesn't close the processes
# >>> # UNSTABLE_DOCTEST
# >>> # python -m utool.util_parallel --test-generate:4
# >>> # Trying to see if we can recreate the problem where there are
# >>> # defunct python processes
# >>> import utool as ut
# >>> #num = 8700 # parallel is slower for smaller numbers
# >>> num = 70000 # parallel has an initial (~.1 second startup overhead)
# >>> print('TESTING PARALLEL')
# >>> flag_generator1 = list(ut.generate2(ut.is_prime, range(0, num)))
# >>> flag_generator1 = list(ut.generate2(ut.is_prime, range(0, num)))
# >>> import time
# >>> time.sleep(10) | [
"r",
"Interfaces",
"to",
"either",
"multiprocessing",
"or",
"futures",
".",
"Esentially",
"maps",
"args_gen",
"onto",
"func",
"using",
"pool",
".",
"imap",
".",
"However",
"args_gen",
"must",
"be",
"a",
"tuple",
"of",
"args",
"that",
"will",
"be",
"unpacked",
"and",
"send",
"to",
"the",
"function",
".",
"Thus",
"the",
"function",
"can",
"take",
"multiple",
"args",
".",
"Also",
"specifing",
"keyword",
"args",
"is",
"supported",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_parallel.py#L51-L279 | train |
Erotemic/utool | utool/util_parallel.py | _generate_serial2 | def _generate_serial2(func, args_gen, kw_gen=None, ntasks=None, progkw={},
verbose=None, nTasks=None):
""" internal serial generator """
if verbose is None:
verbose = 2
if ntasks is None:
ntasks = nTasks
if ntasks is None:
ntasks = len(args_gen)
if verbose > 0:
print('[ut._generate_serial2] executing %d %s tasks in serial' %
(ntasks, get_funcname(func)))
# kw_gen can be a single dict applied to everything
if kw_gen is None:
kw_gen = [{}] * ntasks
if isinstance(kw_gen, dict):
kw_gen = [kw_gen] * ntasks
# Get iterator with or without progress
if verbose > 1:
lbl = '(sergen) %s: ' % (get_funcname(func),)
progkw_ = dict(freq=None, bs=True, adjust=False, freq_est='between')
progkw_.update(progkw)
args_gen = util_progress.ProgIter(args_gen, length=ntasks, lbl=lbl,
**progkw_)
for args, kw in zip(args_gen, kw_gen):
result = func(*args, **kw)
yield result | python | def _generate_serial2(func, args_gen, kw_gen=None, ntasks=None, progkw={},
verbose=None, nTasks=None):
""" internal serial generator """
if verbose is None:
verbose = 2
if ntasks is None:
ntasks = nTasks
if ntasks is None:
ntasks = len(args_gen)
if verbose > 0:
print('[ut._generate_serial2] executing %d %s tasks in serial' %
(ntasks, get_funcname(func)))
# kw_gen can be a single dict applied to everything
if kw_gen is None:
kw_gen = [{}] * ntasks
if isinstance(kw_gen, dict):
kw_gen = [kw_gen] * ntasks
# Get iterator with or without progress
if verbose > 1:
lbl = '(sergen) %s: ' % (get_funcname(func),)
progkw_ = dict(freq=None, bs=True, adjust=False, freq_est='between')
progkw_.update(progkw)
args_gen = util_progress.ProgIter(args_gen, length=ntasks, lbl=lbl,
**progkw_)
for args, kw in zip(args_gen, kw_gen):
result = func(*args, **kw)
yield result | [
"def",
"_generate_serial2",
"(",
"func",
",",
"args_gen",
",",
"kw_gen",
"=",
"None",
",",
"ntasks",
"=",
"None",
",",
"progkw",
"=",
"{",
"}",
",",
"verbose",
"=",
"None",
",",
"nTasks",
"=",
"None",
")",
":",
"if",
"verbose",
"is",
"None",
":",
"verbose",
"=",
"2",
"if",
"ntasks",
"is",
"None",
":",
"ntasks",
"=",
"nTasks",
"if",
"ntasks",
"is",
"None",
":",
"ntasks",
"=",
"len",
"(",
"args_gen",
")",
"if",
"verbose",
">",
"0",
":",
"print",
"(",
"'[ut._generate_serial2] executing %d %s tasks in serial'",
"%",
"(",
"ntasks",
",",
"get_funcname",
"(",
"func",
")",
")",
")",
"# kw_gen can be a single dict applied to everything",
"if",
"kw_gen",
"is",
"None",
":",
"kw_gen",
"=",
"[",
"{",
"}",
"]",
"*",
"ntasks",
"if",
"isinstance",
"(",
"kw_gen",
",",
"dict",
")",
":",
"kw_gen",
"=",
"[",
"kw_gen",
"]",
"*",
"ntasks",
"# Get iterator with or without progress",
"if",
"verbose",
">",
"1",
":",
"lbl",
"=",
"'(sergen) %s: '",
"%",
"(",
"get_funcname",
"(",
"func",
")",
",",
")",
"progkw_",
"=",
"dict",
"(",
"freq",
"=",
"None",
",",
"bs",
"=",
"True",
",",
"adjust",
"=",
"False",
",",
"freq_est",
"=",
"'between'",
")",
"progkw_",
".",
"update",
"(",
"progkw",
")",
"args_gen",
"=",
"util_progress",
".",
"ProgIter",
"(",
"args_gen",
",",
"length",
"=",
"ntasks",
",",
"lbl",
"=",
"lbl",
",",
"*",
"*",
"progkw_",
")",
"for",
"args",
",",
"kw",
"in",
"zip",
"(",
"args_gen",
",",
"kw_gen",
")",
":",
"result",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"yield",
"result"
] | internal serial generator | [
"internal",
"serial",
"generator"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_parallel.py#L287-L316 | train |
Erotemic/utool | utool/util_parallel.py | buffered_generator | def buffered_generator(source_gen, buffer_size=2, use_multiprocessing=False):
r"""
Generator that runs a slow source generator in a separate process.
My generate function still seems faster on test cases.
However, this function is more flexible in its compatability.
Args:
source_gen (iterable): slow generator
buffer_size (int): the maximal number of items to pre-generate
(length of the buffer) (default = 2)
use_multiprocessing (bool): if False uses GIL-hindered threading
instead of multiprocessing (defualt = False).
Note:
use_multiprocessing = True seems to freeze if passed in a generator
built by six.moves.map.
References:
Taken from Sander Dieleman's data augmentation pipeline
https://github.com/benanne/kaggle-ndsb/blob/11a66cdbddee16c69514b9530a727df0ac6e136f/buffering.py
CommandLine:
python -m utool.util_parallel --test-buffered_generator:0
python -m utool.util_parallel --test-buffered_generator:1
Ignore:
>>> #functime = timeit.timeit(
>>> # 'ut.is_prime(' + str(prime) + ')', setup='import utool as ut',
>>> # number=500) / 1000.0
Example:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> from utool.util_parallel import * # NOQA
>>> import utool as ut
>>> num = 2 ** 14
>>> func = ut.is_prime
>>> data = [38873] * num
>>> data = list(range(num))
>>> with ut.Timer('serial') as t1:
... result1 = list(map(func, data))
>>> with ut.Timer('ut.generate2') as t3:
... result3 = list(ut.generate2(func, zip(data), chunksize=2, quiet=1, verbose=0))
>>> with ut.Timer('ut.buffered_generator') as t2:
... result2 = list(ut.buffered_generator(map(func, data)))
>>> assert len(result1) == num and len(result2) == num and len(result3) == num
>>> assert result3 == result2, 'inconsistent results'
>>> assert result1 == result2, 'inconsistent results'
Example1:
>>> # DISABLE_DOCTEST
>>> # VERYSLLOOWWW_DOCTEST
>>> from utool.util_parallel import _test_buffered_generator
>>> _test_buffered_generator2()
"""
if buffer_size < 2:
raise RuntimeError("Minimal buffer_ size is 2!")
if use_multiprocessing:
print('WARNING seems to freeze if passed in a generator')
#assert False, 'dont use this buffered multiprocessing'
if False:
pool = multiprocessing.Pool(processes=get_default_numprocs(),
initializer=init_worker,
maxtasksperchild=None)
Process = pool.Process
else:
Process = multiprocessing.Process
_Queue = multiprocessing.Queue
target = _buffered_generation_process
else:
_Queue = queue.Queue
Process = KillableThread
target = _buffered_generation_thread
# the effective buffer_ size is one less, because the generation process
# will generate one extra element and block until there is room in the
# buffer_.
buffer_ = _Queue(maxsize=buffer_size - 1)
# previously None was used as a sentinal, which fails when source_gen
# genrates None need to make object that it will not be generated by the
# process. A reasonable hack is to use the StopIteration exception instead
sentinal = StopIteration
process = Process(
target=target,
args=(iter(source_gen), buffer_, sentinal)
)
#if not use_multiprocessing:
process.daemon = True
process.start()
while True:
#output = buffer_.get(timeout=1.0)
output = buffer_.get()
if output is sentinal:
raise StopIteration
yield output | python | def buffered_generator(source_gen, buffer_size=2, use_multiprocessing=False):
r"""
Generator that runs a slow source generator in a separate process.
My generate function still seems faster on test cases.
However, this function is more flexible in its compatability.
Args:
source_gen (iterable): slow generator
buffer_size (int): the maximal number of items to pre-generate
(length of the buffer) (default = 2)
use_multiprocessing (bool): if False uses GIL-hindered threading
instead of multiprocessing (defualt = False).
Note:
use_multiprocessing = True seems to freeze if passed in a generator
built by six.moves.map.
References:
Taken from Sander Dieleman's data augmentation pipeline
https://github.com/benanne/kaggle-ndsb/blob/11a66cdbddee16c69514b9530a727df0ac6e136f/buffering.py
CommandLine:
python -m utool.util_parallel --test-buffered_generator:0
python -m utool.util_parallel --test-buffered_generator:1
Ignore:
>>> #functime = timeit.timeit(
>>> # 'ut.is_prime(' + str(prime) + ')', setup='import utool as ut',
>>> # number=500) / 1000.0
Example:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> from utool.util_parallel import * # NOQA
>>> import utool as ut
>>> num = 2 ** 14
>>> func = ut.is_prime
>>> data = [38873] * num
>>> data = list(range(num))
>>> with ut.Timer('serial') as t1:
... result1 = list(map(func, data))
>>> with ut.Timer('ut.generate2') as t3:
... result3 = list(ut.generate2(func, zip(data), chunksize=2, quiet=1, verbose=0))
>>> with ut.Timer('ut.buffered_generator') as t2:
... result2 = list(ut.buffered_generator(map(func, data)))
>>> assert len(result1) == num and len(result2) == num and len(result3) == num
>>> assert result3 == result2, 'inconsistent results'
>>> assert result1 == result2, 'inconsistent results'
Example1:
>>> # DISABLE_DOCTEST
>>> # VERYSLLOOWWW_DOCTEST
>>> from utool.util_parallel import _test_buffered_generator
>>> _test_buffered_generator2()
"""
if buffer_size < 2:
raise RuntimeError("Minimal buffer_ size is 2!")
if use_multiprocessing:
print('WARNING seems to freeze if passed in a generator')
#assert False, 'dont use this buffered multiprocessing'
if False:
pool = multiprocessing.Pool(processes=get_default_numprocs(),
initializer=init_worker,
maxtasksperchild=None)
Process = pool.Process
else:
Process = multiprocessing.Process
_Queue = multiprocessing.Queue
target = _buffered_generation_process
else:
_Queue = queue.Queue
Process = KillableThread
target = _buffered_generation_thread
# the effective buffer_ size is one less, because the generation process
# will generate one extra element and block until there is room in the
# buffer_.
buffer_ = _Queue(maxsize=buffer_size - 1)
# previously None was used as a sentinal, which fails when source_gen
# genrates None need to make object that it will not be generated by the
# process. A reasonable hack is to use the StopIteration exception instead
sentinal = StopIteration
process = Process(
target=target,
args=(iter(source_gen), buffer_, sentinal)
)
#if not use_multiprocessing:
process.daemon = True
process.start()
while True:
#output = buffer_.get(timeout=1.0)
output = buffer_.get()
if output is sentinal:
raise StopIteration
yield output | [
"def",
"buffered_generator",
"(",
"source_gen",
",",
"buffer_size",
"=",
"2",
",",
"use_multiprocessing",
"=",
"False",
")",
":",
"if",
"buffer_size",
"<",
"2",
":",
"raise",
"RuntimeError",
"(",
"\"Minimal buffer_ size is 2!\"",
")",
"if",
"use_multiprocessing",
":",
"print",
"(",
"'WARNING seems to freeze if passed in a generator'",
")",
"#assert False, 'dont use this buffered multiprocessing'",
"if",
"False",
":",
"pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"processes",
"=",
"get_default_numprocs",
"(",
")",
",",
"initializer",
"=",
"init_worker",
",",
"maxtasksperchild",
"=",
"None",
")",
"Process",
"=",
"pool",
".",
"Process",
"else",
":",
"Process",
"=",
"multiprocessing",
".",
"Process",
"_Queue",
"=",
"multiprocessing",
".",
"Queue",
"target",
"=",
"_buffered_generation_process",
"else",
":",
"_Queue",
"=",
"queue",
".",
"Queue",
"Process",
"=",
"KillableThread",
"target",
"=",
"_buffered_generation_thread",
"# the effective buffer_ size is one less, because the generation process",
"# will generate one extra element and block until there is room in the",
"# buffer_.",
"buffer_",
"=",
"_Queue",
"(",
"maxsize",
"=",
"buffer_size",
"-",
"1",
")",
"# previously None was used as a sentinal, which fails when source_gen",
"# genrates None need to make object that it will not be generated by the",
"# process. A reasonable hack is to use the StopIteration exception instead",
"sentinal",
"=",
"StopIteration",
"process",
"=",
"Process",
"(",
"target",
"=",
"target",
",",
"args",
"=",
"(",
"iter",
"(",
"source_gen",
")",
",",
"buffer_",
",",
"sentinal",
")",
")",
"#if not use_multiprocessing:",
"process",
".",
"daemon",
"=",
"True",
"process",
".",
"start",
"(",
")",
"while",
"True",
":",
"#output = buffer_.get(timeout=1.0)",
"output",
"=",
"buffer_",
".",
"get",
"(",
")",
"if",
"output",
"is",
"sentinal",
":",
"raise",
"StopIteration",
"yield",
"output"
] | r"""
Generator that runs a slow source generator in a separate process.
My generate function still seems faster on test cases.
However, this function is more flexible in its compatability.
Args:
source_gen (iterable): slow generator
buffer_size (int): the maximal number of items to pre-generate
(length of the buffer) (default = 2)
use_multiprocessing (bool): if False uses GIL-hindered threading
instead of multiprocessing (defualt = False).
Note:
use_multiprocessing = True seems to freeze if passed in a generator
built by six.moves.map.
References:
Taken from Sander Dieleman's data augmentation pipeline
https://github.com/benanne/kaggle-ndsb/blob/11a66cdbddee16c69514b9530a727df0ac6e136f/buffering.py
CommandLine:
python -m utool.util_parallel --test-buffered_generator:0
python -m utool.util_parallel --test-buffered_generator:1
Ignore:
>>> #functime = timeit.timeit(
>>> # 'ut.is_prime(' + str(prime) + ')', setup='import utool as ut',
>>> # number=500) / 1000.0
Example:
>>> # DISABLE_DOCTEST
>>> # UNSTABLE_DOCTEST
>>> from utool.util_parallel import * # NOQA
>>> import utool as ut
>>> num = 2 ** 14
>>> func = ut.is_prime
>>> data = [38873] * num
>>> data = list(range(num))
>>> with ut.Timer('serial') as t1:
... result1 = list(map(func, data))
>>> with ut.Timer('ut.generate2') as t3:
... result3 = list(ut.generate2(func, zip(data), chunksize=2, quiet=1, verbose=0))
>>> with ut.Timer('ut.buffered_generator') as t2:
... result2 = list(ut.buffered_generator(map(func, data)))
>>> assert len(result1) == num and len(result2) == num and len(result3) == num
>>> assert result3 == result2, 'inconsistent results'
>>> assert result1 == result2, 'inconsistent results'
Example1:
>>> # DISABLE_DOCTEST
>>> # VERYSLLOOWWW_DOCTEST
>>> from utool.util_parallel import _test_buffered_generator
>>> _test_buffered_generator2() | [
"r",
"Generator",
"that",
"runs",
"a",
"slow",
"source",
"generator",
"in",
"a",
"separate",
"process",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_parallel.py#L669-L769 | train |
Erotemic/utool | utool/util_ubuntu.py | XCtrl.sort_window_ids | def sort_window_ids(winid_list, order='mru'):
"""
Orders window ids by most recently used
"""
import utool as ut
winid_order = XCtrl.sorted_window_ids(order)
sorted_win_ids = ut.isect(winid_order, winid_list)
return sorted_win_ids | python | def sort_window_ids(winid_list, order='mru'):
"""
Orders window ids by most recently used
"""
import utool as ut
winid_order = XCtrl.sorted_window_ids(order)
sorted_win_ids = ut.isect(winid_order, winid_list)
return sorted_win_ids | [
"def",
"sort_window_ids",
"(",
"winid_list",
",",
"order",
"=",
"'mru'",
")",
":",
"import",
"utool",
"as",
"ut",
"winid_order",
"=",
"XCtrl",
".",
"sorted_window_ids",
"(",
"order",
")",
"sorted_win_ids",
"=",
"ut",
".",
"isect",
"(",
"winid_order",
",",
"winid_list",
")",
"return",
"sorted_win_ids"
] | Orders window ids by most recently used | [
"Orders",
"window",
"ids",
"by",
"most",
"recently",
"used"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_ubuntu.py#L384-L391 | train |
Erotemic/utool | utool/util_ubuntu.py | XCtrl.focus_window | def focus_window(winhandle, path=None, name=None, sleeptime=.01):
"""
sudo apt-get install xautomation
apt-get install autokey-gtk
wmctrl -xa gnome-terminal.Gnome-terminal
wmctrl -xl
"""
import utool as ut
import time
print('focus: ' + winhandle)
args = ['wmctrl', '-xa', winhandle]
ut.cmd(*args, verbose=False, quiet=True)
time.sleep(sleeptime) | python | def focus_window(winhandle, path=None, name=None, sleeptime=.01):
"""
sudo apt-get install xautomation
apt-get install autokey-gtk
wmctrl -xa gnome-terminal.Gnome-terminal
wmctrl -xl
"""
import utool as ut
import time
print('focus: ' + winhandle)
args = ['wmctrl', '-xa', winhandle]
ut.cmd(*args, verbose=False, quiet=True)
time.sleep(sleeptime) | [
"def",
"focus_window",
"(",
"winhandle",
",",
"path",
"=",
"None",
",",
"name",
"=",
"None",
",",
"sleeptime",
"=",
".01",
")",
":",
"import",
"utool",
"as",
"ut",
"import",
"time",
"print",
"(",
"'focus: '",
"+",
"winhandle",
")",
"args",
"=",
"[",
"'wmctrl'",
",",
"'-xa'",
",",
"winhandle",
"]",
"ut",
".",
"cmd",
"(",
"*",
"args",
",",
"verbose",
"=",
"False",
",",
"quiet",
"=",
"True",
")",
"time",
".",
"sleep",
"(",
"sleeptime",
")"
] | sudo apt-get install xautomation
apt-get install autokey-gtk
wmctrl -xa gnome-terminal.Gnome-terminal
wmctrl -xl | [
"sudo",
"apt",
"-",
"get",
"install",
"xautomation",
"apt",
"-",
"get",
"install",
"autokey",
"-",
"gtk"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_ubuntu.py#L668-L681 | train |
Erotemic/utool | utool/util_setup.py | setup_chmod | def setup_chmod(setup_fpath, setup_dir, chmod_patterns):
""" Gives files matching pattern the same chmod flags as setup.py """
#st_mode = os.stat(setup_fpath).st_mode
st_mode = 33277
for pattern in chmod_patterns:
for fpath in util_path.glob(setup_dir, pattern, recursive=True):
print('[setup] chmod fpath=%r' % fpath)
os.chmod(fpath, st_mode) | python | def setup_chmod(setup_fpath, setup_dir, chmod_patterns):
""" Gives files matching pattern the same chmod flags as setup.py """
#st_mode = os.stat(setup_fpath).st_mode
st_mode = 33277
for pattern in chmod_patterns:
for fpath in util_path.glob(setup_dir, pattern, recursive=True):
print('[setup] chmod fpath=%r' % fpath)
os.chmod(fpath, st_mode) | [
"def",
"setup_chmod",
"(",
"setup_fpath",
",",
"setup_dir",
",",
"chmod_patterns",
")",
":",
"#st_mode = os.stat(setup_fpath).st_mode",
"st_mode",
"=",
"33277",
"for",
"pattern",
"in",
"chmod_patterns",
":",
"for",
"fpath",
"in",
"util_path",
".",
"glob",
"(",
"setup_dir",
",",
"pattern",
",",
"recursive",
"=",
"True",
")",
":",
"print",
"(",
"'[setup] chmod fpath=%r'",
"%",
"fpath",
")",
"os",
".",
"chmod",
"(",
"fpath",
",",
"st_mode",
")"
] | Gives files matching pattern the same chmod flags as setup.py | [
"Gives",
"files",
"matching",
"pattern",
"the",
"same",
"chmod",
"flags",
"as",
"setup",
".",
"py"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_setup.py#L103-L110 | train |
Erotemic/utool | utool/util_setup.py | __infer_setup_kwargs | def __infer_setup_kwargs(module, kwargs):
""" Implicitly build kwargs based on standard info """
# Get project name from the module
#if 'name' not in kwargs:
# kwargs['name'] = module.__name__
#else:
# raise AssertionError('must specify module name!')
name = kwargs['name']
# Our projects depend on utool
#if kwargs['name'] != 'utool':
# install_requires = kwargs.get('install_requires', [])
# if 'utool' not in install_requires:
# install_requires.append('utool')
# kwargs['install_requires'] = install_requires
packages = kwargs.get('packages', [])
if name not in packages:
packages.append(name)
kwargs['packages'] = packages
if 'version' not in kwargs:
version = parse_package_for_version(name)
kwargs['version'] = version
# Parse version
#if 'version' not in kwargs:
# if module is None:
# version_errmsg = 'You must include a version (preferably one that matches the __version__ variable in your modules init file'
# raise AssertionError(version_errmsg)
# else:
# Parse license
if 'license' not in kwargs:
try:
kwargs['license'] = read_license('LICENSE')
except IOError:
pass
# Parse readme
if 'long_description' not in kwargs:
kwargs['long_description'] = parse_readme() | python | def __infer_setup_kwargs(module, kwargs):
""" Implicitly build kwargs based on standard info """
# Get project name from the module
#if 'name' not in kwargs:
# kwargs['name'] = module.__name__
#else:
# raise AssertionError('must specify module name!')
name = kwargs['name']
# Our projects depend on utool
#if kwargs['name'] != 'utool':
# install_requires = kwargs.get('install_requires', [])
# if 'utool' not in install_requires:
# install_requires.append('utool')
# kwargs['install_requires'] = install_requires
packages = kwargs.get('packages', [])
if name not in packages:
packages.append(name)
kwargs['packages'] = packages
if 'version' not in kwargs:
version = parse_package_for_version(name)
kwargs['version'] = version
# Parse version
#if 'version' not in kwargs:
# if module is None:
# version_errmsg = 'You must include a version (preferably one that matches the __version__ variable in your modules init file'
# raise AssertionError(version_errmsg)
# else:
# Parse license
if 'license' not in kwargs:
try:
kwargs['license'] = read_license('LICENSE')
except IOError:
pass
# Parse readme
if 'long_description' not in kwargs:
kwargs['long_description'] = parse_readme() | [
"def",
"__infer_setup_kwargs",
"(",
"module",
",",
"kwargs",
")",
":",
"# Get project name from the module",
"#if 'name' not in kwargs:",
"# kwargs['name'] = module.__name__",
"#else:",
"# raise AssertionError('must specify module name!')",
"name",
"=",
"kwargs",
"[",
"'name'",
"]",
"# Our projects depend on utool",
"#if kwargs['name'] != 'utool':",
"# install_requires = kwargs.get('install_requires', [])",
"# if 'utool' not in install_requires:",
"# install_requires.append('utool')",
"# kwargs['install_requires'] = install_requires",
"packages",
"=",
"kwargs",
".",
"get",
"(",
"'packages'",
",",
"[",
"]",
")",
"if",
"name",
"not",
"in",
"packages",
":",
"packages",
".",
"append",
"(",
"name",
")",
"kwargs",
"[",
"'packages'",
"]",
"=",
"packages",
"if",
"'version'",
"not",
"in",
"kwargs",
":",
"version",
"=",
"parse_package_for_version",
"(",
"name",
")",
"kwargs",
"[",
"'version'",
"]",
"=",
"version",
"# Parse version",
"#if 'version' not in kwargs:",
"# if module is None:",
"# version_errmsg = 'You must include a version (preferably one that matches the __version__ variable in your modules init file'",
"# raise AssertionError(version_errmsg)",
"# else:",
"# Parse license",
"if",
"'license'",
"not",
"in",
"kwargs",
":",
"try",
":",
"kwargs",
"[",
"'license'",
"]",
"=",
"read_license",
"(",
"'LICENSE'",
")",
"except",
"IOError",
":",
"pass",
"# Parse readme",
"if",
"'long_description'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'long_description'",
"]",
"=",
"parse_readme",
"(",
")"
] | Implicitly build kwargs based on standard info | [
"Implicitly",
"build",
"kwargs",
"based",
"on",
"standard",
"info"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_setup.py#L605-L643 | train |
Thermondo/django-heroku-connect | heroku_connect/admin.py | _replaced | def _replaced(__values, **__replacements):
"""
Replace elements in iterable with values from an alias dict, suppressing empty values.
Used to consistently enhance how certain fields are displayed in list and detail pages.
"""
return tuple(o for o in (__replacements.get(name, name) for name in __values) if o) | python | def _replaced(__values, **__replacements):
"""
Replace elements in iterable with values from an alias dict, suppressing empty values.
Used to consistently enhance how certain fields are displayed in list and detail pages.
"""
return tuple(o for o in (__replacements.get(name, name) for name in __values) if o) | [
"def",
"_replaced",
"(",
"__values",
",",
"*",
"*",
"__replacements",
")",
":",
"return",
"tuple",
"(",
"o",
"for",
"o",
"in",
"(",
"__replacements",
".",
"get",
"(",
"name",
",",
"name",
")",
"for",
"name",
"in",
"__values",
")",
"if",
"o",
")"
] | Replace elements in iterable with values from an alias dict, suppressing empty values.
Used to consistently enhance how certain fields are displayed in list and detail pages. | [
"Replace",
"elements",
"in",
"iterable",
"with",
"values",
"from",
"an",
"alias",
"dict",
"suppressing",
"empty",
"values",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/admin.py#L14-L20 | train |
Thermondo/django-heroku-connect | heroku_connect/admin.py | _get_admin_route_name | def _get_admin_route_name(model_or_instance):
"""
Get the base name of the admin route for a model or model instance.
For use with :func:`django.urls.reverse`, although it still needs the specific route suffix
appended, for example ``_changelist``.
"""
model = model_or_instance if isinstance(model_or_instance, type) else type(model_or_instance)
return 'admin:{meta.app_label}_{meta.model_name}'.format(meta=model._meta) | python | def _get_admin_route_name(model_or_instance):
"""
Get the base name of the admin route for a model or model instance.
For use with :func:`django.urls.reverse`, although it still needs the specific route suffix
appended, for example ``_changelist``.
"""
model = model_or_instance if isinstance(model_or_instance, type) else type(model_or_instance)
return 'admin:{meta.app_label}_{meta.model_name}'.format(meta=model._meta) | [
"def",
"_get_admin_route_name",
"(",
"model_or_instance",
")",
":",
"model",
"=",
"model_or_instance",
"if",
"isinstance",
"(",
"model_or_instance",
",",
"type",
")",
"else",
"type",
"(",
"model_or_instance",
")",
"return",
"'admin:{meta.app_label}_{meta.model_name}'",
".",
"format",
"(",
"meta",
"=",
"model",
".",
"_meta",
")"
] | Get the base name of the admin route for a model or model instance.
For use with :func:`django.urls.reverse`, although it still needs the specific route suffix
appended, for example ``_changelist``. | [
"Get",
"the",
"base",
"name",
"of",
"the",
"admin",
"route",
"for",
"a",
"model",
"or",
"model",
"instance",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/admin.py#L23-L31 | train |
Thermondo/django-heroku-connect | heroku_connect/admin.py | _build_admin_filter_url | def _build_admin_filter_url(model, filters):
"""Build a filter URL to an admin changelist of all objects with similar field values."""
url = reverse(_get_admin_route_name(model) + '_changelist')
parts = urlsplit(url)
query = parse_qs(parts.query)
query.update(filters)
parts_with_filter = parts._replace(query=urlencode(query))
return urlunsplit(parts_with_filter) | python | def _build_admin_filter_url(model, filters):
"""Build a filter URL to an admin changelist of all objects with similar field values."""
url = reverse(_get_admin_route_name(model) + '_changelist')
parts = urlsplit(url)
query = parse_qs(parts.query)
query.update(filters)
parts_with_filter = parts._replace(query=urlencode(query))
return urlunsplit(parts_with_filter) | [
"def",
"_build_admin_filter_url",
"(",
"model",
",",
"filters",
")",
":",
"url",
"=",
"reverse",
"(",
"_get_admin_route_name",
"(",
"model",
")",
"+",
"'_changelist'",
")",
"parts",
"=",
"urlsplit",
"(",
"url",
")",
"query",
"=",
"parse_qs",
"(",
"parts",
".",
"query",
")",
"query",
".",
"update",
"(",
"filters",
")",
"parts_with_filter",
"=",
"parts",
".",
"_replace",
"(",
"query",
"=",
"urlencode",
"(",
"query",
")",
")",
"return",
"urlunsplit",
"(",
"parts_with_filter",
")"
] | Build a filter URL to an admin changelist of all objects with similar field values. | [
"Build",
"a",
"filter",
"URL",
"to",
"an",
"admin",
"changelist",
"of",
"all",
"objects",
"with",
"similar",
"field",
"values",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/admin.py#L34-L41 | train |
Thermondo/django-heroku-connect | heroku_connect/admin.py | _make_admin_link_to_similar | def _make_admin_link_to_similar(primary_field, *fields, name=None):
"""Create a function that links to a changelist of all objects with similar field values."""
fields = (primary_field,) + fields
url_template = '<a href="{url}">{name_or_value}</a>'
def field_link(self, obj):
value = getattr(obj, primary_field, None)
name_or_value = name or value
filters = {field_name: getattr(obj, field_name) for field_name in fields}
url = _build_admin_filter_url(obj, filters)
return format_html(url_template, **locals()) if url else value
field_link.allow_tags = True
field_link.short_description = primary_field.replace('_', ' ').capitalize()
field_link.admin_order_field = primary_field
field_link.__name__ = field_link.__name__.replace('field', primary_field)
return field_link | python | def _make_admin_link_to_similar(primary_field, *fields, name=None):
"""Create a function that links to a changelist of all objects with similar field values."""
fields = (primary_field,) + fields
url_template = '<a href="{url}">{name_or_value}</a>'
def field_link(self, obj):
value = getattr(obj, primary_field, None)
name_or_value = name or value
filters = {field_name: getattr(obj, field_name) for field_name in fields}
url = _build_admin_filter_url(obj, filters)
return format_html(url_template, **locals()) if url else value
field_link.allow_tags = True
field_link.short_description = primary_field.replace('_', ' ').capitalize()
field_link.admin_order_field = primary_field
field_link.__name__ = field_link.__name__.replace('field', primary_field)
return field_link | [
"def",
"_make_admin_link_to_similar",
"(",
"primary_field",
",",
"*",
"fields",
",",
"name",
"=",
"None",
")",
":",
"fields",
"=",
"(",
"primary_field",
",",
")",
"+",
"fields",
"url_template",
"=",
"'<a href=\"{url}\">{name_or_value}</a>'",
"def",
"field_link",
"(",
"self",
",",
"obj",
")",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
"primary_field",
",",
"None",
")",
"name_or_value",
"=",
"name",
"or",
"value",
"filters",
"=",
"{",
"field_name",
":",
"getattr",
"(",
"obj",
",",
"field_name",
")",
"for",
"field_name",
"in",
"fields",
"}",
"url",
"=",
"_build_admin_filter_url",
"(",
"obj",
",",
"filters",
")",
"return",
"format_html",
"(",
"url_template",
",",
"*",
"*",
"locals",
"(",
")",
")",
"if",
"url",
"else",
"value",
"field_link",
".",
"allow_tags",
"=",
"True",
"field_link",
".",
"short_description",
"=",
"primary_field",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
".",
"capitalize",
"(",
")",
"field_link",
".",
"admin_order_field",
"=",
"primary_field",
"field_link",
".",
"__name__",
"=",
"field_link",
".",
"__name__",
".",
"replace",
"(",
"'field'",
",",
"primary_field",
")",
"return",
"field_link"
] | Create a function that links to a changelist of all objects with similar field values. | [
"Create",
"a",
"function",
"that",
"links",
"to",
"a",
"changelist",
"of",
"all",
"objects",
"with",
"similar",
"field",
"values",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/admin.py#L44-L60 | train |
Thermondo/django-heroku-connect | heroku_connect/admin.py | _retry_failed_log | def _retry_failed_log(failed_trigger_log):
"""
Try to re-apply a failed trigger log action.
Makes sure the argument trigger log is in a FAILED state and acquires a row lock on it.
Returns:
True if the operation succeeded
"""
model = type(failed_trigger_log)
try:
failed_trigger_log = (
model.objects
.select_for_update()
.get(
id=failed_trigger_log.id,
state=TRIGGER_LOG_STATE['FAILED'],
)
)
except model.DoesNotExist:
return False
failed_trigger_log.redo()
return True | python | def _retry_failed_log(failed_trigger_log):
"""
Try to re-apply a failed trigger log action.
Makes sure the argument trigger log is in a FAILED state and acquires a row lock on it.
Returns:
True if the operation succeeded
"""
model = type(failed_trigger_log)
try:
failed_trigger_log = (
model.objects
.select_for_update()
.get(
id=failed_trigger_log.id,
state=TRIGGER_LOG_STATE['FAILED'],
)
)
except model.DoesNotExist:
return False
failed_trigger_log.redo()
return True | [
"def",
"_retry_failed_log",
"(",
"failed_trigger_log",
")",
":",
"model",
"=",
"type",
"(",
"failed_trigger_log",
")",
"try",
":",
"failed_trigger_log",
"=",
"(",
"model",
".",
"objects",
".",
"select_for_update",
"(",
")",
".",
"get",
"(",
"id",
"=",
"failed_trigger_log",
".",
"id",
",",
"state",
"=",
"TRIGGER_LOG_STATE",
"[",
"'FAILED'",
"]",
",",
")",
")",
"except",
"model",
".",
"DoesNotExist",
":",
"return",
"False",
"failed_trigger_log",
".",
"redo",
"(",
")",
"return",
"True"
] | Try to re-apply a failed trigger log action.
Makes sure the argument trigger log is in a FAILED state and acquires a row lock on it.
Returns:
True if the operation succeeded | [
"Try",
"to",
"re",
"-",
"apply",
"a",
"failed",
"trigger",
"log",
"action",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/admin.py#L69-L92 | train |
Thermondo/django-heroku-connect | heroku_connect/admin.py | TriggerLogAdmin.ignore_failed_logs_action | def ignore_failed_logs_action(self, request, queryset):
"""Set FAILED trigger logs in queryset to IGNORED."""
count = _ignore_failed_logs(queryset)
self.message_user(
request,
_('{count} failed trigger logs marked as ignored.').format(count=count),
) | python | def ignore_failed_logs_action(self, request, queryset):
"""Set FAILED trigger logs in queryset to IGNORED."""
count = _ignore_failed_logs(queryset)
self.message_user(
request,
_('{count} failed trigger logs marked as ignored.').format(count=count),
) | [
"def",
"ignore_failed_logs_action",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"count",
"=",
"_ignore_failed_logs",
"(",
"queryset",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"_",
"(",
"'{count} failed trigger logs marked as ignored.'",
")",
".",
"format",
"(",
"count",
"=",
"count",
")",
",",
")"
] | Set FAILED trigger logs in queryset to IGNORED. | [
"Set",
"FAILED",
"trigger",
"logs",
"in",
"queryset",
"to",
"IGNORED",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/admin.py#L156-L162 | train |
Thermondo/django-heroku-connect | heroku_connect/admin.py | TriggerLogAdmin.retry_failed_logs_action | def retry_failed_logs_action(self, request, queryset):
"""Try to re-apply FAILED trigger log actions in the queryset."""
count = 0
for trigger_log in queryset:
retried = _retry_failed_log(trigger_log)
if retried:
count += 1
self.message_user(
request,
_('{count} failed trigger logs retried.').format(count=count),
) | python | def retry_failed_logs_action(self, request, queryset):
"""Try to re-apply FAILED trigger log actions in the queryset."""
count = 0
for trigger_log in queryset:
retried = _retry_failed_log(trigger_log)
if retried:
count += 1
self.message_user(
request,
_('{count} failed trigger logs retried.').format(count=count),
) | [
"def",
"retry_failed_logs_action",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"count",
"=",
"0",
"for",
"trigger_log",
"in",
"queryset",
":",
"retried",
"=",
"_retry_failed_log",
"(",
"trigger_log",
")",
"if",
"retried",
":",
"count",
"+=",
"1",
"self",
".",
"message_user",
"(",
"request",
",",
"_",
"(",
"'{count} failed trigger logs retried.'",
")",
".",
"format",
"(",
"count",
"=",
"count",
")",
",",
")"
] | Try to re-apply FAILED trigger log actions in the queryset. | [
"Try",
"to",
"re",
"-",
"apply",
"FAILED",
"trigger",
"log",
"actions",
"in",
"the",
"queryset",
"."
] | f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5 | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/admin.py#L165-L175 | train |
glormph/msstitch | src/app/actions/mslookup/psms.py | create_psm_lookup | def create_psm_lookup(fn, fastafn, mapfn, header, pgdb, unroll=False,
specfncol=None, decoy=False,
fastadelim=None, genefield=None):
"""Reads PSMs from file, stores them to a database backend in chunked PSMs.
"""
proteins = store_proteins_descriptions(pgdb, fastafn, fn, mapfn, header,
decoy, fastadelim, genefield)
mzmlmap = pgdb.get_mzmlfile_map()
sequences = {}
for psm in tsvreader.generate_tsv_psms(fn, header):
seq = tsvreader.get_psm_sequence(psm, unroll)
sequences[seq] = 1
pgdb.store_pepseqs(((seq,) for seq in sequences))
pepseqmap = pgdb.get_peptide_seq_map()
psms = []
for row, psm in enumerate(tsvreader.generate_tsv_psms(fn, header)):
specfn, psm_id, scan, seq, score = tsvreader.get_psm(psm, unroll,
specfncol)
if len(psms) % DB_STORE_CHUNK == 0:
pgdb.store_psms(psms)
psms = []
psms.append({'rownr': row,
'psm_id': psm_id,
'seq': pepseqmap[seq],
'score': score,
'specfn': mzmlmap[specfn],
'scannr': scan,
'spec_id': '{}_{}'.format(mzmlmap[specfn], scan),
})
pgdb.store_psms(psms)
pgdb.index_psms()
store_psm_protein_relations(fn, header, pgdb, proteins) | python | def create_psm_lookup(fn, fastafn, mapfn, header, pgdb, unroll=False,
specfncol=None, decoy=False,
fastadelim=None, genefield=None):
"""Reads PSMs from file, stores them to a database backend in chunked PSMs.
"""
proteins = store_proteins_descriptions(pgdb, fastafn, fn, mapfn, header,
decoy, fastadelim, genefield)
mzmlmap = pgdb.get_mzmlfile_map()
sequences = {}
for psm in tsvreader.generate_tsv_psms(fn, header):
seq = tsvreader.get_psm_sequence(psm, unroll)
sequences[seq] = 1
pgdb.store_pepseqs(((seq,) for seq in sequences))
pepseqmap = pgdb.get_peptide_seq_map()
psms = []
for row, psm in enumerate(tsvreader.generate_tsv_psms(fn, header)):
specfn, psm_id, scan, seq, score = tsvreader.get_psm(psm, unroll,
specfncol)
if len(psms) % DB_STORE_CHUNK == 0:
pgdb.store_psms(psms)
psms = []
psms.append({'rownr': row,
'psm_id': psm_id,
'seq': pepseqmap[seq],
'score': score,
'specfn': mzmlmap[specfn],
'scannr': scan,
'spec_id': '{}_{}'.format(mzmlmap[specfn], scan),
})
pgdb.store_psms(psms)
pgdb.index_psms()
store_psm_protein_relations(fn, header, pgdb, proteins) | [
"def",
"create_psm_lookup",
"(",
"fn",
",",
"fastafn",
",",
"mapfn",
",",
"header",
",",
"pgdb",
",",
"unroll",
"=",
"False",
",",
"specfncol",
"=",
"None",
",",
"decoy",
"=",
"False",
",",
"fastadelim",
"=",
"None",
",",
"genefield",
"=",
"None",
")",
":",
"proteins",
"=",
"store_proteins_descriptions",
"(",
"pgdb",
",",
"fastafn",
",",
"fn",
",",
"mapfn",
",",
"header",
",",
"decoy",
",",
"fastadelim",
",",
"genefield",
")",
"mzmlmap",
"=",
"pgdb",
".",
"get_mzmlfile_map",
"(",
")",
"sequences",
"=",
"{",
"}",
"for",
"psm",
"in",
"tsvreader",
".",
"generate_tsv_psms",
"(",
"fn",
",",
"header",
")",
":",
"seq",
"=",
"tsvreader",
".",
"get_psm_sequence",
"(",
"psm",
",",
"unroll",
")",
"sequences",
"[",
"seq",
"]",
"=",
"1",
"pgdb",
".",
"store_pepseqs",
"(",
"(",
"(",
"seq",
",",
")",
"for",
"seq",
"in",
"sequences",
")",
")",
"pepseqmap",
"=",
"pgdb",
".",
"get_peptide_seq_map",
"(",
")",
"psms",
"=",
"[",
"]",
"for",
"row",
",",
"psm",
"in",
"enumerate",
"(",
"tsvreader",
".",
"generate_tsv_psms",
"(",
"fn",
",",
"header",
")",
")",
":",
"specfn",
",",
"psm_id",
",",
"scan",
",",
"seq",
",",
"score",
"=",
"tsvreader",
".",
"get_psm",
"(",
"psm",
",",
"unroll",
",",
"specfncol",
")",
"if",
"len",
"(",
"psms",
")",
"%",
"DB_STORE_CHUNK",
"==",
"0",
":",
"pgdb",
".",
"store_psms",
"(",
"psms",
")",
"psms",
"=",
"[",
"]",
"psms",
".",
"append",
"(",
"{",
"'rownr'",
":",
"row",
",",
"'psm_id'",
":",
"psm_id",
",",
"'seq'",
":",
"pepseqmap",
"[",
"seq",
"]",
",",
"'score'",
":",
"score",
",",
"'specfn'",
":",
"mzmlmap",
"[",
"specfn",
"]",
",",
"'scannr'",
":",
"scan",
",",
"'spec_id'",
":",
"'{}_{}'",
".",
"format",
"(",
"mzmlmap",
"[",
"specfn",
"]",
",",
"scan",
")",
",",
"}",
")",
"pgdb",
".",
"store_psms",
"(",
"psms",
")",
"pgdb",
".",
"index_psms",
"(",
")",
"store_psm_protein_relations",
"(",
"fn",
",",
"header",
",",
"pgdb",
",",
"proteins",
")"
] | Reads PSMs from file, stores them to a database backend in chunked PSMs. | [
"Reads",
"PSMs",
"from",
"file",
"stores",
"them",
"to",
"a",
"database",
"backend",
"in",
"chunked",
"PSMs",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mslookup/psms.py#L9-L40 | train |
glormph/msstitch | src/app/actions/mslookup/psms.py | store_psm_protein_relations | def store_psm_protein_relations(fn, header, pgdb, proteins):
"""Reads PSMs from file, extracts their proteins and peptides and passes
them to a database backend in chunks.
"""
# TODO do we need an OrderedDict or is regular dict enough?
# Sorting for psm_id useful?
allpsms = OrderedDict()
last_id, psmids_to_store = None, set()
store_soon = False
for psm in tsvreader.generate_tsv_psms(fn, header):
psm_id, prots = tsvreader.get_pepproteins(psm)
prots = [x for x in prots if x in proteins]
try:
# In case the PSMs are presented unrolled
allpsms[psm_id].extend(prots)
except KeyError:
allpsms[psm_id] = prots
if len(psmids_to_store) % DB_STORE_CHUNK == 0:
store_soon = True
if store_soon and last_id != psm_id:
pgdb.store_peptides_proteins(allpsms, psmids_to_store)
store_soon = False
psmids_to_store = set()
psmids_to_store.add(psm_id)
last_id = psm_id
if len(psmids_to_store) > 0:
pgdb.store_peptides_proteins(allpsms, psmids_to_store)
pgdb.index_protein_peptides()
return allpsms | python | def store_psm_protein_relations(fn, header, pgdb, proteins):
"""Reads PSMs from file, extracts their proteins and peptides and passes
them to a database backend in chunks.
"""
# TODO do we need an OrderedDict or is regular dict enough?
# Sorting for psm_id useful?
allpsms = OrderedDict()
last_id, psmids_to_store = None, set()
store_soon = False
for psm in tsvreader.generate_tsv_psms(fn, header):
psm_id, prots = tsvreader.get_pepproteins(psm)
prots = [x for x in prots if x in proteins]
try:
# In case the PSMs are presented unrolled
allpsms[psm_id].extend(prots)
except KeyError:
allpsms[psm_id] = prots
if len(psmids_to_store) % DB_STORE_CHUNK == 0:
store_soon = True
if store_soon and last_id != psm_id:
pgdb.store_peptides_proteins(allpsms, psmids_to_store)
store_soon = False
psmids_to_store = set()
psmids_to_store.add(psm_id)
last_id = psm_id
if len(psmids_to_store) > 0:
pgdb.store_peptides_proteins(allpsms, psmids_to_store)
pgdb.index_protein_peptides()
return allpsms | [
"def",
"store_psm_protein_relations",
"(",
"fn",
",",
"header",
",",
"pgdb",
",",
"proteins",
")",
":",
"# TODO do we need an OrderedDict or is regular dict enough?",
"# Sorting for psm_id useful?",
"allpsms",
"=",
"OrderedDict",
"(",
")",
"last_id",
",",
"psmids_to_store",
"=",
"None",
",",
"set",
"(",
")",
"store_soon",
"=",
"False",
"for",
"psm",
"in",
"tsvreader",
".",
"generate_tsv_psms",
"(",
"fn",
",",
"header",
")",
":",
"psm_id",
",",
"prots",
"=",
"tsvreader",
".",
"get_pepproteins",
"(",
"psm",
")",
"prots",
"=",
"[",
"x",
"for",
"x",
"in",
"prots",
"if",
"x",
"in",
"proteins",
"]",
"try",
":",
"# In case the PSMs are presented unrolled",
"allpsms",
"[",
"psm_id",
"]",
".",
"extend",
"(",
"prots",
")",
"except",
"KeyError",
":",
"allpsms",
"[",
"psm_id",
"]",
"=",
"prots",
"if",
"len",
"(",
"psmids_to_store",
")",
"%",
"DB_STORE_CHUNK",
"==",
"0",
":",
"store_soon",
"=",
"True",
"if",
"store_soon",
"and",
"last_id",
"!=",
"psm_id",
":",
"pgdb",
".",
"store_peptides_proteins",
"(",
"allpsms",
",",
"psmids_to_store",
")",
"store_soon",
"=",
"False",
"psmids_to_store",
"=",
"set",
"(",
")",
"psmids_to_store",
".",
"add",
"(",
"psm_id",
")",
"last_id",
"=",
"psm_id",
"if",
"len",
"(",
"psmids_to_store",
")",
">",
"0",
":",
"pgdb",
".",
"store_peptides_proteins",
"(",
"allpsms",
",",
"psmids_to_store",
")",
"pgdb",
".",
"index_protein_peptides",
"(",
")",
"return",
"allpsms"
] | Reads PSMs from file, extracts their proteins and peptides and passes
them to a database backend in chunks. | [
"Reads",
"PSMs",
"from",
"file",
"extracts",
"their",
"proteins",
"and",
"peptides",
"and",
"passes",
"them",
"to",
"a",
"database",
"backend",
"in",
"chunks",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mslookup/psms.py#L92-L120 | train |
Erotemic/utool | utool/util_decor.py | on_exception_report_input | def on_exception_report_input(func_=None, force=False, keys=None):
"""
If an error is thrown in the scope of this function's stack frame then the
decorated function name and the arguments passed to it will be printed to
the utool print function.
"""
def _closure_onexceptreport(func):
if not ONEX_REPORT_INPUT and not force:
return func
@ignores_exc_tb(outer_wrapper=False)
#@wraps(func)
def wrp_onexceptreport(*args, **kwargs):
try:
#import utool
#if utool.DEBUG:
# print('[IN EXCPRPT] args=%r' % (args,))
# print('[IN EXCPRPT] kwargs=%r' % (kwargs,))
return func(*args, **kwargs)
except Exception as ex:
from utool import util_str
print('ERROR occured! Reporting input to function')
if keys is not None:
from utool import util_inspect
from utool import util_list
from utool import util_dict
argspec = util_inspect.get_func_argspec(func)
in_kwargs_flags = [key in kwargs for key in keys]
kwarg_keys = util_list.compress(keys, in_kwargs_flags)
kwarg_vals = [kwargs.get(key) for key in kwarg_keys]
flags = util_list.not_list(in_kwargs_flags)
arg_keys = util_list.compress(keys, flags)
arg_idxs = [argspec.args.index(key) for key in arg_keys]
num_nodefault = len(argspec.args) - len(argspec.defaults)
default_vals = (([None] * (num_nodefault)) +
list(argspec.defaults))
args_ = list(args) + default_vals[len(args) + 1:]
arg_vals = util_list.take(args_, arg_idxs)
requested_dict = dict(util_list.flatten(
[zip(kwarg_keys, kwarg_vals), zip(arg_keys, arg_vals)]))
print('input dict = ' + util_str.repr4(
util_dict.dict_subset(requested_dict, keys)))
# (print out specific keys only)
pass
arg_strs = ', '.join([repr(util_str.truncate_str(str(arg)))
for arg in args])
kwarg_strs = ', '.join([
util_str.truncate_str('%s=%r' % (key, val))
for key, val in six.iteritems(kwargs)])
msg = ('\nERROR: funcname=%r,\n * args=%s,\n * kwargs=%r\n' % (
meta_util_six.get_funcname(func), arg_strs, kwarg_strs))
msg += ' * len(args) = %r\n' % len(args)
msg += ' * len(kwargs) = %r\n' % len(kwargs)
util_dbg.printex(ex, msg, pad_stdout=True)
raise
wrp_onexceptreport = preserve_sig(wrp_onexceptreport, func)
return wrp_onexceptreport
if func_ is None:
return _closure_onexceptreport
else:
return _closure_onexceptreport(func_) | python | def on_exception_report_input(func_=None, force=False, keys=None):
"""
If an error is thrown in the scope of this function's stack frame then the
decorated function name and the arguments passed to it will be printed to
the utool print function.
"""
def _closure_onexceptreport(func):
if not ONEX_REPORT_INPUT and not force:
return func
@ignores_exc_tb(outer_wrapper=False)
#@wraps(func)
def wrp_onexceptreport(*args, **kwargs):
try:
#import utool
#if utool.DEBUG:
# print('[IN EXCPRPT] args=%r' % (args,))
# print('[IN EXCPRPT] kwargs=%r' % (kwargs,))
return func(*args, **kwargs)
except Exception as ex:
from utool import util_str
print('ERROR occured! Reporting input to function')
if keys is not None:
from utool import util_inspect
from utool import util_list
from utool import util_dict
argspec = util_inspect.get_func_argspec(func)
in_kwargs_flags = [key in kwargs for key in keys]
kwarg_keys = util_list.compress(keys, in_kwargs_flags)
kwarg_vals = [kwargs.get(key) for key in kwarg_keys]
flags = util_list.not_list(in_kwargs_flags)
arg_keys = util_list.compress(keys, flags)
arg_idxs = [argspec.args.index(key) for key in arg_keys]
num_nodefault = len(argspec.args) - len(argspec.defaults)
default_vals = (([None] * (num_nodefault)) +
list(argspec.defaults))
args_ = list(args) + default_vals[len(args) + 1:]
arg_vals = util_list.take(args_, arg_idxs)
requested_dict = dict(util_list.flatten(
[zip(kwarg_keys, kwarg_vals), zip(arg_keys, arg_vals)]))
print('input dict = ' + util_str.repr4(
util_dict.dict_subset(requested_dict, keys)))
# (print out specific keys only)
pass
arg_strs = ', '.join([repr(util_str.truncate_str(str(arg)))
for arg in args])
kwarg_strs = ', '.join([
util_str.truncate_str('%s=%r' % (key, val))
for key, val in six.iteritems(kwargs)])
msg = ('\nERROR: funcname=%r,\n * args=%s,\n * kwargs=%r\n' % (
meta_util_six.get_funcname(func), arg_strs, kwarg_strs))
msg += ' * len(args) = %r\n' % len(args)
msg += ' * len(kwargs) = %r\n' % len(kwargs)
util_dbg.printex(ex, msg, pad_stdout=True)
raise
wrp_onexceptreport = preserve_sig(wrp_onexceptreport, func)
return wrp_onexceptreport
if func_ is None:
return _closure_onexceptreport
else:
return _closure_onexceptreport(func_) | [
"def",
"on_exception_report_input",
"(",
"func_",
"=",
"None",
",",
"force",
"=",
"False",
",",
"keys",
"=",
"None",
")",
":",
"def",
"_closure_onexceptreport",
"(",
"func",
")",
":",
"if",
"not",
"ONEX_REPORT_INPUT",
"and",
"not",
"force",
":",
"return",
"func",
"@",
"ignores_exc_tb",
"(",
"outer_wrapper",
"=",
"False",
")",
"#@wraps(func)",
"def",
"wrp_onexceptreport",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"#import utool",
"#if utool.DEBUG:",
"# print('[IN EXCPRPT] args=%r' % (args,))",
"# print('[IN EXCPRPT] kwargs=%r' % (kwargs,))",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"ex",
":",
"from",
"utool",
"import",
"util_str",
"print",
"(",
"'ERROR occured! Reporting input to function'",
")",
"if",
"keys",
"is",
"not",
"None",
":",
"from",
"utool",
"import",
"util_inspect",
"from",
"utool",
"import",
"util_list",
"from",
"utool",
"import",
"util_dict",
"argspec",
"=",
"util_inspect",
".",
"get_func_argspec",
"(",
"func",
")",
"in_kwargs_flags",
"=",
"[",
"key",
"in",
"kwargs",
"for",
"key",
"in",
"keys",
"]",
"kwarg_keys",
"=",
"util_list",
".",
"compress",
"(",
"keys",
",",
"in_kwargs_flags",
")",
"kwarg_vals",
"=",
"[",
"kwargs",
".",
"get",
"(",
"key",
")",
"for",
"key",
"in",
"kwarg_keys",
"]",
"flags",
"=",
"util_list",
".",
"not_list",
"(",
"in_kwargs_flags",
")",
"arg_keys",
"=",
"util_list",
".",
"compress",
"(",
"keys",
",",
"flags",
")",
"arg_idxs",
"=",
"[",
"argspec",
".",
"args",
".",
"index",
"(",
"key",
")",
"for",
"key",
"in",
"arg_keys",
"]",
"num_nodefault",
"=",
"len",
"(",
"argspec",
".",
"args",
")",
"-",
"len",
"(",
"argspec",
".",
"defaults",
")",
"default_vals",
"=",
"(",
"(",
"[",
"None",
"]",
"*",
"(",
"num_nodefault",
")",
")",
"+",
"list",
"(",
"argspec",
".",
"defaults",
")",
")",
"args_",
"=",
"list",
"(",
"args",
")",
"+",
"default_vals",
"[",
"len",
"(",
"args",
")",
"+",
"1",
":",
"]",
"arg_vals",
"=",
"util_list",
".",
"take",
"(",
"args_",
",",
"arg_idxs",
")",
"requested_dict",
"=",
"dict",
"(",
"util_list",
".",
"flatten",
"(",
"[",
"zip",
"(",
"kwarg_keys",
",",
"kwarg_vals",
")",
",",
"zip",
"(",
"arg_keys",
",",
"arg_vals",
")",
"]",
")",
")",
"print",
"(",
"'input dict = '",
"+",
"util_str",
".",
"repr4",
"(",
"util_dict",
".",
"dict_subset",
"(",
"requested_dict",
",",
"keys",
")",
")",
")",
"# (print out specific keys only)",
"pass",
"arg_strs",
"=",
"', '",
".",
"join",
"(",
"[",
"repr",
"(",
"util_str",
".",
"truncate_str",
"(",
"str",
"(",
"arg",
")",
")",
")",
"for",
"arg",
"in",
"args",
"]",
")",
"kwarg_strs",
"=",
"', '",
".",
"join",
"(",
"[",
"util_str",
".",
"truncate_str",
"(",
"'%s=%r'",
"%",
"(",
"key",
",",
"val",
")",
")",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"kwargs",
")",
"]",
")",
"msg",
"=",
"(",
"'\\nERROR: funcname=%r,\\n * args=%s,\\n * kwargs=%r\\n'",
"%",
"(",
"meta_util_six",
".",
"get_funcname",
"(",
"func",
")",
",",
"arg_strs",
",",
"kwarg_strs",
")",
")",
"msg",
"+=",
"' * len(args) = %r\\n'",
"%",
"len",
"(",
"args",
")",
"msg",
"+=",
"' * len(kwargs) = %r\\n'",
"%",
"len",
"(",
"kwargs",
")",
"util_dbg",
".",
"printex",
"(",
"ex",
",",
"msg",
",",
"pad_stdout",
"=",
"True",
")",
"raise",
"wrp_onexceptreport",
"=",
"preserve_sig",
"(",
"wrp_onexceptreport",
",",
"func",
")",
"return",
"wrp_onexceptreport",
"if",
"func_",
"is",
"None",
":",
"return",
"_closure_onexceptreport",
"else",
":",
"return",
"_closure_onexceptreport",
"(",
"func_",
")"
] | If an error is thrown in the scope of this function's stack frame then the
decorated function name and the arguments passed to it will be printed to
the utool print function. | [
"If",
"an",
"error",
"is",
"thrown",
"in",
"the",
"scope",
"of",
"this",
"function",
"s",
"stack",
"frame",
"then",
"the",
"decorated",
"function",
"name",
"and",
"the",
"arguments",
"passed",
"to",
"it",
"will",
"be",
"printed",
"to",
"the",
"utool",
"print",
"function",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_decor.py#L211-L270 | train |
Erotemic/utool | utool/util_decor.py | _indent_decor | def _indent_decor(lbl):
"""
does the actual work of indent_func
"""
def closure_indent(func):
if util_arg.TRACE:
@ignores_exc_tb(outer_wrapper=False)
#@wraps(func)
def wrp_indent(*args, **kwargs):
with util_print.Indenter(lbl):
print(' ...trace[in]')
ret = func(*args, **kwargs)
print(' ...trace[out]')
return ret
else:
@ignores_exc_tb(outer_wrapper=False)
#@wraps(func)
def wrp_indent(*args, **kwargs):
with util_print.Indenter(lbl):
ret = func(*args, **kwargs)
return ret
wrp_indent_ = ignores_exc_tb(wrp_indent)
wrp_indent_ = preserve_sig(wrp_indent, func)
return wrp_indent_
return closure_indent | python | def _indent_decor(lbl):
"""
does the actual work of indent_func
"""
def closure_indent(func):
if util_arg.TRACE:
@ignores_exc_tb(outer_wrapper=False)
#@wraps(func)
def wrp_indent(*args, **kwargs):
with util_print.Indenter(lbl):
print(' ...trace[in]')
ret = func(*args, **kwargs)
print(' ...trace[out]')
return ret
else:
@ignores_exc_tb(outer_wrapper=False)
#@wraps(func)
def wrp_indent(*args, **kwargs):
with util_print.Indenter(lbl):
ret = func(*args, **kwargs)
return ret
wrp_indent_ = ignores_exc_tb(wrp_indent)
wrp_indent_ = preserve_sig(wrp_indent, func)
return wrp_indent_
return closure_indent | [
"def",
"_indent_decor",
"(",
"lbl",
")",
":",
"def",
"closure_indent",
"(",
"func",
")",
":",
"if",
"util_arg",
".",
"TRACE",
":",
"@",
"ignores_exc_tb",
"(",
"outer_wrapper",
"=",
"False",
")",
"#@wraps(func)",
"def",
"wrp_indent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"util_print",
".",
"Indenter",
"(",
"lbl",
")",
":",
"print",
"(",
"' ...trace[in]'",
")",
"ret",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"print",
"(",
"' ...trace[out]'",
")",
"return",
"ret",
"else",
":",
"@",
"ignores_exc_tb",
"(",
"outer_wrapper",
"=",
"False",
")",
"#@wraps(func)",
"def",
"wrp_indent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"util_print",
".",
"Indenter",
"(",
"lbl",
")",
":",
"ret",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"ret",
"wrp_indent_",
"=",
"ignores_exc_tb",
"(",
"wrp_indent",
")",
"wrp_indent_",
"=",
"preserve_sig",
"(",
"wrp_indent",
",",
"func",
")",
"return",
"wrp_indent_",
"return",
"closure_indent"
] | does the actual work of indent_func | [
"does",
"the",
"actual",
"work",
"of",
"indent_func"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_decor.py#L305-L329 | train |
Erotemic/utool | utool/util_decor.py | indent_func | def indent_func(input_):
"""
Takes either no arguments or an alias label
"""
if isinstance(input_, six.string_types):
# A label was specified
lbl = input_
return _indent_decor(lbl)
elif isinstance(input_, (bool, tuple)):
# Allow individually turning of of this decorator
func = input_
return func
else:
# Use the function name as the label
func = input_
lbl = '[' + meta_util_six.get_funcname(func) + ']'
return _indent_decor(lbl)(func) | python | def indent_func(input_):
"""
Takes either no arguments or an alias label
"""
if isinstance(input_, six.string_types):
# A label was specified
lbl = input_
return _indent_decor(lbl)
elif isinstance(input_, (bool, tuple)):
# Allow individually turning of of this decorator
func = input_
return func
else:
# Use the function name as the label
func = input_
lbl = '[' + meta_util_six.get_funcname(func) + ']'
return _indent_decor(lbl)(func) | [
"def",
"indent_func",
"(",
"input_",
")",
":",
"if",
"isinstance",
"(",
"input_",
",",
"six",
".",
"string_types",
")",
":",
"# A label was specified",
"lbl",
"=",
"input_",
"return",
"_indent_decor",
"(",
"lbl",
")",
"elif",
"isinstance",
"(",
"input_",
",",
"(",
"bool",
",",
"tuple",
")",
")",
":",
"# Allow individually turning of of this decorator",
"func",
"=",
"input_",
"return",
"func",
"else",
":",
"# Use the function name as the label",
"func",
"=",
"input_",
"lbl",
"=",
"'['",
"+",
"meta_util_six",
".",
"get_funcname",
"(",
"func",
")",
"+",
"']'",
"return",
"_indent_decor",
"(",
"lbl",
")",
"(",
"func",
")"
] | Takes either no arguments or an alias label | [
"Takes",
"either",
"no",
"arguments",
"or",
"an",
"alias",
"label"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_decor.py#L332-L348 | train |
Erotemic/utool | utool/util_decor.py | tracefunc_xml | def tracefunc_xml(func):
"""
Causes output of function to be printed in an XML style block
"""
funcname = meta_util_six.get_funcname(func)
def wrp_tracefunc2(*args, **kwargs):
verbose = kwargs.get('verbose', True)
if verbose:
print('<%s>' % (funcname,))
with util_print.Indenter(' '):
ret = func(*args, **kwargs)
if verbose:
print('</%s>' % (funcname,))
return ret
wrp_tracefunc2_ = ignores_exc_tb(wrp_tracefunc2)
wrp_tracefunc2_ = preserve_sig(wrp_tracefunc2_, func)
return wrp_tracefunc2_ | python | def tracefunc_xml(func):
"""
Causes output of function to be printed in an XML style block
"""
funcname = meta_util_six.get_funcname(func)
def wrp_tracefunc2(*args, **kwargs):
verbose = kwargs.get('verbose', True)
if verbose:
print('<%s>' % (funcname,))
with util_print.Indenter(' '):
ret = func(*args, **kwargs)
if verbose:
print('</%s>' % (funcname,))
return ret
wrp_tracefunc2_ = ignores_exc_tb(wrp_tracefunc2)
wrp_tracefunc2_ = preserve_sig(wrp_tracefunc2_, func)
return wrp_tracefunc2_ | [
"def",
"tracefunc_xml",
"(",
"func",
")",
":",
"funcname",
"=",
"meta_util_six",
".",
"get_funcname",
"(",
"func",
")",
"def",
"wrp_tracefunc2",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"verbose",
"=",
"kwargs",
".",
"get",
"(",
"'verbose'",
",",
"True",
")",
"if",
"verbose",
":",
"print",
"(",
"'<%s>'",
"%",
"(",
"funcname",
",",
")",
")",
"with",
"util_print",
".",
"Indenter",
"(",
"' '",
")",
":",
"ret",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"verbose",
":",
"print",
"(",
"'</%s>'",
"%",
"(",
"funcname",
",",
")",
")",
"return",
"ret",
"wrp_tracefunc2_",
"=",
"ignores_exc_tb",
"(",
"wrp_tracefunc2",
")",
"wrp_tracefunc2_",
"=",
"preserve_sig",
"(",
"wrp_tracefunc2_",
",",
"func",
")",
"return",
"wrp_tracefunc2_"
] | Causes output of function to be printed in an XML style block | [
"Causes",
"output",
"of",
"function",
"to",
"be",
"printed",
"in",
"an",
"XML",
"style",
"block"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_decor.py#L351-L367 | train |
Erotemic/utool | utool/util_decor.py | accepts_scalar_input | def accepts_scalar_input(func):
"""
DEPRICATE in favor of accepts_scalar_input2
only accepts one input as vector
accepts_scalar_input is a decorator which expects to be used on class
methods. It lets the user pass either a vector or a scalar to a function,
as long as the function treats everything like a vector. Input and output
is sanitized to the user expected format on return.
Args:
func (func):
Returns:
func: wrp_asi
CommandLine:
python -m utool.util_decor --test-accepts_scalar_input
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_decor import * # NOQA
>>> @accepts_scalar_input
... def foobar(self, list_):
... return [x + 1 for x in list_]
>>> self = None # dummy self because this decorator is for classes
>>> assert 2 == foobar(self, 1)
>>> assert [2, 3] == foobar(self, [1, 2])
"""
#@on_exception_report_input
@ignores_exc_tb(outer_wrapper=False)
#@wraps(func)
def wrp_asi(self, input_, *args, **kwargs):
#if HAVE_PANDAS:
# if isinstance(input_, (pd.DataFrame, pd.Series)):
# input_ = input_.values
if util_iter.isiterable(input_):
# If input is already iterable do default behavior
return func(self, input_, *args, **kwargs)
else:
# If input is scalar, wrap input, execute, and unpack result
#ret = func(self, (input_,), *args, **kwargs)
ret = func(self, [input_], *args, **kwargs)
if ret is not None:
return ret[0]
wrp_asi = preserve_sig(wrp_asi, func)
return wrp_asi | python | def accepts_scalar_input(func):
"""
DEPRICATE in favor of accepts_scalar_input2
only accepts one input as vector
accepts_scalar_input is a decorator which expects to be used on class
methods. It lets the user pass either a vector or a scalar to a function,
as long as the function treats everything like a vector. Input and output
is sanitized to the user expected format on return.
Args:
func (func):
Returns:
func: wrp_asi
CommandLine:
python -m utool.util_decor --test-accepts_scalar_input
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_decor import * # NOQA
>>> @accepts_scalar_input
... def foobar(self, list_):
... return [x + 1 for x in list_]
>>> self = None # dummy self because this decorator is for classes
>>> assert 2 == foobar(self, 1)
>>> assert [2, 3] == foobar(self, [1, 2])
"""
#@on_exception_report_input
@ignores_exc_tb(outer_wrapper=False)
#@wraps(func)
def wrp_asi(self, input_, *args, **kwargs):
#if HAVE_PANDAS:
# if isinstance(input_, (pd.DataFrame, pd.Series)):
# input_ = input_.values
if util_iter.isiterable(input_):
# If input is already iterable do default behavior
return func(self, input_, *args, **kwargs)
else:
# If input is scalar, wrap input, execute, and unpack result
#ret = func(self, (input_,), *args, **kwargs)
ret = func(self, [input_], *args, **kwargs)
if ret is not None:
return ret[0]
wrp_asi = preserve_sig(wrp_asi, func)
return wrp_asi | [
"def",
"accepts_scalar_input",
"(",
"func",
")",
":",
"#@on_exception_report_input",
"@",
"ignores_exc_tb",
"(",
"outer_wrapper",
"=",
"False",
")",
"#@wraps(func)",
"def",
"wrp_asi",
"(",
"self",
",",
"input_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#if HAVE_PANDAS:",
"# if isinstance(input_, (pd.DataFrame, pd.Series)):",
"# input_ = input_.values",
"if",
"util_iter",
".",
"isiterable",
"(",
"input_",
")",
":",
"# If input is already iterable do default behavior",
"return",
"func",
"(",
"self",
",",
"input_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"# If input is scalar, wrap input, execute, and unpack result",
"#ret = func(self, (input_,), *args, **kwargs)",
"ret",
"=",
"func",
"(",
"self",
",",
"[",
"input_",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"ret",
"is",
"not",
"None",
":",
"return",
"ret",
"[",
"0",
"]",
"wrp_asi",
"=",
"preserve_sig",
"(",
"wrp_asi",
",",
"func",
")",
"return",
"wrp_asi"
] | DEPRICATE in favor of accepts_scalar_input2
only accepts one input as vector
accepts_scalar_input is a decorator which expects to be used on class
methods. It lets the user pass either a vector or a scalar to a function,
as long as the function treats everything like a vector. Input and output
is sanitized to the user expected format on return.
Args:
func (func):
Returns:
func: wrp_asi
CommandLine:
python -m utool.util_decor --test-accepts_scalar_input
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_decor import * # NOQA
>>> @accepts_scalar_input
... def foobar(self, list_):
... return [x + 1 for x in list_]
>>> self = None # dummy self because this decorator is for classes
>>> assert 2 == foobar(self, 1)
>>> assert [2, 3] == foobar(self, [1, 2]) | [
"DEPRICATE",
"in",
"favor",
"of",
"accepts_scalar_input2",
"only",
"accepts",
"one",
"input",
"as",
"vector"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_decor.py#L372-L418 | train |
Erotemic/utool | utool/util_decor.py | __assert_param_consistency | def __assert_param_consistency(args, argx_list_):
"""
debugging function for accepts_scalar_input2
checks to make sure all the iterable inputs are of the same length
"""
if util_arg.NO_ASSERTS:
return
if len(argx_list_) == 0:
return True
argx_flags = [util_iter.isiterable(args[argx]) for argx in argx_list_]
try:
assert all([argx_flags[0] == flag for flag in argx_flags]), (
'invalid mixing of iterable and scalar inputs')
except AssertionError as ex:
print('!!! ASSERTION ERROR IN UTIL_DECOR !!!')
for argx in argx_list_:
print('[util_decor] args[%d] = %r' % (argx, args[argx]))
raise ex | python | def __assert_param_consistency(args, argx_list_):
"""
debugging function for accepts_scalar_input2
checks to make sure all the iterable inputs are of the same length
"""
if util_arg.NO_ASSERTS:
return
if len(argx_list_) == 0:
return True
argx_flags = [util_iter.isiterable(args[argx]) for argx in argx_list_]
try:
assert all([argx_flags[0] == flag for flag in argx_flags]), (
'invalid mixing of iterable and scalar inputs')
except AssertionError as ex:
print('!!! ASSERTION ERROR IN UTIL_DECOR !!!')
for argx in argx_list_:
print('[util_decor] args[%d] = %r' % (argx, args[argx]))
raise ex | [
"def",
"__assert_param_consistency",
"(",
"args",
",",
"argx_list_",
")",
":",
"if",
"util_arg",
".",
"NO_ASSERTS",
":",
"return",
"if",
"len",
"(",
"argx_list_",
")",
"==",
"0",
":",
"return",
"True",
"argx_flags",
"=",
"[",
"util_iter",
".",
"isiterable",
"(",
"args",
"[",
"argx",
"]",
")",
"for",
"argx",
"in",
"argx_list_",
"]",
"try",
":",
"assert",
"all",
"(",
"[",
"argx_flags",
"[",
"0",
"]",
"==",
"flag",
"for",
"flag",
"in",
"argx_flags",
"]",
")",
",",
"(",
"'invalid mixing of iterable and scalar inputs'",
")",
"except",
"AssertionError",
"as",
"ex",
":",
"print",
"(",
"'!!! ASSERTION ERROR IN UTIL_DECOR !!!'",
")",
"for",
"argx",
"in",
"argx_list_",
":",
"print",
"(",
"'[util_decor] args[%d] = %r'",
"%",
"(",
"argx",
",",
"args",
"[",
"argx",
"]",
")",
")",
"raise",
"ex"
] | debugging function for accepts_scalar_input2
checks to make sure all the iterable inputs are of the same length | [
"debugging",
"function",
"for",
"accepts_scalar_input2",
"checks",
"to",
"make",
"sure",
"all",
"the",
"iterable",
"inputs",
"are",
"of",
"the",
"same",
"length"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_decor.py#L463-L480 | train |
Erotemic/utool | utool/util_decor.py | accepts_scalar_input_vector_output | def accepts_scalar_input_vector_output(func):
"""
DEPRICATE IN FAVOR OF accepts_scalar_input2
accepts_scalar_input_vector_output
Notes:
Input: Excpeted Output 1to1 Expected Output 1toM
scalar : 1 x [X]
n element list : [1, 2, 3] [x, y, z] [[X], [Y], [Z]]
1 element list : [1] [x] [[X]]
0 element list : [] [] []
There seems to be no real issue here, I be the thing that tripped me up
was when using sql and getting multiple columns that returned the
values inside of the N-tuple whereas when you get one column you get
one element inside of a 1-tuple, no that still makes sense. There was
something where when you couln't unpack it becuase it was already
empty...
"""
@ignores_exc_tb(outer_wrapper=False)
#@wraps(func)
def wrp_asivo(self, input_, *args, **kwargs):
#import utool
#if utool.DEBUG:
# print('[IN SIVO] args=%r' % (args,))
# print('[IN SIVO] kwargs=%r' % (kwargs,))
if util_iter.isiterable(input_):
# If input is already iterable do default behavior
return func(self, input_, *args, **kwargs)
else:
# If input is scalar, wrap input, execute, and unpack result
result = func(self, (input_,), *args, **kwargs)
# The output length could be 0 on a scalar input
if len(result) == 0:
return []
else:
assert len(result) == 1, 'error in asivo'
return result[0]
return wrp_asivo | python | def accepts_scalar_input_vector_output(func):
"""
DEPRICATE IN FAVOR OF accepts_scalar_input2
accepts_scalar_input_vector_output
Notes:
Input: Excpeted Output 1to1 Expected Output 1toM
scalar : 1 x [X]
n element list : [1, 2, 3] [x, y, z] [[X], [Y], [Z]]
1 element list : [1] [x] [[X]]
0 element list : [] [] []
There seems to be no real issue here, I be the thing that tripped me up
was when using sql and getting multiple columns that returned the
values inside of the N-tuple whereas when you get one column you get
one element inside of a 1-tuple, no that still makes sense. There was
something where when you couln't unpack it becuase it was already
empty...
"""
@ignores_exc_tb(outer_wrapper=False)
#@wraps(func)
def wrp_asivo(self, input_, *args, **kwargs):
#import utool
#if utool.DEBUG:
# print('[IN SIVO] args=%r' % (args,))
# print('[IN SIVO] kwargs=%r' % (kwargs,))
if util_iter.isiterable(input_):
# If input is already iterable do default behavior
return func(self, input_, *args, **kwargs)
else:
# If input is scalar, wrap input, execute, and unpack result
result = func(self, (input_,), *args, **kwargs)
# The output length could be 0 on a scalar input
if len(result) == 0:
return []
else:
assert len(result) == 1, 'error in asivo'
return result[0]
return wrp_asivo | [
"def",
"accepts_scalar_input_vector_output",
"(",
"func",
")",
":",
"@",
"ignores_exc_tb",
"(",
"outer_wrapper",
"=",
"False",
")",
"#@wraps(func)",
"def",
"wrp_asivo",
"(",
"self",
",",
"input_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#import utool",
"#if utool.DEBUG:",
"# print('[IN SIVO] args=%r' % (args,))",
"# print('[IN SIVO] kwargs=%r' % (kwargs,))",
"if",
"util_iter",
".",
"isiterable",
"(",
"input_",
")",
":",
"# If input is already iterable do default behavior",
"return",
"func",
"(",
"self",
",",
"input_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"# If input is scalar, wrap input, execute, and unpack result",
"result",
"=",
"func",
"(",
"self",
",",
"(",
"input_",
",",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# The output length could be 0 on a scalar input",
"if",
"len",
"(",
"result",
")",
"==",
"0",
":",
"return",
"[",
"]",
"else",
":",
"assert",
"len",
"(",
"result",
")",
"==",
"1",
",",
"'error in asivo'",
"return",
"result",
"[",
"0",
"]",
"return",
"wrp_asivo"
] | DEPRICATE IN FAVOR OF accepts_scalar_input2
accepts_scalar_input_vector_output
Notes:
Input: Excpeted Output 1to1 Expected Output 1toM
scalar : 1 x [X]
n element list : [1, 2, 3] [x, y, z] [[X], [Y], [Z]]
1 element list : [1] [x] [[X]]
0 element list : [] [] []
There seems to be no real issue here, I be the thing that tripped me up
was when using sql and getting multiple columns that returned the
values inside of the N-tuple whereas when you get one column you get
one element inside of a 1-tuple, no that still makes sense. There was
something where when you couln't unpack it becuase it was already
empty... | [
"DEPRICATE",
"IN",
"FAVOR",
"OF",
"accepts_scalar_input2"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_decor.py#L483-L521 | train |
Erotemic/utool | utool/util_decor.py | accepts_numpy | def accepts_numpy(func):
""" Allows the first input to be a numpy array and get result in numpy form """
#@ignores_exc_tb
#@wraps(func)
def wrp_accepts_numpy(self, input_, *args, **kwargs):
if not (util_type.HAVE_NUMPY and isinstance(input_, np.ndarray)):
# If the input is not numpy, just call the function
return func(self, input_, *args, **kwargs)
else:
# TODO: use a variant of util_list.unflat_unique_rowid_map
# If the input is a numpy array, and return the output with the same
# shape as the input
if UNIQUE_NUMPY:
# Remove redundant input (because we are passing it to SQL)
input_list, inverse_unique = np.unique(input_, return_inverse=True)
else:
input_list = input_.flatten()
# Call the function in list format
# TODO: is this necessary?
input_list = input_list.tolist()
output_list = func(self, input_list, *args, **kwargs)
# Put the output back into numpy
if UNIQUE_NUMPY:
# Reconstruct redundant queries
output_arr = np.array(output_list)[inverse_unique]
output_shape = tuple(list(input_.shape) + list(output_arr.shape[1:]))
return np.array(output_arr).reshape(output_shape)
else:
return np.array(output_list).reshape(input_.shape)
wrp_accepts_numpy = preserve_sig(wrp_accepts_numpy, func)
return wrp_accepts_numpy | python | def accepts_numpy(func):
""" Allows the first input to be a numpy array and get result in numpy form """
#@ignores_exc_tb
#@wraps(func)
def wrp_accepts_numpy(self, input_, *args, **kwargs):
if not (util_type.HAVE_NUMPY and isinstance(input_, np.ndarray)):
# If the input is not numpy, just call the function
return func(self, input_, *args, **kwargs)
else:
# TODO: use a variant of util_list.unflat_unique_rowid_map
# If the input is a numpy array, and return the output with the same
# shape as the input
if UNIQUE_NUMPY:
# Remove redundant input (because we are passing it to SQL)
input_list, inverse_unique = np.unique(input_, return_inverse=True)
else:
input_list = input_.flatten()
# Call the function in list format
# TODO: is this necessary?
input_list = input_list.tolist()
output_list = func(self, input_list, *args, **kwargs)
# Put the output back into numpy
if UNIQUE_NUMPY:
# Reconstruct redundant queries
output_arr = np.array(output_list)[inverse_unique]
output_shape = tuple(list(input_.shape) + list(output_arr.shape[1:]))
return np.array(output_arr).reshape(output_shape)
else:
return np.array(output_list).reshape(input_.shape)
wrp_accepts_numpy = preserve_sig(wrp_accepts_numpy, func)
return wrp_accepts_numpy | [
"def",
"accepts_numpy",
"(",
"func",
")",
":",
"#@ignores_exc_tb",
"#@wraps(func)",
"def",
"wrp_accepts_numpy",
"(",
"self",
",",
"input_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"(",
"util_type",
".",
"HAVE_NUMPY",
"and",
"isinstance",
"(",
"input_",
",",
"np",
".",
"ndarray",
")",
")",
":",
"# If the input is not numpy, just call the function",
"return",
"func",
"(",
"self",
",",
"input_",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"# TODO: use a variant of util_list.unflat_unique_rowid_map",
"# If the input is a numpy array, and return the output with the same",
"# shape as the input",
"if",
"UNIQUE_NUMPY",
":",
"# Remove redundant input (because we are passing it to SQL)",
"input_list",
",",
"inverse_unique",
"=",
"np",
".",
"unique",
"(",
"input_",
",",
"return_inverse",
"=",
"True",
")",
"else",
":",
"input_list",
"=",
"input_",
".",
"flatten",
"(",
")",
"# Call the function in list format",
"# TODO: is this necessary?",
"input_list",
"=",
"input_list",
".",
"tolist",
"(",
")",
"output_list",
"=",
"func",
"(",
"self",
",",
"input_list",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Put the output back into numpy",
"if",
"UNIQUE_NUMPY",
":",
"# Reconstruct redundant queries",
"output_arr",
"=",
"np",
".",
"array",
"(",
"output_list",
")",
"[",
"inverse_unique",
"]",
"output_shape",
"=",
"tuple",
"(",
"list",
"(",
"input_",
".",
"shape",
")",
"+",
"list",
"(",
"output_arr",
".",
"shape",
"[",
"1",
":",
"]",
")",
")",
"return",
"np",
".",
"array",
"(",
"output_arr",
")",
".",
"reshape",
"(",
"output_shape",
")",
"else",
":",
"return",
"np",
".",
"array",
"(",
"output_list",
")",
".",
"reshape",
"(",
"input_",
".",
"shape",
")",
"wrp_accepts_numpy",
"=",
"preserve_sig",
"(",
"wrp_accepts_numpy",
",",
"func",
")",
"return",
"wrp_accepts_numpy"
] | Allows the first input to be a numpy array and get result in numpy form | [
"Allows",
"the",
"first",
"input",
"to",
"be",
"a",
"numpy",
"array",
"and",
"get",
"result",
"in",
"numpy",
"form"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_decor.py#L529-L559 | train |
Erotemic/utool | utool/util_decor.py | memoize_nonzero | def memoize_nonzero(func):
"""
Memoization decorator for functions taking a nonzero number of arguments.
References:
http://code.activestate.com/recipes/578231-fastest-memoization-decorator
"""
class _memorizer(dict):
def __init__(self, func):
self.func = func
def __call__(self, *args):
return self[args]
def __missing__(self, key):
ret = self[key] = self.func(*key)
return ret
return _memorizer(func) | python | def memoize_nonzero(func):
"""
Memoization decorator for functions taking a nonzero number of arguments.
References:
http://code.activestate.com/recipes/578231-fastest-memoization-decorator
"""
class _memorizer(dict):
def __init__(self, func):
self.func = func
def __call__(self, *args):
return self[args]
def __missing__(self, key):
ret = self[key] = self.func(*key)
return ret
return _memorizer(func) | [
"def",
"memoize_nonzero",
"(",
"func",
")",
":",
"class",
"_memorizer",
"(",
"dict",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"func",
")",
":",
"self",
".",
"func",
"=",
"func",
"def",
"__call__",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"self",
"[",
"args",
"]",
"def",
"__missing__",
"(",
"self",
",",
"key",
")",
":",
"ret",
"=",
"self",
"[",
"key",
"]",
"=",
"self",
".",
"func",
"(",
"*",
"key",
")",
"return",
"ret",
"return",
"_memorizer",
"(",
"func",
")"
] | Memoization decorator for functions taking a nonzero number of arguments.
References:
http://code.activestate.com/recipes/578231-fastest-memoization-decorator | [
"Memoization",
"decorator",
"for",
"functions",
"taking",
"a",
"nonzero",
"number",
"of",
"arguments",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_decor.py#L562-L577 | train |
Erotemic/utool | utool/util_decor.py | memoize | def memoize(func):
"""
simple memoization decorator
References:
https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
Args:
func (function): live python function
Returns:
func:
CommandLine:
python -m utool.util_decor memoize
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_decor import * # NOQA
>>> import utool as ut
>>> closure = {'a': 'b', 'c': 'd'}
>>> incr = [0]
>>> def foo(key):
>>> value = closure[key]
>>> incr[0] += 1
>>> return value
>>> foo_memo = memoize(foo)
>>> assert foo('a') == 'b' and foo('c') == 'd'
>>> assert incr[0] == 2
>>> print('Call memoized version')
>>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'
>>> assert incr[0] == 4
>>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'
>>> print('Counter should no longer increase')
>>> assert incr[0] == 4
>>> print('Closure changes result without memoization')
>>> closure = {'a': 0, 'c': 1}
>>> assert foo('a') == 0 and foo('c') == 1
>>> assert incr[0] == 6
>>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'
"""
cache = func._util_decor_memoize_cache = {}
# @functools.wraps(func)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
memoizer = preserve_sig(memoizer, func)
memoizer.cache = cache
return memoizer | python | def memoize(func):
"""
simple memoization decorator
References:
https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
Args:
func (function): live python function
Returns:
func:
CommandLine:
python -m utool.util_decor memoize
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_decor import * # NOQA
>>> import utool as ut
>>> closure = {'a': 'b', 'c': 'd'}
>>> incr = [0]
>>> def foo(key):
>>> value = closure[key]
>>> incr[0] += 1
>>> return value
>>> foo_memo = memoize(foo)
>>> assert foo('a') == 'b' and foo('c') == 'd'
>>> assert incr[0] == 2
>>> print('Call memoized version')
>>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'
>>> assert incr[0] == 4
>>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'
>>> print('Counter should no longer increase')
>>> assert incr[0] == 4
>>> print('Closure changes result without memoization')
>>> closure = {'a': 0, 'c': 1}
>>> assert foo('a') == 0 and foo('c') == 1
>>> assert incr[0] == 6
>>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'
"""
cache = func._util_decor_memoize_cache = {}
# @functools.wraps(func)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
memoizer = preserve_sig(memoizer, func)
memoizer.cache = cache
return memoizer | [
"def",
"memoize",
"(",
"func",
")",
":",
"cache",
"=",
"func",
".",
"_util_decor_memoize_cache",
"=",
"{",
"}",
"# @functools.wraps(func)",
"def",
"memoizer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"str",
"(",
"args",
")",
"+",
"str",
"(",
"kwargs",
")",
"if",
"key",
"not",
"in",
"cache",
":",
"cache",
"[",
"key",
"]",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"cache",
"[",
"key",
"]",
"memoizer",
"=",
"preserve_sig",
"(",
"memoizer",
",",
"func",
")",
"memoizer",
".",
"cache",
"=",
"cache",
"return",
"memoizer"
] | simple memoization decorator
References:
https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
Args:
func (function): live python function
Returns:
func:
CommandLine:
python -m utool.util_decor memoize
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_decor import * # NOQA
>>> import utool as ut
>>> closure = {'a': 'b', 'c': 'd'}
>>> incr = [0]
>>> def foo(key):
>>> value = closure[key]
>>> incr[0] += 1
>>> return value
>>> foo_memo = memoize(foo)
>>> assert foo('a') == 'b' and foo('c') == 'd'
>>> assert incr[0] == 2
>>> print('Call memoized version')
>>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'
>>> assert incr[0] == 4
>>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd'
>>> print('Counter should no longer increase')
>>> assert incr[0] == 4
>>> print('Closure changes result without memoization')
>>> closure = {'a': 0, 'c': 1}
>>> assert foo('a') == 0 and foo('c') == 1
>>> assert incr[0] == 6
>>> assert foo_memo('a') == 'b' and foo_memo('c') == 'd' | [
"simple",
"memoization",
"decorator"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_decor.py#L601-L651 | train |
Erotemic/utool | utool/util_decor.py | lazyfunc | def lazyfunc(func):
"""
Returns a memcached version of a function
"""
closuremem_ = [{}]
def wrapper(*args, **kwargs):
mem = closuremem_[0]
key = (repr(args), repr(kwargs))
try:
return mem[key]
except KeyError:
mem[key] = func(*args, **kwargs)
return mem[key]
return wrapper | python | def lazyfunc(func):
"""
Returns a memcached version of a function
"""
closuremem_ = [{}]
def wrapper(*args, **kwargs):
mem = closuremem_[0]
key = (repr(args), repr(kwargs))
try:
return mem[key]
except KeyError:
mem[key] = func(*args, **kwargs)
return mem[key]
return wrapper | [
"def",
"lazyfunc",
"(",
"func",
")",
":",
"closuremem_",
"=",
"[",
"{",
"}",
"]",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"mem",
"=",
"closuremem_",
"[",
"0",
"]",
"key",
"=",
"(",
"repr",
"(",
"args",
")",
",",
"repr",
"(",
"kwargs",
")",
")",
"try",
":",
"return",
"mem",
"[",
"key",
"]",
"except",
"KeyError",
":",
"mem",
"[",
"key",
"]",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"mem",
"[",
"key",
"]",
"return",
"wrapper"
] | Returns a memcached version of a function | [
"Returns",
"a",
"memcached",
"version",
"of",
"a",
"function"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_decor.py#L752-L765 | train |
Erotemic/utool | utool/util_decor.py | apply_docstr | def apply_docstr(docstr_func):
"""
Changes docstr of one functio to that of another
"""
def docstr_applier(func):
#docstr = meta_util_six.get_funcdoc(docstr_func)
#meta_util_six.set_funcdoc(func, docstr)
if isinstance(docstr_func, six.string_types):
olddoc = meta_util_six.get_funcdoc(func)
if olddoc is None:
olddoc = ''
newdoc = olddoc + docstr_func
meta_util_six.set_funcdoc(func, newdoc)
return func
else:
preserved_func = preserve_sig(func, docstr_func)
return preserved_func
return docstr_applier | python | def apply_docstr(docstr_func):
"""
Changes docstr of one functio to that of another
"""
def docstr_applier(func):
#docstr = meta_util_six.get_funcdoc(docstr_func)
#meta_util_six.set_funcdoc(func, docstr)
if isinstance(docstr_func, six.string_types):
olddoc = meta_util_six.get_funcdoc(func)
if olddoc is None:
olddoc = ''
newdoc = olddoc + docstr_func
meta_util_six.set_funcdoc(func, newdoc)
return func
else:
preserved_func = preserve_sig(func, docstr_func)
return preserved_func
return docstr_applier | [
"def",
"apply_docstr",
"(",
"docstr_func",
")",
":",
"def",
"docstr_applier",
"(",
"func",
")",
":",
"#docstr = meta_util_six.get_funcdoc(docstr_func)",
"#meta_util_six.set_funcdoc(func, docstr)",
"if",
"isinstance",
"(",
"docstr_func",
",",
"six",
".",
"string_types",
")",
":",
"olddoc",
"=",
"meta_util_six",
".",
"get_funcdoc",
"(",
"func",
")",
"if",
"olddoc",
"is",
"None",
":",
"olddoc",
"=",
"''",
"newdoc",
"=",
"olddoc",
"+",
"docstr_func",
"meta_util_six",
".",
"set_funcdoc",
"(",
"func",
",",
"newdoc",
")",
"return",
"func",
"else",
":",
"preserved_func",
"=",
"preserve_sig",
"(",
"func",
",",
"docstr_func",
")",
"return",
"preserved_func",
"return",
"docstr_applier"
] | Changes docstr of one functio to that of another | [
"Changes",
"docstr",
"of",
"one",
"functio",
"to",
"that",
"of",
"another"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_decor.py#L768-L785 | train |
Erotemic/utool | utool/util_decor.py | preserve_sig | def preserve_sig(wrapper, orig_func, force=False):
"""
Decorates a wrapper function.
It seems impossible to presever signatures in python 2 without eval
(Maybe another option is to write to a temporary module?)
Args:
wrapper: the function wrapping orig_func to change the signature of
orig_func: the original function to take the signature from
References:
http://emptysqua.re/blog/copying-a-python-functions-signature/
https://code.google.com/p/micheles/source/browse/decorator/src/decorator.py
TODO:
checkout funcsigs
https://funcsigs.readthedocs.org/en/latest/
CommandLine:
python -m utool.util_decor --test-preserve_sig
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> #ut.rrrr(False)
>>> def myfunction(self, listinput_, arg1, *args, **kwargs):
>>> " just a test function "
>>> return [x + 1 for x in listinput_]
>>> #orig_func = ut.take
>>> orig_func = myfunction
>>> wrapper = ut.accepts_scalar_input2([0])(orig_func)
>>> _wrp_preserve1 = ut.preserve_sig(wrapper, orig_func, True)
>>> _wrp_preserve2 = ut.preserve_sig(wrapper, orig_func, False)
>>> print('_wrp_preserve2 = %r' % (_wrp_preserve1,))
>>> print('_wrp_preserve2 = %r' % (_wrp_preserve2,))
>>> #print('source _wrp_preserve1 = %s' % (ut.get_func_sourcecode(_wrp_preserve1),))
>>> #print('source _wrp_preserve2 = %s' % (ut.get_func_sourcecode(_wrp_preserve2)),)
>>> result = str(_wrp_preserve1)
>>> print(result)
"""
#if True:
# import functools
# return functools.wraps(orig_func)(wrapper)
from utool._internal import meta_util_six
from utool import util_str
from utool import util_inspect
if wrapper is orig_func:
# nothing to do
return orig_func
orig_docstr = meta_util_six.get_funcdoc(orig_func)
orig_docstr = '' if orig_docstr is None else orig_docstr
orig_argspec = util_inspect.get_func_argspec(orig_func)
wrap_name = meta_util_six.get_funccode(wrapper).co_name
orig_name = meta_util_six.get_funcname(orig_func)
# At the very least preserve info in a dictionary
_utinfo = {}
_utinfo['orig_func'] = orig_func
_utinfo['wrap_name'] = wrap_name
_utinfo['orig_name'] = orig_name
_utinfo['orig_argspec'] = orig_argspec
if hasattr(wrapper, '_utinfo'):
parent_wrapper_utinfo = wrapper._utinfo
_utinfo['parent_wrapper_utinfo'] = parent_wrapper_utinfo
if hasattr(orig_func, '_utinfo'):
parent_orig_utinfo = orig_func._utinfo
_utinfo['parent_orig_utinfo'] = parent_orig_utinfo
# environment variable is set if you are building documentation
# preserve sig if building docs
building_docs = os.environ.get('UTOOL_AUTOGEN_SPHINX_RUNNING', 'OFF') == 'ON'
if force or SIG_PRESERVE or building_docs:
# PRESERVES ALL SIGNATURES WITH EXECS
src_fmt = r'''
def _wrp_preserve{defsig}:
""" {orig_docstr} """
try:
return wrapper{callsig}
except Exception as ex:
import utool as ut
msg = ('Failure in signature preserving wrapper:\n')
ut.printex(ex, msg)
raise
'''
# Put wrapped function into a scope
globals_ = {'wrapper': wrapper}
locals_ = {}
# argspec is :ArgSpec(args=['bar', 'baz'], varargs=None, keywords=None,
# defaults=(True,))
# get orig functions argspec
# get functions signature
# Get function call signature (no defaults)
# Define an exec function
argspec = inspect.getargspec(orig_func)
(args, varargs, varkw, defaults) = argspec
defsig = inspect.formatargspec(*argspec)
callsig = inspect.formatargspec(*argspec[0:3])
# TODO:
# ut.func_defsig
# ut.func_callsig
src_fmtdict = dict(defsig=defsig, callsig=callsig, orig_docstr=orig_docstr)
src = textwrap.dedent(src_fmt).format(**src_fmtdict)
# Define the new function on the fly
# (I wish there was a non exec / eval way to do this)
#print(src)
code = compile(src, '<string>', 'exec')
six.exec_(code, globals_, locals_)
#six.exec_(src, globals_, locals_)
# Use functools.update_wapper to complete preservation
_wrp_preserve = functools.update_wrapper(locals_['_wrp_preserve'], orig_func)
# Keep debug info
_utinfo['src'] = src
# Set an internal sig variable that we may use
#_wrp_preserve.__sig__ = defsig
else:
# PRESERVES SOME SIGNATURES NO EXEC
# signature preservation is turned off. just preserve the name.
# Does not use any exec or eval statments.
_wrp_preserve = functools.update_wrapper(wrapper, orig_func)
# Just do something to preserve signature
DEBUG_WRAPPED_DOCSTRING = False
if DEBUG_WRAPPED_DOCSTRING:
new_docstr_fmtstr = util_str.codeblock(
'''
Wrapped function {wrap_name}({orig_name})
orig_argspec = {orig_argspec}
orig_docstr = {orig_docstr}
'''
)
else:
new_docstr_fmtstr = util_str.codeblock(
'''
{orig_docstr}
'''
)
new_docstr = new_docstr_fmtstr.format(
wrap_name=wrap_name, orig_name=orig_name, orig_docstr=orig_docstr,
orig_argspec=orig_argspec)
meta_util_six.set_funcdoc(_wrp_preserve, new_docstr)
_wrp_preserve._utinfo = _utinfo
return _wrp_preserve | python | def preserve_sig(wrapper, orig_func, force=False):
"""
Decorates a wrapper function.
It seems impossible to presever signatures in python 2 without eval
(Maybe another option is to write to a temporary module?)
Args:
wrapper: the function wrapping orig_func to change the signature of
orig_func: the original function to take the signature from
References:
http://emptysqua.re/blog/copying-a-python-functions-signature/
https://code.google.com/p/micheles/source/browse/decorator/src/decorator.py
TODO:
checkout funcsigs
https://funcsigs.readthedocs.org/en/latest/
CommandLine:
python -m utool.util_decor --test-preserve_sig
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> #ut.rrrr(False)
>>> def myfunction(self, listinput_, arg1, *args, **kwargs):
>>> " just a test function "
>>> return [x + 1 for x in listinput_]
>>> #orig_func = ut.take
>>> orig_func = myfunction
>>> wrapper = ut.accepts_scalar_input2([0])(orig_func)
>>> _wrp_preserve1 = ut.preserve_sig(wrapper, orig_func, True)
>>> _wrp_preserve2 = ut.preserve_sig(wrapper, orig_func, False)
>>> print('_wrp_preserve2 = %r' % (_wrp_preserve1,))
>>> print('_wrp_preserve2 = %r' % (_wrp_preserve2,))
>>> #print('source _wrp_preserve1 = %s' % (ut.get_func_sourcecode(_wrp_preserve1),))
>>> #print('source _wrp_preserve2 = %s' % (ut.get_func_sourcecode(_wrp_preserve2)),)
>>> result = str(_wrp_preserve1)
>>> print(result)
"""
#if True:
# import functools
# return functools.wraps(orig_func)(wrapper)
from utool._internal import meta_util_six
from utool import util_str
from utool import util_inspect
if wrapper is orig_func:
# nothing to do
return orig_func
orig_docstr = meta_util_six.get_funcdoc(orig_func)
orig_docstr = '' if orig_docstr is None else orig_docstr
orig_argspec = util_inspect.get_func_argspec(orig_func)
wrap_name = meta_util_six.get_funccode(wrapper).co_name
orig_name = meta_util_six.get_funcname(orig_func)
# At the very least preserve info in a dictionary
_utinfo = {}
_utinfo['orig_func'] = orig_func
_utinfo['wrap_name'] = wrap_name
_utinfo['orig_name'] = orig_name
_utinfo['orig_argspec'] = orig_argspec
if hasattr(wrapper, '_utinfo'):
parent_wrapper_utinfo = wrapper._utinfo
_utinfo['parent_wrapper_utinfo'] = parent_wrapper_utinfo
if hasattr(orig_func, '_utinfo'):
parent_orig_utinfo = orig_func._utinfo
_utinfo['parent_orig_utinfo'] = parent_orig_utinfo
# environment variable is set if you are building documentation
# preserve sig if building docs
building_docs = os.environ.get('UTOOL_AUTOGEN_SPHINX_RUNNING', 'OFF') == 'ON'
if force or SIG_PRESERVE or building_docs:
# PRESERVES ALL SIGNATURES WITH EXECS
src_fmt = r'''
def _wrp_preserve{defsig}:
""" {orig_docstr} """
try:
return wrapper{callsig}
except Exception as ex:
import utool as ut
msg = ('Failure in signature preserving wrapper:\n')
ut.printex(ex, msg)
raise
'''
# Put wrapped function into a scope
globals_ = {'wrapper': wrapper}
locals_ = {}
# argspec is :ArgSpec(args=['bar', 'baz'], varargs=None, keywords=None,
# defaults=(True,))
# get orig functions argspec
# get functions signature
# Get function call signature (no defaults)
# Define an exec function
argspec = inspect.getargspec(orig_func)
(args, varargs, varkw, defaults) = argspec
defsig = inspect.formatargspec(*argspec)
callsig = inspect.formatargspec(*argspec[0:3])
# TODO:
# ut.func_defsig
# ut.func_callsig
src_fmtdict = dict(defsig=defsig, callsig=callsig, orig_docstr=orig_docstr)
src = textwrap.dedent(src_fmt).format(**src_fmtdict)
# Define the new function on the fly
# (I wish there was a non exec / eval way to do this)
#print(src)
code = compile(src, '<string>', 'exec')
six.exec_(code, globals_, locals_)
#six.exec_(src, globals_, locals_)
# Use functools.update_wapper to complete preservation
_wrp_preserve = functools.update_wrapper(locals_['_wrp_preserve'], orig_func)
# Keep debug info
_utinfo['src'] = src
# Set an internal sig variable that we may use
#_wrp_preserve.__sig__ = defsig
else:
# PRESERVES SOME SIGNATURES NO EXEC
# signature preservation is turned off. just preserve the name.
# Does not use any exec or eval statments.
_wrp_preserve = functools.update_wrapper(wrapper, orig_func)
# Just do something to preserve signature
DEBUG_WRAPPED_DOCSTRING = False
if DEBUG_WRAPPED_DOCSTRING:
new_docstr_fmtstr = util_str.codeblock(
'''
Wrapped function {wrap_name}({orig_name})
orig_argspec = {orig_argspec}
orig_docstr = {orig_docstr}
'''
)
else:
new_docstr_fmtstr = util_str.codeblock(
'''
{orig_docstr}
'''
)
new_docstr = new_docstr_fmtstr.format(
wrap_name=wrap_name, orig_name=orig_name, orig_docstr=orig_docstr,
orig_argspec=orig_argspec)
meta_util_six.set_funcdoc(_wrp_preserve, new_docstr)
_wrp_preserve._utinfo = _utinfo
return _wrp_preserve | [
"def",
"preserve_sig",
"(",
"wrapper",
",",
"orig_func",
",",
"force",
"=",
"False",
")",
":",
"#if True:",
"# import functools",
"# return functools.wraps(orig_func)(wrapper)",
"from",
"utool",
".",
"_internal",
"import",
"meta_util_six",
"from",
"utool",
"import",
"util_str",
"from",
"utool",
"import",
"util_inspect",
"if",
"wrapper",
"is",
"orig_func",
":",
"# nothing to do",
"return",
"orig_func",
"orig_docstr",
"=",
"meta_util_six",
".",
"get_funcdoc",
"(",
"orig_func",
")",
"orig_docstr",
"=",
"''",
"if",
"orig_docstr",
"is",
"None",
"else",
"orig_docstr",
"orig_argspec",
"=",
"util_inspect",
".",
"get_func_argspec",
"(",
"orig_func",
")",
"wrap_name",
"=",
"meta_util_six",
".",
"get_funccode",
"(",
"wrapper",
")",
".",
"co_name",
"orig_name",
"=",
"meta_util_six",
".",
"get_funcname",
"(",
"orig_func",
")",
"# At the very least preserve info in a dictionary",
"_utinfo",
"=",
"{",
"}",
"_utinfo",
"[",
"'orig_func'",
"]",
"=",
"orig_func",
"_utinfo",
"[",
"'wrap_name'",
"]",
"=",
"wrap_name",
"_utinfo",
"[",
"'orig_name'",
"]",
"=",
"orig_name",
"_utinfo",
"[",
"'orig_argspec'",
"]",
"=",
"orig_argspec",
"if",
"hasattr",
"(",
"wrapper",
",",
"'_utinfo'",
")",
":",
"parent_wrapper_utinfo",
"=",
"wrapper",
".",
"_utinfo",
"_utinfo",
"[",
"'parent_wrapper_utinfo'",
"]",
"=",
"parent_wrapper_utinfo",
"if",
"hasattr",
"(",
"orig_func",
",",
"'_utinfo'",
")",
":",
"parent_orig_utinfo",
"=",
"orig_func",
".",
"_utinfo",
"_utinfo",
"[",
"'parent_orig_utinfo'",
"]",
"=",
"parent_orig_utinfo",
"# environment variable is set if you are building documentation",
"# preserve sig if building docs",
"building_docs",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'UTOOL_AUTOGEN_SPHINX_RUNNING'",
",",
"'OFF'",
")",
"==",
"'ON'",
"if",
"force",
"or",
"SIG_PRESERVE",
"or",
"building_docs",
":",
"# PRESERVES ALL SIGNATURES WITH EXECS",
"src_fmt",
"=",
"r'''\n def _wrp_preserve{defsig}:\n \"\"\" {orig_docstr} \"\"\"\n try:\n return wrapper{callsig}\n except Exception as ex:\n import utool as ut\n msg = ('Failure in signature preserving wrapper:\\n')\n ut.printex(ex, msg)\n raise\n '''",
"# Put wrapped function into a scope",
"globals_",
"=",
"{",
"'wrapper'",
":",
"wrapper",
"}",
"locals_",
"=",
"{",
"}",
"# argspec is :ArgSpec(args=['bar', 'baz'], varargs=None, keywords=None,",
"# defaults=(True,))",
"# get orig functions argspec",
"# get functions signature",
"# Get function call signature (no defaults)",
"# Define an exec function",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"orig_func",
")",
"(",
"args",
",",
"varargs",
",",
"varkw",
",",
"defaults",
")",
"=",
"argspec",
"defsig",
"=",
"inspect",
".",
"formatargspec",
"(",
"*",
"argspec",
")",
"callsig",
"=",
"inspect",
".",
"formatargspec",
"(",
"*",
"argspec",
"[",
"0",
":",
"3",
"]",
")",
"# TODO:",
"# ut.func_defsig",
"# ut.func_callsig",
"src_fmtdict",
"=",
"dict",
"(",
"defsig",
"=",
"defsig",
",",
"callsig",
"=",
"callsig",
",",
"orig_docstr",
"=",
"orig_docstr",
")",
"src",
"=",
"textwrap",
".",
"dedent",
"(",
"src_fmt",
")",
".",
"format",
"(",
"*",
"*",
"src_fmtdict",
")",
"# Define the new function on the fly",
"# (I wish there was a non exec / eval way to do this)",
"#print(src)",
"code",
"=",
"compile",
"(",
"src",
",",
"'<string>'",
",",
"'exec'",
")",
"six",
".",
"exec_",
"(",
"code",
",",
"globals_",
",",
"locals_",
")",
"#six.exec_(src, globals_, locals_)",
"# Use functools.update_wapper to complete preservation",
"_wrp_preserve",
"=",
"functools",
".",
"update_wrapper",
"(",
"locals_",
"[",
"'_wrp_preserve'",
"]",
",",
"orig_func",
")",
"# Keep debug info",
"_utinfo",
"[",
"'src'",
"]",
"=",
"src",
"# Set an internal sig variable that we may use",
"#_wrp_preserve.__sig__ = defsig",
"else",
":",
"# PRESERVES SOME SIGNATURES NO EXEC",
"# signature preservation is turned off. just preserve the name.",
"# Does not use any exec or eval statments.",
"_wrp_preserve",
"=",
"functools",
".",
"update_wrapper",
"(",
"wrapper",
",",
"orig_func",
")",
"# Just do something to preserve signature",
"DEBUG_WRAPPED_DOCSTRING",
"=",
"False",
"if",
"DEBUG_WRAPPED_DOCSTRING",
":",
"new_docstr_fmtstr",
"=",
"util_str",
".",
"codeblock",
"(",
"'''\n Wrapped function {wrap_name}({orig_name})\n\n orig_argspec = {orig_argspec}\n\n orig_docstr = {orig_docstr}\n '''",
")",
"else",
":",
"new_docstr_fmtstr",
"=",
"util_str",
".",
"codeblock",
"(",
"'''\n {orig_docstr}\n '''",
")",
"new_docstr",
"=",
"new_docstr_fmtstr",
".",
"format",
"(",
"wrap_name",
"=",
"wrap_name",
",",
"orig_name",
"=",
"orig_name",
",",
"orig_docstr",
"=",
"orig_docstr",
",",
"orig_argspec",
"=",
"orig_argspec",
")",
"meta_util_six",
".",
"set_funcdoc",
"(",
"_wrp_preserve",
",",
"new_docstr",
")",
"_wrp_preserve",
".",
"_utinfo",
"=",
"_utinfo",
"return",
"_wrp_preserve"
] | Decorates a wrapper function.
It seems impossible to presever signatures in python 2 without eval
(Maybe another option is to write to a temporary module?)
Args:
wrapper: the function wrapping orig_func to change the signature of
orig_func: the original function to take the signature from
References:
http://emptysqua.re/blog/copying-a-python-functions-signature/
https://code.google.com/p/micheles/source/browse/decorator/src/decorator.py
TODO:
checkout funcsigs
https://funcsigs.readthedocs.org/en/latest/
CommandLine:
python -m utool.util_decor --test-preserve_sig
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> #ut.rrrr(False)
>>> def myfunction(self, listinput_, arg1, *args, **kwargs):
>>> " just a test function "
>>> return [x + 1 for x in listinput_]
>>> #orig_func = ut.take
>>> orig_func = myfunction
>>> wrapper = ut.accepts_scalar_input2([0])(orig_func)
>>> _wrp_preserve1 = ut.preserve_sig(wrapper, orig_func, True)
>>> _wrp_preserve2 = ut.preserve_sig(wrapper, orig_func, False)
>>> print('_wrp_preserve2 = %r' % (_wrp_preserve1,))
>>> print('_wrp_preserve2 = %r' % (_wrp_preserve2,))
>>> #print('source _wrp_preserve1 = %s' % (ut.get_func_sourcecode(_wrp_preserve1),))
>>> #print('source _wrp_preserve2 = %s' % (ut.get_func_sourcecode(_wrp_preserve2)),)
>>> result = str(_wrp_preserve1)
>>> print(result) | [
"Decorates",
"a",
"wrapper",
"function",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_decor.py#L788-L935 | train |
kurtbrose/faststat | faststat/faststat.py | _sigfigs | def _sigfigs(n, sigfigs=3):
'helper function to round a number to significant figures'
n = float(n)
if n == 0 or math.isnan(n): # avoid math domain errors
return n
return round(n, -int(math.floor(math.log10(abs(n))) - sigfigs + 1)) | python | def _sigfigs(n, sigfigs=3):
'helper function to round a number to significant figures'
n = float(n)
if n == 0 or math.isnan(n): # avoid math domain errors
return n
return round(n, -int(math.floor(math.log10(abs(n))) - sigfigs + 1)) | [
"def",
"_sigfigs",
"(",
"n",
",",
"sigfigs",
"=",
"3",
")",
":",
"n",
"=",
"float",
"(",
"n",
")",
"if",
"n",
"==",
"0",
"or",
"math",
".",
"isnan",
"(",
"n",
")",
":",
"# avoid math domain errors\r",
"return",
"n",
"return",
"round",
"(",
"n",
",",
"-",
"int",
"(",
"math",
".",
"floor",
"(",
"math",
".",
"log10",
"(",
"abs",
"(",
"n",
")",
")",
")",
"-",
"sigfigs",
"+",
"1",
")",
")"
] | helper function to round a number to significant figures | [
"helper",
"function",
"to",
"round",
"a",
"number",
"to",
"significant",
"figures"
] | 5060c0e10acaafd4a48de3f16869bfccc1deb44a | https://github.com/kurtbrose/faststat/blob/5060c0e10acaafd4a48de3f16869bfccc1deb44a/faststat/faststat.py#L408-L413 | train |
kurtbrose/faststat | faststat/faststat.py | merge_moments | def merge_moments(m_a, m_a2, m_a3, m_a4, n_a, m_b, m_b2, m_b3, m_b4, n_b):
'''
Merge moments of two samples A and B.
parameters are
m_a, ..., m_a4 = first through fourth moment of sample A
n_a = size of sample A
m_b, ..., m_b4 = first through fourth moment of sample B
n_b = size of sample B
'''
delta = m_b - m_a
delta_2 = delta * delta
delta_3 = delta * delta_2
delta_4 = delta * delta_3
n_x = n_a + n_b
m_x = m_a + delta * n_b / n_x
m_x2 = m_a2 + m_b2 + delta_2 * n_a * n_b / n_x
m_x3 = m_a3 + m_b3 + delta_3 * n_a * n_b * (n_a - n_b) + 3 * delta * (n_a * m_2b - n_b * m_2a) / n_x
m_x4 = (m_a4 + m_b4 + delta_4 * (n_a * n_b * (n_a * n_a - n_a * n_b + n_b * n_b)) / (n_x ** 3) +
6 * delta_2 * (n_a * n_a * m_b2 + n_b * n_b * m_a2) / (n_x ** 2) +
4 * delta * (n_a * m_b3 - n_b * m_a3) / n_x )
return m_x, m_x2, m_x3, m_x4, n_x | python | def merge_moments(m_a, m_a2, m_a3, m_a4, n_a, m_b, m_b2, m_b3, m_b4, n_b):
'''
Merge moments of two samples A and B.
parameters are
m_a, ..., m_a4 = first through fourth moment of sample A
n_a = size of sample A
m_b, ..., m_b4 = first through fourth moment of sample B
n_b = size of sample B
'''
delta = m_b - m_a
delta_2 = delta * delta
delta_3 = delta * delta_2
delta_4 = delta * delta_3
n_x = n_a + n_b
m_x = m_a + delta * n_b / n_x
m_x2 = m_a2 + m_b2 + delta_2 * n_a * n_b / n_x
m_x3 = m_a3 + m_b3 + delta_3 * n_a * n_b * (n_a - n_b) + 3 * delta * (n_a * m_2b - n_b * m_2a) / n_x
m_x4 = (m_a4 + m_b4 + delta_4 * (n_a * n_b * (n_a * n_a - n_a * n_b + n_b * n_b)) / (n_x ** 3) +
6 * delta_2 * (n_a * n_a * m_b2 + n_b * n_b * m_a2) / (n_x ** 2) +
4 * delta * (n_a * m_b3 - n_b * m_a3) / n_x )
return m_x, m_x2, m_x3, m_x4, n_x | [
"def",
"merge_moments",
"(",
"m_a",
",",
"m_a2",
",",
"m_a3",
",",
"m_a4",
",",
"n_a",
",",
"m_b",
",",
"m_b2",
",",
"m_b3",
",",
"m_b4",
",",
"n_b",
")",
":",
"delta",
"=",
"m_b",
"-",
"m_a",
"delta_2",
"=",
"delta",
"*",
"delta",
"delta_3",
"=",
"delta",
"*",
"delta_2",
"delta_4",
"=",
"delta",
"*",
"delta_3",
"n_x",
"=",
"n_a",
"+",
"n_b",
"m_x",
"=",
"m_a",
"+",
"delta",
"*",
"n_b",
"/",
"n_x",
"m_x2",
"=",
"m_a2",
"+",
"m_b2",
"+",
"delta_2",
"*",
"n_a",
"*",
"n_b",
"/",
"n_x",
"m_x3",
"=",
"m_a3",
"+",
"m_b3",
"+",
"delta_3",
"*",
"n_a",
"*",
"n_b",
"*",
"(",
"n_a",
"-",
"n_b",
")",
"+",
"3",
"*",
"delta",
"*",
"(",
"n_a",
"*",
"m_2b",
"-",
"n_b",
"*",
"m_2a",
")",
"/",
"n_x",
"m_x4",
"=",
"(",
"m_a4",
"+",
"m_b4",
"+",
"delta_4",
"*",
"(",
"n_a",
"*",
"n_b",
"*",
"(",
"n_a",
"*",
"n_a",
"-",
"n_a",
"*",
"n_b",
"+",
"n_b",
"*",
"n_b",
")",
")",
"/",
"(",
"n_x",
"**",
"3",
")",
"+",
"6",
"*",
"delta_2",
"*",
"(",
"n_a",
"*",
"n_a",
"*",
"m_b2",
"+",
"n_b",
"*",
"n_b",
"*",
"m_a2",
")",
"/",
"(",
"n_x",
"**",
"2",
")",
"+",
"4",
"*",
"delta",
"*",
"(",
"n_a",
"*",
"m_b3",
"-",
"n_b",
"*",
"m_a3",
")",
"/",
"n_x",
")",
"return",
"m_x",
",",
"m_x2",
",",
"m_x3",
",",
"m_x4",
",",
"n_x"
] | Merge moments of two samples A and B.
parameters are
m_a, ..., m_a4 = first through fourth moment of sample A
n_a = size of sample A
m_b, ..., m_b4 = first through fourth moment of sample B
n_b = size of sample B | [
"Merge",
"moments",
"of",
"two",
"samples",
"A",
"and",
"B",
".",
"parameters",
"are",
"m_a",
"...",
"m_a4",
"=",
"first",
"through",
"fourth",
"moment",
"of",
"sample",
"A",
"n_a",
"=",
"size",
"of",
"sample",
"A",
"m_b",
"...",
"m_b4",
"=",
"first",
"through",
"fourth",
"moment",
"of",
"sample",
"B",
"n_b",
"=",
"size",
"of",
"sample",
"B"
] | 5060c0e10acaafd4a48de3f16869bfccc1deb44a | https://github.com/kurtbrose/faststat/blob/5060c0e10acaafd4a48de3f16869bfccc1deb44a/faststat/faststat.py#L416-L436 | train |
kurtbrose/faststat | faststat/faststat.py | Markov._transition | def _transition(self, nxt, cur=None, since=None):
'''
Register that a transition has taken place.
nxt is an identifier for the state being entered.
cur is an identifier for the state being left.
since is the time at which the previous state was entered.
'''
self.transition_intervals[(cur, nxt)].tick()
if since:
self.state_durations[cur].end(since) | python | def _transition(self, nxt, cur=None, since=None):
'''
Register that a transition has taken place.
nxt is an identifier for the state being entered.
cur is an identifier for the state being left.
since is the time at which the previous state was entered.
'''
self.transition_intervals[(cur, nxt)].tick()
if since:
self.state_durations[cur].end(since) | [
"def",
"_transition",
"(",
"self",
",",
"nxt",
",",
"cur",
"=",
"None",
",",
"since",
"=",
"None",
")",
":",
"self",
".",
"transition_intervals",
"[",
"(",
"cur",
",",
"nxt",
")",
"]",
".",
"tick",
"(",
")",
"if",
"since",
":",
"self",
".",
"state_durations",
"[",
"cur",
"]",
".",
"end",
"(",
"since",
")"
] | Register that a transition has taken place.
nxt is an identifier for the state being entered.
cur is an identifier for the state being left.
since is the time at which the previous state was entered. | [
"Register",
"that",
"a",
"transition",
"has",
"taken",
"place",
".",
"nxt",
"is",
"an",
"identifier",
"for",
"the",
"state",
"being",
"entered",
".",
"cur",
"is",
"an",
"identifier",
"for",
"the",
"state",
"being",
"left",
".",
"since",
"is",
"the",
"time",
"at",
"which",
"the",
"previous",
"state",
"was",
"entered",
"."
] | 5060c0e10acaafd4a48de3f16869bfccc1deb44a | https://github.com/kurtbrose/faststat/blob/5060c0e10acaafd4a48de3f16869bfccc1deb44a/faststat/faststat.py#L235-L244 | train |
kurtbrose/faststat | faststat/faststat.py | Markov._cleanup | def _cleanup(self, ref):
'cleanup after a transitor weakref fires'
self.transitor_states[self._weakref_holder[ref]] -= 1
del self._weakref_holder[ref] | python | def _cleanup(self, ref):
'cleanup after a transitor weakref fires'
self.transitor_states[self._weakref_holder[ref]] -= 1
del self._weakref_holder[ref] | [
"def",
"_cleanup",
"(",
"self",
",",
"ref",
")",
":",
"self",
".",
"transitor_states",
"[",
"self",
".",
"_weakref_holder",
"[",
"ref",
"]",
"]",
"-=",
"1",
"del",
"self",
".",
"_weakref_holder",
"[",
"ref",
"]"
] | cleanup after a transitor weakref fires | [
"cleanup",
"after",
"a",
"transitor",
"weakref",
"fires"
] | 5060c0e10acaafd4a48de3f16869bfccc1deb44a | https://github.com/kurtbrose/faststat/blob/5060c0e10acaafd4a48de3f16869bfccc1deb44a/faststat/faststat.py#L252-L255 | train |
kurtbrose/faststat | faststat/faststat.py | PathStats._commit | def _commit(self, ref):
'commit a walkers data after it is collected'
path_times = self._weakref_path_map[ref]
path_times.append(nanotime())
del self._weakref_path_map[ref]
path = tuple(path_times[1::2])
times = path_times[::2]
if path not in self.path_stats:
# tuple to save a tiny bit of memory
self.path_stats[path] = tuple([
Duration(interval=False) for i in range(len(path))])
path_stats = self.path_stats[path]
for i in range(1, len(times)):
path_stats[i - 1]._stats.add(times[i] - times[i - 1]) | python | def _commit(self, ref):
'commit a walkers data after it is collected'
path_times = self._weakref_path_map[ref]
path_times.append(nanotime())
del self._weakref_path_map[ref]
path = tuple(path_times[1::2])
times = path_times[::2]
if path not in self.path_stats:
# tuple to save a tiny bit of memory
self.path_stats[path] = tuple([
Duration(interval=False) for i in range(len(path))])
path_stats = self.path_stats[path]
for i in range(1, len(times)):
path_stats[i - 1]._stats.add(times[i] - times[i - 1]) | [
"def",
"_commit",
"(",
"self",
",",
"ref",
")",
":",
"path_times",
"=",
"self",
".",
"_weakref_path_map",
"[",
"ref",
"]",
"path_times",
".",
"append",
"(",
"nanotime",
"(",
")",
")",
"del",
"self",
".",
"_weakref_path_map",
"[",
"ref",
"]",
"path",
"=",
"tuple",
"(",
"path_times",
"[",
"1",
":",
":",
"2",
"]",
")",
"times",
"=",
"path_times",
"[",
":",
":",
"2",
"]",
"if",
"path",
"not",
"in",
"self",
".",
"path_stats",
":",
"# tuple to save a tiny bit of memory\r",
"self",
".",
"path_stats",
"[",
"path",
"]",
"=",
"tuple",
"(",
"[",
"Duration",
"(",
"interval",
"=",
"False",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"path",
")",
")",
"]",
")",
"path_stats",
"=",
"self",
".",
"path_stats",
"[",
"path",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"times",
")",
")",
":",
"path_stats",
"[",
"i",
"-",
"1",
"]",
".",
"_stats",
".",
"add",
"(",
"times",
"[",
"i",
"]",
"-",
"times",
"[",
"i",
"-",
"1",
"]",
")"
] | commit a walkers data after it is collected | [
"commit",
"a",
"walkers",
"data",
"after",
"it",
"is",
"collected"
] | 5060c0e10acaafd4a48de3f16869bfccc1deb44a | https://github.com/kurtbrose/faststat/blob/5060c0e10acaafd4a48de3f16869bfccc1deb44a/faststat/faststat.py#L310-L323 | train |
kurtbrose/faststat | faststat/faststat.py | PathStats.pformat | def pformat(self, prefix=()):
'''
Makes a pretty ASCII format of the data, suitable for
displaying in a console or saving to a text file.
Returns a list of lines.
'''
nan = float("nan")
def sformat(segment, stat):
FMT = "n={0}, mean={1}, p50/95={2}/{3}, max={4}"
line_segs = [segment]
for s in [stat]:
p = s.get_percentiles()
p50, p95 = p.get(0.50, nan), p.get(0.95, nan)
line_segs.append(FMT.format(s.n, s.mean, p50, p95, s.max))
return '{0}: {1}'.format(*line_segs)
lines = []
for path in sorted(self.path_stats.keys()):
lines.append('=====================')
for seg, stat in zip(path, self.path_stats[path]):
lines.append(sformat(seg, stat))
return lines | python | def pformat(self, prefix=()):
'''
Makes a pretty ASCII format of the data, suitable for
displaying in a console or saving to a text file.
Returns a list of lines.
'''
nan = float("nan")
def sformat(segment, stat):
FMT = "n={0}, mean={1}, p50/95={2}/{3}, max={4}"
line_segs = [segment]
for s in [stat]:
p = s.get_percentiles()
p50, p95 = p.get(0.50, nan), p.get(0.95, nan)
line_segs.append(FMT.format(s.n, s.mean, p50, p95, s.max))
return '{0}: {1}'.format(*line_segs)
lines = []
for path in sorted(self.path_stats.keys()):
lines.append('=====================')
for seg, stat in zip(path, self.path_stats[path]):
lines.append(sformat(seg, stat))
return lines | [
"def",
"pformat",
"(",
"self",
",",
"prefix",
"=",
"(",
")",
")",
":",
"nan",
"=",
"float",
"(",
"\"nan\"",
")",
"def",
"sformat",
"(",
"segment",
",",
"stat",
")",
":",
"FMT",
"=",
"\"n={0}, mean={1}, p50/95={2}/{3}, max={4}\"",
"line_segs",
"=",
"[",
"segment",
"]",
"for",
"s",
"in",
"[",
"stat",
"]",
":",
"p",
"=",
"s",
".",
"get_percentiles",
"(",
")",
"p50",
",",
"p95",
"=",
"p",
".",
"get",
"(",
"0.50",
",",
"nan",
")",
",",
"p",
".",
"get",
"(",
"0.95",
",",
"nan",
")",
"line_segs",
".",
"append",
"(",
"FMT",
".",
"format",
"(",
"s",
".",
"n",
",",
"s",
".",
"mean",
",",
"p50",
",",
"p95",
",",
"s",
".",
"max",
")",
")",
"return",
"'{0}: {1}'",
".",
"format",
"(",
"*",
"line_segs",
")",
"lines",
"=",
"[",
"]",
"for",
"path",
"in",
"sorted",
"(",
"self",
".",
"path_stats",
".",
"keys",
"(",
")",
")",
":",
"lines",
".",
"append",
"(",
"'====================='",
")",
"for",
"seg",
",",
"stat",
"in",
"zip",
"(",
"path",
",",
"self",
".",
"path_stats",
"[",
"path",
"]",
")",
":",
"lines",
".",
"append",
"(",
"sformat",
"(",
"seg",
",",
"stat",
")",
")",
"return",
"lines"
] | Makes a pretty ASCII format of the data, suitable for
displaying in a console or saving to a text file.
Returns a list of lines. | [
"Makes",
"a",
"pretty",
"ASCII",
"format",
"of",
"the",
"data",
"suitable",
"for",
"displaying",
"in",
"a",
"console",
"or",
"saving",
"to",
"a",
"text",
"file",
".",
"Returns",
"a",
"list",
"of",
"lines",
"."
] | 5060c0e10acaafd4a48de3f16869bfccc1deb44a | https://github.com/kurtbrose/faststat/blob/5060c0e10acaafd4a48de3f16869bfccc1deb44a/faststat/faststat.py#L325-L347 | train |
glormph/msstitch | src/app/readers/openms.py | specfn_quant_generator | def specfn_quant_generator(specfiles, quantfiles, tag, ignore_tags):
"""Generates tuples of specfile and quant element for general formats"""
for specfn, qfn in zip(specfiles, quantfiles):
for quant_el in basereader.generate_xmltags(qfn, tag, ignore_tags):
yield os.path.basename(specfn), quant_el | python | def specfn_quant_generator(specfiles, quantfiles, tag, ignore_tags):
"""Generates tuples of specfile and quant element for general formats"""
for specfn, qfn in zip(specfiles, quantfiles):
for quant_el in basereader.generate_xmltags(qfn, tag, ignore_tags):
yield os.path.basename(specfn), quant_el | [
"def",
"specfn_quant_generator",
"(",
"specfiles",
",",
"quantfiles",
",",
"tag",
",",
"ignore_tags",
")",
":",
"for",
"specfn",
",",
"qfn",
"in",
"zip",
"(",
"specfiles",
",",
"quantfiles",
")",
":",
"for",
"quant_el",
"in",
"basereader",
".",
"generate_xmltags",
"(",
"qfn",
",",
"tag",
",",
"ignore_tags",
")",
":",
"yield",
"os",
".",
"path",
".",
"basename",
"(",
"specfn",
")",
",",
"quant_el"
] | Generates tuples of specfile and quant element for general formats | [
"Generates",
"tuples",
"of",
"specfile",
"and",
"quant",
"element",
"for",
"general",
"formats"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/openms.py#L5-L9 | train |
glormph/msstitch | src/app/readers/openms.py | get_feature_info | def get_feature_info(feature):
"""Returns a dict with feature information"""
dimensions = feature.findall('position')
for dim in dimensions:
if dim.attrib['dim'] == '0':
rt = dim.text
elif dim.attrib['dim'] == '1':
mz = dim.text
return {'rt': float(rt), 'mz': float(mz),
'charge': int(feature.find('charge').text),
'intensity': float(feature.find('intensity').text),
} | python | def get_feature_info(feature):
"""Returns a dict with feature information"""
dimensions = feature.findall('position')
for dim in dimensions:
if dim.attrib['dim'] == '0':
rt = dim.text
elif dim.attrib['dim'] == '1':
mz = dim.text
return {'rt': float(rt), 'mz': float(mz),
'charge': int(feature.find('charge').text),
'intensity': float(feature.find('intensity').text),
} | [
"def",
"get_feature_info",
"(",
"feature",
")",
":",
"dimensions",
"=",
"feature",
".",
"findall",
"(",
"'position'",
")",
"for",
"dim",
"in",
"dimensions",
":",
"if",
"dim",
".",
"attrib",
"[",
"'dim'",
"]",
"==",
"'0'",
":",
"rt",
"=",
"dim",
".",
"text",
"elif",
"dim",
".",
"attrib",
"[",
"'dim'",
"]",
"==",
"'1'",
":",
"mz",
"=",
"dim",
".",
"text",
"return",
"{",
"'rt'",
":",
"float",
"(",
"rt",
")",
",",
"'mz'",
":",
"float",
"(",
"mz",
")",
",",
"'charge'",
":",
"int",
"(",
"feature",
".",
"find",
"(",
"'charge'",
")",
".",
"text",
")",
",",
"'intensity'",
":",
"float",
"(",
"feature",
".",
"find",
"(",
"'intensity'",
")",
".",
"text",
")",
",",
"}"
] | Returns a dict with feature information | [
"Returns",
"a",
"dict",
"with",
"feature",
"information"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/openms.py#L31-L42 | train |
LEMS/pylems | lems/base/util.py | merge_maps | def merge_maps(m, base):
"""
Merge in undefined map entries from given map.
@param m: Map to be merged into.
@type m: lems.util.Map
@param base: Map to be merged into.
@type base: lems.util.Map
"""
for k in base.keys():
if k not in m:
m[k] = base[k] | python | def merge_maps(m, base):
"""
Merge in undefined map entries from given map.
@param m: Map to be merged into.
@type m: lems.util.Map
@param base: Map to be merged into.
@type base: lems.util.Map
"""
for k in base.keys():
if k not in m:
m[k] = base[k] | [
"def",
"merge_maps",
"(",
"m",
",",
"base",
")",
":",
"for",
"k",
"in",
"base",
".",
"keys",
"(",
")",
":",
"if",
"k",
"not",
"in",
"m",
":",
"m",
"[",
"k",
"]",
"=",
"base",
"[",
"k",
"]"
] | Merge in undefined map entries from given map.
@param m: Map to be merged into.
@type m: lems.util.Map
@param base: Map to be merged into.
@type base: lems.util.Map | [
"Merge",
"in",
"undefined",
"map",
"entries",
"from",
"given",
"map",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/base/util.py#L16-L29 | train |
LEMS/pylems | lems/base/util.py | merge_lists | def merge_lists(l, base):
"""
Merge in undefined list entries from given list.
@param l: List to be merged into.
@type l: list
@param base: List to be merged into.
@type base: list
"""
for i in base:
if i not in l:
l.append(i) | python | def merge_lists(l, base):
"""
Merge in undefined list entries from given list.
@param l: List to be merged into.
@type l: list
@param base: List to be merged into.
@type base: list
"""
for i in base:
if i not in l:
l.append(i) | [
"def",
"merge_lists",
"(",
"l",
",",
"base",
")",
":",
"for",
"i",
"in",
"base",
":",
"if",
"i",
"not",
"in",
"l",
":",
"l",
".",
"append",
"(",
"i",
")"
] | Merge in undefined list entries from given list.
@param l: List to be merged into.
@type l: list
@param base: List to be merged into.
@type base: list | [
"Merge",
"in",
"undefined",
"list",
"entries",
"from",
"given",
"list",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/base/util.py#L31-L44 | train |
glormph/msstitch | src/app/actions/prottable/precursorarea.py | generate_top_psms | def generate_top_psms(psms, protcol):
"""Fed with a psms generator, this returns the 3 PSMs with
the highest precursor intensities (or areas, or whatever is
given in the HEADER_PRECURSOR_QUANT"""
top_ms1_psms = {}
for psm in psms:
protacc = psm[protcol]
precursor_amount = psm[mzidtsvdata.HEADER_PRECURSOR_QUANT]
if ';' in protacc or precursor_amount == 'NA':
continue
precursor_amount = float(precursor_amount)
psm_seq = psm[mzidtsvdata.HEADER_PEPTIDE]
try:
peptide_area = top_ms1_psms[protacc][psm_seq]
except KeyError:
try:
top_ms1_psms[protacc][psm_seq] = precursor_amount
except KeyError:
top_ms1_psms[protacc] = {psm_seq: precursor_amount}
else:
if precursor_amount > peptide_area:
top_ms1_psms[protacc][psm_seq] = precursor_amount
return top_ms1_psms | python | def generate_top_psms(psms, protcol):
"""Fed with a psms generator, this returns the 3 PSMs with
the highest precursor intensities (or areas, or whatever is
given in the HEADER_PRECURSOR_QUANT"""
top_ms1_psms = {}
for psm in psms:
protacc = psm[protcol]
precursor_amount = psm[mzidtsvdata.HEADER_PRECURSOR_QUANT]
if ';' in protacc or precursor_amount == 'NA':
continue
precursor_amount = float(precursor_amount)
psm_seq = psm[mzidtsvdata.HEADER_PEPTIDE]
try:
peptide_area = top_ms1_psms[protacc][psm_seq]
except KeyError:
try:
top_ms1_psms[protacc][psm_seq] = precursor_amount
except KeyError:
top_ms1_psms[protacc] = {psm_seq: precursor_amount}
else:
if precursor_amount > peptide_area:
top_ms1_psms[protacc][psm_seq] = precursor_amount
return top_ms1_psms | [
"def",
"generate_top_psms",
"(",
"psms",
",",
"protcol",
")",
":",
"top_ms1_psms",
"=",
"{",
"}",
"for",
"psm",
"in",
"psms",
":",
"protacc",
"=",
"psm",
"[",
"protcol",
"]",
"precursor_amount",
"=",
"psm",
"[",
"mzidtsvdata",
".",
"HEADER_PRECURSOR_QUANT",
"]",
"if",
"';'",
"in",
"protacc",
"or",
"precursor_amount",
"==",
"'NA'",
":",
"continue",
"precursor_amount",
"=",
"float",
"(",
"precursor_amount",
")",
"psm_seq",
"=",
"psm",
"[",
"mzidtsvdata",
".",
"HEADER_PEPTIDE",
"]",
"try",
":",
"peptide_area",
"=",
"top_ms1_psms",
"[",
"protacc",
"]",
"[",
"psm_seq",
"]",
"except",
"KeyError",
":",
"try",
":",
"top_ms1_psms",
"[",
"protacc",
"]",
"[",
"psm_seq",
"]",
"=",
"precursor_amount",
"except",
"KeyError",
":",
"top_ms1_psms",
"[",
"protacc",
"]",
"=",
"{",
"psm_seq",
":",
"precursor_amount",
"}",
"else",
":",
"if",
"precursor_amount",
">",
"peptide_area",
":",
"top_ms1_psms",
"[",
"protacc",
"]",
"[",
"psm_seq",
"]",
"=",
"precursor_amount",
"return",
"top_ms1_psms"
] | Fed with a psms generator, this returns the 3 PSMs with
the highest precursor intensities (or areas, or whatever is
given in the HEADER_PRECURSOR_QUANT | [
"Fed",
"with",
"a",
"psms",
"generator",
"this",
"returns",
"the",
"3",
"PSMs",
"with",
"the",
"highest",
"precursor",
"intensities",
"(",
"or",
"areas",
"or",
"whatever",
"is",
"given",
"in",
"the",
"HEADER_PRECURSOR_QUANT"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/prottable/precursorarea.py#L5-L27 | train |
glormph/msstitch | src/app/actions/prottable/precursorarea.py | add_ms1_quant_from_top3_mzidtsv | def add_ms1_quant_from_top3_mzidtsv(proteins, psms, headerfields, protcol):
"""Collects PSMs with the highes precursor quant values,
adds sum of the top 3 of these to a protein table"""
if not protcol:
protcol = mzidtsvdata.HEADER_MASTER_PROT
top_ms1_psms = generate_top_psms(psms, protcol)
for protein in proteins:
prot_acc = protein[prottabledata.HEADER_PROTEIN]
prec_area = calculate_protein_precursor_quant(top_ms1_psms, prot_acc)
outprotein = {k: v for k, v in protein.items()}
outprotein[headerfields['precursorquant'][
prottabledata.HEADER_AREA][None]] = str(prec_area)
yield outprotein | python | def add_ms1_quant_from_top3_mzidtsv(proteins, psms, headerfields, protcol):
"""Collects PSMs with the highes precursor quant values,
adds sum of the top 3 of these to a protein table"""
if not protcol:
protcol = mzidtsvdata.HEADER_MASTER_PROT
top_ms1_psms = generate_top_psms(psms, protcol)
for protein in proteins:
prot_acc = protein[prottabledata.HEADER_PROTEIN]
prec_area = calculate_protein_precursor_quant(top_ms1_psms, prot_acc)
outprotein = {k: v for k, v in protein.items()}
outprotein[headerfields['precursorquant'][
prottabledata.HEADER_AREA][None]] = str(prec_area)
yield outprotein | [
"def",
"add_ms1_quant_from_top3_mzidtsv",
"(",
"proteins",
",",
"psms",
",",
"headerfields",
",",
"protcol",
")",
":",
"if",
"not",
"protcol",
":",
"protcol",
"=",
"mzidtsvdata",
".",
"HEADER_MASTER_PROT",
"top_ms1_psms",
"=",
"generate_top_psms",
"(",
"psms",
",",
"protcol",
")",
"for",
"protein",
"in",
"proteins",
":",
"prot_acc",
"=",
"protein",
"[",
"prottabledata",
".",
"HEADER_PROTEIN",
"]",
"prec_area",
"=",
"calculate_protein_precursor_quant",
"(",
"top_ms1_psms",
",",
"prot_acc",
")",
"outprotein",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"protein",
".",
"items",
"(",
")",
"}",
"outprotein",
"[",
"headerfields",
"[",
"'precursorquant'",
"]",
"[",
"prottabledata",
".",
"HEADER_AREA",
"]",
"[",
"None",
"]",
"]",
"=",
"str",
"(",
"prec_area",
")",
"yield",
"outprotein"
] | Collects PSMs with the highes precursor quant values,
adds sum of the top 3 of these to a protein table | [
"Collects",
"PSMs",
"with",
"the",
"highes",
"precursor",
"quant",
"values",
"adds",
"sum",
"of",
"the",
"top",
"3",
"of",
"these",
"to",
"a",
"protein",
"table"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/prottable/precursorarea.py#L40-L52 | train |
Erotemic/utool | utool/util_time.py | toc | def toc(tt, return_msg=False, write_msg=True, verbose=None):
"""
similar to matlab toc
SeeAlso:
ut.tic
"""
if verbose is not None:
write_msg = verbose
(msg, start_time) = tt
ellapsed = (default_timer() - start_time)
if (not return_msg) and write_msg and msg is not None:
sys.stdout.write('...toc(%.4fs, ' % ellapsed + '"' + str(msg) + '"' + ')\n')
if return_msg:
return msg
else:
return ellapsed | python | def toc(tt, return_msg=False, write_msg=True, verbose=None):
"""
similar to matlab toc
SeeAlso:
ut.tic
"""
if verbose is not None:
write_msg = verbose
(msg, start_time) = tt
ellapsed = (default_timer() - start_time)
if (not return_msg) and write_msg and msg is not None:
sys.stdout.write('...toc(%.4fs, ' % ellapsed + '"' + str(msg) + '"' + ')\n')
if return_msg:
return msg
else:
return ellapsed | [
"def",
"toc",
"(",
"tt",
",",
"return_msg",
"=",
"False",
",",
"write_msg",
"=",
"True",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"verbose",
"is",
"not",
"None",
":",
"write_msg",
"=",
"verbose",
"(",
"msg",
",",
"start_time",
")",
"=",
"tt",
"ellapsed",
"=",
"(",
"default_timer",
"(",
")",
"-",
"start_time",
")",
"if",
"(",
"not",
"return_msg",
")",
"and",
"write_msg",
"and",
"msg",
"is",
"not",
"None",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'...toc(%.4fs, '",
"%",
"ellapsed",
"+",
"'\"'",
"+",
"str",
"(",
"msg",
")",
"+",
"'\"'",
"+",
"')\\n'",
")",
"if",
"return_msg",
":",
"return",
"msg",
"else",
":",
"return",
"ellapsed"
] | similar to matlab toc
SeeAlso:
ut.tic | [
"similar",
"to",
"matlab",
"toc"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_time.py#L42-L58 | train |
Erotemic/utool | utool/util_time.py | parse_timestamp | def parse_timestamp(timestamp, zone='UTC', timestamp_format=None):
r"""
pip install delorean
Args:
timestamp (str): timestampe string
zone (bool): assumes input is zone (only if not specified) and gives
output in zone.
CommandLine:
python -m utool.util_time --test-parse_timestamp
python -m utool.util_time parse_timestamp
Example0:
>>> # ENABLE_DOCTEST
>>> from utool.util_time import * # NOQA
>>> import utool as ut
>>> utc = True
>>> timestampe_format = None
>>> timestamps = [
>>> ('2015:04:01 00:00:00',),
>>> ('2005-10-27T14:35:20+02:00',),
>>> ('2000-01-01T09:00:00-05:00', 'UTC'),
>>> ('2000-01-01T09:00:00-05:00', 'EST'),
>>> ('2000-01-01T09:00:00', 'EST'),
>>> ('2000-01-01T09:00:00', 'UTC'),
>>> ('6:35:01\x002006:03:19 1',),
>>> ('2016/08/18 10:51:02 EST',),
>>> ('2016-08-18T10:51:02-05:00',),
>>> ]
>>> timestamp = timestamps[-1][0]
>>> dn_list = [parse_timestamp(*args) for args in timestamps]
>>> result = ut.NEWLINE.join([str(dn) for dn in dn_list])
>>> print(result)
2015-04-01 00:00:00+00:00
2005-10-27 12:35:20+00:00
2000-01-01 14:00:00+00:00
2000-01-01 09:00:00-05:00
2000-01-01 09:00:00-05:00
2000-01-01 09:00:00+00:00
2006-03-19 06:35:01+00:00
2016-08-18 15:51:02+00:00
2016-08-18 15:51:02+00:00
"""
if timestamp is None:
return None
use_delorean = True or six.PY2
if use_delorean:
import delorean
## customize delorean string method
#def __str__(self):
# return str(self.datetime)
# #return str(self.datetime) + ' ' + str(self.timezone)
#delorean.Delorean.__str__ = __str__
## method types must be injected into the class
##ut.inject_func_as_method(dn, __str__, '__repr__', override=True)
if not isinstance(timestamp, six.string_types):
raise NotImplementedError('Unknown format: timestamp=%r' % (timestamp,))
# Normal format, or non-standard year first data
if timestamp_format is None:
# dont warn because we will take care of utc
timefmt = determine_timestamp_format(timestamp, warn=False)
else:
timefmt = timestamp_format
if timefmt is None or not isinstance(timefmt, six.string_types):
raise AssertionError('unknown timestamp_format=%r' % (timestamp_format,))
# Fixup timestamp
utc_offset = None
if len(timestamp) == 20 and '\x00' in timestamp:
timestamp_ = timestamp.replace('\x00', ' ').strip(';').strip()
elif use_delorean and len(timestamp) > 19:
timestamp_ = timestamp[:19].strip(';').strip()
utc_offset = timestamp[19:]
else:
timestamp_ = timestamp
dt_ = datetime.datetime.strptime(timestamp_, timefmt)
if use_delorean:
#if utc and utc_offset is not None:
#if utc:
# dn_ = delorean.Delorean(dt_, 'UTC')
#else:
if zone is None:
zone = time.tzname[0]
if zone == 'local':
zone = time.tzname[0]
dn_ = delorean.Delorean(dt_, zone)
else:
dn_ = dt_
if utc_offset is not None and zone == 'UTC':
if use_delorean:
# Python 2.7 does not account for timezones
if ':' in utc_offset:
sign = {' ': +1, '+': +1, '-': -1}[utc_offset[0]]
hours, seconds = utc_offset[1:].split(':')
delta_ = datetime.timedelta(hours=int(hours), seconds=int(seconds))
delta = sign * delta_
else:
import pytz
tzname = utc_offset.strip()
delta = pytz.timezone(tzname).utcoffset(dt_)
# Move back to utc
dn = dn_ - delta
else:
raise AssertionError('python3 should take care of timezone')
else:
dn = dn_
if use_delorean:
if not zone != 'UTC':
dn.shift(zone)
return dn.datetime | python | def parse_timestamp(timestamp, zone='UTC', timestamp_format=None):
r"""
pip install delorean
Args:
timestamp (str): timestampe string
zone (bool): assumes input is zone (only if not specified) and gives
output in zone.
CommandLine:
python -m utool.util_time --test-parse_timestamp
python -m utool.util_time parse_timestamp
Example0:
>>> # ENABLE_DOCTEST
>>> from utool.util_time import * # NOQA
>>> import utool as ut
>>> utc = True
>>> timestampe_format = None
>>> timestamps = [
>>> ('2015:04:01 00:00:00',),
>>> ('2005-10-27T14:35:20+02:00',),
>>> ('2000-01-01T09:00:00-05:00', 'UTC'),
>>> ('2000-01-01T09:00:00-05:00', 'EST'),
>>> ('2000-01-01T09:00:00', 'EST'),
>>> ('2000-01-01T09:00:00', 'UTC'),
>>> ('6:35:01\x002006:03:19 1',),
>>> ('2016/08/18 10:51:02 EST',),
>>> ('2016-08-18T10:51:02-05:00',),
>>> ]
>>> timestamp = timestamps[-1][0]
>>> dn_list = [parse_timestamp(*args) for args in timestamps]
>>> result = ut.NEWLINE.join([str(dn) for dn in dn_list])
>>> print(result)
2015-04-01 00:00:00+00:00
2005-10-27 12:35:20+00:00
2000-01-01 14:00:00+00:00
2000-01-01 09:00:00-05:00
2000-01-01 09:00:00-05:00
2000-01-01 09:00:00+00:00
2006-03-19 06:35:01+00:00
2016-08-18 15:51:02+00:00
2016-08-18 15:51:02+00:00
"""
if timestamp is None:
return None
use_delorean = True or six.PY2
if use_delorean:
import delorean
## customize delorean string method
#def __str__(self):
# return str(self.datetime)
# #return str(self.datetime) + ' ' + str(self.timezone)
#delorean.Delorean.__str__ = __str__
## method types must be injected into the class
##ut.inject_func_as_method(dn, __str__, '__repr__', override=True)
if not isinstance(timestamp, six.string_types):
raise NotImplementedError('Unknown format: timestamp=%r' % (timestamp,))
# Normal format, or non-standard year first data
if timestamp_format is None:
# dont warn because we will take care of utc
timefmt = determine_timestamp_format(timestamp, warn=False)
else:
timefmt = timestamp_format
if timefmt is None or not isinstance(timefmt, six.string_types):
raise AssertionError('unknown timestamp_format=%r' % (timestamp_format,))
# Fixup timestamp
utc_offset = None
if len(timestamp) == 20 and '\x00' in timestamp:
timestamp_ = timestamp.replace('\x00', ' ').strip(';').strip()
elif use_delorean and len(timestamp) > 19:
timestamp_ = timestamp[:19].strip(';').strip()
utc_offset = timestamp[19:]
else:
timestamp_ = timestamp
dt_ = datetime.datetime.strptime(timestamp_, timefmt)
if use_delorean:
#if utc and utc_offset is not None:
#if utc:
# dn_ = delorean.Delorean(dt_, 'UTC')
#else:
if zone is None:
zone = time.tzname[0]
if zone == 'local':
zone = time.tzname[0]
dn_ = delorean.Delorean(dt_, zone)
else:
dn_ = dt_
if utc_offset is not None and zone == 'UTC':
if use_delorean:
# Python 2.7 does not account for timezones
if ':' in utc_offset:
sign = {' ': +1, '+': +1, '-': -1}[utc_offset[0]]
hours, seconds = utc_offset[1:].split(':')
delta_ = datetime.timedelta(hours=int(hours), seconds=int(seconds))
delta = sign * delta_
else:
import pytz
tzname = utc_offset.strip()
delta = pytz.timezone(tzname).utcoffset(dt_)
# Move back to utc
dn = dn_ - delta
else:
raise AssertionError('python3 should take care of timezone')
else:
dn = dn_
if use_delorean:
if not zone != 'UTC':
dn.shift(zone)
return dn.datetime | [
"def",
"parse_timestamp",
"(",
"timestamp",
",",
"zone",
"=",
"'UTC'",
",",
"timestamp_format",
"=",
"None",
")",
":",
"if",
"timestamp",
"is",
"None",
":",
"return",
"None",
"use_delorean",
"=",
"True",
"or",
"six",
".",
"PY2",
"if",
"use_delorean",
":",
"import",
"delorean",
"## customize delorean string method",
"#def __str__(self):",
"# return str(self.datetime)",
"# #return str(self.datetime) + ' ' + str(self.timezone)",
"#delorean.Delorean.__str__ = __str__",
"## method types must be injected into the class",
"##ut.inject_func_as_method(dn, __str__, '__repr__', override=True)",
"if",
"not",
"isinstance",
"(",
"timestamp",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Unknown format: timestamp=%r'",
"%",
"(",
"timestamp",
",",
")",
")",
"# Normal format, or non-standard year first data",
"if",
"timestamp_format",
"is",
"None",
":",
"# dont warn because we will take care of utc",
"timefmt",
"=",
"determine_timestamp_format",
"(",
"timestamp",
",",
"warn",
"=",
"False",
")",
"else",
":",
"timefmt",
"=",
"timestamp_format",
"if",
"timefmt",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"timefmt",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"AssertionError",
"(",
"'unknown timestamp_format=%r'",
"%",
"(",
"timestamp_format",
",",
")",
")",
"# Fixup timestamp",
"utc_offset",
"=",
"None",
"if",
"len",
"(",
"timestamp",
")",
"==",
"20",
"and",
"'\\x00'",
"in",
"timestamp",
":",
"timestamp_",
"=",
"timestamp",
".",
"replace",
"(",
"'\\x00'",
",",
"' '",
")",
".",
"strip",
"(",
"';'",
")",
".",
"strip",
"(",
")",
"elif",
"use_delorean",
"and",
"len",
"(",
"timestamp",
")",
">",
"19",
":",
"timestamp_",
"=",
"timestamp",
"[",
":",
"19",
"]",
".",
"strip",
"(",
"';'",
")",
".",
"strip",
"(",
")",
"utc_offset",
"=",
"timestamp",
"[",
"19",
":",
"]",
"else",
":",
"timestamp_",
"=",
"timestamp",
"dt_",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"timestamp_",
",",
"timefmt",
")",
"if",
"use_delorean",
":",
"#if utc and utc_offset is not None:",
"#if utc:",
"# dn_ = delorean.Delorean(dt_, 'UTC')",
"#else:",
"if",
"zone",
"is",
"None",
":",
"zone",
"=",
"time",
".",
"tzname",
"[",
"0",
"]",
"if",
"zone",
"==",
"'local'",
":",
"zone",
"=",
"time",
".",
"tzname",
"[",
"0",
"]",
"dn_",
"=",
"delorean",
".",
"Delorean",
"(",
"dt_",
",",
"zone",
")",
"else",
":",
"dn_",
"=",
"dt_",
"if",
"utc_offset",
"is",
"not",
"None",
"and",
"zone",
"==",
"'UTC'",
":",
"if",
"use_delorean",
":",
"# Python 2.7 does not account for timezones",
"if",
"':'",
"in",
"utc_offset",
":",
"sign",
"=",
"{",
"' '",
":",
"+",
"1",
",",
"'+'",
":",
"+",
"1",
",",
"'-'",
":",
"-",
"1",
"}",
"[",
"utc_offset",
"[",
"0",
"]",
"]",
"hours",
",",
"seconds",
"=",
"utc_offset",
"[",
"1",
":",
"]",
".",
"split",
"(",
"':'",
")",
"delta_",
"=",
"datetime",
".",
"timedelta",
"(",
"hours",
"=",
"int",
"(",
"hours",
")",
",",
"seconds",
"=",
"int",
"(",
"seconds",
")",
")",
"delta",
"=",
"sign",
"*",
"delta_",
"else",
":",
"import",
"pytz",
"tzname",
"=",
"utc_offset",
".",
"strip",
"(",
")",
"delta",
"=",
"pytz",
".",
"timezone",
"(",
"tzname",
")",
".",
"utcoffset",
"(",
"dt_",
")",
"# Move back to utc",
"dn",
"=",
"dn_",
"-",
"delta",
"else",
":",
"raise",
"AssertionError",
"(",
"'python3 should take care of timezone'",
")",
"else",
":",
"dn",
"=",
"dn_",
"if",
"use_delorean",
":",
"if",
"not",
"zone",
"!=",
"'UTC'",
":",
"dn",
".",
"shift",
"(",
"zone",
")",
"return",
"dn",
".",
"datetime"
] | r"""
pip install delorean
Args:
timestamp (str): timestampe string
zone (bool): assumes input is zone (only if not specified) and gives
output in zone.
CommandLine:
python -m utool.util_time --test-parse_timestamp
python -m utool.util_time parse_timestamp
Example0:
>>> # ENABLE_DOCTEST
>>> from utool.util_time import * # NOQA
>>> import utool as ut
>>> utc = True
>>> timestampe_format = None
>>> timestamps = [
>>> ('2015:04:01 00:00:00',),
>>> ('2005-10-27T14:35:20+02:00',),
>>> ('2000-01-01T09:00:00-05:00', 'UTC'),
>>> ('2000-01-01T09:00:00-05:00', 'EST'),
>>> ('2000-01-01T09:00:00', 'EST'),
>>> ('2000-01-01T09:00:00', 'UTC'),
>>> ('6:35:01\x002006:03:19 1',),
>>> ('2016/08/18 10:51:02 EST',),
>>> ('2016-08-18T10:51:02-05:00',),
>>> ]
>>> timestamp = timestamps[-1][0]
>>> dn_list = [parse_timestamp(*args) for args in timestamps]
>>> result = ut.NEWLINE.join([str(dn) for dn in dn_list])
>>> print(result)
2015-04-01 00:00:00+00:00
2005-10-27 12:35:20+00:00
2000-01-01 14:00:00+00:00
2000-01-01 09:00:00-05:00
2000-01-01 09:00:00-05:00
2000-01-01 09:00:00+00:00
2006-03-19 06:35:01+00:00
2016-08-18 15:51:02+00:00
2016-08-18 15:51:02+00:00 | [
"r",
"pip",
"install",
"delorean"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_time.py#L447-L563 | train |
Erotemic/utool | utool/util_time.py | date_to_datetime | def date_to_datetime(date, fraction=0.0):
"""
fraction is how much through the day you are. 0=start of the day, 1=end of the day.
"""
day_seconds = (60 * 60 * 24) - 1
total_seconds = int(day_seconds * fraction)
delta = datetime.timedelta(seconds=total_seconds)
time = datetime.time()
dt = datetime.datetime.combine(date, time) + delta
return dt | python | def date_to_datetime(date, fraction=0.0):
"""
fraction is how much through the day you are. 0=start of the day, 1=end of the day.
"""
day_seconds = (60 * 60 * 24) - 1
total_seconds = int(day_seconds * fraction)
delta = datetime.timedelta(seconds=total_seconds)
time = datetime.time()
dt = datetime.datetime.combine(date, time) + delta
return dt | [
"def",
"date_to_datetime",
"(",
"date",
",",
"fraction",
"=",
"0.0",
")",
":",
"day_seconds",
"=",
"(",
"60",
"*",
"60",
"*",
"24",
")",
"-",
"1",
"total_seconds",
"=",
"int",
"(",
"day_seconds",
"*",
"fraction",
")",
"delta",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"total_seconds",
")",
"time",
"=",
"datetime",
".",
"time",
"(",
")",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"date",
",",
"time",
")",
"+",
"delta",
"return",
"dt"
] | fraction is how much through the day you are. 0=start of the day, 1=end of the day. | [
"fraction",
"is",
"how",
"much",
"through",
"the",
"day",
"you",
"are",
".",
"0",
"=",
"start",
"of",
"the",
"day",
"1",
"=",
"end",
"of",
"the",
"day",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_time.py#L1115-L1124 | train |
garethr/cloth | src/cloth/utils.py | ec2_instances | def ec2_instances():
"Use the EC2 API to get a list of all machines"
region = boto.ec2.get_region(REGION)
reservations = region.connect().get_all_instances()
instances = []
for reservation in reservations:
instances += reservation.instances
return instances | python | def ec2_instances():
"Use the EC2 API to get a list of all machines"
region = boto.ec2.get_region(REGION)
reservations = region.connect().get_all_instances()
instances = []
for reservation in reservations:
instances += reservation.instances
return instances | [
"def",
"ec2_instances",
"(",
")",
":",
"region",
"=",
"boto",
".",
"ec2",
".",
"get_region",
"(",
"REGION",
")",
"reservations",
"=",
"region",
".",
"connect",
"(",
")",
".",
"get_all_instances",
"(",
")",
"instances",
"=",
"[",
"]",
"for",
"reservation",
"in",
"reservations",
":",
"instances",
"+=",
"reservation",
".",
"instances",
"return",
"instances"
] | Use the EC2 API to get a list of all machines | [
"Use",
"the",
"EC2",
"API",
"to",
"get",
"a",
"list",
"of",
"all",
"machines"
] | b50c7cd6b03f49a931ee55ec94212760c50694a9 | https://github.com/garethr/cloth/blob/b50c7cd6b03f49a931ee55ec94212760c50694a9/src/cloth/utils.py#L12-L19 | train |
garethr/cloth | src/cloth/utils.py | instances | def instances(exp=".*"):
"Filter list of machines matching an expression"
expression = re.compile(exp)
instances = []
for node in ec2_instances():
if node.tags and ip(node):
try:
if expression.match(node.tags.get("Name")):
instances.append(node)
except TypeError:
pass
return instances | python | def instances(exp=".*"):
"Filter list of machines matching an expression"
expression = re.compile(exp)
instances = []
for node in ec2_instances():
if node.tags and ip(node):
try:
if expression.match(node.tags.get("Name")):
instances.append(node)
except TypeError:
pass
return instances | [
"def",
"instances",
"(",
"exp",
"=",
"\".*\"",
")",
":",
"expression",
"=",
"re",
".",
"compile",
"(",
"exp",
")",
"instances",
"=",
"[",
"]",
"for",
"node",
"in",
"ec2_instances",
"(",
")",
":",
"if",
"node",
".",
"tags",
"and",
"ip",
"(",
"node",
")",
":",
"try",
":",
"if",
"expression",
".",
"match",
"(",
"node",
".",
"tags",
".",
"get",
"(",
"\"Name\"",
")",
")",
":",
"instances",
".",
"append",
"(",
"node",
")",
"except",
"TypeError",
":",
"pass",
"return",
"instances"
] | Filter list of machines matching an expression | [
"Filter",
"list",
"of",
"machines",
"matching",
"an",
"expression"
] | b50c7cd6b03f49a931ee55ec94212760c50694a9 | https://github.com/garethr/cloth/blob/b50c7cd6b03f49a931ee55ec94212760c50694a9/src/cloth/utils.py#L27-L38 | train |
garethr/cloth | src/cloth/utils.py | use | def use(node):
"Set the fabric environment for the specifed node"
try:
role = node.tags.get("Name").split('-')[1]
env.roledefs[role] += [ip(node)]
except IndexError:
pass
env.nodes += [node]
env.hosts += [ip(node)] | python | def use(node):
"Set the fabric environment for the specifed node"
try:
role = node.tags.get("Name").split('-')[1]
env.roledefs[role] += [ip(node)]
except IndexError:
pass
env.nodes += [node]
env.hosts += [ip(node)] | [
"def",
"use",
"(",
"node",
")",
":",
"try",
":",
"role",
"=",
"node",
".",
"tags",
".",
"get",
"(",
"\"Name\"",
")",
".",
"split",
"(",
"'-'",
")",
"[",
"1",
"]",
"env",
".",
"roledefs",
"[",
"role",
"]",
"+=",
"[",
"ip",
"(",
"node",
")",
"]",
"except",
"IndexError",
":",
"pass",
"env",
".",
"nodes",
"+=",
"[",
"node",
"]",
"env",
".",
"hosts",
"+=",
"[",
"ip",
"(",
"node",
")",
"]"
] | Set the fabric environment for the specifed node | [
"Set",
"the",
"fabric",
"environment",
"for",
"the",
"specifed",
"node"
] | b50c7cd6b03f49a931ee55ec94212760c50694a9 | https://github.com/garethr/cloth/blob/b50c7cd6b03f49a931ee55ec94212760c50694a9/src/cloth/utils.py#L40-L48 | train |
Erotemic/utool | utool/util_tags.py | build_alias_map | def build_alias_map(regex_map, tag_vocab):
"""
Constructs explicit mapping. Order of items in regex map matters.
Items at top are given preference.
Example:
>>> # DISABLE_DOCTEST
>>> tags_list = [['t1', 't2'], [], ['t3'], ['t4', 't5']]
>>> tag_vocab = ut.flat_unique(*tags_list)
>>> regex_map = [('t[3-4]', 'A9'), ('t0', 'a0')]
>>> unmapped = list(set(tag_vocab) - set(alias_map.keys()))
"""
import utool as ut
import re
alias_map = ut.odict([])
for pats, new_tag in reversed(regex_map):
pats = ut.ensure_iterable(pats)
for pat in pats:
flags = [re.match(pat, t) for t in tag_vocab]
for old_tag in ut.compress(tag_vocab, flags):
alias_map[old_tag] = new_tag
identity_map = ut.take_column(regex_map, 1)
for tag in ut.filter_Nones(identity_map):
alias_map[tag] = tag
return alias_map | python | def build_alias_map(regex_map, tag_vocab):
"""
Constructs explicit mapping. Order of items in regex map matters.
Items at top are given preference.
Example:
>>> # DISABLE_DOCTEST
>>> tags_list = [['t1', 't2'], [], ['t3'], ['t4', 't5']]
>>> tag_vocab = ut.flat_unique(*tags_list)
>>> regex_map = [('t[3-4]', 'A9'), ('t0', 'a0')]
>>> unmapped = list(set(tag_vocab) - set(alias_map.keys()))
"""
import utool as ut
import re
alias_map = ut.odict([])
for pats, new_tag in reversed(regex_map):
pats = ut.ensure_iterable(pats)
for pat in pats:
flags = [re.match(pat, t) for t in tag_vocab]
for old_tag in ut.compress(tag_vocab, flags):
alias_map[old_tag] = new_tag
identity_map = ut.take_column(regex_map, 1)
for tag in ut.filter_Nones(identity_map):
alias_map[tag] = tag
return alias_map | [
"def",
"build_alias_map",
"(",
"regex_map",
",",
"tag_vocab",
")",
":",
"import",
"utool",
"as",
"ut",
"import",
"re",
"alias_map",
"=",
"ut",
".",
"odict",
"(",
"[",
"]",
")",
"for",
"pats",
",",
"new_tag",
"in",
"reversed",
"(",
"regex_map",
")",
":",
"pats",
"=",
"ut",
".",
"ensure_iterable",
"(",
"pats",
")",
"for",
"pat",
"in",
"pats",
":",
"flags",
"=",
"[",
"re",
".",
"match",
"(",
"pat",
",",
"t",
")",
"for",
"t",
"in",
"tag_vocab",
"]",
"for",
"old_tag",
"in",
"ut",
".",
"compress",
"(",
"tag_vocab",
",",
"flags",
")",
":",
"alias_map",
"[",
"old_tag",
"]",
"=",
"new_tag",
"identity_map",
"=",
"ut",
".",
"take_column",
"(",
"regex_map",
",",
"1",
")",
"for",
"tag",
"in",
"ut",
".",
"filter_Nones",
"(",
"identity_map",
")",
":",
"alias_map",
"[",
"tag",
"]",
"=",
"tag",
"return",
"alias_map"
] | Constructs explicit mapping. Order of items in regex map matters.
Items at top are given preference.
Example:
>>> # DISABLE_DOCTEST
>>> tags_list = [['t1', 't2'], [], ['t3'], ['t4', 't5']]
>>> tag_vocab = ut.flat_unique(*tags_list)
>>> regex_map = [('t[3-4]', 'A9'), ('t0', 'a0')]
>>> unmapped = list(set(tag_vocab) - set(alias_map.keys())) | [
"Constructs",
"explicit",
"mapping",
".",
"Order",
"of",
"items",
"in",
"regex",
"map",
"matters",
".",
"Items",
"at",
"top",
"are",
"given",
"preference",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_tags.py#L65-L89 | train |
Erotemic/utool | utool/util_tags.py | alias_tags | def alias_tags(tags_list, alias_map):
"""
update tags to new values
Args:
tags_list (list):
alias_map (list): list of 2-tuples with regex, value
Returns:
list: updated tags
CommandLine:
python -m utool.util_tags alias_tags --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_tags import * # NOQA
>>> import utool as ut
>>> tags_list = [['t1', 't2'], [], ['t3'], ['t4', 't5']]
>>> ut.build_alias_map()
>>> result = alias_tags(tags_list, alias_map)
>>> print(result)
"""
def _alias_dict(tags):
tags_ = [alias_map.get(t, t) for t in tags]
return list(set([t for t in tags_ if t is not None]))
tags_list_ = [_alias_dict(tags) for tags in tags_list]
return tags_list_ | python | def alias_tags(tags_list, alias_map):
"""
update tags to new values
Args:
tags_list (list):
alias_map (list): list of 2-tuples with regex, value
Returns:
list: updated tags
CommandLine:
python -m utool.util_tags alias_tags --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_tags import * # NOQA
>>> import utool as ut
>>> tags_list = [['t1', 't2'], [], ['t3'], ['t4', 't5']]
>>> ut.build_alias_map()
>>> result = alias_tags(tags_list, alias_map)
>>> print(result)
"""
def _alias_dict(tags):
tags_ = [alias_map.get(t, t) for t in tags]
return list(set([t for t in tags_ if t is not None]))
tags_list_ = [_alias_dict(tags) for tags in tags_list]
return tags_list_ | [
"def",
"alias_tags",
"(",
"tags_list",
",",
"alias_map",
")",
":",
"def",
"_alias_dict",
"(",
"tags",
")",
":",
"tags_",
"=",
"[",
"alias_map",
".",
"get",
"(",
"t",
",",
"t",
")",
"for",
"t",
"in",
"tags",
"]",
"return",
"list",
"(",
"set",
"(",
"[",
"t",
"for",
"t",
"in",
"tags_",
"if",
"t",
"is",
"not",
"None",
"]",
")",
")",
"tags_list_",
"=",
"[",
"_alias_dict",
"(",
"tags",
")",
"for",
"tags",
"in",
"tags_list",
"]",
"return",
"tags_list_"
] | update tags to new values
Args:
tags_list (list):
alias_map (list): list of 2-tuples with regex, value
Returns:
list: updated tags
CommandLine:
python -m utool.util_tags alias_tags --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_tags import * # NOQA
>>> import utool as ut
>>> tags_list = [['t1', 't2'], [], ['t3'], ['t4', 't5']]
>>> ut.build_alias_map()
>>> result = alias_tags(tags_list, alias_map)
>>> print(result) | [
"update",
"tags",
"to",
"new",
"values"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_tags.py#L92-L119 | train |
ThreatResponse/aws_ir_plugins | aws_ir_plugins/examineracl_host.py | Plugin.setup | def setup(self):
self.client = self._get_client()
sg = self._create_isolation_security_group()
if self.exists is not True:
acl = self._create_network_acl()
self._add_network_acl_entries(acl)
self._add_security_group_rule(sg)
self._add_security_group_to_instance(sg)
"""Conditions that can not be dry_run"""
if self.dry_run is not False:
self._add_security_group_rule(sg)
self._add_security_group_to_instance(sg) | python | def setup(self):
self.client = self._get_client()
sg = self._create_isolation_security_group()
if self.exists is not True:
acl = self._create_network_acl()
self._add_network_acl_entries(acl)
self._add_security_group_rule(sg)
self._add_security_group_to_instance(sg)
"""Conditions that can not be dry_run"""
if self.dry_run is not False:
self._add_security_group_rule(sg)
self._add_security_group_to_instance(sg) | [
"def",
"setup",
"(",
"self",
")",
":",
"self",
".",
"client",
"=",
"self",
".",
"_get_client",
"(",
")",
"sg",
"=",
"self",
".",
"_create_isolation_security_group",
"(",
")",
"if",
"self",
".",
"exists",
"is",
"not",
"True",
":",
"acl",
"=",
"self",
".",
"_create_network_acl",
"(",
")",
"self",
".",
"_add_network_acl_entries",
"(",
"acl",
")",
"self",
".",
"_add_security_group_rule",
"(",
"sg",
")",
"self",
".",
"_add_security_group_to_instance",
"(",
"sg",
")",
"if",
"self",
".",
"dry_run",
"is",
"not",
"False",
":",
"self",
".",
"_add_security_group_rule",
"(",
"sg",
")",
"self",
".",
"_add_security_group_to_instance",
"(",
"sg",
")"
] | Conditions that can not be dry_run | [
"Conditions",
"that",
"can",
"not",
"be",
"dry_run"
] | b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73 | https://github.com/ThreatResponse/aws_ir_plugins/blob/b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73/aws_ir_plugins/examineracl_host.py#L23-L35 | train |
Erotemic/utool | utool/util_cache.py | _args2_fpath | def _args2_fpath(dpath, fname, cfgstr, ext):
r"""
Ensures that the filename is not too long
Internal util_cache helper function
Windows MAX_PATH=260 characters
Absolute length is limited to 32,000 characters
Each filename component is limited to 255 characters
Args:
dpath (str):
fname (str):
cfgstr (str):
ext (str):
Returns:
str: fpath
CommandLine:
python -m utool.util_cache --test-_args2_fpath
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_cache import * # NOQA
>>> from utool.util_cache import _args2_fpath
>>> import utool as ut
>>> dpath = 'F:\\data\\work\\PZ_MTEST\\_ibsdb\\_ibeis_cache'
>>> fname = 'normalizer_'
>>> cfgstr = u'PZ_MTEST_DSUUIDS((9)67j%dr%&bl%4oh4+)_QSUUIDS((9)67j%dr%&bl%4oh4+)zebra_plains_vsone_NN(single,K1+1,last,cks1024)_FILT(ratio<0.625;1.0,fg;1.0)_SV(0.01;2;1.57minIn=4,nRR=50,nsum,)_AGG(nsum)_FLANN(4_kdtrees)_FEATWEIGHT(ON,uselabel,rf)_FEAT(hesaff+sift_)_CHIP(sz450)'
>>> ext = '.cPkl'
>>> fpath = _args2_fpath(dpath, fname, cfgstr, ext)
>>> result = str(ut.ensure_unixslash(fpath))
>>> target = 'F:/data/work/PZ_MTEST/_ibsdb/_ibeis_cache/normalizer_xfylfboirymmcpfg.cPkl'
>>> ut.assert_eq(result, target)
"""
if len(ext) > 0 and ext[0] != '.':
raise ValueError('Please be explicit and use a dot in ext')
max_len = 128
# should hashlen be larger?
cfgstr_hashlen = 16
prefix = fname
fname_cfgstr = consensed_cfgstr(prefix, cfgstr, max_len=max_len,
cfgstr_hashlen=cfgstr_hashlen)
fpath = join(dpath, fname_cfgstr + ext)
fpath = normpath(fpath)
return fpath | python | def _args2_fpath(dpath, fname, cfgstr, ext):
r"""
Ensures that the filename is not too long
Internal util_cache helper function
Windows MAX_PATH=260 characters
Absolute length is limited to 32,000 characters
Each filename component is limited to 255 characters
Args:
dpath (str):
fname (str):
cfgstr (str):
ext (str):
Returns:
str: fpath
CommandLine:
python -m utool.util_cache --test-_args2_fpath
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_cache import * # NOQA
>>> from utool.util_cache import _args2_fpath
>>> import utool as ut
>>> dpath = 'F:\\data\\work\\PZ_MTEST\\_ibsdb\\_ibeis_cache'
>>> fname = 'normalizer_'
>>> cfgstr = u'PZ_MTEST_DSUUIDS((9)67j%dr%&bl%4oh4+)_QSUUIDS((9)67j%dr%&bl%4oh4+)zebra_plains_vsone_NN(single,K1+1,last,cks1024)_FILT(ratio<0.625;1.0,fg;1.0)_SV(0.01;2;1.57minIn=4,nRR=50,nsum,)_AGG(nsum)_FLANN(4_kdtrees)_FEATWEIGHT(ON,uselabel,rf)_FEAT(hesaff+sift_)_CHIP(sz450)'
>>> ext = '.cPkl'
>>> fpath = _args2_fpath(dpath, fname, cfgstr, ext)
>>> result = str(ut.ensure_unixslash(fpath))
>>> target = 'F:/data/work/PZ_MTEST/_ibsdb/_ibeis_cache/normalizer_xfylfboirymmcpfg.cPkl'
>>> ut.assert_eq(result, target)
"""
if len(ext) > 0 and ext[0] != '.':
raise ValueError('Please be explicit and use a dot in ext')
max_len = 128
# should hashlen be larger?
cfgstr_hashlen = 16
prefix = fname
fname_cfgstr = consensed_cfgstr(prefix, cfgstr, max_len=max_len,
cfgstr_hashlen=cfgstr_hashlen)
fpath = join(dpath, fname_cfgstr + ext)
fpath = normpath(fpath)
return fpath | [
"def",
"_args2_fpath",
"(",
"dpath",
",",
"fname",
",",
"cfgstr",
",",
"ext",
")",
":",
"if",
"len",
"(",
"ext",
")",
">",
"0",
"and",
"ext",
"[",
"0",
"]",
"!=",
"'.'",
":",
"raise",
"ValueError",
"(",
"'Please be explicit and use a dot in ext'",
")",
"max_len",
"=",
"128",
"# should hashlen be larger?",
"cfgstr_hashlen",
"=",
"16",
"prefix",
"=",
"fname",
"fname_cfgstr",
"=",
"consensed_cfgstr",
"(",
"prefix",
",",
"cfgstr",
",",
"max_len",
"=",
"max_len",
",",
"cfgstr_hashlen",
"=",
"cfgstr_hashlen",
")",
"fpath",
"=",
"join",
"(",
"dpath",
",",
"fname_cfgstr",
"+",
"ext",
")",
"fpath",
"=",
"normpath",
"(",
"fpath",
")",
"return",
"fpath"
] | r"""
Ensures that the filename is not too long
Internal util_cache helper function
Windows MAX_PATH=260 characters
Absolute length is limited to 32,000 characters
Each filename component is limited to 255 characters
Args:
dpath (str):
fname (str):
cfgstr (str):
ext (str):
Returns:
str: fpath
CommandLine:
python -m utool.util_cache --test-_args2_fpath
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_cache import * # NOQA
>>> from utool.util_cache import _args2_fpath
>>> import utool as ut
>>> dpath = 'F:\\data\\work\\PZ_MTEST\\_ibsdb\\_ibeis_cache'
>>> fname = 'normalizer_'
>>> cfgstr = u'PZ_MTEST_DSUUIDS((9)67j%dr%&bl%4oh4+)_QSUUIDS((9)67j%dr%&bl%4oh4+)zebra_plains_vsone_NN(single,K1+1,last,cks1024)_FILT(ratio<0.625;1.0,fg;1.0)_SV(0.01;2;1.57minIn=4,nRR=50,nsum,)_AGG(nsum)_FLANN(4_kdtrees)_FEATWEIGHT(ON,uselabel,rf)_FEAT(hesaff+sift_)_CHIP(sz450)'
>>> ext = '.cPkl'
>>> fpath = _args2_fpath(dpath, fname, cfgstr, ext)
>>> result = str(ut.ensure_unixslash(fpath))
>>> target = 'F:/data/work/PZ_MTEST/_ibsdb/_ibeis_cache/normalizer_xfylfboirymmcpfg.cPkl'
>>> ut.assert_eq(result, target) | [
"r",
"Ensures",
"that",
"the",
"filename",
"is",
"not",
"too",
"long"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_cache.py#L161-L207 | train |
Erotemic/utool | utool/util_cache.py | save_cache | def save_cache(dpath, fname, cfgstr, data, ext='.cPkl', verbose=None):
"""
Saves data using util_io, but smartly constructs a filename
"""
fpath = _args2_fpath(dpath, fname, cfgstr, ext)
util_io.save_data(fpath, data, verbose=verbose)
return fpath | python | def save_cache(dpath, fname, cfgstr, data, ext='.cPkl', verbose=None):
"""
Saves data using util_io, but smartly constructs a filename
"""
fpath = _args2_fpath(dpath, fname, cfgstr, ext)
util_io.save_data(fpath, data, verbose=verbose)
return fpath | [
"def",
"save_cache",
"(",
"dpath",
",",
"fname",
",",
"cfgstr",
",",
"data",
",",
"ext",
"=",
"'.cPkl'",
",",
"verbose",
"=",
"None",
")",
":",
"fpath",
"=",
"_args2_fpath",
"(",
"dpath",
",",
"fname",
",",
"cfgstr",
",",
"ext",
")",
"util_io",
".",
"save_data",
"(",
"fpath",
",",
"data",
",",
"verbose",
"=",
"verbose",
")",
"return",
"fpath"
] | Saves data using util_io, but smartly constructs a filename | [
"Saves",
"data",
"using",
"util_io",
"but",
"smartly",
"constructs",
"a",
"filename"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_cache.py#L210-L216 | train |
Erotemic/utool | utool/util_cache.py | load_cache | def load_cache(dpath, fname, cfgstr, ext='.cPkl', verbose=None, enabled=True):
"""
Loads data using util_io, but smartly constructs a filename
"""
if verbose is None:
verbose = VERBOSE_CACHE
if not USE_CACHE or not enabled:
if verbose > 1:
print('[util_cache] ... cache disabled: dpath=%s cfgstr=%r' %
(basename(dpath), cfgstr,))
raise IOError(3, 'Cache Loading Is Disabled')
fpath = _args2_fpath(dpath, fname, cfgstr, ext)
if not exists(fpath):
if verbose > 0:
print('[util_cache] ... cache does not exist: dpath=%r fname=%r cfgstr=%r' % (
basename(dpath), fname, cfgstr,))
raise IOError(2, 'No such file or directory: %r' % (fpath,))
else:
if verbose > 2:
print('[util_cache] ... cache exists: dpath=%r fname=%r cfgstr=%r' % (
basename(dpath), fname, cfgstr,))
import utool as ut
nbytes = ut.get_file_nBytes(fpath)
big_verbose = (nbytes > 1E6 and verbose > 2) or verbose > 2
if big_verbose:
print('[util_cache] About to read file of size %s' % (ut.byte_str2(nbytes),))
try:
with ut.Timer(fpath, verbose=big_verbose and verbose > 3):
data = util_io.load_data(fpath, verbose=verbose > 2)
except (EOFError, IOError, ImportError) as ex:
print('CORRUPTED? fpath = %s' % (fpath,))
if verbose > 1:
print('[util_cache] ... cache miss dpath=%s cfgstr=%r' % (
basename(dpath), cfgstr,))
raise IOError(str(ex))
except Exception:
print('CORRUPTED? fpath = %s' % (fpath,))
raise
else:
if verbose > 2:
print('[util_cache] ... cache hit')
return data | python | def load_cache(dpath, fname, cfgstr, ext='.cPkl', verbose=None, enabled=True):
"""
Loads data using util_io, but smartly constructs a filename
"""
if verbose is None:
verbose = VERBOSE_CACHE
if not USE_CACHE or not enabled:
if verbose > 1:
print('[util_cache] ... cache disabled: dpath=%s cfgstr=%r' %
(basename(dpath), cfgstr,))
raise IOError(3, 'Cache Loading Is Disabled')
fpath = _args2_fpath(dpath, fname, cfgstr, ext)
if not exists(fpath):
if verbose > 0:
print('[util_cache] ... cache does not exist: dpath=%r fname=%r cfgstr=%r' % (
basename(dpath), fname, cfgstr,))
raise IOError(2, 'No such file or directory: %r' % (fpath,))
else:
if verbose > 2:
print('[util_cache] ... cache exists: dpath=%r fname=%r cfgstr=%r' % (
basename(dpath), fname, cfgstr,))
import utool as ut
nbytes = ut.get_file_nBytes(fpath)
big_verbose = (nbytes > 1E6 and verbose > 2) or verbose > 2
if big_verbose:
print('[util_cache] About to read file of size %s' % (ut.byte_str2(nbytes),))
try:
with ut.Timer(fpath, verbose=big_verbose and verbose > 3):
data = util_io.load_data(fpath, verbose=verbose > 2)
except (EOFError, IOError, ImportError) as ex:
print('CORRUPTED? fpath = %s' % (fpath,))
if verbose > 1:
print('[util_cache] ... cache miss dpath=%s cfgstr=%r' % (
basename(dpath), cfgstr,))
raise IOError(str(ex))
except Exception:
print('CORRUPTED? fpath = %s' % (fpath,))
raise
else:
if verbose > 2:
print('[util_cache] ... cache hit')
return data | [
"def",
"load_cache",
"(",
"dpath",
",",
"fname",
",",
"cfgstr",
",",
"ext",
"=",
"'.cPkl'",
",",
"verbose",
"=",
"None",
",",
"enabled",
"=",
"True",
")",
":",
"if",
"verbose",
"is",
"None",
":",
"verbose",
"=",
"VERBOSE_CACHE",
"if",
"not",
"USE_CACHE",
"or",
"not",
"enabled",
":",
"if",
"verbose",
">",
"1",
":",
"print",
"(",
"'[util_cache] ... cache disabled: dpath=%s cfgstr=%r'",
"%",
"(",
"basename",
"(",
"dpath",
")",
",",
"cfgstr",
",",
")",
")",
"raise",
"IOError",
"(",
"3",
",",
"'Cache Loading Is Disabled'",
")",
"fpath",
"=",
"_args2_fpath",
"(",
"dpath",
",",
"fname",
",",
"cfgstr",
",",
"ext",
")",
"if",
"not",
"exists",
"(",
"fpath",
")",
":",
"if",
"verbose",
">",
"0",
":",
"print",
"(",
"'[util_cache] ... cache does not exist: dpath=%r fname=%r cfgstr=%r'",
"%",
"(",
"basename",
"(",
"dpath",
")",
",",
"fname",
",",
"cfgstr",
",",
")",
")",
"raise",
"IOError",
"(",
"2",
",",
"'No such file or directory: %r'",
"%",
"(",
"fpath",
",",
")",
")",
"else",
":",
"if",
"verbose",
">",
"2",
":",
"print",
"(",
"'[util_cache] ... cache exists: dpath=%r fname=%r cfgstr=%r'",
"%",
"(",
"basename",
"(",
"dpath",
")",
",",
"fname",
",",
"cfgstr",
",",
")",
")",
"import",
"utool",
"as",
"ut",
"nbytes",
"=",
"ut",
".",
"get_file_nBytes",
"(",
"fpath",
")",
"big_verbose",
"=",
"(",
"nbytes",
">",
"1E6",
"and",
"verbose",
">",
"2",
")",
"or",
"verbose",
">",
"2",
"if",
"big_verbose",
":",
"print",
"(",
"'[util_cache] About to read file of size %s'",
"%",
"(",
"ut",
".",
"byte_str2",
"(",
"nbytes",
")",
",",
")",
")",
"try",
":",
"with",
"ut",
".",
"Timer",
"(",
"fpath",
",",
"verbose",
"=",
"big_verbose",
"and",
"verbose",
">",
"3",
")",
":",
"data",
"=",
"util_io",
".",
"load_data",
"(",
"fpath",
",",
"verbose",
"=",
"verbose",
">",
"2",
")",
"except",
"(",
"EOFError",
",",
"IOError",
",",
"ImportError",
")",
"as",
"ex",
":",
"print",
"(",
"'CORRUPTED? fpath = %s'",
"%",
"(",
"fpath",
",",
")",
")",
"if",
"verbose",
">",
"1",
":",
"print",
"(",
"'[util_cache] ... cache miss dpath=%s cfgstr=%r'",
"%",
"(",
"basename",
"(",
"dpath",
")",
",",
"cfgstr",
",",
")",
")",
"raise",
"IOError",
"(",
"str",
"(",
"ex",
")",
")",
"except",
"Exception",
":",
"print",
"(",
"'CORRUPTED? fpath = %s'",
"%",
"(",
"fpath",
",",
")",
")",
"raise",
"else",
":",
"if",
"verbose",
">",
"2",
":",
"print",
"(",
"'[util_cache] ... cache hit'",
")",
"return",
"data"
] | Loads data using util_io, but smartly constructs a filename | [
"Loads",
"data",
"using",
"util_io",
"but",
"smartly",
"constructs",
"a",
"filename"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_cache.py#L219-L260 | train |
Erotemic/utool | utool/util_cache.py | tryload_cache | def tryload_cache(dpath, fname, cfgstr, verbose=None):
"""
returns None if cache cannot be loaded
"""
try:
return load_cache(dpath, fname, cfgstr, verbose=verbose)
except IOError:
return None | python | def tryload_cache(dpath, fname, cfgstr, verbose=None):
"""
returns None if cache cannot be loaded
"""
try:
return load_cache(dpath, fname, cfgstr, verbose=verbose)
except IOError:
return None | [
"def",
"tryload_cache",
"(",
"dpath",
",",
"fname",
",",
"cfgstr",
",",
"verbose",
"=",
"None",
")",
":",
"try",
":",
"return",
"load_cache",
"(",
"dpath",
",",
"fname",
",",
"cfgstr",
",",
"verbose",
"=",
"verbose",
")",
"except",
"IOError",
":",
"return",
"None"
] | returns None if cache cannot be loaded | [
"returns",
"None",
"if",
"cache",
"cannot",
"be",
"loaded"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_cache.py#L263-L270 | train |
Erotemic/utool | utool/util_cache.py | tryload_cache_list | def tryload_cache_list(dpath, fname, cfgstr_list, verbose=False):
"""
loads a list of similar cached datas. Returns flags that needs to be computed
"""
data_list = [tryload_cache(dpath, fname, cfgstr, verbose) for cfgstr in cfgstr_list]
ismiss_list = [data is None for data in data_list]
return data_list, ismiss_list | python | def tryload_cache_list(dpath, fname, cfgstr_list, verbose=False):
"""
loads a list of similar cached datas. Returns flags that needs to be computed
"""
data_list = [tryload_cache(dpath, fname, cfgstr, verbose) for cfgstr in cfgstr_list]
ismiss_list = [data is None for data in data_list]
return data_list, ismiss_list | [
"def",
"tryload_cache_list",
"(",
"dpath",
",",
"fname",
",",
"cfgstr_list",
",",
"verbose",
"=",
"False",
")",
":",
"data_list",
"=",
"[",
"tryload_cache",
"(",
"dpath",
",",
"fname",
",",
"cfgstr",
",",
"verbose",
")",
"for",
"cfgstr",
"in",
"cfgstr_list",
"]",
"ismiss_list",
"=",
"[",
"data",
"is",
"None",
"for",
"data",
"in",
"data_list",
"]",
"return",
"data_list",
",",
"ismiss_list"
] | loads a list of similar cached datas. Returns flags that needs to be computed | [
"loads",
"a",
"list",
"of",
"similar",
"cached",
"datas",
".",
"Returns",
"flags",
"that",
"needs",
"to",
"be",
"computed"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_cache.py#L274-L280 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.