id
int32
0
252k
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
248,200
kmedian/onepara
onepara/onepara_func.py
onepara
def onepara(R): """Converts an ill-conditioned correlation matrix into well-conditioned matrix with one common correlation coefficient Parameters: ----------- R : ndarray an illconditioned correlation matrix, e.g. oxyba.illcond_corrmat Return: ------- cmat : ndarray DxD matrix with +1 as diagonal elements and 1 common coefficient for all other relations. """ import numpy as np import warnings d = R.shape[0] if d < 2: raise Exception(( "More than one variable is required." "Supply at least a 2x2 matrix.")) # the explicit solution x = (np.sum(R) + np.trace(R)) / (d**2 - d) if x < (-1. / (d - 1)) or x > 1: warnings.warn("No analytic solution found x={:.8f}".format(x)) return None else: C = np.eye(d) C[np.logical_not(C)] = x return C
python
def onepara(R): """Converts an ill-conditioned correlation matrix into well-conditioned matrix with one common correlation coefficient Parameters: ----------- R : ndarray an illconditioned correlation matrix, e.g. oxyba.illcond_corrmat Return: ------- cmat : ndarray DxD matrix with +1 as diagonal elements and 1 common coefficient for all other relations. """ import numpy as np import warnings d = R.shape[0] if d < 2: raise Exception(( "More than one variable is required." "Supply at least a 2x2 matrix.")) # the explicit solution x = (np.sum(R) + np.trace(R)) / (d**2 - d) if x < (-1. / (d - 1)) or x > 1: warnings.warn("No analytic solution found x={:.8f}".format(x)) return None else: C = np.eye(d) C[np.logical_not(C)] = x return C
[ "def", "onepara", "(", "R", ")", ":", "import", "numpy", "as", "np", "import", "warnings", "d", "=", "R", ".", "shape", "[", "0", "]", "if", "d", "<", "2", ":", "raise", "Exception", "(", "(", "\"More than one variable is required.\"", "\"Supply at least a 2x2 matrix.\"", ")", ")", "# the explicit solution", "x", "=", "(", "np", ".", "sum", "(", "R", ")", "+", "np", ".", "trace", "(", "R", ")", ")", "/", "(", "d", "**", "2", "-", "d", ")", "if", "x", "<", "(", "-", "1.", "/", "(", "d", "-", "1", ")", ")", "or", "x", ">", "1", ":", "warnings", ".", "warn", "(", "\"No analytic solution found x={:.8f}\"", ".", "format", "(", "x", ")", ")", "return", "None", "else", ":", "C", "=", "np", ".", "eye", "(", "d", ")", "C", "[", "np", ".", "logical_not", "(", "C", ")", "]", "=", "x", "return", "C" ]
Converts an ill-conditioned correlation matrix into well-conditioned matrix with one common correlation coefficient Parameters: ----------- R : ndarray an illconditioned correlation matrix, e.g. oxyba.illcond_corrmat Return: ------- cmat : ndarray DxD matrix with +1 as diagonal elements and 1 common coefficient for all other relations.
[ "Converts", "an", "ill", "-", "conditioned", "correlation", "matrix", "into", "well", "-", "conditioned", "matrix", "with", "one", "common", "correlation", "coefficient" ]
ed4142b92e3f67bad209dbea1eafc9ea6e3c32b9
https://github.com/kmedian/onepara/blob/ed4142b92e3f67bad209dbea1eafc9ea6e3c32b9/onepara/onepara_func.py#L2-L39
248,201
cbrand/vpnchooser
src/vpnchooser/query/rules_query.py
RulesQuery._load_rules
def _load_rules(self): """ Loads the rules from the SSH-Connection """ with self._sftp_connection.open(self.RULE_PATH) as file: data = file.read() lines = ( line.strip() for line in data.split('\n') ) rule_strings = ( line for line in lines if len(line) > 0 ) rules = ( Rule.parse(rule_string) for rule_string in rule_strings ) self._rules = [ rule for rule in rules if rule is not None ]
python
def _load_rules(self): """ Loads the rules from the SSH-Connection """ with self._sftp_connection.open(self.RULE_PATH) as file: data = file.read() lines = ( line.strip() for line in data.split('\n') ) rule_strings = ( line for line in lines if len(line) > 0 ) rules = ( Rule.parse(rule_string) for rule_string in rule_strings ) self._rules = [ rule for rule in rules if rule is not None ]
[ "def", "_load_rules", "(", "self", ")", ":", "with", "self", ".", "_sftp_connection", ".", "open", "(", "self", ".", "RULE_PATH", ")", "as", "file", ":", "data", "=", "file", ".", "read", "(", ")", "lines", "=", "(", "line", ".", "strip", "(", ")", "for", "line", "in", "data", ".", "split", "(", "'\\n'", ")", ")", "rule_strings", "=", "(", "line", "for", "line", "in", "lines", "if", "len", "(", "line", ")", ">", "0", ")", "rules", "=", "(", "Rule", ".", "parse", "(", "rule_string", ")", "for", "rule_string", "in", "rule_strings", ")", "self", ".", "_rules", "=", "[", "rule", "for", "rule", "in", "rules", "if", "rule", "is", "not", "None", "]" ]
Loads the rules from the SSH-Connection
[ "Loads", "the", "rules", "from", "the", "SSH", "-", "Connection" ]
d153e3d05555c23cf5e8e15e507eecad86465923
https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/query/rules_query.py#L17-L39
248,202
cbrand/vpnchooser
src/vpnchooser/query/rules_query.py
RulesQuery._exec_command
def _exec_command(self, command: str): """ Executes the command and closes the handles afterwards. """ stdin, stdout, stderr = self._ssh.exec_command(command) # Clearing the buffers stdout.read() stderr.read() stdin.close()
python
def _exec_command(self, command: str): """ Executes the command and closes the handles afterwards. """ stdin, stdout, stderr = self._ssh.exec_command(command) # Clearing the buffers stdout.read() stderr.read() stdin.close()
[ "def", "_exec_command", "(", "self", ",", "command", ":", "str", ")", ":", "stdin", ",", "stdout", ",", "stderr", "=", "self", ".", "_ssh", ".", "exec_command", "(", "command", ")", "# Clearing the buffers", "stdout", ".", "read", "(", ")", "stderr", ".", "read", "(", ")", "stdin", ".", "close", "(", ")" ]
Executes the command and closes the handles afterwards.
[ "Executes", "the", "command", "and", "closes", "the", "handles", "afterwards", "." ]
d153e3d05555c23cf5e8e15e507eecad86465923
https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/query/rules_query.py#L71-L80
248,203
cbrand/vpnchooser
src/vpnchooser/query/rules_query.py
RulesQuery.sync
def sync(self, rules: list): """ Synchronizes the given rules with the server and ensures that there are no old rules active which are not in the given list. """ self._reset() old_rules = self.rules to_delete_rules = [ rule for rule in old_rules if rule not in rules ] new_rules = [ rule for rule in rules if rule not in old_rules ] for new_rule in new_rules: assert isinstance(new_rule, Rule) self._exec_command(new_rule.add_command) for to_delete_rule in to_delete_rules: assert isinstance(to_delete_rule, Rule) self._exec_command( to_delete_rule.remove_command ) self._update(rules)
python
def sync(self, rules: list): """ Synchronizes the given rules with the server and ensures that there are no old rules active which are not in the given list. """ self._reset() old_rules = self.rules to_delete_rules = [ rule for rule in old_rules if rule not in rules ] new_rules = [ rule for rule in rules if rule not in old_rules ] for new_rule in new_rules: assert isinstance(new_rule, Rule) self._exec_command(new_rule.add_command) for to_delete_rule in to_delete_rules: assert isinstance(to_delete_rule, Rule) self._exec_command( to_delete_rule.remove_command ) self._update(rules)
[ "def", "sync", "(", "self", ",", "rules", ":", "list", ")", ":", "self", ".", "_reset", "(", ")", "old_rules", "=", "self", ".", "rules", "to_delete_rules", "=", "[", "rule", "for", "rule", "in", "old_rules", "if", "rule", "not", "in", "rules", "]", "new_rules", "=", "[", "rule", "for", "rule", "in", "rules", "if", "rule", "not", "in", "old_rules", "]", "for", "new_rule", "in", "new_rules", ":", "assert", "isinstance", "(", "new_rule", ",", "Rule", ")", "self", ".", "_exec_command", "(", "new_rule", ".", "add_command", ")", "for", "to_delete_rule", "in", "to_delete_rules", ":", "assert", "isinstance", "(", "to_delete_rule", ",", "Rule", ")", "self", ".", "_exec_command", "(", "to_delete_rule", ".", "remove_command", ")", "self", ".", "_update", "(", "rules", ")" ]
Synchronizes the given rules with the server and ensures that there are no old rules active which are not in the given list.
[ "Synchronizes", "the", "given", "rules", "with", "the", "server", "and", "ensures", "that", "there", "are", "no", "old", "rules", "active", "which", "are", "not", "in", "the", "given", "list", "." ]
d153e3d05555c23cf5e8e15e507eecad86465923
https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/query/rules_query.py#L82-L107
248,204
cbrand/vpnchooser
src/vpnchooser/query/rules_query.py
RulesQuery._update
def _update(self, rules: list): """ Updates the given rules and stores them on the router. """ self._rules = rules to_store = '\n'.join( rule.config_string for rule in rules ) sftp_connection = self._sftp_connection with sftp_connection.open(self.RULE_PATH, mode='w') as file_handle: file_handle.write(to_store)
python
def _update(self, rules: list): """ Updates the given rules and stores them on the router. """ self._rules = rules to_store = '\n'.join( rule.config_string for rule in rules ) sftp_connection = self._sftp_connection with sftp_connection.open(self.RULE_PATH, mode='w') as file_handle: file_handle.write(to_store)
[ "def", "_update", "(", "self", ",", "rules", ":", "list", ")", ":", "self", ".", "_rules", "=", "rules", "to_store", "=", "'\\n'", ".", "join", "(", "rule", ".", "config_string", "for", "rule", "in", "rules", ")", "sftp_connection", "=", "self", ".", "_sftp_connection", "with", "sftp_connection", ".", "open", "(", "self", ".", "RULE_PATH", ",", "mode", "=", "'w'", ")", "as", "file_handle", ":", "file_handle", ".", "write", "(", "to_store", ")" ]
Updates the given rules and stores them on the router.
[ "Updates", "the", "given", "rules", "and", "stores", "them", "on", "the", "router", "." ]
d153e3d05555c23cf5e8e15e507eecad86465923
https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/query/rules_query.py#L109-L121
248,205
kynikos/lib.py.cmenu
cmenu.py
_CommandWithFlags.complete
def complete(self, sp_args, line, rl_prefix, rl_begidx, rl_endidx): """ Override in order to have command or argument completion. It is necessary to return a 'list', i.e. not a tuple or other sequences. """ # TODO: Optionally check that flags are not repeated (i.e. exclude # them from the possible matches if they are already in the # command line) # TODO: Support groups of mutually-exclusive flags, i.e. if one is # already present, the others in the group are not accepted if len(sp_args) == 0 or not line.endswith(sp_args[-1]): # if line.endswith(sp_args[-1]) is False, it means that the last # sp_args is already complete return self.accepted_flags else: matches = [] for arg in self.accepted_flags: if arg.startswith(sp_args[-1]): matches.append(arg) if len(matches) == 1: # In general, SPLIT_ARGS and readline use different word # delimiters, see e.g. the docs for # readline.get_completer_delims() # If for example there's a 'foo-bar' argument, SPLIT_ARGS sees # it as a single word, but readline by default will split it # in two words, 'foo' and 'bar', and if 'foo-b' is entered in # the command line, and Tab is pressed, the word will be # completed as 'foo-bfoo-bar', unless we compensate here by # subtracting the rl_prefix from the found match sub = len(sp_args[-1]) - len(rl_prefix) return [matches[0][sub:]] else: return matches
python
def complete(self, sp_args, line, rl_prefix, rl_begidx, rl_endidx): """ Override in order to have command or argument completion. It is necessary to return a 'list', i.e. not a tuple or other sequences. """ # TODO: Optionally check that flags are not repeated (i.e. exclude # them from the possible matches if they are already in the # command line) # TODO: Support groups of mutually-exclusive flags, i.e. if one is # already present, the others in the group are not accepted if len(sp_args) == 0 or not line.endswith(sp_args[-1]): # if line.endswith(sp_args[-1]) is False, it means that the last # sp_args is already complete return self.accepted_flags else: matches = [] for arg in self.accepted_flags: if arg.startswith(sp_args[-1]): matches.append(arg) if len(matches) == 1: # In general, SPLIT_ARGS and readline use different word # delimiters, see e.g. the docs for # readline.get_completer_delims() # If for example there's a 'foo-bar' argument, SPLIT_ARGS sees # it as a single word, but readline by default will split it # in two words, 'foo' and 'bar', and if 'foo-b' is entered in # the command line, and Tab is pressed, the word will be # completed as 'foo-bfoo-bar', unless we compensate here by # subtracting the rl_prefix from the found match sub = len(sp_args[-1]) - len(rl_prefix) return [matches[0][sub:]] else: return matches
[ "def", "complete", "(", "self", ",", "sp_args", ",", "line", ",", "rl_prefix", ",", "rl_begidx", ",", "rl_endidx", ")", ":", "# TODO: Optionally check that flags are not repeated (i.e. exclude", "# them from the possible matches if they are already in the", "# command line)", "# TODO: Support groups of mutually-exclusive flags, i.e. if one is", "# already present, the others in the group are not accepted", "if", "len", "(", "sp_args", ")", "==", "0", "or", "not", "line", ".", "endswith", "(", "sp_args", "[", "-", "1", "]", ")", ":", "# if line.endswith(sp_args[-1]) is False, it means that the last", "# sp_args is already complete", "return", "self", ".", "accepted_flags", "else", ":", "matches", "=", "[", "]", "for", "arg", "in", "self", ".", "accepted_flags", ":", "if", "arg", ".", "startswith", "(", "sp_args", "[", "-", "1", "]", ")", ":", "matches", ".", "append", "(", "arg", ")", "if", "len", "(", "matches", ")", "==", "1", ":", "# In general, SPLIT_ARGS and readline use different word", "# delimiters, see e.g. the docs for", "# readline.get_completer_delims()", "# If for example there's a 'foo-bar' argument, SPLIT_ARGS sees", "# it as a single word, but readline by default will split it", "# in two words, 'foo' and 'bar', and if 'foo-b' is entered in", "# the command line, and Tab is pressed, the word will be", "# completed as 'foo-bfoo-bar', unless we compensate here by", "# subtracting the rl_prefix from the found match", "sub", "=", "len", "(", "sp_args", "[", "-", "1", "]", ")", "-", "len", "(", "rl_prefix", ")", "return", "[", "matches", "[", "0", "]", "[", "sub", ":", "]", "]", "else", ":", "return", "matches" ]
Override in order to have command or argument completion. It is necessary to return a 'list', i.e. not a tuple or other sequences.
[ "Override", "in", "order", "to", "have", "command", "or", "argument", "completion", "." ]
eb1e806f0b674c4deb24730cbd7cf4604150c461
https://github.com/kynikos/lib.py.cmenu/blob/eb1e806f0b674c4deb24730cbd7cf4604150c461/cmenu.py#L264-L298
248,206
troup-system/troup
troup/infrastructure.py
IncomingChannelWSAdapter.local_address
def local_address(self): """ Local endpoint address as a tuple """ if not self._local_address: self._local_address = self.proto.reader._transport.get_extra_info('sockname') if len(self._local_address) == 4: self._local_address = self._local_address[:2] return self._local_address
python
def local_address(self): """ Local endpoint address as a tuple """ if not self._local_address: self._local_address = self.proto.reader._transport.get_extra_info('sockname') if len(self._local_address) == 4: self._local_address = self._local_address[:2] return self._local_address
[ "def", "local_address", "(", "self", ")", ":", "if", "not", "self", ".", "_local_address", ":", "self", ".", "_local_address", "=", "self", ".", "proto", ".", "reader", ".", "_transport", ".", "get_extra_info", "(", "'sockname'", ")", "if", "len", "(", "self", ".", "_local_address", ")", "==", "4", ":", "self", ".", "_local_address", "=", "self", ".", "_local_address", "[", ":", "2", "]", "return", "self", ".", "_local_address" ]
Local endpoint address as a tuple
[ "Local", "endpoint", "address", "as", "a", "tuple" ]
e3c74c363101243dfbfc3d2f0c7c8fce5d9ad1a8
https://github.com/troup-system/troup/blob/e3c74c363101243dfbfc3d2f0c7c8fce5d9ad1a8/troup/infrastructure.py#L198-L206
248,207
troup-system/troup
troup/infrastructure.py
IncomingChannelWSAdapter.peer_address
def peer_address(self): """ Peer endpoint address as a tuple """ if not self._peer_address: self._peer_address = self.proto.reader._transport.get_extra_info('peername') if len(self._peer_address) == 4: self._peer_address = self._peer_address[:2] return self._peer_address
python
def peer_address(self): """ Peer endpoint address as a tuple """ if not self._peer_address: self._peer_address = self.proto.reader._transport.get_extra_info('peername') if len(self._peer_address) == 4: self._peer_address = self._peer_address[:2] return self._peer_address
[ "def", "peer_address", "(", "self", ")", ":", "if", "not", "self", ".", "_peer_address", ":", "self", ".", "_peer_address", "=", "self", ".", "proto", ".", "reader", ".", "_transport", ".", "get_extra_info", "(", "'peername'", ")", "if", "len", "(", "self", ".", "_peer_address", ")", "==", "4", ":", "self", ".", "_peer_address", "=", "self", ".", "_peer_address", "[", ":", "2", "]", "return", "self", ".", "_peer_address" ]
Peer endpoint address as a tuple
[ "Peer", "endpoint", "address", "as", "a", "tuple" ]
e3c74c363101243dfbfc3d2f0c7c8fce5d9ad1a8
https://github.com/troup-system/troup/blob/e3c74c363101243dfbfc3d2f0c7c8fce5d9ad1a8/troup/infrastructure.py#L209-L217
248,208
lambdalisue/tolerance
src/tolerance/utils.py
argument_switch_generator
def argument_switch_generator(argument_name=None, default=True, reverse=False, keep=False): """ Create switch function which return the status from specified named argument Parameters ---------- argument_name : string or None An argument name which is used to judge the status. If ``None`` is specified, the value of ``tolerance.utils.DEFAULT_ARGUMENT_NAME`` will be used instead. default : boolean A default value of this switch function. It is used when specifid ``**kwargs`` does not have named argument reverse : boolean Reverse the status (Default: ``False``) keep : boolean If it is ``True``, keep named argument in ``**kwargs``. Returns ------- function A switch function which return status, args, and kwargs respectively. Examples -------- >>> # >>> # generate switch function with default parameters >>> # >>> fn = argument_switch_generator('fail_silently') >>> # return `default` value and specified *args and **kwargs when >>> # `fail_silently` is not specified in **kwargs >>> fn() == (True, tuple(), {}) True >>> # return `fail_silently` value when it is specified >>> fn(fail_silently=True) == (True, tuple(), {}) True >>> fn(fail_silently=False) == (False, tuple(), {}) True >>> # >>> # generate switch function with `default=False` >>> # >>> fn = argument_switch_generator('fail_silently', default=False) >>> # return `default` value so `False` is returned back >>> fn() == (False, tuple(), {}) True >>> # >>> # generate switch function with `reverse=True` >>> # >>> fn = argument_switch_generator('fail_silently', reverse=True) >>> # `default` value is independent from `reverse=True` >>> fn() == (True, tuple(), {}) True >>> # `fail_silently` value is influenced by `reverse=True` >>> fn(fail_silently=True) == (False, tuple(), {}) True >>> fn(fail_silently=False) == (True, tuple(), {}) True >>> # >>> # generate switch function with `keep=True` >>> # >>> fn = argument_switch_generator('fail_silently', keep=True) >>> # `fail_silently` attribute remains even in returned back kwargs >>> status, args, kwargs = fn(fail_silently=True) >>> 'fail_silently' in kwargs True """ def switch_function(*args, **kwargs): if argument_name in kwargs: if keep: status = kwargs.get(argument_name) else: status = kwargs.pop(argument_name) if reverse: status = not status else: status = default return bool(status), args, kwargs if argument_name is None: argument_name = DEFAULT_ARGUMENT_NAME return switch_function
python
def argument_switch_generator(argument_name=None, default=True, reverse=False, keep=False): """ Create switch function which return the status from specified named argument Parameters ---------- argument_name : string or None An argument name which is used to judge the status. If ``None`` is specified, the value of ``tolerance.utils.DEFAULT_ARGUMENT_NAME`` will be used instead. default : boolean A default value of this switch function. It is used when specifid ``**kwargs`` does not have named argument reverse : boolean Reverse the status (Default: ``False``) keep : boolean If it is ``True``, keep named argument in ``**kwargs``. Returns ------- function A switch function which return status, args, and kwargs respectively. Examples -------- >>> # >>> # generate switch function with default parameters >>> # >>> fn = argument_switch_generator('fail_silently') >>> # return `default` value and specified *args and **kwargs when >>> # `fail_silently` is not specified in **kwargs >>> fn() == (True, tuple(), {}) True >>> # return `fail_silently` value when it is specified >>> fn(fail_silently=True) == (True, tuple(), {}) True >>> fn(fail_silently=False) == (False, tuple(), {}) True >>> # >>> # generate switch function with `default=False` >>> # >>> fn = argument_switch_generator('fail_silently', default=False) >>> # return `default` value so `False` is returned back >>> fn() == (False, tuple(), {}) True >>> # >>> # generate switch function with `reverse=True` >>> # >>> fn = argument_switch_generator('fail_silently', reverse=True) >>> # `default` value is independent from `reverse=True` >>> fn() == (True, tuple(), {}) True >>> # `fail_silently` value is influenced by `reverse=True` >>> fn(fail_silently=True) == (False, tuple(), {}) True >>> fn(fail_silently=False) == (True, tuple(), {}) True >>> # >>> # generate switch function with `keep=True` >>> # >>> fn = argument_switch_generator('fail_silently', keep=True) >>> # `fail_silently` attribute remains even in returned back kwargs >>> status, args, kwargs = fn(fail_silently=True) >>> 'fail_silently' in kwargs True """ def switch_function(*args, **kwargs): if argument_name in kwargs: if keep: status = kwargs.get(argument_name) else: status = kwargs.pop(argument_name) if reverse: status = not status else: status = default return bool(status), args, kwargs if argument_name is None: argument_name = DEFAULT_ARGUMENT_NAME return switch_function
[ "def", "argument_switch_generator", "(", "argument_name", "=", "None", ",", "default", "=", "True", ",", "reverse", "=", "False", ",", "keep", "=", "False", ")", ":", "def", "switch_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "argument_name", "in", "kwargs", ":", "if", "keep", ":", "status", "=", "kwargs", ".", "get", "(", "argument_name", ")", "else", ":", "status", "=", "kwargs", ".", "pop", "(", "argument_name", ")", "if", "reverse", ":", "status", "=", "not", "status", "else", ":", "status", "=", "default", "return", "bool", "(", "status", ")", ",", "args", ",", "kwargs", "if", "argument_name", "is", "None", ":", "argument_name", "=", "DEFAULT_ARGUMENT_NAME", "return", "switch_function" ]
Create switch function which return the status from specified named argument Parameters ---------- argument_name : string or None An argument name which is used to judge the status. If ``None`` is specified, the value of ``tolerance.utils.DEFAULT_ARGUMENT_NAME`` will be used instead. default : boolean A default value of this switch function. It is used when specifid ``**kwargs`` does not have named argument reverse : boolean Reverse the status (Default: ``False``) keep : boolean If it is ``True``, keep named argument in ``**kwargs``. Returns ------- function A switch function which return status, args, and kwargs respectively. Examples -------- >>> # >>> # generate switch function with default parameters >>> # >>> fn = argument_switch_generator('fail_silently') >>> # return `default` value and specified *args and **kwargs when >>> # `fail_silently` is not specified in **kwargs >>> fn() == (True, tuple(), {}) True >>> # return `fail_silently` value when it is specified >>> fn(fail_silently=True) == (True, tuple(), {}) True >>> fn(fail_silently=False) == (False, tuple(), {}) True >>> # >>> # generate switch function with `default=False` >>> # >>> fn = argument_switch_generator('fail_silently', default=False) >>> # return `default` value so `False` is returned back >>> fn() == (False, tuple(), {}) True >>> # >>> # generate switch function with `reverse=True` >>> # >>> fn = argument_switch_generator('fail_silently', reverse=True) >>> # `default` value is independent from `reverse=True` >>> fn() == (True, tuple(), {}) True >>> # `fail_silently` value is influenced by `reverse=True` >>> fn(fail_silently=True) == (False, tuple(), {}) True >>> fn(fail_silently=False) == (True, tuple(), {}) True >>> # >>> # generate switch function with `keep=True` >>> # >>> fn = argument_switch_generator('fail_silently', keep=True) >>> # `fail_silently` attribute remains even in returned back kwargs >>> status, args, kwargs = fn(fail_silently=True) >>> 'fail_silently' in kwargs True
[ "Create", "switch", "function", "which", "return", "the", "status", "from", "specified", "named", "argument" ]
e332622d78b1f8066098cc768af4ed12ccb4153d
https://github.com/lambdalisue/tolerance/blob/e332622d78b1f8066098cc768af4ed12ccb4153d/src/tolerance/utils.py#L10-L93
248,209
jjangsangy/kan
kan/__main__.py
command_line
def command_line(): ''' Parses users command line arguments and returns the namespace containing parsed values. ''' description = 'Kan helps you find the book' version = ' '.join([__version__, __release__]) parser = ArgumentParser(prog='kan', description=description) subparser = parser.add_subparsers(help='Search by') by_title = subparser.add_parser('title', help='Book title',) by_title.add_argument('title', help='Book name') by_isbn = subparser.add_parser('isbn', help='ISBN code') by_isbn.add_argument('code', help='Valid ISBN code') by_author = subparser.add_parser('author', help='Book author') by_author.add_argument('author', help='Authors name') by_author.add_argument('--recent', help='Search by most recent', action='store_true') by_author.add_argument('--top', help='Search by best selling', action='store_true') # Main Parser parser.add_argument( '-v', '--version', action='version', version="%s v%s" % ('kan', version), ) parser.add_argument( '--title', help='Title of the book', metavar='name', ) parser.add_argument( '--author', default=None, metavar='name', help='Name of the author', ) parser.add_argument( '--subject', type=str, help='Specify subject matter by category', metavar='topic', ) parser.add_argument( '--max', type=int, metavar='n', default=3, choices=range(41), help='Maximum results to get per query: default=3, max=40', ) parser.add_argument( '--language', type=str, metavar='code', default='', help='Restrict the search results to those with a certain language code', ) parser.add_argument( '--verbose', action='store_true', help='Print out debug information', ) return parser.parse_args()
python
def command_line(): ''' Parses users command line arguments and returns the namespace containing parsed values. ''' description = 'Kan helps you find the book' version = ' '.join([__version__, __release__]) parser = ArgumentParser(prog='kan', description=description) subparser = parser.add_subparsers(help='Search by') by_title = subparser.add_parser('title', help='Book title',) by_title.add_argument('title', help='Book name') by_isbn = subparser.add_parser('isbn', help='ISBN code') by_isbn.add_argument('code', help='Valid ISBN code') by_author = subparser.add_parser('author', help='Book author') by_author.add_argument('author', help='Authors name') by_author.add_argument('--recent', help='Search by most recent', action='store_true') by_author.add_argument('--top', help='Search by best selling', action='store_true') # Main Parser parser.add_argument( '-v', '--version', action='version', version="%s v%s" % ('kan', version), ) parser.add_argument( '--title', help='Title of the book', metavar='name', ) parser.add_argument( '--author', default=None, metavar='name', help='Name of the author', ) parser.add_argument( '--subject', type=str, help='Specify subject matter by category', metavar='topic', ) parser.add_argument( '--max', type=int, metavar='n', default=3, choices=range(41), help='Maximum results to get per query: default=3, max=40', ) parser.add_argument( '--language', type=str, metavar='code', default='', help='Restrict the search results to those with a certain language code', ) parser.add_argument( '--verbose', action='store_true', help='Print out debug information', ) return parser.parse_args()
[ "def", "command_line", "(", ")", ":", "description", "=", "'Kan helps you find the book'", "version", "=", "' '", ".", "join", "(", "[", "__version__", ",", "__release__", "]", ")", "parser", "=", "ArgumentParser", "(", "prog", "=", "'kan'", ",", "description", "=", "description", ")", "subparser", "=", "parser", ".", "add_subparsers", "(", "help", "=", "'Search by'", ")", "by_title", "=", "subparser", ".", "add_parser", "(", "'title'", ",", "help", "=", "'Book title'", ",", ")", "by_title", ".", "add_argument", "(", "'title'", ",", "help", "=", "'Book name'", ")", "by_isbn", "=", "subparser", ".", "add_parser", "(", "'isbn'", ",", "help", "=", "'ISBN code'", ")", "by_isbn", ".", "add_argument", "(", "'code'", ",", "help", "=", "'Valid ISBN code'", ")", "by_author", "=", "subparser", ".", "add_parser", "(", "'author'", ",", "help", "=", "'Book author'", ")", "by_author", ".", "add_argument", "(", "'author'", ",", "help", "=", "'Authors name'", ")", "by_author", ".", "add_argument", "(", "'--recent'", ",", "help", "=", "'Search by most recent'", ",", "action", "=", "'store_true'", ")", "by_author", ".", "add_argument", "(", "'--top'", ",", "help", "=", "'Search by best selling'", ",", "action", "=", "'store_true'", ")", "# Main Parser", "parser", ".", "add_argument", "(", "'-v'", ",", "'--version'", ",", "action", "=", "'version'", ",", "version", "=", "\"%s v%s\"", "%", "(", "'kan'", ",", "version", ")", ",", ")", "parser", ".", "add_argument", "(", "'--title'", ",", "help", "=", "'Title of the book'", ",", "metavar", "=", "'name'", ",", ")", "parser", ".", "add_argument", "(", "'--author'", ",", "default", "=", "None", ",", "metavar", "=", "'name'", ",", "help", "=", "'Name of the author'", ",", ")", "parser", ".", "add_argument", "(", "'--subject'", ",", "type", "=", "str", ",", "help", "=", "'Specify subject matter by category'", ",", "metavar", "=", "'topic'", ",", ")", "parser", ".", "add_argument", "(", "'--max'", ",", "type", "=", "int", ",", "metavar", "=", "'n'", ",", "default", "=", "3", ",", "choices", "=", "range", "(", "41", ")", ",", "help", "=", "'Maximum results to get per query: default=3, max=40'", ",", ")", "parser", ".", "add_argument", "(", "'--language'", ",", "type", "=", "str", ",", "metavar", "=", "'code'", ",", "default", "=", "''", ",", "help", "=", "'Restrict the search results to those with a certain language code'", ",", ")", "parser", ".", "add_argument", "(", "'--verbose'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Print out debug information'", ",", ")", "return", "parser", ".", "parse_args", "(", ")" ]
Parses users command line arguments and returns the namespace containing parsed values.
[ "Parses", "users", "command", "line", "arguments", "and", "returns", "the", "namespace", "containing", "parsed", "values", "." ]
7da9d9ec5dc6b8bbb86cfd27d737978a406d9fa6
https://github.com/jjangsangy/kan/blob/7da9d9ec5dc6b8bbb86cfd27d737978a406d9fa6/kan/__main__.py#L18-L83
248,210
edeposit/edeposit.amqp.calibre
src/edeposit/amqp/calibre/calibre.py
convert
def convert(input_format, output_format, b64_data): """ Convert `b64_data` fron `input_format` to `output_format`. Args: input_format (str): Specification of input format (pdf/epub/whatever), see :attr:`INPUT_FORMATS` for list. output_format (str): Specification of output format (pdf/epub/..), see :attr:`OUTPUT_FORMATS` for list. b64_data (str): Base64 encoded data. Returns: ConversionResponse: `namedtuple` structure with information about \ output ``format``, data (``b64_data``) and \ ``protocol`` from conversion. Structure is defined\ in :class:`.ConversionResponse`. Raises: AssertionError: When bad arguments are handed over. UserWarning: When conversion failed. """ # checks assert input_format in INPUT_FORMATS, "Unsupported input format!" assert output_format in OUTPUT_FORMATS, "Unsupported output format!" with NTFile(mode="wb", suffix="." + input_format, dir="/tmp") as ifile: ofilename = ifile.name + "." + output_format # save received data to the temporary file ifile.write(b64decode(b64_data)) ifile.flush() # free memory from base64 data b64_data = None gc.collect() # convert file protocol = "" try: with NTFile(mode="wb", suffix = ".stdout", dir="/tmp") as stdout: sh.ebook_convert(ifile.name, ofilename, _out=stdout).wait() stdout.flush() protocol = open(stdout.name).read() stdout.close() except sh.ErrorReturnCode_1, e: raise UserWarning( "Conversion failed:\n" + e.message.encode("utf-8", errors='ignore') ) if output_format.upper() + " output written to" not in protocol: raise UserWarning("Conversion failed:\n" + protocol) # read the data from the converted file output_data = None with open(ofilename, "rb") as ofile: output_data = _wrap( b64encode(ofile.read()) ) gc.collect() # we have experienced unplesant memory spikes # remove temporary output file os.remove(ofilename) return ConversionResponse( format=output_format, b64_data=output_data, protocol=protocol )
python
def convert(input_format, output_format, b64_data): """ Convert `b64_data` fron `input_format` to `output_format`. Args: input_format (str): Specification of input format (pdf/epub/whatever), see :attr:`INPUT_FORMATS` for list. output_format (str): Specification of output format (pdf/epub/..), see :attr:`OUTPUT_FORMATS` for list. b64_data (str): Base64 encoded data. Returns: ConversionResponse: `namedtuple` structure with information about \ output ``format``, data (``b64_data``) and \ ``protocol`` from conversion. Structure is defined\ in :class:`.ConversionResponse`. Raises: AssertionError: When bad arguments are handed over. UserWarning: When conversion failed. """ # checks assert input_format in INPUT_FORMATS, "Unsupported input format!" assert output_format in OUTPUT_FORMATS, "Unsupported output format!" with NTFile(mode="wb", suffix="." + input_format, dir="/tmp") as ifile: ofilename = ifile.name + "." + output_format # save received data to the temporary file ifile.write(b64decode(b64_data)) ifile.flush() # free memory from base64 data b64_data = None gc.collect() # convert file protocol = "" try: with NTFile(mode="wb", suffix = ".stdout", dir="/tmp") as stdout: sh.ebook_convert(ifile.name, ofilename, _out=stdout).wait() stdout.flush() protocol = open(stdout.name).read() stdout.close() except sh.ErrorReturnCode_1, e: raise UserWarning( "Conversion failed:\n" + e.message.encode("utf-8", errors='ignore') ) if output_format.upper() + " output written to" not in protocol: raise UserWarning("Conversion failed:\n" + protocol) # read the data from the converted file output_data = None with open(ofilename, "rb") as ofile: output_data = _wrap( b64encode(ofile.read()) ) gc.collect() # we have experienced unplesant memory spikes # remove temporary output file os.remove(ofilename) return ConversionResponse( format=output_format, b64_data=output_data, protocol=protocol )
[ "def", "convert", "(", "input_format", ",", "output_format", ",", "b64_data", ")", ":", "# checks", "assert", "input_format", "in", "INPUT_FORMATS", ",", "\"Unsupported input format!\"", "assert", "output_format", "in", "OUTPUT_FORMATS", ",", "\"Unsupported output format!\"", "with", "NTFile", "(", "mode", "=", "\"wb\"", ",", "suffix", "=", "\".\"", "+", "input_format", ",", "dir", "=", "\"/tmp\"", ")", "as", "ifile", ":", "ofilename", "=", "ifile", ".", "name", "+", "\".\"", "+", "output_format", "# save received data to the temporary file", "ifile", ".", "write", "(", "b64decode", "(", "b64_data", ")", ")", "ifile", ".", "flush", "(", ")", "# free memory from base64 data", "b64_data", "=", "None", "gc", ".", "collect", "(", ")", "# convert file", "protocol", "=", "\"\"", "try", ":", "with", "NTFile", "(", "mode", "=", "\"wb\"", ",", "suffix", "=", "\".stdout\"", ",", "dir", "=", "\"/tmp\"", ")", "as", "stdout", ":", "sh", ".", "ebook_convert", "(", "ifile", ".", "name", ",", "ofilename", ",", "_out", "=", "stdout", ")", ".", "wait", "(", ")", "stdout", ".", "flush", "(", ")", "protocol", "=", "open", "(", "stdout", ".", "name", ")", ".", "read", "(", ")", "stdout", ".", "close", "(", ")", "except", "sh", ".", "ErrorReturnCode_1", ",", "e", ":", "raise", "UserWarning", "(", "\"Conversion failed:\\n\"", "+", "e", ".", "message", ".", "encode", "(", "\"utf-8\"", ",", "errors", "=", "'ignore'", ")", ")", "if", "output_format", ".", "upper", "(", ")", "+", "\" output written to\"", "not", "in", "protocol", ":", "raise", "UserWarning", "(", "\"Conversion failed:\\n\"", "+", "protocol", ")", "# read the data from the converted file", "output_data", "=", "None", "with", "open", "(", "ofilename", ",", "\"rb\"", ")", "as", "ofile", ":", "output_data", "=", "_wrap", "(", "b64encode", "(", "ofile", ".", "read", "(", ")", ")", ")", "gc", ".", "collect", "(", ")", "# we have experienced unplesant memory spikes", "# remove temporary output file", "os", ".", "remove", "(", "ofilename", ")", "return", "ConversionResponse", "(", "format", "=", "output_format", ",", "b64_data", "=", "output_data", ",", "protocol", "=", "protocol", ")" ]
Convert `b64_data` fron `input_format` to `output_format`. Args: input_format (str): Specification of input format (pdf/epub/whatever), see :attr:`INPUT_FORMATS` for list. output_format (str): Specification of output format (pdf/epub/..), see :attr:`OUTPUT_FORMATS` for list. b64_data (str): Base64 encoded data. Returns: ConversionResponse: `namedtuple` structure with information about \ output ``format``, data (``b64_data``) and \ ``protocol`` from conversion. Structure is defined\ in :class:`.ConversionResponse`. Raises: AssertionError: When bad arguments are handed over. UserWarning: When conversion failed.
[ "Convert", "b64_data", "fron", "input_format", "to", "output_format", "." ]
60ba5de0c30452d41f6e0da58d2ec6729ebdd7f1
https://github.com/edeposit/edeposit.amqp.calibre/blob/60ba5de0c30452d41f6e0da58d2ec6729ebdd7f1/src/edeposit/amqp/calibre/calibre.py#L46-L114
248,211
thibault/libnexmo
libnexmo/base.py
Nexmo.send_sms
def send_sms(self, frm, to, text): """Sends a simple text message. Example usage:: >>> msg = "Cherie, n'oublie pas les gauffres !" >>> nexmo.send_sms('+33123456780', '+33987654321', msg) :arg frm: The `from` field, a phone number (international format with or without a leading "+" or alphanumerical). :arg to: The `to` field, a phone number, same format as the `frm` argument. :arg text: The message body. See :meth:`send_request` for return value and exceptions. """ frm = re.sub('[^\d]', '', frm) to = re.sub('[^\d]', '', to) api_url = '%s/sms/json' % API_ENDPOINT params = { 'api_key': self.api_key, 'api_secret': self.api_secret, 'from': frm, 'to': to, 'text': text, } return self.send_request(api_url, params, method='POST')
python
def send_sms(self, frm, to, text): """Sends a simple text message. Example usage:: >>> msg = "Cherie, n'oublie pas les gauffres !" >>> nexmo.send_sms('+33123456780', '+33987654321', msg) :arg frm: The `from` field, a phone number (international format with or without a leading "+" or alphanumerical). :arg to: The `to` field, a phone number, same format as the `frm` argument. :arg text: The message body. See :meth:`send_request` for return value and exceptions. """ frm = re.sub('[^\d]', '', frm) to = re.sub('[^\d]', '', to) api_url = '%s/sms/json' % API_ENDPOINT params = { 'api_key': self.api_key, 'api_secret': self.api_secret, 'from': frm, 'to': to, 'text': text, } return self.send_request(api_url, params, method='POST')
[ "def", "send_sms", "(", "self", ",", "frm", ",", "to", ",", "text", ")", ":", "frm", "=", "re", ".", "sub", "(", "'[^\\d]'", ",", "''", ",", "frm", ")", "to", "=", "re", ".", "sub", "(", "'[^\\d]'", ",", "''", ",", "to", ")", "api_url", "=", "'%s/sms/json'", "%", "API_ENDPOINT", "params", "=", "{", "'api_key'", ":", "self", ".", "api_key", ",", "'api_secret'", ":", "self", ".", "api_secret", ",", "'from'", ":", "frm", ",", "'to'", ":", "to", ",", "'text'", ":", "text", ",", "}", "return", "self", ".", "send_request", "(", "api_url", ",", "params", ",", "method", "=", "'POST'", ")" ]
Sends a simple text message. Example usage:: >>> msg = "Cherie, n'oublie pas les gauffres !" >>> nexmo.send_sms('+33123456780', '+33987654321', msg) :arg frm: The `from` field, a phone number (international format with or without a leading "+" or alphanumerical). :arg to: The `to` field, a phone number, same format as the `frm` argument. :arg text: The message body. See :meth:`send_request` for return value and exceptions.
[ "Sends", "a", "simple", "text", "message", "." ]
ed6cb6379bbcfd622f32d4e65f1a3f40f7910286
https://github.com/thibault/libnexmo/blob/ed6cb6379bbcfd622f32d4e65f1a3f40f7910286/libnexmo/base.py#L32-L60
248,212
thibault/libnexmo
libnexmo/base.py
Nexmo.send_request
def send_request(self, url, params, method='GET'): """Sends a raw request to the given api endpoint. :arg url: A Nexmpo api endpoint (json only) :arg params: A parameter dictionnary Returns a :class:`~libnexmo.NexmoResponse`. Raises: The library uses `Requests <http://docs.python-requests.org/en/latest/>`_ to perform http requests. `Requests exceptions <http://docs.python-requests.org/en/latest/api/#requests.exceptions.RequestException>`_ won't be caught in case of connection error. Any :class:`~libnexmo.exceptions.NexmoError` subclass. """ method = method.lower() if method not in ['get', 'post']: raise ValueError('The `method` parameter must be either `get` or `post`') response = requests.request(method, url, data=params) response_json = response.json() status = int(response_json['messages'][0]['status']) if status != 0: ErrorClass = status_to_error(status) error = response_json['messages'][0]['error-text'] raise ErrorClass(error) return NexmoResponse(response_json)
python
def send_request(self, url, params, method='GET'): """Sends a raw request to the given api endpoint. :arg url: A Nexmpo api endpoint (json only) :arg params: A parameter dictionnary Returns a :class:`~libnexmo.NexmoResponse`. Raises: The library uses `Requests <http://docs.python-requests.org/en/latest/>`_ to perform http requests. `Requests exceptions <http://docs.python-requests.org/en/latest/api/#requests.exceptions.RequestException>`_ won't be caught in case of connection error. Any :class:`~libnexmo.exceptions.NexmoError` subclass. """ method = method.lower() if method not in ['get', 'post']: raise ValueError('The `method` parameter must be either `get` or `post`') response = requests.request(method, url, data=params) response_json = response.json() status = int(response_json['messages'][0]['status']) if status != 0: ErrorClass = status_to_error(status) error = response_json['messages'][0]['error-text'] raise ErrorClass(error) return NexmoResponse(response_json)
[ "def", "send_request", "(", "self", ",", "url", ",", "params", ",", "method", "=", "'GET'", ")", ":", "method", "=", "method", ".", "lower", "(", ")", "if", "method", "not", "in", "[", "'get'", ",", "'post'", "]", ":", "raise", "ValueError", "(", "'The `method` parameter must be either `get` or `post`'", ")", "response", "=", "requests", ".", "request", "(", "method", ",", "url", ",", "data", "=", "params", ")", "response_json", "=", "response", ".", "json", "(", ")", "status", "=", "int", "(", "response_json", "[", "'messages'", "]", "[", "0", "]", "[", "'status'", "]", ")", "if", "status", "!=", "0", ":", "ErrorClass", "=", "status_to_error", "(", "status", ")", "error", "=", "response_json", "[", "'messages'", "]", "[", "0", "]", "[", "'error-text'", "]", "raise", "ErrorClass", "(", "error", ")", "return", "NexmoResponse", "(", "response_json", ")" ]
Sends a raw request to the given api endpoint. :arg url: A Nexmpo api endpoint (json only) :arg params: A parameter dictionnary Returns a :class:`~libnexmo.NexmoResponse`. Raises: The library uses `Requests <http://docs.python-requests.org/en/latest/>`_ to perform http requests. `Requests exceptions <http://docs.python-requests.org/en/latest/api/#requests.exceptions.RequestException>`_ won't be caught in case of connection error. Any :class:`~libnexmo.exceptions.NexmoError` subclass.
[ "Sends", "a", "raw", "request", "to", "the", "given", "api", "endpoint", "." ]
ed6cb6379bbcfd622f32d4e65f1a3f40f7910286
https://github.com/thibault/libnexmo/blob/ed6cb6379bbcfd622f32d4e65f1a3f40f7910286/libnexmo/base.py#L62-L95
248,213
pavelsof/ipatok
ipatok/tokens.py
tokenise
def tokenise(string, strict=False, replace=False, diphtongs=False, tones=False, unknown=False, merge=None): """ Tokenise an IPA string into a list of tokens. Raise ValueError if there is a problem; if strict=True, this includes the string not being compliant to the IPA spec. If replace=True, replace some common non-IPA symbols with their IPA counterparts. If diphtongs=True, try to group diphtongs into single tokens. If tones=True, do not ignore tone symbols. If unknown=True, do not ignore symbols that cannot be classified into a relevant category. If merge is not None, use it for within-word token grouping. Part of ipatok's public API. """ words = string.strip().replace('_', ' ').split() output = [] for word in words: tokens = tokenise_word(word, strict, replace, tones, unknown) if diphtongs: tokens = group(are_diphtong, tokens) if merge is not None: tokens = group(merge, tokens) output.extend(tokens) return output
python
def tokenise(string, strict=False, replace=False, diphtongs=False, tones=False, unknown=False, merge=None): """ Tokenise an IPA string into a list of tokens. Raise ValueError if there is a problem; if strict=True, this includes the string not being compliant to the IPA spec. If replace=True, replace some common non-IPA symbols with their IPA counterparts. If diphtongs=True, try to group diphtongs into single tokens. If tones=True, do not ignore tone symbols. If unknown=True, do not ignore symbols that cannot be classified into a relevant category. If merge is not None, use it for within-word token grouping. Part of ipatok's public API. """ words = string.strip().replace('_', ' ').split() output = [] for word in words: tokens = tokenise_word(word, strict, replace, tones, unknown) if diphtongs: tokens = group(are_diphtong, tokens) if merge is not None: tokens = group(merge, tokens) output.extend(tokens) return output
[ "def", "tokenise", "(", "string", ",", "strict", "=", "False", ",", "replace", "=", "False", ",", "diphtongs", "=", "False", ",", "tones", "=", "False", ",", "unknown", "=", "False", ",", "merge", "=", "None", ")", ":", "words", "=", "string", ".", "strip", "(", ")", ".", "replace", "(", "'_'", ",", "' '", ")", ".", "split", "(", ")", "output", "=", "[", "]", "for", "word", "in", "words", ":", "tokens", "=", "tokenise_word", "(", "word", ",", "strict", ",", "replace", ",", "tones", ",", "unknown", ")", "if", "diphtongs", ":", "tokens", "=", "group", "(", "are_diphtong", ",", "tokens", ")", "if", "merge", "is", "not", "None", ":", "tokens", "=", "group", "(", "merge", ",", "tokens", ")", "output", ".", "extend", "(", "tokens", ")", "return", "output" ]
Tokenise an IPA string into a list of tokens. Raise ValueError if there is a problem; if strict=True, this includes the string not being compliant to the IPA spec. If replace=True, replace some common non-IPA symbols with their IPA counterparts. If diphtongs=True, try to group diphtongs into single tokens. If tones=True, do not ignore tone symbols. If unknown=True, do not ignore symbols that cannot be classified into a relevant category. If merge is not None, use it for within-word token grouping. Part of ipatok's public API.
[ "Tokenise", "an", "IPA", "string", "into", "a", "list", "of", "tokens", ".", "Raise", "ValueError", "if", "there", "is", "a", "problem", ";", "if", "strict", "=", "True", "this", "includes", "the", "string", "not", "being", "compliant", "to", "the", "IPA", "spec", "." ]
fde3c334b8573315fd1073f14341b71f50f7f006
https://github.com/pavelsof/ipatok/blob/fde3c334b8573315fd1073f14341b71f50f7f006/ipatok/tokens.py#L150-L179
248,214
KnowledgeLinks/rdfframework
rdfframework/framework.py
verify_server_core
def verify_server_core(timeout=120, start_delay=90): ''' checks to see if the server_core is running args: delay: will cycle till core is up. timeout: number of seconds to wait ''' timestamp = time.time() last_check = time.time() + start_delay - 10 last_delay_notification = time.time() - 10 server_down = True return_val = False timeout += 1 # loop until the server is up or the timeout is reached while((time.time()-timestamp) < timeout) and server_down: # if delaying, the start of the check, print waiting to start if start_delay > 0 and time.time() - timestamp < start_delay \ and (time.time()-last_delay_notification) > 5: print("Delaying server status check until %ss. Current time: %ss" \ % (start_delay, int(time.time() - timestamp))) last_delay_notification = time.time() # send a request check every 10s until the server is up while ((time.time()-last_check) > 10) and server_down: print("Checking status of servers at %ss" % \ int((time.time()-timestamp))) last_check = time.time() try: repo = requests.get(CFG.REPOSITORY_URL) repo_code = repo.status_code print ("\t", CFG.REPOSITORY_URL, " - ", repo_code) except: repo_code = 400 print ("\t", CFG.REPOSITORY_URL, " - DOWN") try: triple = requests.get(CFG.DATA_TRIPLESTORE.url) triple_code = triple.status_code print ("\t", CFG.DATA_TRIPLESTORE.url, " - ", triple_code) except: triple_code = 400 print ("\t", CFG.DATA_TRIPLESTORE.url, " - down") if repo_code == 200 and triple_code == 200: server_down = False return_val = True print("**** Servers up at %ss" % \ int((time.time()-timestamp))) break return return_val
python
def verify_server_core(timeout=120, start_delay=90): ''' checks to see if the server_core is running args: delay: will cycle till core is up. timeout: number of seconds to wait ''' timestamp = time.time() last_check = time.time() + start_delay - 10 last_delay_notification = time.time() - 10 server_down = True return_val = False timeout += 1 # loop until the server is up or the timeout is reached while((time.time()-timestamp) < timeout) and server_down: # if delaying, the start of the check, print waiting to start if start_delay > 0 and time.time() - timestamp < start_delay \ and (time.time()-last_delay_notification) > 5: print("Delaying server status check until %ss. Current time: %ss" \ % (start_delay, int(time.time() - timestamp))) last_delay_notification = time.time() # send a request check every 10s until the server is up while ((time.time()-last_check) > 10) and server_down: print("Checking status of servers at %ss" % \ int((time.time()-timestamp))) last_check = time.time() try: repo = requests.get(CFG.REPOSITORY_URL) repo_code = repo.status_code print ("\t", CFG.REPOSITORY_URL, " - ", repo_code) except: repo_code = 400 print ("\t", CFG.REPOSITORY_URL, " - DOWN") try: triple = requests.get(CFG.DATA_TRIPLESTORE.url) triple_code = triple.status_code print ("\t", CFG.DATA_TRIPLESTORE.url, " - ", triple_code) except: triple_code = 400 print ("\t", CFG.DATA_TRIPLESTORE.url, " - down") if repo_code == 200 and triple_code == 200: server_down = False return_val = True print("**** Servers up at %ss" % \ int((time.time()-timestamp))) break return return_val
[ "def", "verify_server_core", "(", "timeout", "=", "120", ",", "start_delay", "=", "90", ")", ":", "timestamp", "=", "time", ".", "time", "(", ")", "last_check", "=", "time", ".", "time", "(", ")", "+", "start_delay", "-", "10", "last_delay_notification", "=", "time", ".", "time", "(", ")", "-", "10", "server_down", "=", "True", "return_val", "=", "False", "timeout", "+=", "1", "# loop until the server is up or the timeout is reached", "while", "(", "(", "time", ".", "time", "(", ")", "-", "timestamp", ")", "<", "timeout", ")", "and", "server_down", ":", "# if delaying, the start of the check, print waiting to start", "if", "start_delay", ">", "0", "and", "time", ".", "time", "(", ")", "-", "timestamp", "<", "start_delay", "and", "(", "time", ".", "time", "(", ")", "-", "last_delay_notification", ")", ">", "5", ":", "print", "(", "\"Delaying server status check until %ss. Current time: %ss\"", "%", "(", "start_delay", ",", "int", "(", "time", ".", "time", "(", ")", "-", "timestamp", ")", ")", ")", "last_delay_notification", "=", "time", ".", "time", "(", ")", "# send a request check every 10s until the server is up", "while", "(", "(", "time", ".", "time", "(", ")", "-", "last_check", ")", ">", "10", ")", "and", "server_down", ":", "print", "(", "\"Checking status of servers at %ss\"", "%", "int", "(", "(", "time", ".", "time", "(", ")", "-", "timestamp", ")", ")", ")", "last_check", "=", "time", ".", "time", "(", ")", "try", ":", "repo", "=", "requests", ".", "get", "(", "CFG", ".", "REPOSITORY_URL", ")", "repo_code", "=", "repo", ".", "status_code", "print", "(", "\"\\t\"", ",", "CFG", ".", "REPOSITORY_URL", ",", "\" - \"", ",", "repo_code", ")", "except", ":", "repo_code", "=", "400", "print", "(", "\"\\t\"", ",", "CFG", ".", "REPOSITORY_URL", ",", "\" - DOWN\"", ")", "try", ":", "triple", "=", "requests", ".", "get", "(", "CFG", ".", "DATA_TRIPLESTORE", ".", "url", ")", "triple_code", "=", "triple", ".", "status_code", "print", "(", "\"\\t\"", ",", "CFG", ".", "DATA_TRIPLESTORE", ".", "url", ",", "\" - \"", ",", "triple_code", ")", "except", ":", "triple_code", "=", "400", "print", "(", "\"\\t\"", ",", "CFG", ".", "DATA_TRIPLESTORE", ".", "url", ",", "\" - down\"", ")", "if", "repo_code", "==", "200", "and", "triple_code", "==", "200", ":", "server_down", "=", "False", "return_val", "=", "True", "print", "(", "\"**** Servers up at %ss\"", "%", "int", "(", "(", "time", ".", "time", "(", ")", "-", "timestamp", ")", ")", ")", "break", "return", "return_val" ]
checks to see if the server_core is running args: delay: will cycle till core is up. timeout: number of seconds to wait
[ "checks", "to", "see", "if", "the", "server_core", "is", "running" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/framework.py#L221-L267
248,215
KnowledgeLinks/rdfframework
rdfframework/framework.py
RdfFramework.load_rml
def load_rml(self, rml_name): """ loads an rml mapping into memory args: rml_name(str): the name of the rml file """ conn = CFG.rml_tstore cache_path = os.path.join(CFG.CACHE_DATA_PATH, 'rml_files', rml_name) if not os.path.exists(cache_path): results = get_graph(NSM.uri(getattr(NSM.kdr, rml_name), False), conn) with open(cache_path, "w") as file_obj: file_obj.write(json.dumps(results, indent=4)) else: results = json.loads(open(cache_path).read()) self.rml[rml_name] = RdfDataset(results) return self.rml[rml_name]
python
def load_rml(self, rml_name): """ loads an rml mapping into memory args: rml_name(str): the name of the rml file """ conn = CFG.rml_tstore cache_path = os.path.join(CFG.CACHE_DATA_PATH, 'rml_files', rml_name) if not os.path.exists(cache_path): results = get_graph(NSM.uri(getattr(NSM.kdr, rml_name), False), conn) with open(cache_path, "w") as file_obj: file_obj.write(json.dumps(results, indent=4)) else: results = json.loads(open(cache_path).read()) self.rml[rml_name] = RdfDataset(results) return self.rml[rml_name]
[ "def", "load_rml", "(", "self", ",", "rml_name", ")", ":", "conn", "=", "CFG", ".", "rml_tstore", "cache_path", "=", "os", ".", "path", ".", "join", "(", "CFG", ".", "CACHE_DATA_PATH", ",", "'rml_files'", ",", "rml_name", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "cache_path", ")", ":", "results", "=", "get_graph", "(", "NSM", ".", "uri", "(", "getattr", "(", "NSM", ".", "kdr", ",", "rml_name", ")", ",", "False", ")", ",", "conn", ")", "with", "open", "(", "cache_path", ",", "\"w\"", ")", "as", "file_obj", ":", "file_obj", ".", "write", "(", "json", ".", "dumps", "(", "results", ",", "indent", "=", "4", ")", ")", "else", ":", "results", "=", "json", ".", "loads", "(", "open", "(", "cache_path", ")", ".", "read", "(", ")", ")", "self", ".", "rml", "[", "rml_name", "]", "=", "RdfDataset", "(", "results", ")", "return", "self", ".", "rml", "[", "rml_name", "]" ]
loads an rml mapping into memory args: rml_name(str): the name of the rml file
[ "loads", "an", "rml", "mapping", "into", "memory" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/framework.py#L87-L103
248,216
KnowledgeLinks/rdfframework
rdfframework/framework.py
RdfFramework.get_rml
def get_rml(self, rml_name): """ returns the rml mapping RdfDataset rml_name(str): Name of the rml mapping to retrieve """ try: return getattr(self, rml_name) except AttributeError: return self.load_rml(rml_name)
python
def get_rml(self, rml_name): """ returns the rml mapping RdfDataset rml_name(str): Name of the rml mapping to retrieve """ try: return getattr(self, rml_name) except AttributeError: return self.load_rml(rml_name)
[ "def", "get_rml", "(", "self", ",", "rml_name", ")", ":", "try", ":", "return", "getattr", "(", "self", ",", "rml_name", ")", "except", "AttributeError", ":", "return", "self", ".", "load_rml", "(", "rml_name", ")" ]
returns the rml mapping RdfDataset rml_name(str): Name of the rml mapping to retrieve
[ "returns", "the", "rml", "mapping", "RdfDataset" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/framework.py#L105-L114
248,217
KnowledgeLinks/rdfframework
rdfframework/framework.py
RdfFramework._set_data_filelist
def _set_data_filelist(self, start_path, attr_name, conn, file_exts=[], dir_filter=set()): ''' does a directory search for data files ''' def filter_path(filter_terms, dir_path): """ sees if any of the terms are present in the path if so returns True args: filter_terms(list): terms to check dir_path: the path of the directory """ if filter_terms.intersection(set(dir_path.split(os.path.sep))): return True else: return False data_obj = {} files_dict = {} latest_mod = 0 dir_filter = set(dir_filter) for root, dirnames, filenames in os.walk(start_path): if not dir_filter or filter_path(dir_filter, root): if file_exts: filenames = [x for x in filenames if x.split('.')[-1].lower() in file_exts] files_dict[root] = filenames for def_file in filenames: file_mod = os.path.getmtime(os.path.join(root,def_file)) if file_mod > latest_mod: latest_mod = file_mod data_obj['latest_mod'] = latest_mod data_obj['files'] = files_dict json_mod = 0 cache_path = os.path.join(CFG.CACHE_DATA_PATH, attr_name) if cache_path: for root, dirnames, filenames in os.walk(cache_path): for json_file in filenames: file_mod = os.path.getmtime(os.path.join(root,json_file)) if file_mod > json_mod: json_mod = file_mod data_obj['last_json_mod'] = json_mod data_obj['conn'] = conn data_obj['cache_path'] = cache_path self.datafile_obj[attr_name] = data_obj
python
def _set_data_filelist(self, start_path, attr_name, conn, file_exts=[], dir_filter=set()): ''' does a directory search for data files ''' def filter_path(filter_terms, dir_path): """ sees if any of the terms are present in the path if so returns True args: filter_terms(list): terms to check dir_path: the path of the directory """ if filter_terms.intersection(set(dir_path.split(os.path.sep))): return True else: return False data_obj = {} files_dict = {} latest_mod = 0 dir_filter = set(dir_filter) for root, dirnames, filenames in os.walk(start_path): if not dir_filter or filter_path(dir_filter, root): if file_exts: filenames = [x for x in filenames if x.split('.')[-1].lower() in file_exts] files_dict[root] = filenames for def_file in filenames: file_mod = os.path.getmtime(os.path.join(root,def_file)) if file_mod > latest_mod: latest_mod = file_mod data_obj['latest_mod'] = latest_mod data_obj['files'] = files_dict json_mod = 0 cache_path = os.path.join(CFG.CACHE_DATA_PATH, attr_name) if cache_path: for root, dirnames, filenames in os.walk(cache_path): for json_file in filenames: file_mod = os.path.getmtime(os.path.join(root,json_file)) if file_mod > json_mod: json_mod = file_mod data_obj['last_json_mod'] = json_mod data_obj['conn'] = conn data_obj['cache_path'] = cache_path self.datafile_obj[attr_name] = data_obj
[ "def", "_set_data_filelist", "(", "self", ",", "start_path", ",", "attr_name", ",", "conn", ",", "file_exts", "=", "[", "]", ",", "dir_filter", "=", "set", "(", ")", ")", ":", "def", "filter_path", "(", "filter_terms", ",", "dir_path", ")", ":", "\"\"\" sees if any of the terms are present in the path if so returns\n True\n\n args:\n filter_terms(list): terms to check\n dir_path: the path of the directory\n \"\"\"", "if", "filter_terms", ".", "intersection", "(", "set", "(", "dir_path", ".", "split", "(", "os", ".", "path", ".", "sep", ")", ")", ")", ":", "return", "True", "else", ":", "return", "False", "data_obj", "=", "{", "}", "files_dict", "=", "{", "}", "latest_mod", "=", "0", "dir_filter", "=", "set", "(", "dir_filter", ")", "for", "root", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "start_path", ")", ":", "if", "not", "dir_filter", "or", "filter_path", "(", "dir_filter", ",", "root", ")", ":", "if", "file_exts", ":", "filenames", "=", "[", "x", "for", "x", "in", "filenames", "if", "x", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", ".", "lower", "(", ")", "in", "file_exts", "]", "files_dict", "[", "root", "]", "=", "filenames", "for", "def_file", "in", "filenames", ":", "file_mod", "=", "os", ".", "path", ".", "getmtime", "(", "os", ".", "path", ".", "join", "(", "root", ",", "def_file", ")", ")", "if", "file_mod", ">", "latest_mod", ":", "latest_mod", "=", "file_mod", "data_obj", "[", "'latest_mod'", "]", "=", "latest_mod", "data_obj", "[", "'files'", "]", "=", "files_dict", "json_mod", "=", "0", "cache_path", "=", "os", ".", "path", ".", "join", "(", "CFG", ".", "CACHE_DATA_PATH", ",", "attr_name", ")", "if", "cache_path", ":", "for", "root", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "cache_path", ")", ":", "for", "json_file", "in", "filenames", ":", "file_mod", "=", "os", ".", "path", ".", "getmtime", "(", "os", ".", "path", ".", "join", "(", "root", ",", "json_file", ")", ")", "if", "file_mod", ">", "json_mod", ":", "json_mod", "=", "file_mod", "data_obj", "[", "'last_json_mod'", "]", "=", "json_mod", "data_obj", "[", "'conn'", "]", "=", "conn", "data_obj", "[", "'cache_path'", "]", "=", "cache_path", "self", ".", "datafile_obj", "[", "attr_name", "]", "=", "data_obj" ]
does a directory search for data files
[ "does", "a", "directory", "search", "for", "data", "files" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/framework.py#L171-L219
248,218
devricks/soft_drf
soft_drf/auth/authentication.py
BaseJSONWebTokenAuthentication.authenticate
def authenticate(self, request): """ Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`. """ jwt_value = self.get_jwt_value(request) if jwt_value is None: return None try: payload = jwt_decode_handler(jwt_value) except jwt.ExpiredSignature: msg = _('Signature has expired.') raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: msg = _('Error decoding signature.') raise exceptions.AuthenticationFailed(msg) except jwt.InvalidTokenError: raise exceptions.AuthenticationFailed() user = self.authenticate_credentials(payload) return (user, jwt_value)
python
def authenticate(self, request): """ Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`. """ jwt_value = self.get_jwt_value(request) if jwt_value is None: return None try: payload = jwt_decode_handler(jwt_value) except jwt.ExpiredSignature: msg = _('Signature has expired.') raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: msg = _('Error decoding signature.') raise exceptions.AuthenticationFailed(msg) except jwt.InvalidTokenError: raise exceptions.AuthenticationFailed() user = self.authenticate_credentials(payload) return (user, jwt_value)
[ "def", "authenticate", "(", "self", ",", "request", ")", ":", "jwt_value", "=", "self", ".", "get_jwt_value", "(", "request", ")", "if", "jwt_value", "is", "None", ":", "return", "None", "try", ":", "payload", "=", "jwt_decode_handler", "(", "jwt_value", ")", "except", "jwt", ".", "ExpiredSignature", ":", "msg", "=", "_", "(", "'Signature has expired.'", ")", "raise", "exceptions", ".", "AuthenticationFailed", "(", "msg", ")", "except", "jwt", ".", "DecodeError", ":", "msg", "=", "_", "(", "'Error decoding signature.'", ")", "raise", "exceptions", ".", "AuthenticationFailed", "(", "msg", ")", "except", "jwt", ".", "InvalidTokenError", ":", "raise", "exceptions", ".", "AuthenticationFailed", "(", ")", "user", "=", "self", ".", "authenticate_credentials", "(", "payload", ")", "return", "(", "user", ",", "jwt_value", ")" ]
Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`.
[ "Returns", "a", "two", "-", "tuple", "of", "User", "and", "token", "if", "a", "valid", "signature", "has", "been", "supplied", "using", "JWT", "-", "based", "authentication", ".", "Otherwise", "returns", "None", "." ]
1869b13f9341bfcebd931059e93de2bc38570da3
https://github.com/devricks/soft_drf/blob/1869b13f9341bfcebd931059e93de2bc38570da3/soft_drf/auth/authentication.py#L29-L51
248,219
rorr73/LifeSOSpy
lifesospy/util.py
to_ascii_hex
def to_ascii_hex(value: int, digits: int) -> str: """Converts an int value to ASCII hex, as used by LifeSOS. Unlike regular hex, it uses the first 6 characters that follow numerics on the ASCII table instead of A - F.""" if digits < 1: return '' text = '' for _ in range(0, digits): text = chr(ord('0') + (value % 0x10)) + text value //= 0x10 return text
python
def to_ascii_hex(value: int, digits: int) -> str: """Converts an int value to ASCII hex, as used by LifeSOS. Unlike regular hex, it uses the first 6 characters that follow numerics on the ASCII table instead of A - F.""" if digits < 1: return '' text = '' for _ in range(0, digits): text = chr(ord('0') + (value % 0x10)) + text value //= 0x10 return text
[ "def", "to_ascii_hex", "(", "value", ":", "int", ",", "digits", ":", "int", ")", "->", "str", ":", "if", "digits", "<", "1", ":", "return", "''", "text", "=", "''", "for", "_", "in", "range", "(", "0", ",", "digits", ")", ":", "text", "=", "chr", "(", "ord", "(", "'0'", ")", "+", "(", "value", "%", "0x10", ")", ")", "+", "text", "value", "//=", "0x10", "return", "text" ]
Converts an int value to ASCII hex, as used by LifeSOS. Unlike regular hex, it uses the first 6 characters that follow numerics on the ASCII table instead of A - F.
[ "Converts", "an", "int", "value", "to", "ASCII", "hex", "as", "used", "by", "LifeSOS", ".", "Unlike", "regular", "hex", "it", "uses", "the", "first", "6", "characters", "that", "follow", "numerics", "on", "the", "ASCII", "table", "instead", "of", "A", "-", "F", "." ]
62360fbab2e90bf04d52b547093bdab2d4e389b4
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/util.py#L17-L27
248,220
rorr73/LifeSOSpy
lifesospy/util.py
serializable
def serializable(obj: Any, on_filter: Callable[[Any, str], bool] = None) -> Any: """ Ensures the specified object is serializable, converting if necessary. :param obj: the object to use. :param on_filter: optional function that can be used to filter which properties on the object will be included. :return value representing the object, which is serializable. """ # Will be called recursively when object has children def _serializable(parent_obj: Any, obj: Any, on_filter: Callable[[Any, str], bool]) -> Any: # None can be left as-is if obj is None: return obj # IntFlag enums should be broken down to a list of names elif isinstance(obj, IntFlag): value = str(obj) if value == '0': return None return value.split('|') # Any other enum just use the name elif isinstance(obj, Enum): return str(obj) # Simple types can be left as-is elif isinstance(obj, (bool, int, float, str)): return obj # Class supports method to convert to serializable dictionary; use it elif hasattr(obj, 'as_dict') and parent_obj is not None: return obj.as_dict() elif isinstance(obj, dict): # Dictionaries will require us to check each key and value new_dict = {} for item in obj.items(): new_dict[_serializable(obj, item[0], on_filter=on_filter)] = \ _serializable(obj, item[1], on_filter=on_filter) return new_dict elif isinstance(obj, (list, Container)): # Lists will require us to check each item items = obj # type: Iterable new_list = [] for item in items: new_list.append(_serializable(obj, item, on_filter=on_filter)) return new_list # Convert to a dictionary of property name/values data = {} for name in dir(obj.__class__): if not isinstance(getattr(obj.__class__, name), property): continue elif on_filter and not on_filter(obj, name): continue value = getattr(obj, name) data[name] = _serializable(obj, value, on_filter=on_filter) return data return _serializable(None, obj, on_filter)
python
def serializable(obj: Any, on_filter: Callable[[Any, str], bool] = None) -> Any: """ Ensures the specified object is serializable, converting if necessary. :param obj: the object to use. :param on_filter: optional function that can be used to filter which properties on the object will be included. :return value representing the object, which is serializable. """ # Will be called recursively when object has children def _serializable(parent_obj: Any, obj: Any, on_filter: Callable[[Any, str], bool]) -> Any: # None can be left as-is if obj is None: return obj # IntFlag enums should be broken down to a list of names elif isinstance(obj, IntFlag): value = str(obj) if value == '0': return None return value.split('|') # Any other enum just use the name elif isinstance(obj, Enum): return str(obj) # Simple types can be left as-is elif isinstance(obj, (bool, int, float, str)): return obj # Class supports method to convert to serializable dictionary; use it elif hasattr(obj, 'as_dict') and parent_obj is not None: return obj.as_dict() elif isinstance(obj, dict): # Dictionaries will require us to check each key and value new_dict = {} for item in obj.items(): new_dict[_serializable(obj, item[0], on_filter=on_filter)] = \ _serializable(obj, item[1], on_filter=on_filter) return new_dict elif isinstance(obj, (list, Container)): # Lists will require us to check each item items = obj # type: Iterable new_list = [] for item in items: new_list.append(_serializable(obj, item, on_filter=on_filter)) return new_list # Convert to a dictionary of property name/values data = {} for name in dir(obj.__class__): if not isinstance(getattr(obj.__class__, name), property): continue elif on_filter and not on_filter(obj, name): continue value = getattr(obj, name) data[name] = _serializable(obj, value, on_filter=on_filter) return data return _serializable(None, obj, on_filter)
[ "def", "serializable", "(", "obj", ":", "Any", ",", "on_filter", ":", "Callable", "[", "[", "Any", ",", "str", "]", ",", "bool", "]", "=", "None", ")", "->", "Any", ":", "# Will be called recursively when object has children", "def", "_serializable", "(", "parent_obj", ":", "Any", ",", "obj", ":", "Any", ",", "on_filter", ":", "Callable", "[", "[", "Any", ",", "str", "]", ",", "bool", "]", ")", "->", "Any", ":", "# None can be left as-is", "if", "obj", "is", "None", ":", "return", "obj", "# IntFlag enums should be broken down to a list of names", "elif", "isinstance", "(", "obj", ",", "IntFlag", ")", ":", "value", "=", "str", "(", "obj", ")", "if", "value", "==", "'0'", ":", "return", "None", "return", "value", ".", "split", "(", "'|'", ")", "# Any other enum just use the name", "elif", "isinstance", "(", "obj", ",", "Enum", ")", ":", "return", "str", "(", "obj", ")", "# Simple types can be left as-is", "elif", "isinstance", "(", "obj", ",", "(", "bool", ",", "int", ",", "float", ",", "str", ")", ")", ":", "return", "obj", "# Class supports method to convert to serializable dictionary; use it", "elif", "hasattr", "(", "obj", ",", "'as_dict'", ")", "and", "parent_obj", "is", "not", "None", ":", "return", "obj", ".", "as_dict", "(", ")", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "# Dictionaries will require us to check each key and value", "new_dict", "=", "{", "}", "for", "item", "in", "obj", ".", "items", "(", ")", ":", "new_dict", "[", "_serializable", "(", "obj", ",", "item", "[", "0", "]", ",", "on_filter", "=", "on_filter", ")", "]", "=", "_serializable", "(", "obj", ",", "item", "[", "1", "]", ",", "on_filter", "=", "on_filter", ")", "return", "new_dict", "elif", "isinstance", "(", "obj", ",", "(", "list", ",", "Container", ")", ")", ":", "# Lists will require us to check each item", "items", "=", "obj", "# type: Iterable", "new_list", "=", "[", "]", "for", "item", "in", "items", ":", "new_list", ".", "append", "(", "_serializable", "(", "obj", ",", "item", ",", "on_filter", "=", "on_filter", ")", ")", "return", "new_list", "# Convert to a dictionary of property name/values", "data", "=", "{", "}", "for", "name", "in", "dir", "(", "obj", ".", "__class__", ")", ":", "if", "not", "isinstance", "(", "getattr", "(", "obj", ".", "__class__", ",", "name", ")", ",", "property", ")", ":", "continue", "elif", "on_filter", "and", "not", "on_filter", "(", "obj", ",", "name", ")", ":", "continue", "value", "=", "getattr", "(", "obj", ",", "name", ")", "data", "[", "name", "]", "=", "_serializable", "(", "obj", ",", "value", ",", "on_filter", "=", "on_filter", ")", "return", "data", "return", "_serializable", "(", "None", ",", "obj", ",", "on_filter", ")" ]
Ensures the specified object is serializable, converting if necessary. :param obj: the object to use. :param on_filter: optional function that can be used to filter which properties on the object will be included. :return value representing the object, which is serializable.
[ "Ensures", "the", "specified", "object", "is", "serializable", "converting", "if", "necessary", "." ]
62360fbab2e90bf04d52b547093bdab2d4e389b4
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/util.py#L61-L124
248,221
rorr73/LifeSOSpy
lifesospy/util.py
encode_value_using_ma
def encode_value_using_ma(message_attribute: int, value: Optional[Union[int, float]]) -> int: """Encode special sensor value using the message attribute.""" if message_attribute == MA_TX3AC_100A: # TX-3AC in 100A mode; use value as-is, with 0xFE indicating null if value is None: return 0xfe return int(value) elif message_attribute == MA_TX3AC_10A: # TX-3AC in 10A mode; shift decimal point, with 0xFE indicating null if value is None: return 0xfe return int(value * 10) else: # Signed byte, with 0x80 indicating null if value is None: return 0x80 elif value < 0: return 0x100 + int(value) return int(value)
python
def encode_value_using_ma(message_attribute: int, value: Optional[Union[int, float]]) -> int: """Encode special sensor value using the message attribute.""" if message_attribute == MA_TX3AC_100A: # TX-3AC in 100A mode; use value as-is, with 0xFE indicating null if value is None: return 0xfe return int(value) elif message_attribute == MA_TX3AC_10A: # TX-3AC in 10A mode; shift decimal point, with 0xFE indicating null if value is None: return 0xfe return int(value * 10) else: # Signed byte, with 0x80 indicating null if value is None: return 0x80 elif value < 0: return 0x100 + int(value) return int(value)
[ "def", "encode_value_using_ma", "(", "message_attribute", ":", "int", ",", "value", ":", "Optional", "[", "Union", "[", "int", ",", "float", "]", "]", ")", "->", "int", ":", "if", "message_attribute", "==", "MA_TX3AC_100A", ":", "# TX-3AC in 100A mode; use value as-is, with 0xFE indicating null", "if", "value", "is", "None", ":", "return", "0xfe", "return", "int", "(", "value", ")", "elif", "message_attribute", "==", "MA_TX3AC_10A", ":", "# TX-3AC in 10A mode; shift decimal point, with 0xFE indicating null", "if", "value", "is", "None", ":", "return", "0xfe", "return", "int", "(", "value", "*", "10", ")", "else", ":", "# Signed byte, with 0x80 indicating null", "if", "value", "is", "None", ":", "return", "0x80", "elif", "value", "<", "0", ":", "return", "0x100", "+", "int", "(", "value", ")", "return", "int", "(", "value", ")" ]
Encode special sensor value using the message attribute.
[ "Encode", "special", "sensor", "value", "using", "the", "message", "attribute", "." ]
62360fbab2e90bf04d52b547093bdab2d4e389b4
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/util.py#L149-L167
248,222
openpermissions/perch
perch/validators.py
partial_schema
def partial_schema(schema, filtered_fields): """ Validator for part of a schema, ignoring some fields :param schema: the Schema :param filtered_fields: fields to filter out """ return Schema({ k: v for k, v in schema.schema.items() if getattr(k, 'schema', k) not in filtered_fields }, extra=ALLOW_EXTRA)
python
def partial_schema(schema, filtered_fields): """ Validator for part of a schema, ignoring some fields :param schema: the Schema :param filtered_fields: fields to filter out """ return Schema({ k: v for k, v in schema.schema.items() if getattr(k, 'schema', k) not in filtered_fields }, extra=ALLOW_EXTRA)
[ "def", "partial_schema", "(", "schema", ",", "filtered_fields", ")", ":", "return", "Schema", "(", "{", "k", ":", "v", "for", "k", ",", "v", "in", "schema", ".", "schema", ".", "items", "(", ")", "if", "getattr", "(", "k", ",", "'schema'", ",", "k", ")", "not", "in", "filtered_fields", "}", ",", "extra", "=", "ALLOW_EXTRA", ")" ]
Validator for part of a schema, ignoring some fields :param schema: the Schema :param filtered_fields: fields to filter out
[ "Validator", "for", "part", "of", "a", "schema", "ignoring", "some", "fields" ]
36d78994133918f3c52c187f19e50132960a0156
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/validators.py#L53-L63
248,223
openpermissions/perch
perch/validators.py
validate_url
def validate_url(url): """Validate URL is valid NOTE: only support http & https """ schemes = ['http', 'https'] netloc_re = re.compile( r'^' r'(?:\S+(?::\S*)?@)?' # user:pass auth r'(?:[a-z0-9]|[a-z0-9][a-z0-9\-]{0,61}[a-z0-9])' r'(?:\.(?:[a-z0-9]|[a-z0-9][a-z0-9\-]{0,61}[a-z0-9]))*' # host r'(?::[0-9]{2,5})?' # port r'$', re.IGNORECASE ) try: scheme, netloc, path, query, fragment = urlsplit(url) except ValueError: raise Invalid('Invalid URL') if scheme not in schemes: raise Invalid('Missing URL scheme') if not netloc_re.search(netloc): raise Invalid('Invalid URL') return url
python
def validate_url(url): """Validate URL is valid NOTE: only support http & https """ schemes = ['http', 'https'] netloc_re = re.compile( r'^' r'(?:\S+(?::\S*)?@)?' # user:pass auth r'(?:[a-z0-9]|[a-z0-9][a-z0-9\-]{0,61}[a-z0-9])' r'(?:\.(?:[a-z0-9]|[a-z0-9][a-z0-9\-]{0,61}[a-z0-9]))*' # host r'(?::[0-9]{2,5})?' # port r'$', re.IGNORECASE ) try: scheme, netloc, path, query, fragment = urlsplit(url) except ValueError: raise Invalid('Invalid URL') if scheme not in schemes: raise Invalid('Missing URL scheme') if not netloc_re.search(netloc): raise Invalid('Invalid URL') return url
[ "def", "validate_url", "(", "url", ")", ":", "schemes", "=", "[", "'http'", ",", "'https'", "]", "netloc_re", "=", "re", ".", "compile", "(", "r'^'", "r'(?:\\S+(?::\\S*)?@)?'", "# user:pass auth", "r'(?:[a-z0-9]|[a-z0-9][a-z0-9\\-]{0,61}[a-z0-9])'", "r'(?:\\.(?:[a-z0-9]|[a-z0-9][a-z0-9\\-]{0,61}[a-z0-9]))*'", "# host", "r'(?::[0-9]{2,5})?'", "# port", "r'$'", ",", "re", ".", "IGNORECASE", ")", "try", ":", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "fragment", "=", "urlsplit", "(", "url", ")", "except", "ValueError", ":", "raise", "Invalid", "(", "'Invalid URL'", ")", "if", "scheme", "not", "in", "schemes", ":", "raise", "Invalid", "(", "'Missing URL scheme'", ")", "if", "not", "netloc_re", ".", "search", "(", "netloc", ")", ":", "raise", "Invalid", "(", "'Invalid URL'", ")", "return", "url" ]
Validate URL is valid NOTE: only support http & https
[ "Validate", "URL", "is", "valid" ]
36d78994133918f3c52c187f19e50132960a0156
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/validators.py#L83-L109
248,224
openpermissions/perch
perch/validators.py
validate_reference_links
def validate_reference_links(reference_links): """ Vaidate reference links data structure Expected data structure: { "links": { id_type1: url1, id_type2: url2 }, "redirect_id_type": id_type1 | id1_type2 } where links is an optional key but must be a dictionary with id types to URLs if it exists, and redirect_id_type is optional but if it exists, it must point to one of the existing id types in the links object. It is used to set a default redirect URL that is used by the resolution service. """ allowed_keys = ['links', 'redirect_id_type'] if not isinstance(reference_links, dict): raise Invalid('Expected reference_links to be an object') if 'links' in reference_links and not isinstance(reference_links['links'], dict): raise Invalid('Expected links in reference_links to be an object') links = reference_links.get('links', {}) redirect_id_type = reference_links.get('redirect_id_type') for key in reference_links: if key not in allowed_keys: raise Invalid('Key {} is not allowed'.format(key)) if redirect_id_type and redirect_id_type not in links: raise Invalid('Redirect ID type must point to one of the links\' ID types') [validate_url(url) for url in links.values()] return reference_links
python
def validate_reference_links(reference_links): """ Vaidate reference links data structure Expected data structure: { "links": { id_type1: url1, id_type2: url2 }, "redirect_id_type": id_type1 | id1_type2 } where links is an optional key but must be a dictionary with id types to URLs if it exists, and redirect_id_type is optional but if it exists, it must point to one of the existing id types in the links object. It is used to set a default redirect URL that is used by the resolution service. """ allowed_keys = ['links', 'redirect_id_type'] if not isinstance(reference_links, dict): raise Invalid('Expected reference_links to be an object') if 'links' in reference_links and not isinstance(reference_links['links'], dict): raise Invalid('Expected links in reference_links to be an object') links = reference_links.get('links', {}) redirect_id_type = reference_links.get('redirect_id_type') for key in reference_links: if key not in allowed_keys: raise Invalid('Key {} is not allowed'.format(key)) if redirect_id_type and redirect_id_type not in links: raise Invalid('Redirect ID type must point to one of the links\' ID types') [validate_url(url) for url in links.values()] return reference_links
[ "def", "validate_reference_links", "(", "reference_links", ")", ":", "allowed_keys", "=", "[", "'links'", ",", "'redirect_id_type'", "]", "if", "not", "isinstance", "(", "reference_links", ",", "dict", ")", ":", "raise", "Invalid", "(", "'Expected reference_links to be an object'", ")", "if", "'links'", "in", "reference_links", "and", "not", "isinstance", "(", "reference_links", "[", "'links'", "]", ",", "dict", ")", ":", "raise", "Invalid", "(", "'Expected links in reference_links to be an object'", ")", "links", "=", "reference_links", ".", "get", "(", "'links'", ",", "{", "}", ")", "redirect_id_type", "=", "reference_links", ".", "get", "(", "'redirect_id_type'", ")", "for", "key", "in", "reference_links", ":", "if", "key", "not", "in", "allowed_keys", ":", "raise", "Invalid", "(", "'Key {} is not allowed'", ".", "format", "(", "key", ")", ")", "if", "redirect_id_type", "and", "redirect_id_type", "not", "in", "links", ":", "raise", "Invalid", "(", "'Redirect ID type must point to one of the links\\' ID types'", ")", "[", "validate_url", "(", "url", ")", "for", "url", "in", "links", ".", "values", "(", ")", "]", "return", "reference_links" ]
Vaidate reference links data structure Expected data structure: { "links": { id_type1: url1, id_type2: url2 }, "redirect_id_type": id_type1 | id1_type2 } where links is an optional key but must be a dictionary with id types to URLs if it exists, and redirect_id_type is optional but if it exists, it must point to one of the existing id types in the links object. It is used to set a default redirect URL that is used by the resolution service.
[ "Vaidate", "reference", "links", "data", "structure" ]
36d78994133918f3c52c187f19e50132960a0156
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/validators.py#L112-L150
248,225
openpermissions/perch
perch/validators.py
_validate_state
def _validate_state(state, valid_states): """Validate a state string""" if state in State: return state.name elif state in valid_states: return state else: raise Invalid('Invalid state')
python
def _validate_state(state, valid_states): """Validate a state string""" if state in State: return state.name elif state in valid_states: return state else: raise Invalid('Invalid state')
[ "def", "_validate_state", "(", "state", ",", "valid_states", ")", ":", "if", "state", "in", "State", ":", "return", "state", ".", "name", "elif", "state", "in", "valid_states", ":", "return", "state", "else", ":", "raise", "Invalid", "(", "'Invalid state'", ")" ]
Validate a state string
[ "Validate", "a", "state", "string" ]
36d78994133918f3c52c187f19e50132960a0156
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/validators.py#L165-L172
248,226
blubberdiblub/eztemplate
eztemplate/__main__.py
is_filelike
def is_filelike(ob): """Check for filelikeness of an object. Needed to distinguish it from file names. Returns true if it has a read or a write method. """ if hasattr(ob, 'read') and callable(ob.read): return True if hasattr(ob, 'write') and callable(ob.write): return True return False
python
def is_filelike(ob): """Check for filelikeness of an object. Needed to distinguish it from file names. Returns true if it has a read or a write method. """ if hasattr(ob, 'read') and callable(ob.read): return True if hasattr(ob, 'write') and callable(ob.write): return True return False
[ "def", "is_filelike", "(", "ob", ")", ":", "if", "hasattr", "(", "ob", ",", "'read'", ")", "and", "callable", "(", "ob", ".", "read", ")", ":", "return", "True", "if", "hasattr", "(", "ob", ",", "'write'", ")", "and", "callable", "(", "ob", ".", "write", ")", ":", "return", "True", "return", "False" ]
Check for filelikeness of an object. Needed to distinguish it from file names. Returns true if it has a read or a write method.
[ "Check", "for", "filelikeness", "of", "an", "object", "." ]
ab5b2b4987c045116d130fd83e216704b8edfb5d
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L18-L30
248,227
blubberdiblub/eztemplate
eztemplate/__main__.py
dump_engines
def dump_engines(target=sys.stderr): """Print successfully imported templating engines.""" print("Available templating engines:", file=target) width = max(len(engine) for engine in engines.engines) for handle, engine in sorted(engines.engines.items()): description = engine.__doc__.split('\n', 0)[0] print(" %-*s - %s" % (width, handle, description), file=target)
python
def dump_engines(target=sys.stderr): """Print successfully imported templating engines.""" print("Available templating engines:", file=target) width = max(len(engine) for engine in engines.engines) for handle, engine in sorted(engines.engines.items()): description = engine.__doc__.split('\n', 0)[0] print(" %-*s - %s" % (width, handle, description), file=target)
[ "def", "dump_engines", "(", "target", "=", "sys", ".", "stderr", ")", ":", "print", "(", "\"Available templating engines:\"", ",", "file", "=", "target", ")", "width", "=", "max", "(", "len", "(", "engine", ")", "for", "engine", "in", "engines", ".", "engines", ")", "for", "handle", ",", "engine", "in", "sorted", "(", "engines", ".", "engines", ".", "items", "(", ")", ")", ":", "description", "=", "engine", ".", "__doc__", ".", "split", "(", "'\\n'", ",", "0", ")", "[", "0", "]", "print", "(", "\" %-*s - %s\"", "%", "(", "width", ",", "handle", ",", "description", ")", ",", "file", "=", "target", ")" ]
Print successfully imported templating engines.
[ "Print", "successfully", "imported", "templating", "engines", "." ]
ab5b2b4987c045116d130fd83e216704b8edfb5d
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L220-L227
248,228
blubberdiblub/eztemplate
eztemplate/__main__.py
check_engine
def check_engine(handle): """Check availability of requested template engine.""" if handle == 'help': dump_engines() sys.exit(0) if handle not in engines.engines: print('Engine "%s" is not available.' % (handle,), file=sys.stderr) sys.exit(1)
python
def check_engine(handle): """Check availability of requested template engine.""" if handle == 'help': dump_engines() sys.exit(0) if handle not in engines.engines: print('Engine "%s" is not available.' % (handle,), file=sys.stderr) sys.exit(1)
[ "def", "check_engine", "(", "handle", ")", ":", "if", "handle", "==", "'help'", ":", "dump_engines", "(", ")", "sys", ".", "exit", "(", "0", ")", "if", "handle", "not", "in", "engines", ".", "engines", ":", "print", "(", "'Engine \"%s\" is not available.'", "%", "(", "handle", ",", ")", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")" ]
Check availability of requested template engine.
[ "Check", "availability", "of", "requested", "template", "engine", "." ]
ab5b2b4987c045116d130fd83e216704b8edfb5d
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L230-L238
248,229
blubberdiblub/eztemplate
eztemplate/__main__.py
make_mapping
def make_mapping(args): """Make a mapping from the name=value pairs.""" mapping = {} if args: for arg in args: name_value = arg.split('=', 1) mapping[name_value[0]] = (name_value[1] if len(name_value) > 1 else None) return mapping
python
def make_mapping(args): """Make a mapping from the name=value pairs.""" mapping = {} if args: for arg in args: name_value = arg.split('=', 1) mapping[name_value[0]] = (name_value[1] if len(name_value) > 1 else None) return mapping
[ "def", "make_mapping", "(", "args", ")", ":", "mapping", "=", "{", "}", "if", "args", ":", "for", "arg", "in", "args", ":", "name_value", "=", "arg", ".", "split", "(", "'='", ",", "1", ")", "mapping", "[", "name_value", "[", "0", "]", "]", "=", "(", "name_value", "[", "1", "]", "if", "len", "(", "name_value", ")", ">", "1", "else", "None", ")", "return", "mapping" ]
Make a mapping from the name=value pairs.
[ "Make", "a", "mapping", "from", "the", "name", "=", "value", "pairs", "." ]
ab5b2b4987c045116d130fd83e216704b8edfb5d
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L241-L252
248,230
blubberdiblub/eztemplate
eztemplate/__main__.py
make_path_properties
def make_path_properties(file_or_path, prefix=''): """Build useful properties from a file path.""" is_std = file_or_path in (sys.stdin, sys.stdout, sys.stderr) if is_std: path = '-' elif is_filelike(file_or_path): try: path = str(file_or_path.name) except AttributeError: path = None else: path = str(file_or_path) if is_std or not path: abspath = dirname = basename = stem = ext = None realpath = realdrive = realdir = realbase = realstem = realext = None numbers = num = None else: abspath = os.path.abspath(path) dirname, basename = os.path.split(path) stem, ext = os.path.splitext(basename) if not dirname: dirname = os.curdir realpath = os.path.realpath(path) realdrive, tail = os.path.splitdrive(realpath) realdir, realbase = os.path.split(tail) realstem, realext = os.path.splitext(realbase) numbers = [int(s) for s in re.findall(r'\d+', basename)] num = numbers[-1] if numbers else None return { prefix + 'path': path, prefix + 'abspath': abspath, prefix + 'dirname': dirname, prefix + 'basename': basename, prefix + 'stem': stem, prefix + 'ext': ext, prefix + 'realpath': realpath, prefix + 'realdrive': realdrive, prefix + 'realdir': realdir, prefix + 'realbase': realbase, prefix + 'realstem': realstem, prefix + 'realext': realext, prefix + 'numbers': numbers, prefix + 'num': num, }
python
def make_path_properties(file_or_path, prefix=''): """Build useful properties from a file path.""" is_std = file_or_path in (sys.stdin, sys.stdout, sys.stderr) if is_std: path = '-' elif is_filelike(file_or_path): try: path = str(file_or_path.name) except AttributeError: path = None else: path = str(file_or_path) if is_std or not path: abspath = dirname = basename = stem = ext = None realpath = realdrive = realdir = realbase = realstem = realext = None numbers = num = None else: abspath = os.path.abspath(path) dirname, basename = os.path.split(path) stem, ext = os.path.splitext(basename) if not dirname: dirname = os.curdir realpath = os.path.realpath(path) realdrive, tail = os.path.splitdrive(realpath) realdir, realbase = os.path.split(tail) realstem, realext = os.path.splitext(realbase) numbers = [int(s) for s in re.findall(r'\d+', basename)] num = numbers[-1] if numbers else None return { prefix + 'path': path, prefix + 'abspath': abspath, prefix + 'dirname': dirname, prefix + 'basename': basename, prefix + 'stem': stem, prefix + 'ext': ext, prefix + 'realpath': realpath, prefix + 'realdrive': realdrive, prefix + 'realdir': realdir, prefix + 'realbase': realbase, prefix + 'realstem': realstem, prefix + 'realext': realext, prefix + 'numbers': numbers, prefix + 'num': num, }
[ "def", "make_path_properties", "(", "file_or_path", ",", "prefix", "=", "''", ")", ":", "is_std", "=", "file_or_path", "in", "(", "sys", ".", "stdin", ",", "sys", ".", "stdout", ",", "sys", ".", "stderr", ")", "if", "is_std", ":", "path", "=", "'-'", "elif", "is_filelike", "(", "file_or_path", ")", ":", "try", ":", "path", "=", "str", "(", "file_or_path", ".", "name", ")", "except", "AttributeError", ":", "path", "=", "None", "else", ":", "path", "=", "str", "(", "file_or_path", ")", "if", "is_std", "or", "not", "path", ":", "abspath", "=", "dirname", "=", "basename", "=", "stem", "=", "ext", "=", "None", "realpath", "=", "realdrive", "=", "realdir", "=", "realbase", "=", "realstem", "=", "realext", "=", "None", "numbers", "=", "num", "=", "None", "else", ":", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "dirname", ",", "basename", "=", "os", ".", "path", ".", "split", "(", "path", ")", "stem", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "basename", ")", "if", "not", "dirname", ":", "dirname", "=", "os", ".", "curdir", "realpath", "=", "os", ".", "path", ".", "realpath", "(", "path", ")", "realdrive", ",", "tail", "=", "os", ".", "path", ".", "splitdrive", "(", "realpath", ")", "realdir", ",", "realbase", "=", "os", ".", "path", ".", "split", "(", "tail", ")", "realstem", ",", "realext", "=", "os", ".", "path", ".", "splitext", "(", "realbase", ")", "numbers", "=", "[", "int", "(", "s", ")", "for", "s", "in", "re", ".", "findall", "(", "r'\\d+'", ",", "basename", ")", "]", "num", "=", "numbers", "[", "-", "1", "]", "if", "numbers", "else", "None", "return", "{", "prefix", "+", "'path'", ":", "path", ",", "prefix", "+", "'abspath'", ":", "abspath", ",", "prefix", "+", "'dirname'", ":", "dirname", ",", "prefix", "+", "'basename'", ":", "basename", ",", "prefix", "+", "'stem'", ":", "stem", ",", "prefix", "+", "'ext'", ":", "ext", ",", "prefix", "+", "'realpath'", ":", "realpath", ",", "prefix", "+", "'realdrive'", ":", "realdrive", ",", "prefix", "+", "'realdir'", ":", "realdir", ",", "prefix", "+", "'realbase'", ":", "realbase", ",", "prefix", "+", "'realstem'", ":", "realstem", ",", "prefix", "+", "'realext'", ":", "realext", ",", "prefix", "+", "'numbers'", ":", "numbers", ",", "prefix", "+", "'num'", ":", "num", ",", "}" ]
Build useful properties from a file path.
[ "Build", "useful", "properties", "from", "a", "file", "path", "." ]
ab5b2b4987c045116d130fd83e216704b8edfb5d
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L255-L305
248,231
blubberdiblub/eztemplate
eztemplate/__main__.py
constant_outfile_iterator
def constant_outfile_iterator(outfiles, infiles, arggroups): """Iterate over all output files.""" assert len(infiles) == 1 assert len(arggroups) == 1 return ((outfile, infiles[0], arggroups[0]) for outfile in outfiles)
python
def constant_outfile_iterator(outfiles, infiles, arggroups): """Iterate over all output files.""" assert len(infiles) == 1 assert len(arggroups) == 1 return ((outfile, infiles[0], arggroups[0]) for outfile in outfiles)
[ "def", "constant_outfile_iterator", "(", "outfiles", ",", "infiles", ",", "arggroups", ")", ":", "assert", "len", "(", "infiles", ")", "==", "1", "assert", "len", "(", "arggroups", ")", "==", "1", "return", "(", "(", "outfile", ",", "infiles", "[", "0", "]", ",", "arggroups", "[", "0", "]", ")", "for", "outfile", "in", "outfiles", ")" ]
Iterate over all output files.
[ "Iterate", "over", "all", "output", "files", "." ]
ab5b2b4987c045116d130fd83e216704b8edfb5d
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L308-L313
248,232
blubberdiblub/eztemplate
eztemplate/__main__.py
variable_outfile_iterator
def variable_outfile_iterator(outfiles, infiles, arggroups, engine): """Iterate over variable output file name template.""" assert len(outfiles) == 1 template = engine(outfiles[0], tolerant=False) for infile in infiles: properties = make_path_properties(infile, prefix='') for arggroup in arggroups: outfile = template.apply(dict(arggroup, **properties)) yield (outfile, infile, arggroup)
python
def variable_outfile_iterator(outfiles, infiles, arggroups, engine): """Iterate over variable output file name template.""" assert len(outfiles) == 1 template = engine(outfiles[0], tolerant=False) for infile in infiles: properties = make_path_properties(infile, prefix='') for arggroup in arggroups: outfile = template.apply(dict(arggroup, **properties)) yield (outfile, infile, arggroup)
[ "def", "variable_outfile_iterator", "(", "outfiles", ",", "infiles", ",", "arggroups", ",", "engine", ")", ":", "assert", "len", "(", "outfiles", ")", "==", "1", "template", "=", "engine", "(", "outfiles", "[", "0", "]", ",", "tolerant", "=", "False", ")", "for", "infile", "in", "infiles", ":", "properties", "=", "make_path_properties", "(", "infile", ",", "prefix", "=", "''", ")", "for", "arggroup", "in", "arggroups", ":", "outfile", "=", "template", ".", "apply", "(", "dict", "(", "arggroup", ",", "*", "*", "properties", ")", ")", "yield", "(", "outfile", ",", "infile", ",", "arggroup", ")" ]
Iterate over variable output file name template.
[ "Iterate", "over", "variable", "output", "file", "name", "template", "." ]
ab5b2b4987c045116d130fd83e216704b8edfb5d
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L316-L327
248,233
blubberdiblub/eztemplate
eztemplate/__main__.py
process_combinations
def process_combinations(combinations, engine, tolerant=False, read_old=False, delete_empty=False, ): """Process outfile-infile-arggroup combinations.""" outfiles = set() templatereader = CachedTemplateReader(engine, tolerant=tolerant) for outfile, infile, arggroup in combinations: template = templatereader.read(infile) properties = make_path_properties(outfile, prefix='ez_') if read_old: if is_filelike(outfile): raise Exception("cannot read already open output streams") try: with open(outfile, 'r') as f: properties['ez_content'] = f.read() except IOError: properties['ez_content'] = None result = template.apply(dict(arggroup, **properties)) if is_filelike(outfile): if result: outfile.write(result) elif result or not delete_empty: if outfile in outfiles: raise IOError("trying to write twice to the same file") outfiles.add(outfile) with open(outfile, 'w') as f: f.write(result) else: try: os.remove(outfile) except OSError as e: if e.errno != errno.ENOENT: raise
python
def process_combinations(combinations, engine, tolerant=False, read_old=False, delete_empty=False, ): """Process outfile-infile-arggroup combinations.""" outfiles = set() templatereader = CachedTemplateReader(engine, tolerant=tolerant) for outfile, infile, arggroup in combinations: template = templatereader.read(infile) properties = make_path_properties(outfile, prefix='ez_') if read_old: if is_filelike(outfile): raise Exception("cannot read already open output streams") try: with open(outfile, 'r') as f: properties['ez_content'] = f.read() except IOError: properties['ez_content'] = None result = template.apply(dict(arggroup, **properties)) if is_filelike(outfile): if result: outfile.write(result) elif result or not delete_empty: if outfile in outfiles: raise IOError("trying to write twice to the same file") outfiles.add(outfile) with open(outfile, 'w') as f: f.write(result) else: try: os.remove(outfile) except OSError as e: if e.errno != errno.ENOENT: raise
[ "def", "process_combinations", "(", "combinations", ",", "engine", ",", "tolerant", "=", "False", ",", "read_old", "=", "False", ",", "delete_empty", "=", "False", ",", ")", ":", "outfiles", "=", "set", "(", ")", "templatereader", "=", "CachedTemplateReader", "(", "engine", ",", "tolerant", "=", "tolerant", ")", "for", "outfile", ",", "infile", ",", "arggroup", "in", "combinations", ":", "template", "=", "templatereader", ".", "read", "(", "infile", ")", "properties", "=", "make_path_properties", "(", "outfile", ",", "prefix", "=", "'ez_'", ")", "if", "read_old", ":", "if", "is_filelike", "(", "outfile", ")", ":", "raise", "Exception", "(", "\"cannot read already open output streams\"", ")", "try", ":", "with", "open", "(", "outfile", ",", "'r'", ")", "as", "f", ":", "properties", "[", "'ez_content'", "]", "=", "f", ".", "read", "(", ")", "except", "IOError", ":", "properties", "[", "'ez_content'", "]", "=", "None", "result", "=", "template", ".", "apply", "(", "dict", "(", "arggroup", ",", "*", "*", "properties", ")", ")", "if", "is_filelike", "(", "outfile", ")", ":", "if", "result", ":", "outfile", ".", "write", "(", "result", ")", "elif", "result", "or", "not", "delete_empty", ":", "if", "outfile", "in", "outfiles", ":", "raise", "IOError", "(", "\"trying to write twice to the same file\"", ")", "outfiles", ".", "add", "(", "outfile", ")", "with", "open", "(", "outfile", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "result", ")", "else", ":", "try", ":", "os", ".", "remove", "(", "outfile", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "raise" ]
Process outfile-infile-arggroup combinations.
[ "Process", "outfile", "-", "infile", "-", "arggroup", "combinations", "." ]
ab5b2b4987c045116d130fd83e216704b8edfb5d
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L361-L400
248,234
blubberdiblub/eztemplate
eztemplate/__main__.py
perform_templating
def perform_templating(args): """Perform templating according to the given arguments.""" engine = engines.engines[args.engine] if args.vary: it = variable_outfile_iterator(args.outfiles, args.infiles, args.args, engine) else: it = constant_outfile_iterator(args.outfiles, args.infiles, args.args) process_combinations(it, engine, tolerant=args.tolerant, read_old=args.read_old, delete_empty=args.delete_empty, )
python
def perform_templating(args): """Perform templating according to the given arguments.""" engine = engines.engines[args.engine] if args.vary: it = variable_outfile_iterator(args.outfiles, args.infiles, args.args, engine) else: it = constant_outfile_iterator(args.outfiles, args.infiles, args.args) process_combinations(it, engine, tolerant=args.tolerant, read_old=args.read_old, delete_empty=args.delete_empty, )
[ "def", "perform_templating", "(", "args", ")", ":", "engine", "=", "engines", ".", "engines", "[", "args", ".", "engine", "]", "if", "args", ".", "vary", ":", "it", "=", "variable_outfile_iterator", "(", "args", ".", "outfiles", ",", "args", ".", "infiles", ",", "args", ".", "args", ",", "engine", ")", "else", ":", "it", "=", "constant_outfile_iterator", "(", "args", ".", "outfiles", ",", "args", ".", "infiles", ",", "args", ".", "args", ")", "process_combinations", "(", "it", ",", "engine", ",", "tolerant", "=", "args", ".", "tolerant", ",", "read_old", "=", "args", ".", "read_old", ",", "delete_empty", "=", "args", ".", "delete_empty", ",", ")" ]
Perform templating according to the given arguments.
[ "Perform", "templating", "according", "to", "the", "given", "arguments", "." ]
ab5b2b4987c045116d130fd83e216704b8edfb5d
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L403-L421
248,235
blubberdiblub/eztemplate
eztemplate/__main__.py
CachedTemplateReader.read
def read(self, file_or_path): """Read template from cache or file.""" if file_or_path in self._cached_templates: return self._cached_templates[file_or_path] if is_filelike(file_or_path): template = file_or_path.read() dirname = None else: with open(file_or_path, 'r') as f: template = f.read() dirname = os.path.dirname(file_or_path) template = self._engine(template, dirname=dirname, tolerant=self._tolerant) self._cached_templates[file_or_path] = template return template
python
def read(self, file_or_path): """Read template from cache or file.""" if file_or_path in self._cached_templates: return self._cached_templates[file_or_path] if is_filelike(file_or_path): template = file_or_path.read() dirname = None else: with open(file_or_path, 'r') as f: template = f.read() dirname = os.path.dirname(file_or_path) template = self._engine(template, dirname=dirname, tolerant=self._tolerant) self._cached_templates[file_or_path] = template return template
[ "def", "read", "(", "self", ",", "file_or_path", ")", ":", "if", "file_or_path", "in", "self", ".", "_cached_templates", ":", "return", "self", ".", "_cached_templates", "[", "file_or_path", "]", "if", "is_filelike", "(", "file_or_path", ")", ":", "template", "=", "file_or_path", ".", "read", "(", ")", "dirname", "=", "None", "else", ":", "with", "open", "(", "file_or_path", ",", "'r'", ")", "as", "f", ":", "template", "=", "f", ".", "read", "(", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "file_or_path", ")", "template", "=", "self", ".", "_engine", "(", "template", ",", "dirname", "=", "dirname", ",", "tolerant", "=", "self", ".", "_tolerant", ")", "self", ".", "_cached_templates", "[", "file_or_path", "]", "=", "template", "return", "template" ]
Read template from cache or file.
[ "Read", "template", "from", "cache", "or", "file", "." ]
ab5b2b4987c045116d130fd83e216704b8edfb5d
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/__main__.py#L340-L358
248,236
nws-cip/zenconf
examples/config.py
get_config
def get_config(cli_args=None, config_path=None): """ Perform standard setup - get the merged config :param cli_args dict: A dictionary of CLI arguments :param config_path string: Path to the config file to load :return dict: A dictionary of config values drawn from different sources """ config = Config(app_name="MYAPP", cli_args=cli_args, config_path=config_path) config_dict = config.get_config() return config_dict
python
def get_config(cli_args=None, config_path=None): """ Perform standard setup - get the merged config :param cli_args dict: A dictionary of CLI arguments :param config_path string: Path to the config file to load :return dict: A dictionary of config values drawn from different sources """ config = Config(app_name="MYAPP", cli_args=cli_args, config_path=config_path) config_dict = config.get_config() return config_dict
[ "def", "get_config", "(", "cli_args", "=", "None", ",", "config_path", "=", "None", ")", ":", "config", "=", "Config", "(", "app_name", "=", "\"MYAPP\"", ",", "cli_args", "=", "cli_args", ",", "config_path", "=", "config_path", ")", "config_dict", "=", "config", ".", "get_config", "(", ")", "return", "config_dict" ]
Perform standard setup - get the merged config :param cli_args dict: A dictionary of CLI arguments :param config_path string: Path to the config file to load :return dict: A dictionary of config values drawn from different sources
[ "Perform", "standard", "setup", "-", "get", "the", "merged", "config" ]
fc96706468c0741fb1b54b2eeb9f9225737e3e36
https://github.com/nws-cip/zenconf/blob/fc96706468c0741fb1b54b2eeb9f9225737e3e36/examples/config.py#L101-L114
248,237
OldhamMade/PySO8601
PySO8601/intervals.py
parse_interval
def parse_interval(interval): """ Attepmt to parse an ISO8601 formatted ``interval``. Returns a tuple of ``datetime.datetime`` and ``datetime.timedelta`` objects, order dependent on ``interval``. """ a, b = str(interval).upper().strip().split('/') if a[0] is 'P' and b[0] is 'P': raise ParseError() if a[0] != 'P' and b[0] != 'P': return parse_date(a), parse_date(b) if a[0] is 'P': a = parse_duration(a) else: a = parse_date(a) if b[0] is 'P': b = parse_duration(b) else: b = parse_date(b) return a, b
python
def parse_interval(interval): """ Attepmt to parse an ISO8601 formatted ``interval``. Returns a tuple of ``datetime.datetime`` and ``datetime.timedelta`` objects, order dependent on ``interval``. """ a, b = str(interval).upper().strip().split('/') if a[0] is 'P' and b[0] is 'P': raise ParseError() if a[0] != 'P' and b[0] != 'P': return parse_date(a), parse_date(b) if a[0] is 'P': a = parse_duration(a) else: a = parse_date(a) if b[0] is 'P': b = parse_duration(b) else: b = parse_date(b) return a, b
[ "def", "parse_interval", "(", "interval", ")", ":", "a", ",", "b", "=", "str", "(", "interval", ")", ".", "upper", "(", ")", ".", "strip", "(", ")", ".", "split", "(", "'/'", ")", "if", "a", "[", "0", "]", "is", "'P'", "and", "b", "[", "0", "]", "is", "'P'", ":", "raise", "ParseError", "(", ")", "if", "a", "[", "0", "]", "!=", "'P'", "and", "b", "[", "0", "]", "!=", "'P'", ":", "return", "parse_date", "(", "a", ")", ",", "parse_date", "(", "b", ")", "if", "a", "[", "0", "]", "is", "'P'", ":", "a", "=", "parse_duration", "(", "a", ")", "else", ":", "a", "=", "parse_date", "(", "a", ")", "if", "b", "[", "0", "]", "is", "'P'", ":", "b", "=", "parse_duration", "(", "b", ")", "else", ":", "b", "=", "parse_date", "(", "b", ")", "return", "a", ",", "b" ]
Attepmt to parse an ISO8601 formatted ``interval``. Returns a tuple of ``datetime.datetime`` and ``datetime.timedelta`` objects, order dependent on ``interval``.
[ "Attepmt", "to", "parse", "an", "ISO8601", "formatted", "interval", "." ]
b7d3b3cb3ed3e12eb2a21caa26a3abeab3c96fe4
https://github.com/OldhamMade/PySO8601/blob/b7d3b3cb3ed3e12eb2a21caa26a3abeab3c96fe4/PySO8601/intervals.py#L6-L31
248,238
hitchtest/hitchserve
hitchserve/hitch_service.py
Subcommand.run
def run(self, shell=False, ignore_errors=False, stdin=False, check_output=False): """Run subcommand. Args: shell (Optional[bool]): Run command using shell (default False) ignore_errors (Optional[bool]): If the command has a non-zero return code, don't raise an exception (default False) stdin (Optional[bool]): Plug input from stdin when running command (default False) check_output (Optional[bool]): Return command output as string (default False) Returns: String if check_output is True, else None. Raises: subprocess.CalledProcessError when the command has an error, unless ignore_errors is True. """ previous_directory = os.getcwd() os.chdir(self.directory) try: kwargs = { 'stderr': sys.stderr, 'stdin': sys.stdin if stdin else None, 'env': self.env_vars, 'shell': shell, } if check_output: return subprocess.check_output(self.command, **kwargs).decode("utf8") else: kwargs['stdout'] = sys.stdout return subprocess.check_call(self.command, **kwargs) except subprocess.CalledProcessError: if ignore_errors: pass else: raise # Return to previous directory os.chdir(previous_directory)
python
def run(self, shell=False, ignore_errors=False, stdin=False, check_output=False): """Run subcommand. Args: shell (Optional[bool]): Run command using shell (default False) ignore_errors (Optional[bool]): If the command has a non-zero return code, don't raise an exception (default False) stdin (Optional[bool]): Plug input from stdin when running command (default False) check_output (Optional[bool]): Return command output as string (default False) Returns: String if check_output is True, else None. Raises: subprocess.CalledProcessError when the command has an error, unless ignore_errors is True. """ previous_directory = os.getcwd() os.chdir(self.directory) try: kwargs = { 'stderr': sys.stderr, 'stdin': sys.stdin if stdin else None, 'env': self.env_vars, 'shell': shell, } if check_output: return subprocess.check_output(self.command, **kwargs).decode("utf8") else: kwargs['stdout'] = sys.stdout return subprocess.check_call(self.command, **kwargs) except subprocess.CalledProcessError: if ignore_errors: pass else: raise # Return to previous directory os.chdir(previous_directory)
[ "def", "run", "(", "self", ",", "shell", "=", "False", ",", "ignore_errors", "=", "False", ",", "stdin", "=", "False", ",", "check_output", "=", "False", ")", ":", "previous_directory", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "self", ".", "directory", ")", "try", ":", "kwargs", "=", "{", "'stderr'", ":", "sys", ".", "stderr", ",", "'stdin'", ":", "sys", ".", "stdin", "if", "stdin", "else", "None", ",", "'env'", ":", "self", ".", "env_vars", ",", "'shell'", ":", "shell", ",", "}", "if", "check_output", ":", "return", "subprocess", ".", "check_output", "(", "self", ".", "command", ",", "*", "*", "kwargs", ")", ".", "decode", "(", "\"utf8\"", ")", "else", ":", "kwargs", "[", "'stdout'", "]", "=", "sys", ".", "stdout", "return", "subprocess", ".", "check_call", "(", "self", ".", "command", ",", "*", "*", "kwargs", ")", "except", "subprocess", ".", "CalledProcessError", ":", "if", "ignore_errors", ":", "pass", "else", ":", "raise", "# Return to previous directory", "os", ".", "chdir", "(", "previous_directory", ")" ]
Run subcommand. Args: shell (Optional[bool]): Run command using shell (default False) ignore_errors (Optional[bool]): If the command has a non-zero return code, don't raise an exception (default False) stdin (Optional[bool]): Plug input from stdin when running command (default False) check_output (Optional[bool]): Return command output as string (default False) Returns: String if check_output is True, else None. Raises: subprocess.CalledProcessError when the command has an error, unless ignore_errors is True.
[ "Run", "subcommand", "." ]
a2def19979264186d283e76f7f0c88f3ed97f2e0
https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/hitch_service.py#L52-L88
248,239
hitchtest/hitchserve
hitchserve/hitch_service.py
Service.subcommand
def subcommand(self, *args): """Get subcommand acting on a service. Subcommand will run in service directory and with the environment variables used to run the service itself. Args: *args: Arguments to run command (e.g. "redis-cli", "-n", "1") Returns: Subcommand object. """ return Subcommand(*args, directory=self.directory, env_vars=self.env_vars)
python
def subcommand(self, *args): """Get subcommand acting on a service. Subcommand will run in service directory and with the environment variables used to run the service itself. Args: *args: Arguments to run command (e.g. "redis-cli", "-n", "1") Returns: Subcommand object. """ return Subcommand(*args, directory=self.directory, env_vars=self.env_vars)
[ "def", "subcommand", "(", "self", ",", "*", "args", ")", ":", "return", "Subcommand", "(", "*", "args", ",", "directory", "=", "self", ".", "directory", ",", "env_vars", "=", "self", ".", "env_vars", ")" ]
Get subcommand acting on a service. Subcommand will run in service directory and with the environment variables used to run the service itself. Args: *args: Arguments to run command (e.g. "redis-cli", "-n", "1") Returns: Subcommand object.
[ "Get", "subcommand", "acting", "on", "a", "service", ".", "Subcommand", "will", "run", "in", "service", "directory", "and", "with", "the", "environment", "variables", "used", "to", "run", "the", "service", "itself", "." ]
a2def19979264186d283e76f7f0c88f3ed97f2e0
https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/hitch_service.py#L237-L247
248,240
pydsigner/taskit
taskit/resync.py
Mediator.set_error
def set_error(self, e): """ Rather than allowing unmanaged exceptions to explode, or raising errors within thread, the worker thread should call this function with an error class or instance. """ self.result = (False, e) self._lock.release()
python
def set_error(self, e): """ Rather than allowing unmanaged exceptions to explode, or raising errors within thread, the worker thread should call this function with an error class or instance. """ self.result = (False, e) self._lock.release()
[ "def", "set_error", "(", "self", ",", "e", ")", ":", "self", ".", "result", "=", "(", "False", ",", "e", ")", "self", ".", "_lock", ".", "release", "(", ")" ]
Rather than allowing unmanaged exceptions to explode, or raising errors within thread, the worker thread should call this function with an error class or instance.
[ "Rather", "than", "allowing", "unmanaged", "exceptions", "to", "explode", "or", "raising", "errors", "within", "thread", "the", "worker", "thread", "should", "call", "this", "function", "with", "an", "error", "class", "or", "instance", "." ]
3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f
https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/resync.py#L128-L135
248,241
pydsigner/taskit
taskit/resync.py
Resyncer._wrapper
def _wrapper(self): """ Wraps around a few calls which need to be made in the same thread. """ try: res = self.func(*self.args, **self.kw) except Exception as e: self.mediator.set_error(e) else: self.mediator.set_result(res)
python
def _wrapper(self): """ Wraps around a few calls which need to be made in the same thread. """ try: res = self.func(*self.args, **self.kw) except Exception as e: self.mediator.set_error(e) else: self.mediator.set_result(res)
[ "def", "_wrapper", "(", "self", ")", ":", "try", ":", "res", "=", "self", ".", "func", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kw", ")", "except", "Exception", "as", "e", ":", "self", ".", "mediator", ".", "set_error", "(", "e", ")", "else", ":", "self", ".", "mediator", ".", "set_result", "(", "res", ")" ]
Wraps around a few calls which need to be made in the same thread.
[ "Wraps", "around", "a", "few", "calls", "which", "need", "to", "be", "made", "in", "the", "same", "thread", "." ]
3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f
https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/resync.py#L170-L179
248,242
merryspankersltd/irenee
irenee/catfish.py
addinterval
def addinterval(instr, add, interval): ''' adds string every n character. returns string ''' if not isinstance(instr, str): instr = str(instr) return add.join( instr[i:i+interval] for i in xrange(0,len(instr),interval))
python
def addinterval(instr, add, interval): ''' adds string every n character. returns string ''' if not isinstance(instr, str): instr = str(instr) return add.join( instr[i:i+interval] for i in xrange(0,len(instr),interval))
[ "def", "addinterval", "(", "instr", ",", "add", ",", "interval", ")", ":", "if", "not", "isinstance", "(", "instr", ",", "str", ")", ":", "instr", "=", "str", "(", "instr", ")", "return", "add", ".", "join", "(", "instr", "[", "i", ":", "i", "+", "interval", "]", "for", "i", "in", "xrange", "(", "0", ",", "len", "(", "instr", ")", ",", "interval", ")", ")" ]
adds string every n character. returns string
[ "adds", "string", "every", "n", "character", ".", "returns", "string" ]
8bf3c7644dc69001fa4b09be5fbb770dbf06a465
https://github.com/merryspankersltd/irenee/blob/8bf3c7644dc69001fa4b09be5fbb770dbf06a465/irenee/catfish.py#L27-L36
248,243
merryspankersltd/irenee
irenee/catfish.py
parse_ok
def parse_ok(l1, l3): ''' parse html when siren is ok ''' return { 'annee': l1.text.split(' : ')[1].split()[2], 'siren valide': ''.join( l1.text.split(' : ')[1].split(u'\xab')[0].split()[-4:-1]), 'categorie': ' '.join( l1.text.split(' : ')[1].split(u'\xab')[1].split()[:-1]), 'raison sociale': l3.text.split(' : ')[1][:-1], 'statut': 'ok'}
python
def parse_ok(l1, l3): ''' parse html when siren is ok ''' return { 'annee': l1.text.split(' : ')[1].split()[2], 'siren valide': ''.join( l1.text.split(' : ')[1].split(u'\xab')[0].split()[-4:-1]), 'categorie': ' '.join( l1.text.split(' : ')[1].split(u'\xab')[1].split()[:-1]), 'raison sociale': l3.text.split(' : ')[1][:-1], 'statut': 'ok'}
[ "def", "parse_ok", "(", "l1", ",", "l3", ")", ":", "return", "{", "'annee'", ":", "l1", ".", "text", ".", "split", "(", "' : '", ")", "[", "1", "]", ".", "split", "(", ")", "[", "2", "]", ",", "'siren valide'", ":", "''", ".", "join", "(", "l1", ".", "text", ".", "split", "(", "' : '", ")", "[", "1", "]", ".", "split", "(", "u'\\xab'", ")", "[", "0", "]", ".", "split", "(", ")", "[", "-", "4", ":", "-", "1", "]", ")", ",", "'categorie'", ":", "' '", ".", "join", "(", "l1", ".", "text", ".", "split", "(", "' : '", ")", "[", "1", "]", ".", "split", "(", "u'\\xab'", ")", "[", "1", "]", ".", "split", "(", ")", "[", ":", "-", "1", "]", ")", ",", "'raison sociale'", ":", "l3", ".", "text", ".", "split", "(", "' : '", ")", "[", "1", "]", "[", ":", "-", "1", "]", ",", "'statut'", ":", "'ok'", "}" ]
parse html when siren is ok
[ "parse", "html", "when", "siren", "is", "ok" ]
8bf3c7644dc69001fa4b09be5fbb770dbf06a465
https://github.com/merryspankersltd/irenee/blob/8bf3c7644dc69001fa4b09be5fbb770dbf06a465/irenee/catfish.py#L86-L97
248,244
pjanis/funtool
funtool/lib/general.py
sort_states
def sort_states(states, sort_list): """ Returns a list of sorted states, original states list remains unsorted The sort list is a list of state field: field key pairs For example (as YAML): - data: position - meta: created_at The field_key part can be a list to simplify input - meta: created_at - meta: updated_at or - meta: - created_at - updated_at It is also possible to sort by grouping values For example, with a grouping called student_id: - groupings: - student_id: index: !!null (optional: when null or missing it uses the first group in the grouping values: - meta: student_id A key which begins with a - inverts the sort, so - -data: position is the inverse of - data: position With groupings only values can have a - to invert the sort (always on the key) - groupings: - student_id: index: !!null values: - -meta: student_id NOT - -groupings: ... """ sorted_states= states.copy() for sort_pair in reversed( _convert_list_of_dict_to_tuple(sort_list) ): if sort_pair[0].lstrip('-') in ['data','measure','meta']: sorted_states= _state_value_sort(sorted_states, sort_pair, _state_key_function) elif sort_pair[0] == 'groupings': for grouping in reversed(sort_pair[1]): sorted_states= _groupings_values_sort(sorted_states, grouping) return sorted_states
python
def sort_states(states, sort_list): """ Returns a list of sorted states, original states list remains unsorted The sort list is a list of state field: field key pairs For example (as YAML): - data: position - meta: created_at The field_key part can be a list to simplify input - meta: created_at - meta: updated_at or - meta: - created_at - updated_at It is also possible to sort by grouping values For example, with a grouping called student_id: - groupings: - student_id: index: !!null (optional: when null or missing it uses the first group in the grouping values: - meta: student_id A key which begins with a - inverts the sort, so - -data: position is the inverse of - data: position With groupings only values can have a - to invert the sort (always on the key) - groupings: - student_id: index: !!null values: - -meta: student_id NOT - -groupings: ... """ sorted_states= states.copy() for sort_pair in reversed( _convert_list_of_dict_to_tuple(sort_list) ): if sort_pair[0].lstrip('-') in ['data','measure','meta']: sorted_states= _state_value_sort(sorted_states, sort_pair, _state_key_function) elif sort_pair[0] == 'groupings': for grouping in reversed(sort_pair[1]): sorted_states= _groupings_values_sort(sorted_states, grouping) return sorted_states
[ "def", "sort_states", "(", "states", ",", "sort_list", ")", ":", "sorted_states", "=", "states", ".", "copy", "(", ")", "for", "sort_pair", "in", "reversed", "(", "_convert_list_of_dict_to_tuple", "(", "sort_list", ")", ")", ":", "if", "sort_pair", "[", "0", "]", ".", "lstrip", "(", "'-'", ")", "in", "[", "'data'", ",", "'measure'", ",", "'meta'", "]", ":", "sorted_states", "=", "_state_value_sort", "(", "sorted_states", ",", "sort_pair", ",", "_state_key_function", ")", "elif", "sort_pair", "[", "0", "]", "==", "'groupings'", ":", "for", "grouping", "in", "reversed", "(", "sort_pair", "[", "1", "]", ")", ":", "sorted_states", "=", "_groupings_values_sort", "(", "sorted_states", ",", "grouping", ")", "return", "sorted_states" ]
Returns a list of sorted states, original states list remains unsorted The sort list is a list of state field: field key pairs For example (as YAML): - data: position - meta: created_at The field_key part can be a list to simplify input - meta: created_at - meta: updated_at or - meta: - created_at - updated_at It is also possible to sort by grouping values For example, with a grouping called student_id: - groupings: - student_id: index: !!null (optional: when null or missing it uses the first group in the grouping values: - meta: student_id A key which begins with a - inverts the sort, so - -data: position is the inverse of - data: position With groupings only values can have a - to invert the sort (always on the key) - groupings: - student_id: index: !!null values: - -meta: student_id NOT - -groupings: ...
[ "Returns", "a", "list", "of", "sorted", "states", "original", "states", "list", "remains", "unsorted" ]
231851238f0a62bc3682d8fa937db9053378c53d
https://github.com/pjanis/funtool/blob/231851238f0a62bc3682d8fa937db9053378c53d/funtool/lib/general.py#L27-L75
248,245
jmgilman/Neolib
neolib/pyamf/__init__.py
load_class
def load_class(alias): """ Finds the class registered to the alias. The search is done in order: 1. Checks if the class name has been registered via L{register_class} or L{register_package}. 2. Checks all functions registered via L{register_class_loader}. 3. Attempts to load the class via standard module loading techniques. @param alias: The class name. @type alias: C{string} @raise UnknownClassAlias: The C{alias} was not found. @raise TypeError: Expecting class type or L{ClassAlias} from loader. @return: Class registered to the alias. @rtype: C{classobj} """ # Try the CLASS_CACHE first try: return CLASS_CACHE[alias] except KeyError: pass for loader in CLASS_LOADERS: klass = loader(alias) if klass is None: continue if isinstance(klass, python.class_types): return register_class(klass, alias) elif isinstance(klass, ClassAlias): CLASS_CACHE[klass.alias] = klass CLASS_CACHE[klass.klass] = klass return klass raise TypeError("Expecting class object or ClassAlias from loader") mod_class = alias.split('.') if mod_class: module = '.'.join(mod_class[:-1]) klass = mod_class[-1] try: module = util.get_module(module) except (ImportError, AttributeError): pass else: klass = getattr(module, klass) if isinstance(klass, python.class_types): return register_class(klass, alias) elif isinstance(klass, ClassAlias): CLASS_CACHE[klass.alias] = klass CLASS_CACHE[klass.klass] = klass return klass.klass else: raise TypeError("Expecting class type or ClassAlias from loader") # All available methods for finding the class have been exhausted raise UnknownClassAlias("Unknown alias for %r" % (alias,))
python
def load_class(alias): """ Finds the class registered to the alias. The search is done in order: 1. Checks if the class name has been registered via L{register_class} or L{register_package}. 2. Checks all functions registered via L{register_class_loader}. 3. Attempts to load the class via standard module loading techniques. @param alias: The class name. @type alias: C{string} @raise UnknownClassAlias: The C{alias} was not found. @raise TypeError: Expecting class type or L{ClassAlias} from loader. @return: Class registered to the alias. @rtype: C{classobj} """ # Try the CLASS_CACHE first try: return CLASS_CACHE[alias] except KeyError: pass for loader in CLASS_LOADERS: klass = loader(alias) if klass is None: continue if isinstance(klass, python.class_types): return register_class(klass, alias) elif isinstance(klass, ClassAlias): CLASS_CACHE[klass.alias] = klass CLASS_CACHE[klass.klass] = klass return klass raise TypeError("Expecting class object or ClassAlias from loader") mod_class = alias.split('.') if mod_class: module = '.'.join(mod_class[:-1]) klass = mod_class[-1] try: module = util.get_module(module) except (ImportError, AttributeError): pass else: klass = getattr(module, klass) if isinstance(klass, python.class_types): return register_class(klass, alias) elif isinstance(klass, ClassAlias): CLASS_CACHE[klass.alias] = klass CLASS_CACHE[klass.klass] = klass return klass.klass else: raise TypeError("Expecting class type or ClassAlias from loader") # All available methods for finding the class have been exhausted raise UnknownClassAlias("Unknown alias for %r" % (alias,))
[ "def", "load_class", "(", "alias", ")", ":", "# Try the CLASS_CACHE first", "try", ":", "return", "CLASS_CACHE", "[", "alias", "]", "except", "KeyError", ":", "pass", "for", "loader", "in", "CLASS_LOADERS", ":", "klass", "=", "loader", "(", "alias", ")", "if", "klass", "is", "None", ":", "continue", "if", "isinstance", "(", "klass", ",", "python", ".", "class_types", ")", ":", "return", "register_class", "(", "klass", ",", "alias", ")", "elif", "isinstance", "(", "klass", ",", "ClassAlias", ")", ":", "CLASS_CACHE", "[", "klass", ".", "alias", "]", "=", "klass", "CLASS_CACHE", "[", "klass", ".", "klass", "]", "=", "klass", "return", "klass", "raise", "TypeError", "(", "\"Expecting class object or ClassAlias from loader\"", ")", "mod_class", "=", "alias", ".", "split", "(", "'.'", ")", "if", "mod_class", ":", "module", "=", "'.'", ".", "join", "(", "mod_class", "[", ":", "-", "1", "]", ")", "klass", "=", "mod_class", "[", "-", "1", "]", "try", ":", "module", "=", "util", ".", "get_module", "(", "module", ")", "except", "(", "ImportError", ",", "AttributeError", ")", ":", "pass", "else", ":", "klass", "=", "getattr", "(", "module", ",", "klass", ")", "if", "isinstance", "(", "klass", ",", "python", ".", "class_types", ")", ":", "return", "register_class", "(", "klass", ",", "alias", ")", "elif", "isinstance", "(", "klass", ",", "ClassAlias", ")", ":", "CLASS_CACHE", "[", "klass", ".", "alias", "]", "=", "klass", "CLASS_CACHE", "[", "klass", ".", "klass", "]", "=", "klass", "return", "klass", ".", "klass", "else", ":", "raise", "TypeError", "(", "\"Expecting class type or ClassAlias from loader\"", ")", "# All available methods for finding the class have been exhausted", "raise", "UnknownClassAlias", "(", "\"Unknown alias for %r\"", "%", "(", "alias", ",", ")", ")" ]
Finds the class registered to the alias. The search is done in order: 1. Checks if the class name has been registered via L{register_class} or L{register_package}. 2. Checks all functions registered via L{register_class_loader}. 3. Attempts to load the class via standard module loading techniques. @param alias: The class name. @type alias: C{string} @raise UnknownClassAlias: The C{alias} was not found. @raise TypeError: Expecting class type or L{ClassAlias} from loader. @return: Class registered to the alias. @rtype: C{classobj}
[ "Finds", "the", "class", "registered", "to", "the", "alias", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L336-L399
248,246
jmgilman/Neolib
neolib/pyamf/__init__.py
decode
def decode(stream, *args, **kwargs): """ A generator function to decode a datastream. @param stream: AMF data to be decoded. @type stream: byte data. @kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}. @return: A generator that will decode each element in the stream. """ encoding = kwargs.pop('encoding', DEFAULT_ENCODING) decoder = get_decoder(encoding, stream, *args, **kwargs) return decoder
python
def decode(stream, *args, **kwargs): """ A generator function to decode a datastream. @param stream: AMF data to be decoded. @type stream: byte data. @kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}. @return: A generator that will decode each element in the stream. """ encoding = kwargs.pop('encoding', DEFAULT_ENCODING) decoder = get_decoder(encoding, stream, *args, **kwargs) return decoder
[ "def", "decode", "(", "stream", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "encoding", "=", "kwargs", ".", "pop", "(", "'encoding'", ",", "DEFAULT_ENCODING", ")", "decoder", "=", "get_decoder", "(", "encoding", ",", "stream", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "decoder" ]
A generator function to decode a datastream. @param stream: AMF data to be decoded. @type stream: byte data. @kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}. @return: A generator that will decode each element in the stream.
[ "A", "generator", "function", "to", "decode", "a", "datastream", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L402-L414
248,247
jmgilman/Neolib
neolib/pyamf/__init__.py
encode
def encode(*args, **kwargs): """ A helper function to encode an element. @param args: The python data to be encoded. @kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}. @return: A L{util.BufferedByteStream} object that contains the data. """ encoding = kwargs.pop('encoding', DEFAULT_ENCODING) encoder = get_encoder(encoding, **kwargs) [encoder.writeElement(el) for el in args] stream = encoder.stream stream.seek(0) return stream
python
def encode(*args, **kwargs): """ A helper function to encode an element. @param args: The python data to be encoded. @kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}. @return: A L{util.BufferedByteStream} object that contains the data. """ encoding = kwargs.pop('encoding', DEFAULT_ENCODING) encoder = get_encoder(encoding, **kwargs) [encoder.writeElement(el) for el in args] stream = encoder.stream stream.seek(0) return stream
[ "def", "encode", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "encoding", "=", "kwargs", ".", "pop", "(", "'encoding'", ",", "DEFAULT_ENCODING", ")", "encoder", "=", "get_encoder", "(", "encoding", ",", "*", "*", "kwargs", ")", "[", "encoder", ".", "writeElement", "(", "el", ")", "for", "el", "in", "args", "]", "stream", "=", "encoder", ".", "stream", "stream", ".", "seek", "(", "0", ")", "return", "stream" ]
A helper function to encode an element. @param args: The python data to be encoded. @kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}. @return: A L{util.BufferedByteStream} object that contains the data.
[ "A", "helper", "function", "to", "encode", "an", "element", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L417-L433
248,248
jmgilman/Neolib
neolib/pyamf/__init__.py
get_type
def get_type(type_): """ Gets the declaration for the corresponding custom type. @raise KeyError: Unknown type. @see: L{add_type} and L{remove_type} """ if isinstance(type_, list): type_ = tuple(type_) for k, v in TYPE_MAP.iteritems(): if k == type_: return v raise KeyError("Unknown type %r" % (type_,))
python
def get_type(type_): """ Gets the declaration for the corresponding custom type. @raise KeyError: Unknown type. @see: L{add_type} and L{remove_type} """ if isinstance(type_, list): type_ = tuple(type_) for k, v in TYPE_MAP.iteritems(): if k == type_: return v raise KeyError("Unknown type %r" % (type_,))
[ "def", "get_type", "(", "type_", ")", ":", "if", "isinstance", "(", "type_", ",", "list", ")", ":", "type_", "=", "tuple", "(", "type_", ")", "for", "k", ",", "v", "in", "TYPE_MAP", ".", "iteritems", "(", ")", ":", "if", "k", "==", "type_", ":", "return", "v", "raise", "KeyError", "(", "\"Unknown type %r\"", "%", "(", "type_", ",", ")", ")" ]
Gets the declaration for the corresponding custom type. @raise KeyError: Unknown type. @see: L{add_type} and L{remove_type}
[ "Gets", "the", "declaration", "for", "the", "corresponding", "custom", "type", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/__init__.py#L558-L572
248,249
madisona/apysigner
apysigner.py
Signer.create_signature
def create_signature(self, base_url, payload=None): """ Creates unique signature for request. Make sure ALL 'GET' and 'POST' data is already included before creating the signature or receiver won't be able to re-create it. :param base_url: The url you'll using for your request. :param payload: The POST data that you'll be sending. """ url = urlparse(base_url) url_to_sign = "{path}?{query}".format(path=url.path, query=url.query) converted_payload = self._convert(payload) decoded_key = base64.urlsafe_b64decode(self.private_key.encode('utf-8')) signature = hmac.new(decoded_key, str.encode(url_to_sign + converted_payload), hashlib.sha256) return bytes.decode(base64.urlsafe_b64encode(signature.digest()))
python
def create_signature(self, base_url, payload=None): """ Creates unique signature for request. Make sure ALL 'GET' and 'POST' data is already included before creating the signature or receiver won't be able to re-create it. :param base_url: The url you'll using for your request. :param payload: The POST data that you'll be sending. """ url = urlparse(base_url) url_to_sign = "{path}?{query}".format(path=url.path, query=url.query) converted_payload = self._convert(payload) decoded_key = base64.urlsafe_b64decode(self.private_key.encode('utf-8')) signature = hmac.new(decoded_key, str.encode(url_to_sign + converted_payload), hashlib.sha256) return bytes.decode(base64.urlsafe_b64encode(signature.digest()))
[ "def", "create_signature", "(", "self", ",", "base_url", ",", "payload", "=", "None", ")", ":", "url", "=", "urlparse", "(", "base_url", ")", "url_to_sign", "=", "\"{path}?{query}\"", ".", "format", "(", "path", "=", "url", ".", "path", ",", "query", "=", "url", ".", "query", ")", "converted_payload", "=", "self", ".", "_convert", "(", "payload", ")", "decoded_key", "=", "base64", ".", "urlsafe_b64decode", "(", "self", ".", "private_key", ".", "encode", "(", "'utf-8'", ")", ")", "signature", "=", "hmac", ".", "new", "(", "decoded_key", ",", "str", ".", "encode", "(", "url_to_sign", "+", "converted_payload", ")", ",", "hashlib", ".", "sha256", ")", "return", "bytes", ".", "decode", "(", "base64", ".", "urlsafe_b64encode", "(", "signature", ".", "digest", "(", ")", ")", ")" ]
Creates unique signature for request. Make sure ALL 'GET' and 'POST' data is already included before creating the signature or receiver won't be able to re-create it. :param base_url: The url you'll using for your request. :param payload: The POST data that you'll be sending.
[ "Creates", "unique", "signature", "for", "request", ".", "Make", "sure", "ALL", "GET", "and", "POST", "data", "is", "already", "included", "before", "creating", "the", "signature", "or", "receiver", "won", "t", "be", "able", "to", "re", "-", "create", "it", "." ]
3666b478d228a38aca66a1b73d0aaf4aa67e765d
https://github.com/madisona/apysigner/blob/3666b478d228a38aca66a1b73d0aaf4aa67e765d/apysigner.py#L66-L85
248,250
madisona/apysigner
apysigner.py
Signer._convert
def _convert(self, payload): """ Converts payload to a string. Complex objects are dumped to json """ if not isinstance(payload, six.string_types): payload = json.dumps(payload, cls=DefaultJSONEncoder, sort_keys=True) return str(payload)
python
def _convert(self, payload): """ Converts payload to a string. Complex objects are dumped to json """ if not isinstance(payload, six.string_types): payload = json.dumps(payload, cls=DefaultJSONEncoder, sort_keys=True) return str(payload)
[ "def", "_convert", "(", "self", ",", "payload", ")", ":", "if", "not", "isinstance", "(", "payload", ",", "six", ".", "string_types", ")", ":", "payload", "=", "json", ".", "dumps", "(", "payload", ",", "cls", "=", "DefaultJSONEncoder", ",", "sort_keys", "=", "True", ")", "return", "str", "(", "payload", ")" ]
Converts payload to a string. Complex objects are dumped to json
[ "Converts", "payload", "to", "a", "string", ".", "Complex", "objects", "are", "dumped", "to", "json" ]
3666b478d228a38aca66a1b73d0aaf4aa67e765d
https://github.com/madisona/apysigner/blob/3666b478d228a38aca66a1b73d0aaf4aa67e765d/apysigner.py#L87-L93
248,251
heikomuller/sco-datastore
scodata/funcdata.py
DefaultFunctionalDataManager.from_dict
def from_dict(self, document): """Create functional data object from JSON document retrieved from database. Parameters ---------- document : JSON Json document in database Returns ------- FunctionalDataHandle Handle for functional data object """ identifier = str(document['_id']) active = document['active'] # The directory is not materilaized in database to allow moving the # base directory without having to update the database. directory = os.path.join(self.directory, identifier) timestamp = datetime.datetime.strptime(document['timestamp'], '%Y-%m-%dT%H:%M:%S.%f') properties = document['properties'] return FunctionalDataHandle(identifier, properties, directory, timestamp=timestamp, is_active=active)
python
def from_dict(self, document): """Create functional data object from JSON document retrieved from database. Parameters ---------- document : JSON Json document in database Returns ------- FunctionalDataHandle Handle for functional data object """ identifier = str(document['_id']) active = document['active'] # The directory is not materilaized in database to allow moving the # base directory without having to update the database. directory = os.path.join(self.directory, identifier) timestamp = datetime.datetime.strptime(document['timestamp'], '%Y-%m-%dT%H:%M:%S.%f') properties = document['properties'] return FunctionalDataHandle(identifier, properties, directory, timestamp=timestamp, is_active=active)
[ "def", "from_dict", "(", "self", ",", "document", ")", ":", "identifier", "=", "str", "(", "document", "[", "'_id'", "]", ")", "active", "=", "document", "[", "'active'", "]", "# The directory is not materilaized in database to allow moving the", "# base directory without having to update the database.", "directory", "=", "os", ".", "path", ".", "join", "(", "self", ".", "directory", ",", "identifier", ")", "timestamp", "=", "datetime", ".", "datetime", ".", "strptime", "(", "document", "[", "'timestamp'", "]", ",", "'%Y-%m-%dT%H:%M:%S.%f'", ")", "properties", "=", "document", "[", "'properties'", "]", "return", "FunctionalDataHandle", "(", "identifier", ",", "properties", ",", "directory", ",", "timestamp", "=", "timestamp", ",", "is_active", "=", "active", ")" ]
Create functional data object from JSON document retrieved from database. Parameters ---------- document : JSON Json document in database Returns ------- FunctionalDataHandle Handle for functional data object
[ "Create", "functional", "data", "object", "from", "JSON", "document", "retrieved", "from", "database", "." ]
7180a6b51150667e47629da566aedaa742e39342
https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/funcdata.py#L238-L259
248,252
kennydo/nyaalib
nyaalib/__init__.py
NyaaClient.view_torrent
def view_torrent(self, torrent_id): """Retrieves and parses the torrent page for a given `torrent_id`. :param torrent_id: the ID of the torrent to view :raises TorrentNotFoundError: if the torrent does not exist :returns: a :class:`TorrentPage` with a snapshot view of the torrent detail page """ params = { 'page': 'view', 'tid': torrent_id, } r = requests.get(self.base_url, params=params) content = self._get_page_content(r) # Check if the content div has any child elements if not len(content): # The "torrent not found" text in the page has some unicode junk # that we can safely ignore. text = str(content.text.encode('ascii', 'ignore')) if TORRENT_NOT_FOUND_TEXT in text: raise TorrentNotFoundError(TORRENT_NOT_FOUND_TEXT) cell_td_elems = content.findall('.//td') name = cell_td_elems[3].text category_href = content\ .findall(".//td[@class='viewcategory']/a[2]")[0]\ .attrib['href'] category_value = category_href.split('cats=')[1] category = Category.lookup_category(category_value) # parse the submitter details submitter_a_elem = cell_td_elems[7].findall('a')[0] submitter_id = submitter_a_elem.attrib['href'].split('=')[1] submitter_name = submitter_a_elem.findall('span')[0].text submitter = User(submitter_id, submitter_name) tracker = cell_td_elems[11].text date_created = datetime.datetime.strptime( cell_td_elems[5].text, '%Y-%m-%d, %H:%M %Z') seeders = int(content.findall(".//span[@class='viewsn']")[0].text) leechers = int(content.findall(".//span[@class='viewln']")[0].text) downloads = int(content.findall(".//span[@class='viewdn']")[0].text) file_size = cell_td_elems[21].text # note that the tree returned by html5lib might not exactly match the # original contents of the description div description = ElementTree.tostring( content.findall(".//div[@class='viewdescription']")[0], encoding='utf8', method='html') return TorrentPage( torrent_id, name, submitter, category, tracker, date_created, seeders, leechers, downloads, file_size, description)
python
def view_torrent(self, torrent_id): """Retrieves and parses the torrent page for a given `torrent_id`. :param torrent_id: the ID of the torrent to view :raises TorrentNotFoundError: if the torrent does not exist :returns: a :class:`TorrentPage` with a snapshot view of the torrent detail page """ params = { 'page': 'view', 'tid': torrent_id, } r = requests.get(self.base_url, params=params) content = self._get_page_content(r) # Check if the content div has any child elements if not len(content): # The "torrent not found" text in the page has some unicode junk # that we can safely ignore. text = str(content.text.encode('ascii', 'ignore')) if TORRENT_NOT_FOUND_TEXT in text: raise TorrentNotFoundError(TORRENT_NOT_FOUND_TEXT) cell_td_elems = content.findall('.//td') name = cell_td_elems[3].text category_href = content\ .findall(".//td[@class='viewcategory']/a[2]")[0]\ .attrib['href'] category_value = category_href.split('cats=')[1] category = Category.lookup_category(category_value) # parse the submitter details submitter_a_elem = cell_td_elems[7].findall('a')[0] submitter_id = submitter_a_elem.attrib['href'].split('=')[1] submitter_name = submitter_a_elem.findall('span')[0].text submitter = User(submitter_id, submitter_name) tracker = cell_td_elems[11].text date_created = datetime.datetime.strptime( cell_td_elems[5].text, '%Y-%m-%d, %H:%M %Z') seeders = int(content.findall(".//span[@class='viewsn']")[0].text) leechers = int(content.findall(".//span[@class='viewln']")[0].text) downloads = int(content.findall(".//span[@class='viewdn']")[0].text) file_size = cell_td_elems[21].text # note that the tree returned by html5lib might not exactly match the # original contents of the description div description = ElementTree.tostring( content.findall(".//div[@class='viewdescription']")[0], encoding='utf8', method='html') return TorrentPage( torrent_id, name, submitter, category, tracker, date_created, seeders, leechers, downloads, file_size, description)
[ "def", "view_torrent", "(", "self", ",", "torrent_id", ")", ":", "params", "=", "{", "'page'", ":", "'view'", ",", "'tid'", ":", "torrent_id", ",", "}", "r", "=", "requests", ".", "get", "(", "self", ".", "base_url", ",", "params", "=", "params", ")", "content", "=", "self", ".", "_get_page_content", "(", "r", ")", "# Check if the content div has any child elements", "if", "not", "len", "(", "content", ")", ":", "# The \"torrent not found\" text in the page has some unicode junk", "# that we can safely ignore.", "text", "=", "str", "(", "content", ".", "text", ".", "encode", "(", "'ascii'", ",", "'ignore'", ")", ")", "if", "TORRENT_NOT_FOUND_TEXT", "in", "text", ":", "raise", "TorrentNotFoundError", "(", "TORRENT_NOT_FOUND_TEXT", ")", "cell_td_elems", "=", "content", ".", "findall", "(", "'.//td'", ")", "name", "=", "cell_td_elems", "[", "3", "]", ".", "text", "category_href", "=", "content", ".", "findall", "(", "\".//td[@class='viewcategory']/a[2]\"", ")", "[", "0", "]", ".", "attrib", "[", "'href'", "]", "category_value", "=", "category_href", ".", "split", "(", "'cats='", ")", "[", "1", "]", "category", "=", "Category", ".", "lookup_category", "(", "category_value", ")", "# parse the submitter details", "submitter_a_elem", "=", "cell_td_elems", "[", "7", "]", ".", "findall", "(", "'a'", ")", "[", "0", "]", "submitter_id", "=", "submitter_a_elem", ".", "attrib", "[", "'href'", "]", ".", "split", "(", "'='", ")", "[", "1", "]", "submitter_name", "=", "submitter_a_elem", ".", "findall", "(", "'span'", ")", "[", "0", "]", ".", "text", "submitter", "=", "User", "(", "submitter_id", ",", "submitter_name", ")", "tracker", "=", "cell_td_elems", "[", "11", "]", ".", "text", "date_created", "=", "datetime", ".", "datetime", ".", "strptime", "(", "cell_td_elems", "[", "5", "]", ".", "text", ",", "'%Y-%m-%d, %H:%M %Z'", ")", "seeders", "=", "int", "(", "content", ".", "findall", "(", "\".//span[@class='viewsn']\"", ")", "[", "0", "]", ".", "text", ")", "leechers", "=", "int", "(", "content", ".", "findall", "(", "\".//span[@class='viewln']\"", ")", "[", "0", "]", ".", "text", ")", "downloads", "=", "int", "(", "content", ".", "findall", "(", "\".//span[@class='viewdn']\"", ")", "[", "0", "]", ".", "text", ")", "file_size", "=", "cell_td_elems", "[", "21", "]", ".", "text", "# note that the tree returned by html5lib might not exactly match the", "# original contents of the description div", "description", "=", "ElementTree", ".", "tostring", "(", "content", ".", "findall", "(", "\".//div[@class='viewdescription']\"", ")", "[", "0", "]", ",", "encoding", "=", "'utf8'", ",", "method", "=", "'html'", ")", "return", "TorrentPage", "(", "torrent_id", ",", "name", ",", "submitter", ",", "category", ",", "tracker", ",", "date_created", ",", "seeders", ",", "leechers", ",", "downloads", ",", "file_size", ",", "description", ")" ]
Retrieves and parses the torrent page for a given `torrent_id`. :param torrent_id: the ID of the torrent to view :raises TorrentNotFoundError: if the torrent does not exist :returns: a :class:`TorrentPage` with a snapshot view of the torrent detail page
[ "Retrieves", "and", "parses", "the", "torrent", "page", "for", "a", "given", "torrent_id", "." ]
ab787b7ba141ed53d2ad978bf13eb7b8bcdd4b0d
https://github.com/kennydo/nyaalib/blob/ab787b7ba141ed53d2ad978bf13eb7b8bcdd4b0d/nyaalib/__init__.py#L67-L122
248,253
kennydo/nyaalib
nyaalib/__init__.py
NyaaClient.get_torrent
def get_torrent(self, torrent_id): """Gets the `.torrent` data for the given `torrent_id`. :param torrent_id: the ID of the torrent to download :raises TorrentNotFoundError: if the torrent does not exist :returns: :class:`Torrent` of the associated torrent """ params = { 'page': 'download', 'tid': torrent_id, } r = requests.get(self.base_url, params=params) if r.headers.get('content-type') != 'application/x-bittorrent': raise TorrentNotFoundError(TORRENT_NOT_FOUND_TEXT) torrent_data = r.content return Torrent(torrent_id, torrent_data)
python
def get_torrent(self, torrent_id): """Gets the `.torrent` data for the given `torrent_id`. :param torrent_id: the ID of the torrent to download :raises TorrentNotFoundError: if the torrent does not exist :returns: :class:`Torrent` of the associated torrent """ params = { 'page': 'download', 'tid': torrent_id, } r = requests.get(self.base_url, params=params) if r.headers.get('content-type') != 'application/x-bittorrent': raise TorrentNotFoundError(TORRENT_NOT_FOUND_TEXT) torrent_data = r.content return Torrent(torrent_id, torrent_data)
[ "def", "get_torrent", "(", "self", ",", "torrent_id", ")", ":", "params", "=", "{", "'page'", ":", "'download'", ",", "'tid'", ":", "torrent_id", ",", "}", "r", "=", "requests", ".", "get", "(", "self", ".", "base_url", ",", "params", "=", "params", ")", "if", "r", ".", "headers", ".", "get", "(", "'content-type'", ")", "!=", "'application/x-bittorrent'", ":", "raise", "TorrentNotFoundError", "(", "TORRENT_NOT_FOUND_TEXT", ")", "torrent_data", "=", "r", ".", "content", "return", "Torrent", "(", "torrent_id", ",", "torrent_data", ")" ]
Gets the `.torrent` data for the given `torrent_id`. :param torrent_id: the ID of the torrent to download :raises TorrentNotFoundError: if the torrent does not exist :returns: :class:`Torrent` of the associated torrent
[ "Gets", "the", ".", "torrent", "data", "for", "the", "given", "torrent_id", "." ]
ab787b7ba141ed53d2ad978bf13eb7b8bcdd4b0d
https://github.com/kennydo/nyaalib/blob/ab787b7ba141ed53d2ad978bf13eb7b8bcdd4b0d/nyaalib/__init__.py#L124-L139
248,254
kennydo/nyaalib
nyaalib/__init__.py
NyaaClient.search
def search(self, terms, category=Category.all_categories, page=1, sort_key=SearchSortKey.date, order_key=SearchOrderKey.descending): """Get a list of torrents that match the given search term :param terms: the `str` needle :param category: the desired :class:`Category` of the results :param page: the 1-based page to return the result :param sort_key: the :class:`SearchSortKey` of the results list :param order_key: the :class:`SearchOrderkey` of the results list :return: a :class:`SearchPage` of results """ params = { 'page': 'search', 'term': terms, 'cats': category.value, 'sort': sort_key.value, 'order': order_key.value, } r = requests.get(self.base_url, params=params) content = self._get_page_content(r) # first, get the total number of pages returned. this findall returns # two results (one from the top half of the page, one from the bottom), # so only take the first element. a_to_last_page = content.findall('.//div[@class="rightpages"]/a[2]') if not a_to_last_page: total_pages = 1 else: last_page_url = a_to_last_page[0].attrib['href'] offset = extract_url_query_parameter(last_page_url, "offset")[0] total_pages = int(offset) torrent_stubs = [] rows = (x for x in content.findall('.//table//tr') if 'tlistrow' in x.attrib.get('class', '')) for row in rows: cell_td_elems = row.findall('td') category_value = extract_url_query_parameter( cell_td_elems[0].find('a').attrib['href'], 'cats')[0] category = Category.lookup_category(category_value) torrent_id = extract_url_query_parameter( cell_td_elems[1].find('a').attrib['href'], "tid")[0] name = cell_td_elems[1].find('a').text file_size = cell_td_elems[3].text if cell_td_elems[4].text.isdigit(): seeders = int(cell_td_elems[4].text) else: seeders = None if cell_td_elems[5].text.isdigit(): leechers = int(cell_td_elems[5].text) else: leechers = None downloads = int(cell_td_elems[6].text) stub = TorrentStub(torrent_id, name, category, seeders, leechers, file_size, downloads) torrent_stubs.append(stub) return SearchResultPage( terms, category, sort_key, order_key, page, total_pages, torrent_stubs)
python
def search(self, terms, category=Category.all_categories, page=1, sort_key=SearchSortKey.date, order_key=SearchOrderKey.descending): """Get a list of torrents that match the given search term :param terms: the `str` needle :param category: the desired :class:`Category` of the results :param page: the 1-based page to return the result :param sort_key: the :class:`SearchSortKey` of the results list :param order_key: the :class:`SearchOrderkey` of the results list :return: a :class:`SearchPage` of results """ params = { 'page': 'search', 'term': terms, 'cats': category.value, 'sort': sort_key.value, 'order': order_key.value, } r = requests.get(self.base_url, params=params) content = self._get_page_content(r) # first, get the total number of pages returned. this findall returns # two results (one from the top half of the page, one from the bottom), # so only take the first element. a_to_last_page = content.findall('.//div[@class="rightpages"]/a[2]') if not a_to_last_page: total_pages = 1 else: last_page_url = a_to_last_page[0].attrib['href'] offset = extract_url_query_parameter(last_page_url, "offset")[0] total_pages = int(offset) torrent_stubs = [] rows = (x for x in content.findall('.//table//tr') if 'tlistrow' in x.attrib.get('class', '')) for row in rows: cell_td_elems = row.findall('td') category_value = extract_url_query_parameter( cell_td_elems[0].find('a').attrib['href'], 'cats')[0] category = Category.lookup_category(category_value) torrent_id = extract_url_query_parameter( cell_td_elems[1].find('a').attrib['href'], "tid")[0] name = cell_td_elems[1].find('a').text file_size = cell_td_elems[3].text if cell_td_elems[4].text.isdigit(): seeders = int(cell_td_elems[4].text) else: seeders = None if cell_td_elems[5].text.isdigit(): leechers = int(cell_td_elems[5].text) else: leechers = None downloads = int(cell_td_elems[6].text) stub = TorrentStub(torrent_id, name, category, seeders, leechers, file_size, downloads) torrent_stubs.append(stub) return SearchResultPage( terms, category, sort_key, order_key, page, total_pages, torrent_stubs)
[ "def", "search", "(", "self", ",", "terms", ",", "category", "=", "Category", ".", "all_categories", ",", "page", "=", "1", ",", "sort_key", "=", "SearchSortKey", ".", "date", ",", "order_key", "=", "SearchOrderKey", ".", "descending", ")", ":", "params", "=", "{", "'page'", ":", "'search'", ",", "'term'", ":", "terms", ",", "'cats'", ":", "category", ".", "value", ",", "'sort'", ":", "sort_key", ".", "value", ",", "'order'", ":", "order_key", ".", "value", ",", "}", "r", "=", "requests", ".", "get", "(", "self", ".", "base_url", ",", "params", "=", "params", ")", "content", "=", "self", ".", "_get_page_content", "(", "r", ")", "# first, get the total number of pages returned. this findall returns", "# two results (one from the top half of the page, one from the bottom),", "# so only take the first element.", "a_to_last_page", "=", "content", ".", "findall", "(", "'.//div[@class=\"rightpages\"]/a[2]'", ")", "if", "not", "a_to_last_page", ":", "total_pages", "=", "1", "else", ":", "last_page_url", "=", "a_to_last_page", "[", "0", "]", ".", "attrib", "[", "'href'", "]", "offset", "=", "extract_url_query_parameter", "(", "last_page_url", ",", "\"offset\"", ")", "[", "0", "]", "total_pages", "=", "int", "(", "offset", ")", "torrent_stubs", "=", "[", "]", "rows", "=", "(", "x", "for", "x", "in", "content", ".", "findall", "(", "'.//table//tr'", ")", "if", "'tlistrow'", "in", "x", ".", "attrib", ".", "get", "(", "'class'", ",", "''", ")", ")", "for", "row", "in", "rows", ":", "cell_td_elems", "=", "row", ".", "findall", "(", "'td'", ")", "category_value", "=", "extract_url_query_parameter", "(", "cell_td_elems", "[", "0", "]", ".", "find", "(", "'a'", ")", ".", "attrib", "[", "'href'", "]", ",", "'cats'", ")", "[", "0", "]", "category", "=", "Category", ".", "lookup_category", "(", "category_value", ")", "torrent_id", "=", "extract_url_query_parameter", "(", "cell_td_elems", "[", "1", "]", ".", "find", "(", "'a'", ")", ".", "attrib", "[", "'href'", "]", ",", "\"tid\"", ")", "[", "0", "]", "name", "=", "cell_td_elems", "[", "1", "]", ".", "find", "(", "'a'", ")", ".", "text", "file_size", "=", "cell_td_elems", "[", "3", "]", ".", "text", "if", "cell_td_elems", "[", "4", "]", ".", "text", ".", "isdigit", "(", ")", ":", "seeders", "=", "int", "(", "cell_td_elems", "[", "4", "]", ".", "text", ")", "else", ":", "seeders", "=", "None", "if", "cell_td_elems", "[", "5", "]", ".", "text", ".", "isdigit", "(", ")", ":", "leechers", "=", "int", "(", "cell_td_elems", "[", "5", "]", ".", "text", ")", "else", ":", "leechers", "=", "None", "downloads", "=", "int", "(", "cell_td_elems", "[", "6", "]", ".", "text", ")", "stub", "=", "TorrentStub", "(", "torrent_id", ",", "name", ",", "category", ",", "seeders", ",", "leechers", ",", "file_size", ",", "downloads", ")", "torrent_stubs", ".", "append", "(", "stub", ")", "return", "SearchResultPage", "(", "terms", ",", "category", ",", "sort_key", ",", "order_key", ",", "page", ",", "total_pages", ",", "torrent_stubs", ")" ]
Get a list of torrents that match the given search term :param terms: the `str` needle :param category: the desired :class:`Category` of the results :param page: the 1-based page to return the result :param sort_key: the :class:`SearchSortKey` of the results list :param order_key: the :class:`SearchOrderkey` of the results list :return: a :class:`SearchPage` of results
[ "Get", "a", "list", "of", "torrents", "that", "match", "the", "given", "search", "term" ]
ab787b7ba141ed53d2ad978bf13eb7b8bcdd4b0d
https://github.com/kennydo/nyaalib/blob/ab787b7ba141ed53d2ad978bf13eb7b8bcdd4b0d/nyaalib/__init__.py#L141-L204
248,255
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/scrappers/grada_cz.py
_parse_format_pages_isbn
def _parse_format_pages_isbn(html_chunk): """ Parse format, number of pages and ISBN. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: tuple: (format, pages, isbn), all as string. """ ppi = get_first_content( html_chunk.find("div", {"class": "price-overflow"}) ) if not ppi: return None, None, None # all information this function should parse are at one line ppi = filter(lambda x: x.strip(), ppi.split("<br />"))[0] # parse isbn isbn = dhtmlparser.parseString(ppi) isbn = isbn.find("b") isbn = isbn[0].getContent() if isbn else None # parse pages and format pages = None book_format = None details = ppi.split("|") if len(details) >= 2: book_format = details[0].strip() pages = details[1].strip() return book_format, pages, isbn
python
def _parse_format_pages_isbn(html_chunk): """ Parse format, number of pages and ISBN. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: tuple: (format, pages, isbn), all as string. """ ppi = get_first_content( html_chunk.find("div", {"class": "price-overflow"}) ) if not ppi: return None, None, None # all information this function should parse are at one line ppi = filter(lambda x: x.strip(), ppi.split("<br />"))[0] # parse isbn isbn = dhtmlparser.parseString(ppi) isbn = isbn.find("b") isbn = isbn[0].getContent() if isbn else None # parse pages and format pages = None book_format = None details = ppi.split("|") if len(details) >= 2: book_format = details[0].strip() pages = details[1].strip() return book_format, pages, isbn
[ "def", "_parse_format_pages_isbn", "(", "html_chunk", ")", ":", "ppi", "=", "get_first_content", "(", "html_chunk", ".", "find", "(", "\"div\"", ",", "{", "\"class\"", ":", "\"price-overflow\"", "}", ")", ")", "if", "not", "ppi", ":", "return", "None", ",", "None", ",", "None", "# all information this function should parse are at one line", "ppi", "=", "filter", "(", "lambda", "x", ":", "x", ".", "strip", "(", ")", ",", "ppi", ".", "split", "(", "\"<br />\"", ")", ")", "[", "0", "]", "# parse isbn", "isbn", "=", "dhtmlparser", ".", "parseString", "(", "ppi", ")", "isbn", "=", "isbn", ".", "find", "(", "\"b\"", ")", "isbn", "=", "isbn", "[", "0", "]", ".", "getContent", "(", ")", "if", "isbn", "else", "None", "# parse pages and format", "pages", "=", "None", "book_format", "=", "None", "details", "=", "ppi", ".", "split", "(", "\"|\"", ")", "if", "len", "(", "details", ")", ">=", "2", ":", "book_format", "=", "details", "[", "0", "]", ".", "strip", "(", ")", "pages", "=", "details", "[", "1", "]", ".", "strip", "(", ")", "return", "book_format", ",", "pages", ",", "isbn" ]
Parse format, number of pages and ISBN. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: tuple: (format, pages, isbn), all as string.
[ "Parse", "format", "number", "of", "pages", "and", "ISBN", "." ]
38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/grada_cz.py#L148-L182
248,256
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/scrappers/grada_cz.py
_parse_price
def _parse_price(html_chunk): """ Parse price of the book. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: str/None: Price as string with currency or None if not found. """ price = get_first_content( html_chunk.find("div", {"class": "prices"}) ) if not price: return None # it is always in format Cena:\n150kč price = dhtmlparser.removeTags(price) price = price.split("\n")[-1] return price
python
def _parse_price(html_chunk): """ Parse price of the book. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: str/None: Price as string with currency or None if not found. """ price = get_first_content( html_chunk.find("div", {"class": "prices"}) ) if not price: return None # it is always in format Cena:\n150kč price = dhtmlparser.removeTags(price) price = price.split("\n")[-1] return price
[ "def", "_parse_price", "(", "html_chunk", ")", ":", "price", "=", "get_first_content", "(", "html_chunk", ".", "find", "(", "\"div\"", ",", "{", "\"class\"", ":", "\"prices\"", "}", ")", ")", "if", "not", "price", ":", "return", "None", "# it is always in format Cena:\\n150kč", "price", "=", "dhtmlparser", ".", "removeTags", "(", "price", ")", "price", "=", "price", ".", "split", "(", "\"\\n\"", ")", "[", "-", "1", "]", "return", "price" ]
Parse price of the book. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: str/None: Price as string with currency or None if not found.
[ "Parse", "price", "of", "the", "book", "." ]
38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/grada_cz.py#L185-L206
248,257
radjkarl/appBase
appbase/MultiWorkspaceWindow.py
MultiWorkspaceWindow.workspaces
def workspaces(self, index=None): """return generator for all all workspace instances""" c = self.centralWidget() if index is None: return (c.widget(n) for n in range(c.count())) else: return c.widget(index)
python
def workspaces(self, index=None): """return generator for all all workspace instances""" c = self.centralWidget() if index is None: return (c.widget(n) for n in range(c.count())) else: return c.widget(index)
[ "def", "workspaces", "(", "self", ",", "index", "=", "None", ")", ":", "c", "=", "self", ".", "centralWidget", "(", ")", "if", "index", "is", "None", ":", "return", "(", "c", ".", "widget", "(", "n", ")", "for", "n", "in", "range", "(", "c", ".", "count", "(", ")", ")", ")", "else", ":", "return", "c", ".", "widget", "(", "index", ")" ]
return generator for all all workspace instances
[ "return", "generator", "for", "all", "all", "workspace", "instances" ]
72b514e6dee7c083f01a2d0b2cc93d46df55bdcb
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/MultiWorkspaceWindow.py#L77-L83
248,258
zyga/call
examples/example2.py
validate
def validate(func): """ Check if annotated function arguments validate according to spec """ call = PythonCall(func) @wraps(func) def decorator(*args, **kwargs): parameters = call.bind(args, kwargs) for arg_name, validator in func.__annotations__.items(): if not validator(parameters[arg_name]): raise TypeError( "Argument {!r} failed to validate".format(arg_name)) return call.apply(args, kwargs) return decorator
python
def validate(func): """ Check if annotated function arguments validate according to spec """ call = PythonCall(func) @wraps(func) def decorator(*args, **kwargs): parameters = call.bind(args, kwargs) for arg_name, validator in func.__annotations__.items(): if not validator(parameters[arg_name]): raise TypeError( "Argument {!r} failed to validate".format(arg_name)) return call.apply(args, kwargs) return decorator
[ "def", "validate", "(", "func", ")", ":", "call", "=", "PythonCall", "(", "func", ")", "@", "wraps", "(", "func", ")", "def", "decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "parameters", "=", "call", ".", "bind", "(", "args", ",", "kwargs", ")", "for", "arg_name", ",", "validator", "in", "func", ".", "__annotations__", ".", "items", "(", ")", ":", "if", "not", "validator", "(", "parameters", "[", "arg_name", "]", ")", ":", "raise", "TypeError", "(", "\"Argument {!r} failed to validate\"", ".", "format", "(", "arg_name", ")", ")", "return", "call", ".", "apply", "(", "args", ",", "kwargs", ")", "return", "decorator" ]
Check if annotated function arguments validate according to spec
[ "Check", "if", "annotated", "function", "arguments", "validate", "according", "to", "spec" ]
dcef9a5aac7f9085bd4829dd6bcedc5fc2945d87
https://github.com/zyga/call/blob/dcef9a5aac7f9085bd4829dd6bcedc5fc2945d87/examples/example2.py#L20-L34
248,259
abe-winter/pg13-py
pg13/pgmock_dbapi2.py
expression_type
def expression_type(con, topx, ex): "take a BaseX descendant from sqparse2, return a type class from above" if isinstance(ex,sqparse2.Literal): if isinstance(ex.val,basestring): return STRING else: raise NotImplementedError('literal', type(ex.val)) elif isinstance(ex,sqparse2.AttrX): if ex.parent.name in con.db: # warning: what if it's not a table? what if it's aliased? return expression_type(con, topx, con.db[ex.parent.name].get_column(ex.attr.name).coltp) else: raise NotImplementedError(ex.parent) elif isinstance(ex,sqparse2.TypeX): return dict( integer=NUMBER, text=STRING, )[ex.type.lower()] else: raise NotImplementedError('unk type', type(ex))
python
def expression_type(con, topx, ex): "take a BaseX descendant from sqparse2, return a type class from above" if isinstance(ex,sqparse2.Literal): if isinstance(ex.val,basestring): return STRING else: raise NotImplementedError('literal', type(ex.val)) elif isinstance(ex,sqparse2.AttrX): if ex.parent.name in con.db: # warning: what if it's not a table? what if it's aliased? return expression_type(con, topx, con.db[ex.parent.name].get_column(ex.attr.name).coltp) else: raise NotImplementedError(ex.parent) elif isinstance(ex,sqparse2.TypeX): return dict( integer=NUMBER, text=STRING, )[ex.type.lower()] else: raise NotImplementedError('unk type', type(ex))
[ "def", "expression_type", "(", "con", ",", "topx", ",", "ex", ")", ":", "if", "isinstance", "(", "ex", ",", "sqparse2", ".", "Literal", ")", ":", "if", "isinstance", "(", "ex", ".", "val", ",", "basestring", ")", ":", "return", "STRING", "else", ":", "raise", "NotImplementedError", "(", "'literal'", ",", "type", "(", "ex", ".", "val", ")", ")", "elif", "isinstance", "(", "ex", ",", "sqparse2", ".", "AttrX", ")", ":", "if", "ex", ".", "parent", ".", "name", "in", "con", ".", "db", ":", "# warning: what if it's not a table? what if it's aliased?", "return", "expression_type", "(", "con", ",", "topx", ",", "con", ".", "db", "[", "ex", ".", "parent", ".", "name", "]", ".", "get_column", "(", "ex", ".", "attr", ".", "name", ")", ".", "coltp", ")", "else", ":", "raise", "NotImplementedError", "(", "ex", ".", "parent", ")", "elif", "isinstance", "(", "ex", ",", "sqparse2", ".", "TypeX", ")", ":", "return", "dict", "(", "integer", "=", "NUMBER", ",", "text", "=", "STRING", ",", ")", "[", "ex", ".", "type", ".", "lower", "(", ")", "]", "else", ":", "raise", "NotImplementedError", "(", "'unk type'", ",", "type", "(", "ex", ")", ")" ]
take a BaseX descendant from sqparse2, return a type class from above
[ "take", "a", "BaseX", "descendant", "from", "sqparse2", "return", "a", "type", "class", "from", "above" ]
c78806f99f35541a8756987e86edca3438aa97f5
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pgmock_dbapi2.py#L55-L71
248,260
abe-winter/pg13-py
pg13/pgmock_dbapi2.py
call_cur
def call_cur(f): "decorator for opening a connection and passing a cursor to the function" @functools.wraps(f) def f2(self, *args, **kwargs): with self.withcur() as cur: return f(self, cur, *args, **kwargs) return f2
python
def call_cur(f): "decorator for opening a connection and passing a cursor to the function" @functools.wraps(f) def f2(self, *args, **kwargs): with self.withcur() as cur: return f(self, cur, *args, **kwargs) return f2
[ "def", "call_cur", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "f2", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "withcur", "(", ")", "as", "cur", ":", "return", "f", "(", "self", ",", "cur", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "f2" ]
decorator for opening a connection and passing a cursor to the function
[ "decorator", "for", "opening", "a", "connection", "and", "passing", "a", "cursor", "to", "the", "function" ]
c78806f99f35541a8756987e86edca3438aa97f5
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pgmock_dbapi2.py#L195-L201
248,261
abe-winter/pg13-py
pg13/pgmock_dbapi2.py
Cursor.description
def description(self): "this is only a property so it can raise; make it an attr once it works" if self.lastx is None: return if type(self.lastx) not in (sqparse2.SelectX,sqparse2.UpdateX,sqparse2.InsertX): return if type(self.lastx) in (sqparse2.UpdateX,sqparse2.InsertX) and self.lastx.ret is None: return # at this point we know this is an operation that returns rows if type(self.lastx) in (sqparse2.UpdateX,sqparse2.InsertX): raise NotImplementedError('todo: Cursor.description for non-select') else: # select case return [description_from_colx(self.connection,self.lastx,colx) for colx in self.lastx.cols.children]
python
def description(self): "this is only a property so it can raise; make it an attr once it works" if self.lastx is None: return if type(self.lastx) not in (sqparse2.SelectX,sqparse2.UpdateX,sqparse2.InsertX): return if type(self.lastx) in (sqparse2.UpdateX,sqparse2.InsertX) and self.lastx.ret is None: return # at this point we know this is an operation that returns rows if type(self.lastx) in (sqparse2.UpdateX,sqparse2.InsertX): raise NotImplementedError('todo: Cursor.description for non-select') else: # select case return [description_from_colx(self.connection,self.lastx,colx) for colx in self.lastx.cols.children]
[ "def", "description", "(", "self", ")", ":", "if", "self", ".", "lastx", "is", "None", ":", "return", "if", "type", "(", "self", ".", "lastx", ")", "not", "in", "(", "sqparse2", ".", "SelectX", ",", "sqparse2", ".", "UpdateX", ",", "sqparse2", ".", "InsertX", ")", ":", "return", "if", "type", "(", "self", ".", "lastx", ")", "in", "(", "sqparse2", ".", "UpdateX", ",", "sqparse2", ".", "InsertX", ")", "and", "self", ".", "lastx", ".", "ret", "is", "None", ":", "return", "# at this point we know this is an operation that returns rows", "if", "type", "(", "self", ".", "lastx", ")", "in", "(", "sqparse2", ".", "UpdateX", ",", "sqparse2", ".", "InsertX", ")", ":", "raise", "NotImplementedError", "(", "'todo: Cursor.description for non-select'", ")", "else", ":", "# select case", "return", "[", "description_from_colx", "(", "self", ".", "connection", ",", "self", ".", "lastx", ",", "colx", ")", "for", "colx", "in", "self", ".", "lastx", ".", "cols", ".", "children", "]" ]
this is only a property so it can raise; make it an attr once it works
[ "this", "is", "only", "a", "property", "so", "it", "can", "raise", ";", "make", "it", "an", "attr", "once", "it", "works" ]
c78806f99f35541a8756987e86edca3438aa97f5
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pgmock_dbapi2.py#L93-L102
248,262
KnowledgeLinks/rdfframework
rdfframework/utilities/mapreduce.py
SimpleMapReduce.partition
def partition(self, mapped_values): """Organize the mapped values by their key. Returns an unsorted sequence of tuples with a key and a sequence of values. """ partitioned_data = collections.defaultdict(list) for key, value in mapped_values: partitioned_data[key].append(value) return partitioned_data.items()
python
def partition(self, mapped_values): """Organize the mapped values by their key. Returns an unsorted sequence of tuples with a key and a sequence of values. """ partitioned_data = collections.defaultdict(list) for key, value in mapped_values: partitioned_data[key].append(value) return partitioned_data.items()
[ "def", "partition", "(", "self", ",", "mapped_values", ")", ":", "partitioned_data", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "key", ",", "value", "in", "mapped_values", ":", "partitioned_data", "[", "key", "]", ".", "append", "(", "value", ")", "return", "partitioned_data", ".", "items", "(", ")" ]
Organize the mapped values by their key. Returns an unsorted sequence of tuples with a key and a sequence of values.
[ "Organize", "the", "mapped", "values", "by", "their", "key", ".", "Returns", "an", "unsorted", "sequence", "of", "tuples", "with", "a", "key", "and", "a", "sequence", "of", "values", "." ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/mapreduce.py#L31-L38
248,263
emencia/emencia_paste_djangocms_3
emencia_paste_djangocms_3/templates.py
Django.pre
def pre(self, command, output_dir, kw): """ Prepare some context before install Added kwargs in ``kw`` will be accessible into paste template files """ # Build a random secret_key chars = u'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' kw['secret_key'] = ''.join([ choice(chars) for i in range(50) ]) # Paste version kw['epaster_template_name'] = u'emencia-paste-djangocms-3' kw['epaster_template_version'] = template_version
python
def pre(self, command, output_dir, kw): """ Prepare some context before install Added kwargs in ``kw`` will be accessible into paste template files """ # Build a random secret_key chars = u'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' kw['secret_key'] = ''.join([ choice(chars) for i in range(50) ]) # Paste version kw['epaster_template_name'] = u'emencia-paste-djangocms-3' kw['epaster_template_version'] = template_version
[ "def", "pre", "(", "self", ",", "command", ",", "output_dir", ",", "kw", ")", ":", "# Build a random secret_key", "chars", "=", "u'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'", "kw", "[", "'secret_key'", "]", "=", "''", ".", "join", "(", "[", "choice", "(", "chars", ")", "for", "i", "in", "range", "(", "50", ")", "]", ")", "# Paste version", "kw", "[", "'epaster_template_name'", "]", "=", "u'emencia-paste-djangocms-3'", "kw", "[", "'epaster_template_version'", "]", "=", "template_version" ]
Prepare some context before install Added kwargs in ``kw`` will be accessible into paste template files
[ "Prepare", "some", "context", "before", "install", "Added", "kwargs", "in", "kw", "will", "be", "accessible", "into", "paste", "template", "files" ]
29eabbcb17e21996a6e1d99592fc719dc8833b59
https://github.com/emencia/emencia_paste_djangocms_3/blob/29eabbcb17e21996a6e1d99592fc719dc8833b59/emencia_paste_djangocms_3/templates.py#L63-L75
248,264
emencia/emencia_paste_djangocms_3
emencia_paste_djangocms_3/templates.py
Django.get_mods
def get_mods(self, project_path, vars): """ Build the mod list to enable """ # Start with answers from interactive command mods = [var.name for var in self.vars if vars[var.name].lower() == 'yes'] mods = set(mods) # Base mods for name in self.mods_list: mods.add(name) # Conditionnal mods dependancies if 'accounts' in mods or 'contact_form' in mods: mods.add('crispy_forms') mods.add('recaptcha') return mods
python
def get_mods(self, project_path, vars): """ Build the mod list to enable """ # Start with answers from interactive command mods = [var.name for var in self.vars if vars[var.name].lower() == 'yes'] mods = set(mods) # Base mods for name in self.mods_list: mods.add(name) # Conditionnal mods dependancies if 'accounts' in mods or 'contact_form' in mods: mods.add('crispy_forms') mods.add('recaptcha') return mods
[ "def", "get_mods", "(", "self", ",", "project_path", ",", "vars", ")", ":", "# Start with answers from interactive command", "mods", "=", "[", "var", ".", "name", "for", "var", "in", "self", ".", "vars", "if", "vars", "[", "var", ".", "name", "]", ".", "lower", "(", ")", "==", "'yes'", "]", "mods", "=", "set", "(", "mods", ")", "# Base mods", "for", "name", "in", "self", ".", "mods_list", ":", "mods", ".", "add", "(", "name", ")", "# Conditionnal mods dependancies", "if", "'accounts'", "in", "mods", "or", "'contact_form'", "in", "mods", ":", "mods", ".", "add", "(", "'crispy_forms'", ")", "mods", ".", "add", "(", "'recaptcha'", ")", "return", "mods" ]
Build the mod list to enable
[ "Build", "the", "mod", "list", "to", "enable" ]
29eabbcb17e21996a6e1d99592fc719dc8833b59
https://github.com/emencia/emencia_paste_djangocms_3/blob/29eabbcb17e21996a6e1d99592fc719dc8833b59/emencia_paste_djangocms_3/templates.py#L77-L94
248,265
emencia/emencia_paste_djangocms_3
emencia_paste_djangocms_3/templates.py
Django.post
def post(self, command, output_dir, vars): """ Do some tasks after install """ if command.simulate: return # Find the 'project/' dir in the created paste project project_path = join(getcwd(), vars['project'], 'project') # 1. Mods mods = self.get_mods(project_path, vars) # 2. Create symlinks for target, linkfile in self.get_symlinks(project_path, vars, mods): print "* Symlink TO:", target, 'INTO:', linkfile symlink(target, linkfile) # 3. Git first initialization call = Caller(vars['project']) call('git', 'init', '.') call('git', 'add', '.') call('git', 'commit', '-m', 'First commit')
python
def post(self, command, output_dir, vars): """ Do some tasks after install """ if command.simulate: return # Find the 'project/' dir in the created paste project project_path = join(getcwd(), vars['project'], 'project') # 1. Mods mods = self.get_mods(project_path, vars) # 2. Create symlinks for target, linkfile in self.get_symlinks(project_path, vars, mods): print "* Symlink TO:", target, 'INTO:', linkfile symlink(target, linkfile) # 3. Git first initialization call = Caller(vars['project']) call('git', 'init', '.') call('git', 'add', '.') call('git', 'commit', '-m', 'First commit')
[ "def", "post", "(", "self", ",", "command", ",", "output_dir", ",", "vars", ")", ":", "if", "command", ".", "simulate", ":", "return", "# Find the 'project/' dir in the created paste project", "project_path", "=", "join", "(", "getcwd", "(", ")", ",", "vars", "[", "'project'", "]", ",", "'project'", ")", "# 1. Mods", "mods", "=", "self", ".", "get_mods", "(", "project_path", ",", "vars", ")", "# 2. Create symlinks", "for", "target", ",", "linkfile", "in", "self", ".", "get_symlinks", "(", "project_path", ",", "vars", ",", "mods", ")", ":", "print", "\"* Symlink TO:\"", ",", "target", ",", "'INTO:'", ",", "linkfile", "symlink", "(", "target", ",", "linkfile", ")", "# 3. Git first initialization", "call", "=", "Caller", "(", "vars", "[", "'project'", "]", ")", "call", "(", "'git'", ",", "'init'", ",", "'.'", ")", "call", "(", "'git'", ",", "'add'", ",", "'.'", ")", "call", "(", "'git'", ",", "'commit'", ",", "'-m'", ",", "'First commit'", ")" ]
Do some tasks after install
[ "Do", "some", "tasks", "after", "install" ]
29eabbcb17e21996a6e1d99592fc719dc8833b59
https://github.com/emencia/emencia_paste_djangocms_3/blob/29eabbcb17e21996a6e1d99592fc719dc8833b59/emencia_paste_djangocms_3/templates.py#L116-L138
248,266
dugan/coverage-reporter
coverage_reporter/collectors/base.py
_iter_full_paths
def _iter_full_paths(path_list): """ Iterates over all paths that are in a directory and its subdirectory, returning fully-specified paths. """ for path in path_list: if not os.path.isdir(path): full_path = os.path.realpath(path) yield path else: for root, dirs, filenames in os.walk(path): for filename in filenames: full_path = os.path.realpath(os.path.join(root, filename)) yield full_path
python
def _iter_full_paths(path_list): """ Iterates over all paths that are in a directory and its subdirectory, returning fully-specified paths. """ for path in path_list: if not os.path.isdir(path): full_path = os.path.realpath(path) yield path else: for root, dirs, filenames in os.walk(path): for filename in filenames: full_path = os.path.realpath(os.path.join(root, filename)) yield full_path
[ "def", "_iter_full_paths", "(", "path_list", ")", ":", "for", "path", "in", "path_list", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "full_path", "=", "os", ".", "path", ".", "realpath", "(", "path", ")", "yield", "path", "else", ":", "for", "root", ",", "dirs", ",", "filenames", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "filename", "in", "filenames", ":", "full_path", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "root", ",", "filename", ")", ")", "yield", "full_path" ]
Iterates over all paths that are in a directory and its subdirectory, returning fully-specified paths.
[ "Iterates", "over", "all", "paths", "that", "are", "in", "a", "directory", "and", "its", "subdirectory", "returning", "fully", "-", "specified", "paths", "." ]
18ecc9189de4f62b15366901b2451b8047f1ccfb
https://github.com/dugan/coverage-reporter/blob/18ecc9189de4f62b15366901b2451b8047f1ccfb/coverage_reporter/collectors/base.py#L53-L66
248,267
f213/rumetr-client
rumetr/scrapy/pipeline.py
UploadPipeline.c
def c(self): """Caching client for not repeapting checks""" if self._client is None: self._parse_settings() self._client = Rumetr(**self.settings) return self._client
python
def c(self): """Caching client for not repeapting checks""" if self._client is None: self._parse_settings() self._client = Rumetr(**self.settings) return self._client
[ "def", "c", "(", "self", ")", ":", "if", "self", ".", "_client", "is", "None", ":", "self", ".", "_parse_settings", "(", ")", "self", ".", "_client", "=", "Rumetr", "(", "*", "*", "self", ".", "settings", ")", "return", "self", ".", "_client" ]
Caching client for not repeapting checks
[ "Caching", "client", "for", "not", "repeapting", "checks" ]
5180152bcb2eed8246b88035db7c0bb1fe603166
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/scrapy/pipeline.py#L81-L86
248,268
f213/rumetr-client
rumetr/scrapy/pipeline.py
UploadPipeline._parse_settings
def _parse_settings(self): """Gets upload options from the scrapy settings""" if hasattr(self, 'settings'): # parse setting only one time return self.settings = { 'auth_key': self._check_required_setting('RUMETR_TOKEN'), 'developer': self._check_required_setting('RUMETR_DEVELOPER'), } self.settings.update(self._non_required_settings('RUMETR_API_HOST'))
python
def _parse_settings(self): """Gets upload options from the scrapy settings""" if hasattr(self, 'settings'): # parse setting only one time return self.settings = { 'auth_key': self._check_required_setting('RUMETR_TOKEN'), 'developer': self._check_required_setting('RUMETR_DEVELOPER'), } self.settings.update(self._non_required_settings('RUMETR_API_HOST'))
[ "def", "_parse_settings", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'settings'", ")", ":", "# parse setting only one time", "return", "self", ".", "settings", "=", "{", "'auth_key'", ":", "self", ".", "_check_required_setting", "(", "'RUMETR_TOKEN'", ")", ",", "'developer'", ":", "self", ".", "_check_required_setting", "(", "'RUMETR_DEVELOPER'", ")", ",", "}", "self", ".", "settings", ".", "update", "(", "self", ".", "_non_required_settings", "(", "'RUMETR_API_HOST'", ")", ")" ]
Gets upload options from the scrapy settings
[ "Gets", "upload", "options", "from", "the", "scrapy", "settings" ]
5180152bcb2eed8246b88035db7c0bb1fe603166
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/scrapy/pipeline.py#L88-L97
248,269
f213/rumetr-client
rumetr/scrapy/pipeline.py
UploadPipeline._parse_deadline
def _parse_deadline(deadline): """Translate deadline date from human-acceptable format to the machine-acceptable""" if '-' in deadline and len(deadline) == 10: return deadline if '.' in deadline and len(deadline) == 10: # russian format dd.mm.yyyy to yyyy-mm-dd dmy = deadline.split('.') if len(dmy) == 3 and all(v is not None for v in dmy): return '-'.join(reversed(dmy)) raise exceptions.RumetrUnparsableDeadline()
python
def _parse_deadline(deadline): """Translate deadline date from human-acceptable format to the machine-acceptable""" if '-' in deadline and len(deadline) == 10: return deadline if '.' in deadline and len(deadline) == 10: # russian format dd.mm.yyyy to yyyy-mm-dd dmy = deadline.split('.') if len(dmy) == 3 and all(v is not None for v in dmy): return '-'.join(reversed(dmy)) raise exceptions.RumetrUnparsableDeadline()
[ "def", "_parse_deadline", "(", "deadline", ")", ":", "if", "'-'", "in", "deadline", "and", "len", "(", "deadline", ")", "==", "10", ":", "return", "deadline", "if", "'.'", "in", "deadline", "and", "len", "(", "deadline", ")", "==", "10", ":", "# russian format dd.mm.yyyy to yyyy-mm-dd", "dmy", "=", "deadline", ".", "split", "(", "'.'", ")", "if", "len", "(", "dmy", ")", "==", "3", "and", "all", "(", "v", "is", "not", "None", "for", "v", "in", "dmy", ")", ":", "return", "'-'", ".", "join", "(", "reversed", "(", "dmy", ")", ")", "raise", "exceptions", ".", "RumetrUnparsableDeadline", "(", ")" ]
Translate deadline date from human-acceptable format to the machine-acceptable
[ "Translate", "deadline", "date", "from", "human", "-", "acceptable", "format", "to", "the", "machine", "-", "acceptable" ]
5180152bcb2eed8246b88035db7c0bb1fe603166
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/scrapy/pipeline.py#L109-L119
248,270
tylerbutler/propane
propane/paths.py
has_files
def has_files(the_path): """Given a path, returns whether the path has any files in it or any subfolders. Works recursively.""" the_path = Path(the_path) try: for _ in the_path.walkfiles(): return True return False except OSError as ex: if ex.errno == errno.ENOENT: # ignore return False else: raise
python
def has_files(the_path): """Given a path, returns whether the path has any files in it or any subfolders. Works recursively.""" the_path = Path(the_path) try: for _ in the_path.walkfiles(): return True return False except OSError as ex: if ex.errno == errno.ENOENT: # ignore return False else: raise
[ "def", "has_files", "(", "the_path", ")", ":", "the_path", "=", "Path", "(", "the_path", ")", "try", ":", "for", "_", "in", "the_path", ".", "walkfiles", "(", ")", ":", "return", "True", "return", "False", "except", "OSError", "as", "ex", ":", "if", "ex", ".", "errno", "==", "errno", ".", "ENOENT", ":", "# ignore", "return", "False", "else", ":", "raise" ]
Given a path, returns whether the path has any files in it or any subfolders. Works recursively.
[ "Given", "a", "path", "returns", "whether", "the", "path", "has", "any", "files", "in", "it", "or", "any", "subfolders", ".", "Works", "recursively", "." ]
6c404285ab8d78865b7175a5c8adf8fae12d6be5
https://github.com/tylerbutler/propane/blob/6c404285ab8d78865b7175a5c8adf8fae12d6be5/propane/paths.py#L88-L100
248,271
hapylestat/apputils
apputils/settings/ast/cmd.py
DefaultTokenizer.tokenize
def tokenize(cls, obj): """ Convert input data to tokens :type obj list|set|tuple """ tokens = {} try: token_iterator = cls.make_iterable(obj) _lang = cls.language_definition() tokens = {k: [] for k in _lang.argument_types} prev, current = None, next(token_iterator) while True: token = [None, None] arg_type = None for arg_type in _lang.argument_types: arg_start_seq = _lang.argument_types[arg_type] arg_delimiters = _lang.value_delimiters[arg_type] if prev is None and arg_start_seq is None: # just start to scan and got "default" token token[1] = current break elif arg_start_seq is None and prev[0] is None: # next default token token[1] = current break elif arg_start_seq is None and prev[0] is not None: # default token used after non-default tokens token[1] = current break elif arg_start_seq is None: # value of non-default token prev[1] = current token = None break elif current[:len(arg_start_seq)] == arg_start_seq: token[0] = current[len(arg_start_seq):] for delimiter in arg_delimiters: if delimiter == " ": continue if delimiter in token[0]: _delim = str(token[0]).partition(delimiter) token = [_delim[0], _delim[2]] break break if token: tokens[arg_type].append(token) prev, current = token, next(token_iterator) except StopIteration: return tokens
python
def tokenize(cls, obj): """ Convert input data to tokens :type obj list|set|tuple """ tokens = {} try: token_iterator = cls.make_iterable(obj) _lang = cls.language_definition() tokens = {k: [] for k in _lang.argument_types} prev, current = None, next(token_iterator) while True: token = [None, None] arg_type = None for arg_type in _lang.argument_types: arg_start_seq = _lang.argument_types[arg_type] arg_delimiters = _lang.value_delimiters[arg_type] if prev is None and arg_start_seq is None: # just start to scan and got "default" token token[1] = current break elif arg_start_seq is None and prev[0] is None: # next default token token[1] = current break elif arg_start_seq is None and prev[0] is not None: # default token used after non-default tokens token[1] = current break elif arg_start_seq is None: # value of non-default token prev[1] = current token = None break elif current[:len(arg_start_seq)] == arg_start_seq: token[0] = current[len(arg_start_seq):] for delimiter in arg_delimiters: if delimiter == " ": continue if delimiter in token[0]: _delim = str(token[0]).partition(delimiter) token = [_delim[0], _delim[2]] break break if token: tokens[arg_type].append(token) prev, current = token, next(token_iterator) except StopIteration: return tokens
[ "def", "tokenize", "(", "cls", ",", "obj", ")", ":", "tokens", "=", "{", "}", "try", ":", "token_iterator", "=", "cls", ".", "make_iterable", "(", "obj", ")", "_lang", "=", "cls", ".", "language_definition", "(", ")", "tokens", "=", "{", "k", ":", "[", "]", "for", "k", "in", "_lang", ".", "argument_types", "}", "prev", ",", "current", "=", "None", ",", "next", "(", "token_iterator", ")", "while", "True", ":", "token", "=", "[", "None", ",", "None", "]", "arg_type", "=", "None", "for", "arg_type", "in", "_lang", ".", "argument_types", ":", "arg_start_seq", "=", "_lang", ".", "argument_types", "[", "arg_type", "]", "arg_delimiters", "=", "_lang", ".", "value_delimiters", "[", "arg_type", "]", "if", "prev", "is", "None", "and", "arg_start_seq", "is", "None", ":", "# just start to scan and got \"default\" token", "token", "[", "1", "]", "=", "current", "break", "elif", "arg_start_seq", "is", "None", "and", "prev", "[", "0", "]", "is", "None", ":", "# next default token", "token", "[", "1", "]", "=", "current", "break", "elif", "arg_start_seq", "is", "None", "and", "prev", "[", "0", "]", "is", "not", "None", ":", "# default token used after non-default tokens", "token", "[", "1", "]", "=", "current", "break", "elif", "arg_start_seq", "is", "None", ":", "# value of non-default token", "prev", "[", "1", "]", "=", "current", "token", "=", "None", "break", "elif", "current", "[", ":", "len", "(", "arg_start_seq", ")", "]", "==", "arg_start_seq", ":", "token", "[", "0", "]", "=", "current", "[", "len", "(", "arg_start_seq", ")", ":", "]", "for", "delimiter", "in", "arg_delimiters", ":", "if", "delimiter", "==", "\" \"", ":", "continue", "if", "delimiter", "in", "token", "[", "0", "]", ":", "_delim", "=", "str", "(", "token", "[", "0", "]", ")", ".", "partition", "(", "delimiter", ")", "token", "=", "[", "_delim", "[", "0", "]", ",", "_delim", "[", "2", "]", "]", "break", "break", "if", "token", ":", "tokens", "[", "arg_type", "]", ".", "append", "(", "token", ")", "prev", ",", "current", "=", "token", ",", "next", "(", "token_iterator", ")", "except", "StopIteration", ":", "return", "tokens" ]
Convert input data to tokens :type obj list|set|tuple
[ "Convert", "input", "data", "to", "tokens" ]
5d185616feda27e6e21273307161471ef11a3518
https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/settings/ast/cmd.py#L66-L120
248,272
hapylestat/apputils
apputils/settings/ast/cmd.py
CommandLineAST.parse
def parse(self, argv, tokenizer=DefaultTokenizer): """ Parse command line to out tree :type argv object :type tokenizer AbstractTokenizer """ args = tokenizer.tokenize(argv) _lang = tokenizer.language_definition() # # for param in self.__args: # if self._is_default_arg(param): # self.__out_tree[self.__default_arg_tag].append(param.strip()) # else: # param = param.lstrip("-").partition('=') # if len(param) == 3: # self.__parse_one_param(param) pass
python
def parse(self, argv, tokenizer=DefaultTokenizer): """ Parse command line to out tree :type argv object :type tokenizer AbstractTokenizer """ args = tokenizer.tokenize(argv) _lang = tokenizer.language_definition() # # for param in self.__args: # if self._is_default_arg(param): # self.__out_tree[self.__default_arg_tag].append(param.strip()) # else: # param = param.lstrip("-").partition('=') # if len(param) == 3: # self.__parse_one_param(param) pass
[ "def", "parse", "(", "self", ",", "argv", ",", "tokenizer", "=", "DefaultTokenizer", ")", ":", "args", "=", "tokenizer", ".", "tokenize", "(", "argv", ")", "_lang", "=", "tokenizer", ".", "language_definition", "(", ")", "#", "# for param in self.__args:", "# if self._is_default_arg(param):", "# self.__out_tree[self.__default_arg_tag].append(param.strip())", "# else:", "# param = param.lstrip(\"-\").partition('=')", "# if len(param) == 3:", "# self.__parse_one_param(param)", "pass" ]
Parse command line to out tree :type argv object :type tokenizer AbstractTokenizer
[ "Parse", "command", "line", "to", "out", "tree" ]
5d185616feda27e6e21273307161471ef11a3518
https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/settings/ast/cmd.py#L142-L160
248,273
kervi/kervi-core
kervi/actions/__init__.py
action
def action(method=None, **kwargs): """ Decorator that turns a function or controller method into an kervi action. it is possible to call the action in other kervi processes or modules. @action def my_action(p) ... call it via Actions["my_action"](10) @action(action_id="action_1", name="This is my action") def my_action(p) ... call it via Actions["action_1"](10) :Keyword Arguments: * *action_id* (``str``) -- The action_id is the id you use when you call the action. By default the action takes the name of function but you can override it with action_id. * *name* (``str``) -- Name to show in UI if the action is linked to a panel. """ def action_wrap(f): action_id = kwargs.get("action_id", f.__name__) name = kwargs.get("name", action_id) if not _is_method(f): # not "." in f.__qualname__: action = Action(f, action_id, name) Actions.add(action) return action else: qual_name = getattr(f, "__qualname__", None) owner_class = kwargs.get("controller_class", None) if owner_class: qual_name = owner_class + "." + f.__name__ if qual_name: Actions.add_unbound(qual_name, action_id, name) setattr(f, "set_interrupt", _SetInterrupt(action_id)) else: print("using upython? if yes you need to pass the name of the controller class via the controller_class parameter.") return f if method: return action_wrap(method) else: return action_wrap
python
def action(method=None, **kwargs): """ Decorator that turns a function or controller method into an kervi action. it is possible to call the action in other kervi processes or modules. @action def my_action(p) ... call it via Actions["my_action"](10) @action(action_id="action_1", name="This is my action") def my_action(p) ... call it via Actions["action_1"](10) :Keyword Arguments: * *action_id* (``str``) -- The action_id is the id you use when you call the action. By default the action takes the name of function but you can override it with action_id. * *name* (``str``) -- Name to show in UI if the action is linked to a panel. """ def action_wrap(f): action_id = kwargs.get("action_id", f.__name__) name = kwargs.get("name", action_id) if not _is_method(f): # not "." in f.__qualname__: action = Action(f, action_id, name) Actions.add(action) return action else: qual_name = getattr(f, "__qualname__", None) owner_class = kwargs.get("controller_class", None) if owner_class: qual_name = owner_class + "." + f.__name__ if qual_name: Actions.add_unbound(qual_name, action_id, name) setattr(f, "set_interrupt", _SetInterrupt(action_id)) else: print("using upython? if yes you need to pass the name of the controller class via the controller_class parameter.") return f if method: return action_wrap(method) else: return action_wrap
[ "def", "action", "(", "method", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "action_wrap", "(", "f", ")", ":", "action_id", "=", "kwargs", ".", "get", "(", "\"action_id\"", ",", "f", ".", "__name__", ")", "name", "=", "kwargs", ".", "get", "(", "\"name\"", ",", "action_id", ")", "if", "not", "_is_method", "(", "f", ")", ":", "# not \".\" in f.__qualname__:", "action", "=", "Action", "(", "f", ",", "action_id", ",", "name", ")", "Actions", ".", "add", "(", "action", ")", "return", "action", "else", ":", "qual_name", "=", "getattr", "(", "f", ",", "\"__qualname__\"", ",", "None", ")", "owner_class", "=", "kwargs", ".", "get", "(", "\"controller_class\"", ",", "None", ")", "if", "owner_class", ":", "qual_name", "=", "owner_class", "+", "\".\"", "+", "f", ".", "__name__", "if", "qual_name", ":", "Actions", ".", "add_unbound", "(", "qual_name", ",", "action_id", ",", "name", ")", "setattr", "(", "f", ",", "\"set_interrupt\"", ",", "_SetInterrupt", "(", "action_id", ")", ")", "else", ":", "print", "(", "\"using upython? if yes you need to pass the name of the controller class via the controller_class parameter.\"", ")", "return", "f", "if", "method", ":", "return", "action_wrap", "(", "method", ")", "else", ":", "return", "action_wrap" ]
Decorator that turns a function or controller method into an kervi action. it is possible to call the action in other kervi processes or modules. @action def my_action(p) ... call it via Actions["my_action"](10) @action(action_id="action_1", name="This is my action") def my_action(p) ... call it via Actions["action_1"](10) :Keyword Arguments: * *action_id* (``str``) -- The action_id is the id you use when you call the action. By default the action takes the name of function but you can override it with action_id. * *name* (``str``) -- Name to show in UI if the action is linked to a panel.
[ "Decorator", "that", "turns", "a", "function", "or", "controller", "method", "into", "an", "kervi", "action", ".", "it", "is", "possible", "to", "call", "the", "action", "in", "other", "kervi", "processes", "or", "modules", "." ]
3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23
https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/actions/__init__.py#L42-L92
248,274
b3j0f/conf
b3j0f/conf/model/base.py
ModelElement.copy
def copy(self, *args, **kwargs): """Copy this model element and contained elements if they exist.""" for slot in self.__slots__: attr = getattr(self, slot) if slot[0] == '_': # convert protected attribute name to public slot = slot[1:] if slot not in kwargs: kwargs[slot] = attr result = type(self)(*args, **kwargs) return result
python
def copy(self, *args, **kwargs): """Copy this model element and contained elements if they exist.""" for slot in self.__slots__: attr = getattr(self, slot) if slot[0] == '_': # convert protected attribute name to public slot = slot[1:] if slot not in kwargs: kwargs[slot] = attr result = type(self)(*args, **kwargs) return result
[ "def", "copy", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "slot", "in", "self", ".", "__slots__", ":", "attr", "=", "getattr", "(", "self", ",", "slot", ")", "if", "slot", "[", "0", "]", "==", "'_'", ":", "# convert protected attribute name to public", "slot", "=", "slot", "[", "1", ":", "]", "if", "slot", "not", "in", "kwargs", ":", "kwargs", "[", "slot", "]", "=", "attr", "result", "=", "type", "(", "self", ")", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "result" ]
Copy this model element and contained elements if they exist.
[ "Copy", "this", "model", "element", "and", "contained", "elements", "if", "they", "exist", "." ]
18dd6d5d6560f9b202793739e2330a2181163511
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/model/base.py#L48-L60
248,275
b3j0f/conf
b3j0f/conf/model/base.py
ModelElement.update
def update(self, other, copy=True, *args, **kwargs): """Update this element related to other element. :param other: same type than this. :param bool copy: copy other before update attributes. :param tuple args: copy args. :param dict kwargs: copy kwargs. :return: this""" if other: # dirty hack for python2.6 if isinstance(other, self.__class__): if copy: other = other.copy(*args, **kwargs) for slot in other.__slots__: attr = getattr(other, slot) if attr is not None: setattr(self, slot, attr) else: raise TypeError( 'Wrong element to update with {0}: {1}'.format(self, other) ) return self
python
def update(self, other, copy=True, *args, **kwargs): """Update this element related to other element. :param other: same type than this. :param bool copy: copy other before update attributes. :param tuple args: copy args. :param dict kwargs: copy kwargs. :return: this""" if other: # dirty hack for python2.6 if isinstance(other, self.__class__): if copy: other = other.copy(*args, **kwargs) for slot in other.__slots__: attr = getattr(other, slot) if attr is not None: setattr(self, slot, attr) else: raise TypeError( 'Wrong element to update with {0}: {1}'.format(self, other) ) return self
[ "def", "update", "(", "self", ",", "other", ",", "copy", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "other", ":", "# dirty hack for python2.6", "if", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "if", "copy", ":", "other", "=", "other", ".", "copy", "(", "*", "args", ",", "*", "*", "kwargs", ")", "for", "slot", "in", "other", ".", "__slots__", ":", "attr", "=", "getattr", "(", "other", ",", "slot", ")", "if", "attr", "is", "not", "None", ":", "setattr", "(", "self", ",", "slot", ",", "attr", ")", "else", ":", "raise", "TypeError", "(", "'Wrong element to update with {0}: {1}'", ".", "format", "(", "self", ",", "other", ")", ")", "return", "self" ]
Update this element related to other element. :param other: same type than this. :param bool copy: copy other before update attributes. :param tuple args: copy args. :param dict kwargs: copy kwargs. :return: this
[ "Update", "this", "element", "related", "to", "other", "element", "." ]
18dd6d5d6560f9b202793739e2330a2181163511
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/model/base.py#L108-L134
248,276
b3j0f/conf
b3j0f/conf/model/base.py
CompositeModelElement.__i
def __i(self, other, func): """Process input other with input func. :param ModelElement(s) other: other ModelElement(s) to process. :param func: function to apply on a ModelElement. :return: self. :raise: TypeError if other is not a ModelElement(s).""" if isinstance(other, type(self)): other = tuple(other) elif isinstance(other, self.__contenttype__): other = (other, ) for melt in list(other): if not isinstance(melt, self.__contenttype__): raise TypeError('Wrong element {0}'.format(melt)) else: func(melt) return self
python
def __i(self, other, func): """Process input other with input func. :param ModelElement(s) other: other ModelElement(s) to process. :param func: function to apply on a ModelElement. :return: self. :raise: TypeError if other is not a ModelElement(s).""" if isinstance(other, type(self)): other = tuple(other) elif isinstance(other, self.__contenttype__): other = (other, ) for melt in list(other): if not isinstance(melt, self.__contenttype__): raise TypeError('Wrong element {0}'.format(melt)) else: func(melt) return self
[ "def", "__i", "(", "self", ",", "other", ",", "func", ")", ":", "if", "isinstance", "(", "other", ",", "type", "(", "self", ")", ")", ":", "other", "=", "tuple", "(", "other", ")", "elif", "isinstance", "(", "other", ",", "self", ".", "__contenttype__", ")", ":", "other", "=", "(", "other", ",", ")", "for", "melt", "in", "list", "(", "other", ")", ":", "if", "not", "isinstance", "(", "melt", ",", "self", ".", "__contenttype__", ")", ":", "raise", "TypeError", "(", "'Wrong element {0}'", ".", "format", "(", "melt", ")", ")", "else", ":", "func", "(", "melt", ")", "return", "self" ]
Process input other with input func. :param ModelElement(s) other: other ModelElement(s) to process. :param func: function to apply on a ModelElement. :return: self. :raise: TypeError if other is not a ModelElement(s).
[ "Process", "input", "other", "with", "input", "func", "." ]
18dd6d5d6560f9b202793739e2330a2181163511
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/model/base.py#L179-L200
248,277
b3j0f/conf
b3j0f/conf/model/base.py
CompositeModelElement.update
def update(self, other, copy=True, *args, **kwargs): """Update this composite model element with other element content. :param other: element to update with this. Must be the same type of this or this __contenttype__. :param bool copy: copy other before updating. :return: self""" super(CompositeModelElement, self).update( other, copy=copy, *args, **kwargs ) if other: # dirty hack for python2.6 contents = [] if isinstance(other, self.__class__): contents = list(other.values()) elif isinstance(other, self.__contenttype__): contents = [other] else: raise TypeError( 'Wrong element to update with {0}: {1}'.format(self, other) ) for content in contents: selfcontent = self.get(content.name) if selfcontent is None: if copy: content = content.copy(local=False) self[content.name] = content else: selfcontent.update(content, copy=copy, *args, **kwargs) return self
python
def update(self, other, copy=True, *args, **kwargs): """Update this composite model element with other element content. :param other: element to update with this. Must be the same type of this or this __contenttype__. :param bool copy: copy other before updating. :return: self""" super(CompositeModelElement, self).update( other, copy=copy, *args, **kwargs ) if other: # dirty hack for python2.6 contents = [] if isinstance(other, self.__class__): contents = list(other.values()) elif isinstance(other, self.__contenttype__): contents = [other] else: raise TypeError( 'Wrong element to update with {0}: {1}'.format(self, other) ) for content in contents: selfcontent = self.get(content.name) if selfcontent is None: if copy: content = content.copy(local=False) self[content.name] = content else: selfcontent.update(content, copy=copy, *args, **kwargs) return self
[ "def", "update", "(", "self", ",", "other", ",", "copy", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "CompositeModelElement", ",", "self", ")", ".", "update", "(", "other", ",", "copy", "=", "copy", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "other", ":", "# dirty hack for python2.6", "contents", "=", "[", "]", "if", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "contents", "=", "list", "(", "other", ".", "values", "(", ")", ")", "elif", "isinstance", "(", "other", ",", "self", ".", "__contenttype__", ")", ":", "contents", "=", "[", "other", "]", "else", ":", "raise", "TypeError", "(", "'Wrong element to update with {0}: {1}'", ".", "format", "(", "self", ",", "other", ")", ")", "for", "content", "in", "contents", ":", "selfcontent", "=", "self", ".", "get", "(", "content", ".", "name", ")", "if", "selfcontent", "is", "None", ":", "if", "copy", ":", "content", "=", "content", ".", "copy", "(", "local", "=", "False", ")", "self", "[", "content", ".", "name", "]", "=", "content", "else", ":", "selfcontent", ".", "update", "(", "content", ",", "copy", "=", "copy", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self" ]
Update this composite model element with other element content. :param other: element to update with this. Must be the same type of this or this __contenttype__. :param bool copy: copy other before updating. :return: self
[ "Update", "this", "composite", "model", "element", "with", "other", "element", "content", "." ]
18dd6d5d6560f9b202793739e2330a2181163511
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/model/base.py#L253-L292
248,278
b3j0f/conf
b3j0f/conf/model/base.py
CompositeModelElement.params
def params(self): """Get set of parameters by names. :rtype: dict""" result = {} for content in list(self.values()): if isinstance(content, CompositeModelElement): cparams = content.params for cpname in cparams: cparam = cparams[cpname] if cpname in result: result[cpname].update(cparam) else: result[cpname] = cparam.copy() elif content.name in result: result[content.name].update(content) else: result[content.name] = content.copy() return result
python
def params(self): """Get set of parameters by names. :rtype: dict""" result = {} for content in list(self.values()): if isinstance(content, CompositeModelElement): cparams = content.params for cpname in cparams: cparam = cparams[cpname] if cpname in result: result[cpname].update(cparam) else: result[cpname] = cparam.copy() elif content.name in result: result[content.name].update(content) else: result[content.name] = content.copy() return result
[ "def", "params", "(", "self", ")", ":", "result", "=", "{", "}", "for", "content", "in", "list", "(", "self", ".", "values", "(", ")", ")", ":", "if", "isinstance", "(", "content", ",", "CompositeModelElement", ")", ":", "cparams", "=", "content", ".", "params", "for", "cpname", "in", "cparams", ":", "cparam", "=", "cparams", "[", "cpname", "]", "if", "cpname", "in", "result", ":", "result", "[", "cpname", "]", ".", "update", "(", "cparam", ")", "else", ":", "result", "[", "cpname", "]", "=", "cparam", ".", "copy", "(", ")", "elif", "content", ".", "name", "in", "result", ":", "result", "[", "content", ".", "name", "]", ".", "update", "(", "content", ")", "else", ":", "result", "[", "content", ".", "name", "]", "=", "content", ".", "copy", "(", ")", "return", "result" ]
Get set of parameters by names. :rtype: dict
[ "Get", "set", "of", "parameters", "by", "names", "." ]
18dd6d5d6560f9b202793739e2330a2181163511
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/model/base.py#L295-L322
248,279
anti1869/sunhead
src/sunhead/decorators.py
cached_property
def cached_property(): """ Handy utility to build caching properties in your classes. Decorated code will be run only once and then result will be stored in private class property with the given name. When called for the second time, property will return cached value. :param storage_var_name: Name of the class property to store cached data. :type storage_var_name: str :return: Decorator for the class property """ def _stored_value(f): storage_var_name = "__{}".format(f.__name__) def _wrapper(self, *args, **kwargs): value_in_cache = getattr(self, storage_var_name, Sentinel) if value_in_cache is not Sentinel: return value_in_cache calculated_value = f(self, *args, **kwargs) setattr(self, storage_var_name, calculated_value) return calculated_value return _wrapper return _stored_value
python
def cached_property(): """ Handy utility to build caching properties in your classes. Decorated code will be run only once and then result will be stored in private class property with the given name. When called for the second time, property will return cached value. :param storage_var_name: Name of the class property to store cached data. :type storage_var_name: str :return: Decorator for the class property """ def _stored_value(f): storage_var_name = "__{}".format(f.__name__) def _wrapper(self, *args, **kwargs): value_in_cache = getattr(self, storage_var_name, Sentinel) if value_in_cache is not Sentinel: return value_in_cache calculated_value = f(self, *args, **kwargs) setattr(self, storage_var_name, calculated_value) return calculated_value return _wrapper return _stored_value
[ "def", "cached_property", "(", ")", ":", "def", "_stored_value", "(", "f", ")", ":", "storage_var_name", "=", "\"__{}\"", ".", "format", "(", "f", ".", "__name__", ")", "def", "_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "value_in_cache", "=", "getattr", "(", "self", ",", "storage_var_name", ",", "Sentinel", ")", "if", "value_in_cache", "is", "not", "Sentinel", ":", "return", "value_in_cache", "calculated_value", "=", "f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "setattr", "(", "self", ",", "storage_var_name", ",", "calculated_value", ")", "return", "calculated_value", "return", "_wrapper", "return", "_stored_value" ]
Handy utility to build caching properties in your classes. Decorated code will be run only once and then result will be stored in private class property with the given name. When called for the second time, property will return cached value. :param storage_var_name: Name of the class property to store cached data. :type storage_var_name: str :return: Decorator for the class property
[ "Handy", "utility", "to", "build", "caching", "properties", "in", "your", "classes", ".", "Decorated", "code", "will", "be", "run", "only", "once", "and", "then", "result", "will", "be", "stored", "in", "private", "class", "property", "with", "the", "given", "name", ".", "When", "called", "for", "the", "second", "time", "property", "will", "return", "cached", "value", "." ]
5117ec797a38eb82d955241d20547d125efe80f3
https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/decorators.py#L18-L40
248,280
anti1869/sunhead
src/sunhead/decorators.py
deprecated
def deprecated(message=DEPRECATION_MESSAGE, logger=None): """ This decorator will simply print warning before running decoratee. So, presumably, you want to use it with console-based commands. :return: Decorator for the function. """ if logger is None: logger = default_logger def _deprecated(f): def _wrapper(*args, **kwargs): f_name = f.__name__ logger.warning(message.format(name=f_name)) result = f(*args, **kwargs) return result return _wrapper return _deprecated
python
def deprecated(message=DEPRECATION_MESSAGE, logger=None): """ This decorator will simply print warning before running decoratee. So, presumably, you want to use it with console-based commands. :return: Decorator for the function. """ if logger is None: logger = default_logger def _deprecated(f): def _wrapper(*args, **kwargs): f_name = f.__name__ logger.warning(message.format(name=f_name)) result = f(*args, **kwargs) return result return _wrapper return _deprecated
[ "def", "deprecated", "(", "message", "=", "DEPRECATION_MESSAGE", ",", "logger", "=", "None", ")", ":", "if", "logger", "is", "None", ":", "logger", "=", "default_logger", "def", "_deprecated", "(", "f", ")", ":", "def", "_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "f_name", "=", "f", ".", "__name__", "logger", ".", "warning", "(", "message", ".", "format", "(", "name", "=", "f_name", ")", ")", "result", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "result", "return", "_wrapper", "return", "_deprecated" ]
This decorator will simply print warning before running decoratee. So, presumably, you want to use it with console-based commands. :return: Decorator for the function.
[ "This", "decorator", "will", "simply", "print", "warning", "before", "running", "decoratee", ".", "So", "presumably", "you", "want", "to", "use", "it", "with", "console", "-", "based", "commands", "." ]
5117ec797a38eb82d955241d20547d125efe80f3
https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/decorators.py#L43-L59
248,281
AndreLouisCaron/runwith
features/steps/cli.py
write_fixture_file
def write_fixture_file(context, path): """Write fixture to disk.""" print('CWD:', os.getcwd()) print('FIXTURE:', path) with open(path, 'w') as stream: stream.write(context.text)
python
def write_fixture_file(context, path): """Write fixture to disk.""" print('CWD:', os.getcwd()) print('FIXTURE:', path) with open(path, 'w') as stream: stream.write(context.text)
[ "def", "write_fixture_file", "(", "context", ",", "path", ")", ":", "print", "(", "'CWD:'", ",", "os", ".", "getcwd", "(", ")", ")", "print", "(", "'FIXTURE:'", ",", "path", ")", "with", "open", "(", "path", ",", "'w'", ")", "as", "stream", ":", "stream", ".", "write", "(", "context", ".", "text", ")" ]
Write fixture to disk.
[ "Write", "fixture", "to", "disk", "." ]
cfa2b6ae67d73ec5b24f1502a37060d838276e8b
https://github.com/AndreLouisCaron/runwith/blob/cfa2b6ae67d73ec5b24f1502a37060d838276e8b/features/steps/cli.py#L140-L146
248,282
fred49/argtoolbox
argtoolbox/argtoolbox.py
Config.add_section
def add_section(self, section): """Add a new Section object to the config. Should be a subclass of _AbstractSection.""" if not issubclass(section.__class__, _AbstractSection): raise TypeError("argument should be a subclass of Section") self.sections[section.get_key_name()] = section return section
python
def add_section(self, section): """Add a new Section object to the config. Should be a subclass of _AbstractSection.""" if not issubclass(section.__class__, _AbstractSection): raise TypeError("argument should be a subclass of Section") self.sections[section.get_key_name()] = section return section
[ "def", "add_section", "(", "self", ",", "section", ")", ":", "if", "not", "issubclass", "(", "section", ".", "__class__", ",", "_AbstractSection", ")", ":", "raise", "TypeError", "(", "\"argument should be a subclass of Section\"", ")", "self", ".", "sections", "[", "section", ".", "get_key_name", "(", ")", "]", "=", "section", "return", "section" ]
Add a new Section object to the config. Should be a subclass of _AbstractSection.
[ "Add", "a", "new", "Section", "object", "to", "the", "config", ".", "Should", "be", "a", "subclass", "of", "_AbstractSection", "." ]
e32ad6265567d5a1891df3c3425423774dafab41
https://github.com/fred49/argtoolbox/blob/e32ad6265567d5a1891df3c3425423774dafab41/argtoolbox/argtoolbox.py#L160-L166
248,283
fred49/argtoolbox
argtoolbox/argtoolbox.py
Config.get_parser
def get_parser(self, **kwargs): """This method will create and return a new parser with prog_name, description, and a config file argument. """ self.parser = argparse.ArgumentParser(prog=self.prog_name, description=self._desc, add_help=False, **kwargs) # help is removed because parser.parse_known_args() show help, # often partial help. help action will be added during # reloading step for parser.parse_args() if self.use_config_file: self.parser.add_argument('--config-file', action="store", help="Other configuration file.") return self.parser
python
def get_parser(self, **kwargs): """This method will create and return a new parser with prog_name, description, and a config file argument. """ self.parser = argparse.ArgumentParser(prog=self.prog_name, description=self._desc, add_help=False, **kwargs) # help is removed because parser.parse_known_args() show help, # often partial help. help action will be added during # reloading step for parser.parse_args() if self.use_config_file: self.parser.add_argument('--config-file', action="store", help="Other configuration file.") return self.parser
[ "def", "get_parser", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "self", ".", "prog_name", ",", "description", "=", "self", ".", "_desc", ",", "add_help", "=", "False", ",", "*", "*", "kwargs", ")", "# help is removed because parser.parse_known_args() show help,", "# often partial help. help action will be added during", "# reloading step for parser.parse_args()", "if", "self", ".", "use_config_file", ":", "self", ".", "parser", ".", "add_argument", "(", "'--config-file'", ",", "action", "=", "\"store\"", ",", "help", "=", "\"Other configuration file.\"", ")", "return", "self", ".", "parser" ]
This method will create and return a new parser with prog_name, description, and a config file argument.
[ "This", "method", "will", "create", "and", "return", "a", "new", "parser", "with", "prog_name", "description", "and", "a", "config", "file", "argument", "." ]
e32ad6265567d5a1891df3c3425423774dafab41
https://github.com/fred49/argtoolbox/blob/e32ad6265567d5a1891df3c3425423774dafab41/argtoolbox/argtoolbox.py#L228-L242
248,284
fred49/argtoolbox
argtoolbox/argtoolbox.py
Config.reload
def reload(self, hooks=None): """This method will reload the configuration using input argument from the command line interface. 1. pasing arguments 2. applying hooks 3. addding help argument 4. reloading configuration using cli argument like a configuration file name. """ #from argcomplete import debug # Parsing the command line looking for the previous options like # configuration file name or server section. Extra arguments # will be store into argv. args = None if os.environ.get('_ARGCOMPLETE'): # During argcomplete completion, parse_known_args will return an # empty Namespace. In this case, we feed the previous function with # data comming from the input completion data compline = os.environ.get('COMP_LINE') args = self.parser.parse_known_args(compline.split()[1:])[0] else: args = self.parser.parse_known_args()[0] if hooks is not None: if isinstance(hooks, list): for h in hooks: if isinstance(h, SectionHook): h(args) else: if isinstance(hooks, SectionHook): hooks(args) # After the first argument parsing, for configuration reloading, # we can add the help action. self.parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS, help='show this help message and exit') # Reloading if self.use_config_file: # pylint: disable-msg=W0621 log = logging.getLogger('argtoolbox') log.debug("reloading configuration ...") if args.config_file: self.file_parser = ConfigParser.SafeConfigParser() discoveredFileList = self.file_parser.read(args.config_file) log.debug("discoveredFileList: " + str(discoveredFileList)) for s in self.sections.values(): log.debug("loading section : " + s.get_section_name()) s.reset() s.load(self.file_parser) log.debug("configuration reloaded.")
python
def reload(self, hooks=None): """This method will reload the configuration using input argument from the command line interface. 1. pasing arguments 2. applying hooks 3. addding help argument 4. reloading configuration using cli argument like a configuration file name. """ #from argcomplete import debug # Parsing the command line looking for the previous options like # configuration file name or server section. Extra arguments # will be store into argv. args = None if os.environ.get('_ARGCOMPLETE'): # During argcomplete completion, parse_known_args will return an # empty Namespace. In this case, we feed the previous function with # data comming from the input completion data compline = os.environ.get('COMP_LINE') args = self.parser.parse_known_args(compline.split()[1:])[0] else: args = self.parser.parse_known_args()[0] if hooks is not None: if isinstance(hooks, list): for h in hooks: if isinstance(h, SectionHook): h(args) else: if isinstance(hooks, SectionHook): hooks(args) # After the first argument parsing, for configuration reloading, # we can add the help action. self.parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS, help='show this help message and exit') # Reloading if self.use_config_file: # pylint: disable-msg=W0621 log = logging.getLogger('argtoolbox') log.debug("reloading configuration ...") if args.config_file: self.file_parser = ConfigParser.SafeConfigParser() discoveredFileList = self.file_parser.read(args.config_file) log.debug("discoveredFileList: " + str(discoveredFileList)) for s in self.sections.values(): log.debug("loading section : " + s.get_section_name()) s.reset() s.load(self.file_parser) log.debug("configuration reloaded.")
[ "def", "reload", "(", "self", ",", "hooks", "=", "None", ")", ":", "#from argcomplete import debug", "# Parsing the command line looking for the previous options like", "# configuration file name or server section. Extra arguments", "# will be store into argv.", "args", "=", "None", "if", "os", ".", "environ", ".", "get", "(", "'_ARGCOMPLETE'", ")", ":", "# During argcomplete completion, parse_known_args will return an", "# empty Namespace. In this case, we feed the previous function with", "# data comming from the input completion data", "compline", "=", "os", ".", "environ", ".", "get", "(", "'COMP_LINE'", ")", "args", "=", "self", ".", "parser", ".", "parse_known_args", "(", "compline", ".", "split", "(", ")", "[", "1", ":", "]", ")", "[", "0", "]", "else", ":", "args", "=", "self", ".", "parser", ".", "parse_known_args", "(", ")", "[", "0", "]", "if", "hooks", "is", "not", "None", ":", "if", "isinstance", "(", "hooks", ",", "list", ")", ":", "for", "h", "in", "hooks", ":", "if", "isinstance", "(", "h", ",", "SectionHook", ")", ":", "h", "(", "args", ")", "else", ":", "if", "isinstance", "(", "hooks", ",", "SectionHook", ")", ":", "hooks", "(", "args", ")", "# After the first argument parsing, for configuration reloading,", "# we can add the help action.", "self", ".", "parser", ".", "add_argument", "(", "'-h'", ",", "'--help'", ",", "action", "=", "'help'", ",", "default", "=", "argparse", ".", "SUPPRESS", ",", "help", "=", "'show this help message and exit'", ")", "# Reloading", "if", "self", ".", "use_config_file", ":", "# pylint: disable-msg=W0621", "log", "=", "logging", ".", "getLogger", "(", "'argtoolbox'", ")", "log", ".", "debug", "(", "\"reloading configuration ...\"", ")", "if", "args", ".", "config_file", ":", "self", ".", "file_parser", "=", "ConfigParser", ".", "SafeConfigParser", "(", ")", "discoveredFileList", "=", "self", ".", "file_parser", ".", "read", "(", "args", ".", "config_file", ")", "log", ".", "debug", "(", "\"discoveredFileList: \"", "+", "str", "(", "discoveredFileList", ")", ")", "for", "s", "in", "self", ".", "sections", ".", "values", "(", ")", ":", "log", ".", "debug", "(", "\"loading section : \"", "+", "s", ".", "get_section_name", "(", ")", ")", "s", ".", "reset", "(", ")", "s", ".", "load", "(", "self", ".", "file_parser", ")", "log", ".", "debug", "(", "\"configuration reloaded.\"", ")" ]
This method will reload the configuration using input argument from the command line interface. 1. pasing arguments 2. applying hooks 3. addding help argument 4. reloading configuration using cli argument like a configuration file name.
[ "This", "method", "will", "reload", "the", "configuration", "using", "input", "argument", "from", "the", "command", "line", "interface", ".", "1", ".", "pasing", "arguments", "2", ".", "applying", "hooks", "3", ".", "addding", "help", "argument", "4", ".", "reloading", "configuration", "using", "cli", "argument", "like", "a", "configuration", "file", "name", "." ]
e32ad6265567d5a1891df3c3425423774dafab41
https://github.com/fred49/argtoolbox/blob/e32ad6265567d5a1891df3c3425423774dafab41/argtoolbox/argtoolbox.py#L244-L295
248,285
fred49/argtoolbox
argtoolbox/argtoolbox.py
_AbstractSection.get_representation
def get_representation(self, prefix="", suffix="\n"): """return the string representation of the current object.""" res = prefix + "Section " + self.get_section_name().upper() + suffix return res
python
def get_representation(self, prefix="", suffix="\n"): """return the string representation of the current object.""" res = prefix + "Section " + self.get_section_name().upper() + suffix return res
[ "def", "get_representation", "(", "self", ",", "prefix", "=", "\"\"", ",", "suffix", "=", "\"\\n\"", ")", ":", "res", "=", "prefix", "+", "\"Section \"", "+", "self", ".", "get_section_name", "(", ")", ".", "upper", "(", ")", "+", "suffix", "return", "res" ]
return the string representation of the current object.
[ "return", "the", "string", "representation", "of", "the", "current", "object", "." ]
e32ad6265567d5a1891df3c3425423774dafab41
https://github.com/fred49/argtoolbox/blob/e32ad6265567d5a1891df3c3425423774dafab41/argtoolbox/argtoolbox.py#L379-L382
248,286
fred49/argtoolbox
argtoolbox/argtoolbox.py
_Section.add_element
def add_element(self, elt): """Helper to add a element to the current section. The Element name will be used as an identifier.""" if not isinstance(elt, Element): raise TypeError("argument should be a subclass of Element") self.elements[elt.get_name()] = elt return elt
python
def add_element(self, elt): """Helper to add a element to the current section. The Element name will be used as an identifier.""" if not isinstance(elt, Element): raise TypeError("argument should be a subclass of Element") self.elements[elt.get_name()] = elt return elt
[ "def", "add_element", "(", "self", ",", "elt", ")", ":", "if", "not", "isinstance", "(", "elt", ",", "Element", ")", ":", "raise", "TypeError", "(", "\"argument should be a subclass of Element\"", ")", "self", ".", "elements", "[", "elt", ".", "get_name", "(", ")", "]", "=", "elt", "return", "elt" ]
Helper to add a element to the current section. The Element name will be used as an identifier.
[ "Helper", "to", "add", "a", "element", "to", "the", "current", "section", ".", "The", "Element", "name", "will", "be", "used", "as", "an", "identifier", "." ]
e32ad6265567d5a1891df3c3425423774dafab41
https://github.com/fred49/argtoolbox/blob/e32ad6265567d5a1891df3c3425423774dafab41/argtoolbox/argtoolbox.py#L414-L420
248,287
fred49/argtoolbox
argtoolbox/argtoolbox.py
_Section.add_element_list
def add_element_list(self, elt_list, **kwargs): """Helper to add a list of similar elements to the current section. Element names will be used as an identifier.""" for e in elt_list: self.add_element(Element(e, **kwargs))
python
def add_element_list(self, elt_list, **kwargs): """Helper to add a list of similar elements to the current section. Element names will be used as an identifier.""" for e in elt_list: self.add_element(Element(e, **kwargs))
[ "def", "add_element_list", "(", "self", ",", "elt_list", ",", "*", "*", "kwargs", ")", ":", "for", "e", "in", "elt_list", ":", "self", ".", "add_element", "(", "Element", "(", "e", ",", "*", "*", "kwargs", ")", ")" ]
Helper to add a list of similar elements to the current section. Element names will be used as an identifier.
[ "Helper", "to", "add", "a", "list", "of", "similar", "elements", "to", "the", "current", "section", ".", "Element", "names", "will", "be", "used", "as", "an", "identifier", "." ]
e32ad6265567d5a1891df3c3425423774dafab41
https://github.com/fred49/argtoolbox/blob/e32ad6265567d5a1891df3c3425423774dafab41/argtoolbox/argtoolbox.py#L422-L426
248,288
fred49/argtoolbox
argtoolbox/argtoolbox.py
Element.get_representation
def get_representation(self, prefix="", suffix="\n"): """This method build a array that will contain the string representation of the current object. Every lines could be prefixed and suffixed. """ res = [] if self.hidden: res.append(prefix + " - " + str(self._name) + " : xxxxxxxx" + suffix) else: default = self.default if default is None: default = " - " a = prefix + " - " a += str(self._name) + " : " if isinstance(default, types.UnicodeType): a += default else: a += str(default) a += suffix res.append(a) return res
python
def get_representation(self, prefix="", suffix="\n"): """This method build a array that will contain the string representation of the current object. Every lines could be prefixed and suffixed. """ res = [] if self.hidden: res.append(prefix + " - " + str(self._name) + " : xxxxxxxx" + suffix) else: default = self.default if default is None: default = " - " a = prefix + " - " a += str(self._name) + " : " if isinstance(default, types.UnicodeType): a += default else: a += str(default) a += suffix res.append(a) return res
[ "def", "get_representation", "(", "self", ",", "prefix", "=", "\"\"", ",", "suffix", "=", "\"\\n\"", ")", ":", "res", "=", "[", "]", "if", "self", ".", "hidden", ":", "res", ".", "append", "(", "prefix", "+", "\" - \"", "+", "str", "(", "self", ".", "_name", ")", "+", "\" : xxxxxxxx\"", "+", "suffix", ")", "else", ":", "default", "=", "self", ".", "default", "if", "default", "is", "None", ":", "default", "=", "\" - \"", "a", "=", "prefix", "+", "\" - \"", "a", "+=", "str", "(", "self", ".", "_name", ")", "+", "\" : \"", "if", "isinstance", "(", "default", ",", "types", ".", "UnicodeType", ")", ":", "a", "+=", "default", "else", ":", "a", "+=", "str", "(", "default", ")", "a", "+=", "suffix", "res", ".", "append", "(", "a", ")", "return", "res" ]
This method build a array that will contain the string representation of the current object. Every lines could be prefixed and suffixed.
[ "This", "method", "build", "a", "array", "that", "will", "contain", "the", "string", "representation", "of", "the", "current", "object", ".", "Every", "lines", "could", "be", "prefixed", "and", "suffixed", "." ]
e32ad6265567d5a1891df3c3425423774dafab41
https://github.com/fred49/argtoolbox/blob/e32ad6265567d5a1891df3c3425423774dafab41/argtoolbox/argtoolbox.py#L658-L679
248,289
fred49/argtoolbox
argtoolbox/argtoolbox.py
Element.load
def load(self, file_parser, section_name): """The current element is loaded from the configuration file, all constraints and requirements are checked. Then element hooks are applied. """ self._load(file_parser, section_name) self.post_load()
python
def load(self, file_parser, section_name): """The current element is loaded from the configuration file, all constraints and requirements are checked. Then element hooks are applied. """ self._load(file_parser, section_name) self.post_load()
[ "def", "load", "(", "self", ",", "file_parser", ",", "section_name", ")", ":", "self", ".", "_load", "(", "file_parser", ",", "section_name", ")", "self", ".", "post_load", "(", ")" ]
The current element is loaded from the configuration file, all constraints and requirements are checked. Then element hooks are applied.
[ "The", "current", "element", "is", "loaded", "from", "the", "configuration", "file", "all", "constraints", "and", "requirements", "are", "checked", ".", "Then", "element", "hooks", "are", "applied", "." ]
e32ad6265567d5a1891df3c3425423774dafab41
https://github.com/fred49/argtoolbox/blob/e32ad6265567d5a1891df3c3425423774dafab41/argtoolbox/argtoolbox.py#L697-L703
248,290
fred49/argtoolbox
argtoolbox/argtoolbox.py
Element.get_arg_parse_arguments
def get_arg_parse_arguments(self): """ During the element declaration, all configuration file requirements and all cli requirements have been described once. This method will build a dict containing all argparse options. It can be used to feed argparse.ArgumentParser. You does not need to have multiple declarations. """ ret = dict() if self._required: if self.value is not None: ret["default"] = self.value else: ret["required"] = True ret["dest"] = self._name if not self.e_type_exclude: if self.e_type == int or self.e_type == float: # Just override argparse.add_argument 'type' parameter for int or float. ret["type"] = self.e_type if self.value is not None: ret["default"] = self.value if self._desc: ret["help"] = self._desc return ret
python
def get_arg_parse_arguments(self): """ During the element declaration, all configuration file requirements and all cli requirements have been described once. This method will build a dict containing all argparse options. It can be used to feed argparse.ArgumentParser. You does not need to have multiple declarations. """ ret = dict() if self._required: if self.value is not None: ret["default"] = self.value else: ret["required"] = True ret["dest"] = self._name if not self.e_type_exclude: if self.e_type == int or self.e_type == float: # Just override argparse.add_argument 'type' parameter for int or float. ret["type"] = self.e_type if self.value is not None: ret["default"] = self.value if self._desc: ret["help"] = self._desc return ret
[ "def", "get_arg_parse_arguments", "(", "self", ")", ":", "ret", "=", "dict", "(", ")", "if", "self", ".", "_required", ":", "if", "self", ".", "value", "is", "not", "None", ":", "ret", "[", "\"default\"", "]", "=", "self", ".", "value", "else", ":", "ret", "[", "\"required\"", "]", "=", "True", "ret", "[", "\"dest\"", "]", "=", "self", ".", "_name", "if", "not", "self", ".", "e_type_exclude", ":", "if", "self", ".", "e_type", "==", "int", "or", "self", ".", "e_type", "==", "float", ":", "# Just override argparse.add_argument 'type' parameter for int or float.", "ret", "[", "\"type\"", "]", "=", "self", ".", "e_type", "if", "self", ".", "value", "is", "not", "None", ":", "ret", "[", "\"default\"", "]", "=", "self", ".", "value", "if", "self", ".", "_desc", ":", "ret", "[", "\"help\"", "]", "=", "self", ".", "_desc", "return", "ret" ]
During the element declaration, all configuration file requirements and all cli requirements have been described once. This method will build a dict containing all argparse options. It can be used to feed argparse.ArgumentParser. You does not need to have multiple declarations.
[ "During", "the", "element", "declaration", "all", "configuration", "file", "requirements", "and", "all", "cli", "requirements", "have", "been", "described", "once", ".", "This", "method", "will", "build", "a", "dict", "containing", "all", "argparse", "options", ".", "It", "can", "be", "used", "to", "feed", "argparse", ".", "ArgumentParser", ".", "You", "does", "not", "need", "to", "have", "multiple", "declarations", "." ]
e32ad6265567d5a1891df3c3425423774dafab41
https://github.com/fred49/argtoolbox/blob/e32ad6265567d5a1891df3c3425423774dafab41/argtoolbox/argtoolbox.py#L789-L813
248,291
fred49/argtoolbox
argtoolbox/argtoolbox.py
ElementWithSubSections.add_section
def add_section(self, section): """You can add section inside a Element, the section must be a subclass of SubSection. You can use this class to represent a tree. """ if not issubclass(section.__class__, SubSection): raise TypeError("Argument should be a subclass of SubSection, \ not :" + str(section.__class__)) self.sections[section.name] = section return section
python
def add_section(self, section): """You can add section inside a Element, the section must be a subclass of SubSection. You can use this class to represent a tree. """ if not issubclass(section.__class__, SubSection): raise TypeError("Argument should be a subclass of SubSection, \ not :" + str(section.__class__)) self.sections[section.name] = section return section
[ "def", "add_section", "(", "self", ",", "section", ")", ":", "if", "not", "issubclass", "(", "section", ".", "__class__", ",", "SubSection", ")", ":", "raise", "TypeError", "(", "\"Argument should be a subclass of SubSection, \\\n not :\"", "+", "str", "(", "section", ".", "__class__", ")", ")", "self", ".", "sections", "[", "section", ".", "name", "]", "=", "section", "return", "section" ]
You can add section inside a Element, the section must be a subclass of SubSection. You can use this class to represent a tree.
[ "You", "can", "add", "section", "inside", "a", "Element", "the", "section", "must", "be", "a", "subclass", "of", "SubSection", ".", "You", "can", "use", "this", "class", "to", "represent", "a", "tree", "." ]
e32ad6265567d5a1891df3c3425423774dafab41
https://github.com/fred49/argtoolbox/blob/e32ad6265567d5a1891df3c3425423774dafab41/argtoolbox/argtoolbox.py#L881-L890
248,292
fred49/argtoolbox
argtoolbox/argtoolbox.py
BasicProgram.add_commands
def add_commands(self): """ You can override this method in order to add your command line arguments to the argparse parser. The configuration file was reloaded at this time.""" self.parser.add_argument( '-d', action="count", **self.config.default.debug.get_arg_parse_arguments())
python
def add_commands(self): """ You can override this method in order to add your command line arguments to the argparse parser. The configuration file was reloaded at this time.""" self.parser.add_argument( '-d', action="count", **self.config.default.debug.get_arg_parse_arguments())
[ "def", "add_commands", "(", "self", ")", ":", "self", ".", "parser", ".", "add_argument", "(", "'-d'", ",", "action", "=", "\"count\"", ",", "*", "*", "self", ".", "config", ".", "default", ".", "debug", ".", "get_arg_parse_arguments", "(", ")", ")" ]
You can override this method in order to add your command line arguments to the argparse parser. The configuration file was reloaded at this time.
[ "You", "can", "override", "this", "method", "in", "order", "to", "add", "your", "command", "line", "arguments", "to", "the", "argparse", "parser", ".", "The", "configuration", "file", "was", "reloaded", "at", "this", "time", "." ]
e32ad6265567d5a1891df3c3425423774dafab41
https://github.com/fred49/argtoolbox/blob/e32ad6265567d5a1891df3c3425423774dafab41/argtoolbox/argtoolbox.py#L1283-L1290
248,293
henrysher/kotocore
kotocore/introspection.py
Introspection.strip_html
def strip_html(self, doc): """ This method removes all HTML from a docstring. Lighter than ``convert_docs``, this is intended for the documentation on **parameters**, not the overall docs themselves. :param doc: The initial docstring :type doc: string :returns: The stripped/cleaned docstring :rtype: string """ if not isinstance(doc, six.string_types): return '' doc = doc.strip() doc = self.tag_re.sub('', doc) return doc
python
def strip_html(self, doc): """ This method removes all HTML from a docstring. Lighter than ``convert_docs``, this is intended for the documentation on **parameters**, not the overall docs themselves. :param doc: The initial docstring :type doc: string :returns: The stripped/cleaned docstring :rtype: string """ if not isinstance(doc, six.string_types): return '' doc = doc.strip() doc = self.tag_re.sub('', doc) return doc
[ "def", "strip_html", "(", "self", ",", "doc", ")", ":", "if", "not", "isinstance", "(", "doc", ",", "six", ".", "string_types", ")", ":", "return", "''", "doc", "=", "doc", ".", "strip", "(", ")", "doc", "=", "self", ".", "tag_re", ".", "sub", "(", "''", ",", "doc", ")", "return", "doc" ]
This method removes all HTML from a docstring. Lighter than ``convert_docs``, this is intended for the documentation on **parameters**, not the overall docs themselves. :param doc: The initial docstring :type doc: string :returns: The stripped/cleaned docstring :rtype: string
[ "This", "method", "removes", "all", "HTML", "from", "a", "docstring", "." ]
c52d2f3878b924ceabca07f61c91abcb1b230ecc
https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/introspection.py#L84-L102
248,294
henrysher/kotocore
kotocore/introspection.py
Introspection.parse_param
def parse_param(self, core_param): """ Returns data about a specific parameter. :param core_param: The ``Parameter`` to introspect :type core_param: A ``<botocore.parameters.Parameter>`` subclass :returns: A dict of the relevant information """ return { 'var_name': core_param.py_name, 'api_name': core_param.name, 'required': core_param.required, 'docs': self.strip_html(core_param.documentation), 'type': core_param.type, }
python
def parse_param(self, core_param): """ Returns data about a specific parameter. :param core_param: The ``Parameter`` to introspect :type core_param: A ``<botocore.parameters.Parameter>`` subclass :returns: A dict of the relevant information """ return { 'var_name': core_param.py_name, 'api_name': core_param.name, 'required': core_param.required, 'docs': self.strip_html(core_param.documentation), 'type': core_param.type, }
[ "def", "parse_param", "(", "self", ",", "core_param", ")", ":", "return", "{", "'var_name'", ":", "core_param", ".", "py_name", ",", "'api_name'", ":", "core_param", ".", "name", ",", "'required'", ":", "core_param", ".", "required", ",", "'docs'", ":", "self", ".", "strip_html", "(", "core_param", ".", "documentation", ")", ",", "'type'", ":", "core_param", ".", "type", ",", "}" ]
Returns data about a specific parameter. :param core_param: The ``Parameter`` to introspect :type core_param: A ``<botocore.parameters.Parameter>`` subclass :returns: A dict of the relevant information
[ "Returns", "data", "about", "a", "specific", "parameter", "." ]
c52d2f3878b924ceabca07f61c91abcb1b230ecc
https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/introspection.py#L104-L119
248,295
henrysher/kotocore
kotocore/introspection.py
Introspection.parse_params
def parse_params(self, core_params): """ Goes through a set of parameters, extracting information about each. :param core_params: The collection of parameters :type core_params: A collection of ``<botocore.parameters.Parameter>`` subclasses :returns: A list of dictionaries """ params = [] for core_param in core_params: params.append(self.parse_param(core_param)) return params
python
def parse_params(self, core_params): """ Goes through a set of parameters, extracting information about each. :param core_params: The collection of parameters :type core_params: A collection of ``<botocore.parameters.Parameter>`` subclasses :returns: A list of dictionaries """ params = [] for core_param in core_params: params.append(self.parse_param(core_param)) return params
[ "def", "parse_params", "(", "self", ",", "core_params", ")", ":", "params", "=", "[", "]", "for", "core_param", "in", "core_params", ":", "params", ".", "append", "(", "self", ".", "parse_param", "(", "core_param", ")", ")", "return", "params" ]
Goes through a set of parameters, extracting information about each. :param core_params: The collection of parameters :type core_params: A collection of ``<botocore.parameters.Parameter>`` subclasses :returns: A list of dictionaries
[ "Goes", "through", "a", "set", "of", "parameters", "extracting", "information", "about", "each", "." ]
c52d2f3878b924ceabca07f61c91abcb1b230ecc
https://github.com/henrysher/kotocore/blob/c52d2f3878b924ceabca07f61c91abcb1b230ecc/kotocore/introspection.py#L121-L136
248,296
Nydareld/ConfigEnv
ConfigEnv/Config.py
Config.addFile
def addFile(self,file): """ Permet d'ajouter un fichier Args: file (string): path d'un fichier json Returns: type: None Raises: FileFormatException: Erreur du format de fichier """ mylambda= lambda adict : { key.upper() : mylambda(adict[key]) if isinstance(adict[key],dict) else adict[key] for key in adict.keys() } if file.endswith('.json') : with open(file, 'r') as f: fileContent = mylambda(json.load(f)) elif file.endswith('.ini') : parser = configparser.ConfigParser() parser.read(file) fileContent = { section : { conflist[0].upper() : conflist[1] for conflist in parser.items(section) } for section in parser.sections() } else : raise FileFormatException() self._config = {**self._config, **mylambda(fileContent)}
python
def addFile(self,file): """ Permet d'ajouter un fichier Args: file (string): path d'un fichier json Returns: type: None Raises: FileFormatException: Erreur du format de fichier """ mylambda= lambda adict : { key.upper() : mylambda(adict[key]) if isinstance(adict[key],dict) else adict[key] for key in adict.keys() } if file.endswith('.json') : with open(file, 'r') as f: fileContent = mylambda(json.load(f)) elif file.endswith('.ini') : parser = configparser.ConfigParser() parser.read(file) fileContent = { section : { conflist[0].upper() : conflist[1] for conflist in parser.items(section) } for section in parser.sections() } else : raise FileFormatException() self._config = {**self._config, **mylambda(fileContent)}
[ "def", "addFile", "(", "self", ",", "file", ")", ":", "mylambda", "=", "lambda", "adict", ":", "{", "key", ".", "upper", "(", ")", ":", "mylambda", "(", "adict", "[", "key", "]", ")", "if", "isinstance", "(", "adict", "[", "key", "]", ",", "dict", ")", "else", "adict", "[", "key", "]", "for", "key", "in", "adict", ".", "keys", "(", ")", "}", "if", "file", ".", "endswith", "(", "'.json'", ")", ":", "with", "open", "(", "file", ",", "'r'", ")", "as", "f", ":", "fileContent", "=", "mylambda", "(", "json", ".", "load", "(", "f", ")", ")", "elif", "file", ".", "endswith", "(", "'.ini'", ")", ":", "parser", "=", "configparser", ".", "ConfigParser", "(", ")", "parser", ".", "read", "(", "file", ")", "fileContent", "=", "{", "section", ":", "{", "conflist", "[", "0", "]", ".", "upper", "(", ")", ":", "conflist", "[", "1", "]", "for", "conflist", "in", "parser", ".", "items", "(", "section", ")", "}", "for", "section", "in", "parser", ".", "sections", "(", ")", "}", "else", ":", "raise", "FileFormatException", "(", ")", "self", ".", "_config", "=", "{", "*", "*", "self", ".", "_config", ",", "*", "*", "mylambda", "(", "fileContent", ")", "}" ]
Permet d'ajouter un fichier Args: file (string): path d'un fichier json Returns: type: None Raises: FileFormatException: Erreur du format de fichier
[ "Permet", "d", "ajouter", "un", "fichier" ]
38c13e5dd9d6c5f3dcd4c1194507a43384c31e29
https://github.com/Nydareld/ConfigEnv/blob/38c13e5dd9d6c5f3dcd4c1194507a43384c31e29/ConfigEnv/Config.py#L16-L41
248,297
AguaClara/aide_document-DEPRECATED
aide_document/combine.py
render_document
def render_document(template_name, data_name, output_name): """ Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file. Parameters ========== template_name : String Exact name of the MarkDown template file from the aide_document/templates folder. Do not use the file path. data_name : String Relative file path from where this method is called to the location of the YAML data file to be used. output_name : String Relative file path from where this method is called to the location to which the output file is written. Examples ======== Suppose we have template.md in aide_document and a directory as follows: data/ params.yaml To render the document: >>> from aide_document import combine >>> combine.render_document('template.md', 'data/params.yaml', 'data/output.md') This will then combine the data and template files and write to a new output file within data/. """ # Set up environment and load templates from pip package env = Environment(loader=PackageLoader('aide_document')) #TODO: add custom path to templates # Create output file, open template and data files, then combine with open(output_name, 'w') as output_file: output = env.get_template(template_name).render(yaml.load(open(data_name))) output_file.write(output)
python
def render_document(template_name, data_name, output_name): """ Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file. Parameters ========== template_name : String Exact name of the MarkDown template file from the aide_document/templates folder. Do not use the file path. data_name : String Relative file path from where this method is called to the location of the YAML data file to be used. output_name : String Relative file path from where this method is called to the location to which the output file is written. Examples ======== Suppose we have template.md in aide_document and a directory as follows: data/ params.yaml To render the document: >>> from aide_document import combine >>> combine.render_document('template.md', 'data/params.yaml', 'data/output.md') This will then combine the data and template files and write to a new output file within data/. """ # Set up environment and load templates from pip package env = Environment(loader=PackageLoader('aide_document')) #TODO: add custom path to templates # Create output file, open template and data files, then combine with open(output_name, 'w') as output_file: output = env.get_template(template_name).render(yaml.load(open(data_name))) output_file.write(output)
[ "def", "render_document", "(", "template_name", ",", "data_name", ",", "output_name", ")", ":", "# Set up environment and load templates from pip package", "env", "=", "Environment", "(", "loader", "=", "PackageLoader", "(", "'aide_document'", ")", ")", "#TODO: add custom path to templates", "# Create output file, open template and data files, then combine", "with", "open", "(", "output_name", ",", "'w'", ")", "as", "output_file", ":", "output", "=", "env", ".", "get_template", "(", "template_name", ")", ".", "render", "(", "yaml", ".", "load", "(", "open", "(", "data_name", ")", ")", ")", "output_file", ".", "write", "(", "output", ")" ]
Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file. Parameters ========== template_name : String Exact name of the MarkDown template file from the aide_document/templates folder. Do not use the file path. data_name : String Relative file path from where this method is called to the location of the YAML data file to be used. output_name : String Relative file path from where this method is called to the location to which the output file is written. Examples ======== Suppose we have template.md in aide_document and a directory as follows: data/ params.yaml To render the document: >>> from aide_document import combine >>> combine.render_document('template.md', 'data/params.yaml', 'data/output.md') This will then combine the data and template files and write to a new output file within data/.
[ "Combines", "a", "MarkDown", "template", "file", "from", "the", "aide_document", "package", "with", "a", "local", "associated", "YAML", "data", "file", "then", "outputs", "the", "rendered", "combination", "to", "a", "local", "MarkDown", "output", "file", "." ]
3f3b5c9f321264e0e4d8ed68dfbc080762579815
https://github.com/AguaClara/aide_document-DEPRECATED/blob/3f3b5c9f321264e0e4d8ed68dfbc080762579815/aide_document/combine.py#L5-L37
248,298
echinopsii/net.echinopsii.ariane.community.cli.python3
ariane_clip3/injector.py
InjectorComponentSkeleton.cache
def cache(self, refreshing=None, next_action=None, data_blob=None, json_last_refresh=None, rollback_point=False): """ push this component into the cache :param refreshing: the new refreshing value :param next_action: the new next action value :param data_blob: the new data blob value :param json_last_refresh: the new json last refresh value - if None the date of this call :param rollback_point: define the rollback point with provided values (refreshing, next_action, data_blob and json_last_refresh) :return: """ LOGGER.debug("InjectorComponentSkeleton.cache") if json_last_refresh is None: json_last_refresh = datetime.datetime.now() if rollback_point: self.rollback_point_refreshing = refreshing self.rollback_point_next_action = next_action self.rollback_point_data_blob = data_blob self.rollback_point_refreshing = refreshing return self.component_cache_actor.save(refreshing=refreshing, next_action=next_action, json_last_refresh=json_last_refresh, data_blob=data_blob).get()
python
def cache(self, refreshing=None, next_action=None, data_blob=None, json_last_refresh=None, rollback_point=False): """ push this component into the cache :param refreshing: the new refreshing value :param next_action: the new next action value :param data_blob: the new data blob value :param json_last_refresh: the new json last refresh value - if None the date of this call :param rollback_point: define the rollback point with provided values (refreshing, next_action, data_blob and json_last_refresh) :return: """ LOGGER.debug("InjectorComponentSkeleton.cache") if json_last_refresh is None: json_last_refresh = datetime.datetime.now() if rollback_point: self.rollback_point_refreshing = refreshing self.rollback_point_next_action = next_action self.rollback_point_data_blob = data_blob self.rollback_point_refreshing = refreshing return self.component_cache_actor.save(refreshing=refreshing, next_action=next_action, json_last_refresh=json_last_refresh, data_blob=data_blob).get()
[ "def", "cache", "(", "self", ",", "refreshing", "=", "None", ",", "next_action", "=", "None", ",", "data_blob", "=", "None", ",", "json_last_refresh", "=", "None", ",", "rollback_point", "=", "False", ")", ":", "LOGGER", ".", "debug", "(", "\"InjectorComponentSkeleton.cache\"", ")", "if", "json_last_refresh", "is", "None", ":", "json_last_refresh", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "if", "rollback_point", ":", "self", ".", "rollback_point_refreshing", "=", "refreshing", "self", ".", "rollback_point_next_action", "=", "next_action", "self", ".", "rollback_point_data_blob", "=", "data_blob", "self", ".", "rollback_point_refreshing", "=", "refreshing", "return", "self", ".", "component_cache_actor", ".", "save", "(", "refreshing", "=", "refreshing", ",", "next_action", "=", "next_action", ",", "json_last_refresh", "=", "json_last_refresh", ",", "data_blob", "=", "data_blob", ")", ".", "get", "(", ")" ]
push this component into the cache :param refreshing: the new refreshing value :param next_action: the new next action value :param data_blob: the new data blob value :param json_last_refresh: the new json last refresh value - if None the date of this call :param rollback_point: define the rollback point with provided values (refreshing, next_action, data_blob and json_last_refresh) :return:
[ "push", "this", "component", "into", "the", "cache" ]
0a7feddebf66fee4bef38d64f456d93a7e9fcd68
https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/injector.py#L808-L829
248,299
echinopsii/net.echinopsii.ariane.community.cli.python3
ariane_clip3/injector.py
InjectorComponentSkeleton.rollback
def rollback(self): """ push back last rollbackpoint into the cache :return: """ return self.component_cache_actor.save(refreshing=self.rollback_point_refreshing, next_action=self.rollback_point_next_action, json_last_refresh=self.rollback_point_last_refresh, data_blob=self.rollback_point_data_blob).get()
python
def rollback(self): """ push back last rollbackpoint into the cache :return: """ return self.component_cache_actor.save(refreshing=self.rollback_point_refreshing, next_action=self.rollback_point_next_action, json_last_refresh=self.rollback_point_last_refresh, data_blob=self.rollback_point_data_blob).get()
[ "def", "rollback", "(", "self", ")", ":", "return", "self", ".", "component_cache_actor", ".", "save", "(", "refreshing", "=", "self", ".", "rollback_point_refreshing", ",", "next_action", "=", "self", ".", "rollback_point_next_action", ",", "json_last_refresh", "=", "self", ".", "rollback_point_last_refresh", ",", "data_blob", "=", "self", ".", "rollback_point_data_blob", ")", ".", "get", "(", ")" ]
push back last rollbackpoint into the cache :return:
[ "push", "back", "last", "rollbackpoint", "into", "the", "cache" ]
0a7feddebf66fee4bef38d64f456d93a7e9fcd68
https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/injector.py#L831-L840