repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
DeepHorizons/iarm
iarm/arm_instructions/conditional_branch.py
ConditionalBranch.BVS
def BVS(self, params): """ BVS label Branch to the instruction at label if the V flag is set """ label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) # BVS label def BVS_func(): if self.is_V_...
python
def BVS(self, params): """ BVS label Branch to the instruction at label if the V flag is set """ label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) # BVS label def BVS_func(): if self.is_V_...
[ "def", "BVS", "(", "self", ",", "params", ")", ":", "label", "=", "self", ".", "get_one_parameter", "(", "self", ".", "ONE_PARAMETER", ",", "params", ")", "self", ".", "check_arguments", "(", "label_exists", "=", "(", "label", ",", ")", ")", "# BVS label...
BVS label Branch to the instruction at label if the V flag is set
[ "BVS", "label" ]
train
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/conditional_branch.py#L260-L275
lincolnloop/salmon
salmon/metrics/admin.py
MetricGroupAdmin.get_queryset
def get_queryset(self, request): """Shows one entry per distinct metric name""" queryset = super(MetricGroupAdmin, self).get_queryset(request) # poor-man's DISTINCT ON for Sqlite3 qs_values = queryset.values('id', 'name') # 2.7+ only :( # = {metric['name']: metric['id'] f...
python
def get_queryset(self, request): """Shows one entry per distinct metric name""" queryset = super(MetricGroupAdmin, self).get_queryset(request) # poor-man's DISTINCT ON for Sqlite3 qs_values = queryset.values('id', 'name') # 2.7+ only :( # = {metric['name']: metric['id'] f...
[ "def", "get_queryset", "(", "self", ",", "request", ")", ":", "queryset", "=", "super", "(", "MetricGroupAdmin", ",", "self", ")", ".", "get_queryset", "(", "request", ")", "# poor-man's DISTINCT ON for Sqlite3", "qs_values", "=", "queryset", ".", "values", "(",...
Shows one entry per distinct metric name
[ "Shows", "one", "entry", "per", "distinct", "metric", "name" ]
train
https://github.com/lincolnloop/salmon/blob/62a965ad9716707ea1db4afb5d9646766f29b64b/salmon/metrics/admin.py#L34-L45
lincolnloop/salmon
salmon/metrics/admin.py
MetricGroupAdmin.save_model
def save_model(self, request, obj, form, change): """Updates all metrics with the same name""" like_metrics = self.model.objects.filter(name=obj.name) # 2.7+ only :( # = {key: form.cleaned_data[key] for key in form.changed_data} updates = {} for key in form.changed_data: ...
python
def save_model(self, request, obj, form, change): """Updates all metrics with the same name""" like_metrics = self.model.objects.filter(name=obj.name) # 2.7+ only :( # = {key: form.cleaned_data[key] for key in form.changed_data} updates = {} for key in form.changed_data: ...
[ "def", "save_model", "(", "self", ",", "request", ",", "obj", ",", "form", ",", "change", ")", ":", "like_metrics", "=", "self", ".", "model", ".", "objects", ".", "filter", "(", "name", "=", "obj", ".", "name", ")", "# 2.7+ only :(", "# = {key: form.cle...
Updates all metrics with the same name
[ "Updates", "all", "metrics", "with", "the", "same", "name" ]
train
https://github.com/lincolnloop/salmon/blob/62a965ad9716707ea1db4afb5d9646766f29b64b/salmon/metrics/admin.py#L47-L55
DeepHorizons/iarm
iarm/arm_instructions/_meta.py
_Meta.parse_lines
def parse_lines(self, code): """ Return a list of the parsed code For each line, return a three-tuple containing: 1. The label 2. The instruction 3. Any arguments or parameters An element in the tuple may be None or '' if it did not find anything :param ...
python
def parse_lines(self, code): """ Return a list of the parsed code For each line, return a three-tuple containing: 1. The label 2. The instruction 3. Any arguments or parameters An element in the tuple may be None or '' if it did not find anything :param ...
[ "def", "parse_lines", "(", "self", ",", "code", ")", ":", "remove_comments", "=", "re", ".", "compile", "(", "r'^([^;@\\n]*);?.*$'", ",", "re", ".", "MULTILINE", ")", "code", "=", "'\\n'", ".", "join", "(", "remove_comments", ".", "findall", "(", "code", ...
Return a list of the parsed code For each line, return a three-tuple containing: 1. The label 2. The instruction 3. Any arguments or parameters An element in the tuple may be None or '' if it did not find anything :param code: The code to parse :return: A list o...
[ "Return", "a", "list", "of", "the", "parsed", "code" ]
train
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/_meta.py#L20-L40
DeepHorizons/iarm
iarm/arm_instructions/_meta.py
_Meta.check_register
def check_register(self, arg): """ Is the parameter a register in the form of 'R<d>', and if so is it within the bounds of registers defined Raises an exception if 1. The parameter is not in the form of 'R<d>' 2. <d> is outside the range of registers defined in the init ...
python
def check_register(self, arg): """ Is the parameter a register in the form of 'R<d>', and if so is it within the bounds of registers defined Raises an exception if 1. The parameter is not in the form of 'R<d>' 2. <d> is outside the range of registers defined in the init ...
[ "def", "check_register", "(", "self", ",", "arg", ")", ":", "self", ".", "check_parameter", "(", "arg", ")", "match", "=", "re", ".", "search", "(", "self", ".", "REGISTER_REGEX", ",", "arg", ")", "if", "match", "is", "None", ":", "raise", "iarm", "....
Is the parameter a register in the form of 'R<d>', and if so is it within the bounds of registers defined Raises an exception if 1. The parameter is not in the form of 'R<d>' 2. <d> is outside the range of registers defined in the init value registers or _max_registers ...
[ "Is", "the", "parameter", "a", "register", "in", "the", "form", "of", "R<d", ">", "and", "if", "so", "is", "it", "within", "the", "bounds", "of", "registers", "defined" ]
train
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/_meta.py#L76-L109
DeepHorizons/iarm
iarm/arm_instructions/_meta.py
_Meta.check_immediate
def check_immediate(self, arg): """ Is the parameter an immediate in the form of '#<d>', Raises an exception if 1. The parameter is not in the form of '#<d>' :param arg: The parameter to check :return: The value of the immediate """ self.check_parameter(a...
python
def check_immediate(self, arg): """ Is the parameter an immediate in the form of '#<d>', Raises an exception if 1. The parameter is not in the form of '#<d>' :param arg: The parameter to check :return: The value of the immediate """ self.check_parameter(a...
[ "def", "check_immediate", "(", "self", ",", "arg", ")", ":", "self", ".", "check_parameter", "(", "arg", ")", "match", "=", "re", ".", "search", "(", "self", ".", "IMMEDIATE_REGEX", ",", "arg", ")", "if", "match", "is", "None", ":", "raise", "iarm", ...
Is the parameter an immediate in the form of '#<d>', Raises an exception if 1. The parameter is not in the form of '#<d>' :param arg: The parameter to check :return: The value of the immediate
[ "Is", "the", "parameter", "an", "immediate", "in", "the", "form", "of", "#<d", ">" ]
train
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/_meta.py#L111-L124
DeepHorizons/iarm
iarm/arm_instructions/_meta.py
_Meta.check_immediate_unsigned_value
def check_immediate_unsigned_value(self, arg, bit): """ Is the immediate within the unsigned value of 2**bit - 1 Raises an exception if 1. The immediate value is > 2**bit - 1 :param arg: The parameter to check :param bit: The number of bits to use in 2**bit :retu...
python
def check_immediate_unsigned_value(self, arg, bit): """ Is the immediate within the unsigned value of 2**bit - 1 Raises an exception if 1. The immediate value is > 2**bit - 1 :param arg: The parameter to check :param bit: The number of bits to use in 2**bit :retu...
[ "def", "check_immediate_unsigned_value", "(", "self", ",", "arg", ",", "bit", ")", ":", "i_num", "=", "self", ".", "check_immediate", "(", "arg", ")", "if", "(", "i_num", ">", "(", "2", "**", "bit", "-", "1", ")", ")", "or", "(", "i_num", "<", "0",...
Is the immediate within the unsigned value of 2**bit - 1 Raises an exception if 1. The immediate value is > 2**bit - 1 :param arg: The parameter to check :param bit: The number of bits to use in 2**bit :return: The value of the immediate
[ "Is", "the", "immediate", "within", "the", "unsigned", "value", "of", "2", "**", "bit", "-", "1" ]
train
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/_meta.py#L134-L147
DeepHorizons/iarm
iarm/arm_instructions/_meta.py
_Meta.check_immediate_value
def check_immediate_value(self, arg, _max, _min=0): """ Is the immediate within the range of [_min, _max] Raises an exception if 1. The immediate value is < _min or > _max :param arg: The parameter to check :param _max: The maximum value :param _min: The minimum ...
python
def check_immediate_value(self, arg, _max, _min=0): """ Is the immediate within the range of [_min, _max] Raises an exception if 1. The immediate value is < _min or > _max :param arg: The parameter to check :param _max: The maximum value :param _min: The minimum ...
[ "def", "check_immediate_value", "(", "self", ",", "arg", ",", "_max", ",", "_min", "=", "0", ")", ":", "i_num", "=", "self", ".", "check_immediate", "(", "arg", ")", "if", "(", "i_num", ">", "_max", ")", "or", "(", "i_num", "<", "_min", ")", ":", ...
Is the immediate within the range of [_min, _max] Raises an exception if 1. The immediate value is < _min or > _max :param arg: The parameter to check :param _max: The maximum value :param _min: The minimum value, optional, default is zero :return: The immediate value
[ "Is", "the", "immediate", "within", "the", "range", "of", "[", "_min", "_max", "]" ]
train
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/_meta.py#L149-L163
DeepHorizons/iarm
iarm/arm_instructions/_meta.py
_Meta.rule_low_registers
def rule_low_registers(self, arg): """Low registers are R0 - R7""" r_num = self.check_register(arg) if r_num > 7: raise iarm.exceptions.RuleError( "Register {} is not a low register".format(arg))
python
def rule_low_registers(self, arg): """Low registers are R0 - R7""" r_num = self.check_register(arg) if r_num > 7: raise iarm.exceptions.RuleError( "Register {} is not a low register".format(arg))
[ "def", "rule_low_registers", "(", "self", ",", "arg", ")", ":", "r_num", "=", "self", ".", "check_register", "(", "arg", ")", "if", "r_num", ">", "7", ":", "raise", "iarm", ".", "exceptions", ".", "RuleError", "(", "\"Register {} is not a low register\"", "....
Low registers are R0 - R7
[ "Low", "registers", "are", "R0", "-", "R7" ]
train
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/_meta.py#L170-L175
DeepHorizons/iarm
iarm/arm_instructions/_meta.py
_Meta.get_parameters
def get_parameters(self, regex_exp, parameters): """ Given a regex expression and the string with the paramers, either return a regex match object or raise an exception if the regex did not find a match :param regex_exp: :param parameters: :return: """ ...
python
def get_parameters(self, regex_exp, parameters): """ Given a regex expression and the string with the paramers, either return a regex match object or raise an exception if the regex did not find a match :param regex_exp: :param parameters: :return: """ ...
[ "def", "get_parameters", "(", "self", ",", "regex_exp", ",", "parameters", ")", ":", "# TODO find a better way to do the equate replacement", "for", "rep", "in", "self", ".", "equates", ":", "parameters", "=", "parameters", ".", "replace", "(", "rep", ",", "str", ...
Given a regex expression and the string with the paramers, either return a regex match object or raise an exception if the regex did not find a match :param regex_exp: :param parameters: :return:
[ "Given", "a", "regex", "expression", "and", "the", "string", "with", "the", "paramers", "either", "return", "a", "regex", "match", "object", "or", "raise", "an", "exception", "if", "the", "regex", "did", "not", "find", "a", "match", ":", "param", "regex_ex...
train
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/_meta.py#L241-L257
DeepHorizons/iarm
iarm/arm_instructions/_meta.py
_Meta.get_one_parameter
def get_one_parameter(self, regex_exp, parameters): """ Get three parameters from a given regex expression Raise an exception if more than three were found :param regex_exp: :param parameters: :return: """ Rx, other = self.get_parameters(regex_exp, parame...
python
def get_one_parameter(self, regex_exp, parameters): """ Get three parameters from a given regex expression Raise an exception if more than three were found :param regex_exp: :param parameters: :return: """ Rx, other = self.get_parameters(regex_exp, parame...
[ "def", "get_one_parameter", "(", "self", ",", "regex_exp", ",", "parameters", ")", ":", "Rx", ",", "other", "=", "self", ".", "get_parameters", "(", "regex_exp", ",", "parameters", ")", "if", "other", "is", "not", "None", "and", "other", ".", "strip", "(...
Get three parameters from a given regex expression Raise an exception if more than three were found :param regex_exp: :param parameters: :return:
[ "Get", "three", "parameters", "from", "a", "given", "regex", "expression" ]
train
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/_meta.py#L259-L271
DeepHorizons/iarm
iarm/arm_instructions/_meta.py
_Meta.get_two_parameters
def get_two_parameters(self, regex_exp, parameters): """ Get two parameters from a given regex expression Raise an exception if more than two were found :param regex_exp: :param parameters: :return: """ Rx, Ry, other = self.get_parameters(regex_exp, param...
python
def get_two_parameters(self, regex_exp, parameters): """ Get two parameters from a given regex expression Raise an exception if more than two were found :param regex_exp: :param parameters: :return: """ Rx, Ry, other = self.get_parameters(regex_exp, param...
[ "def", "get_two_parameters", "(", "self", ",", "regex_exp", ",", "parameters", ")", ":", "Rx", ",", "Ry", ",", "other", "=", "self", ".", "get_parameters", "(", "regex_exp", ",", "parameters", ")", "if", "other", "is", "not", "None", "and", "other", ".",...
Get two parameters from a given regex expression Raise an exception if more than two were found :param regex_exp: :param parameters: :return:
[ "Get", "two", "parameters", "from", "a", "given", "regex", "expression" ]
train
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/_meta.py#L273-L290
DeepHorizons/iarm
iarm/arm_instructions/_meta.py
_Meta.get_three_parameters
def get_three_parameters(self, regex_exp, parameters): """ Get three parameters from a given regex expression Raise an exception if more than three were found :param regex_exp: :param parameters: :return: """ Rx, Ry, Rz, other = self.get_parameters(regex_...
python
def get_three_parameters(self, regex_exp, parameters): """ Get three parameters from a given regex expression Raise an exception if more than three were found :param regex_exp: :param parameters: :return: """ Rx, Ry, Rz, other = self.get_parameters(regex_...
[ "def", "get_three_parameters", "(", "self", ",", "regex_exp", ",", "parameters", ")", ":", "Rx", ",", "Ry", ",", "Rz", ",", "other", "=", "self", ".", "get_parameters", "(", "regex_exp", ",", "parameters", ")", "if", "other", "is", "not", "None", "and", ...
Get three parameters from a given regex expression Raise an exception if more than three were found :param regex_exp: :param parameters: :return:
[ "Get", "three", "parameters", "from", "a", "given", "regex", "expression" ]
train
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/_meta.py#L292-L304
DeepHorizons/iarm
iarm/arm_instructions/_meta.py
_Meta.set_APSR_flag_to_value
def set_APSR_flag_to_value(self, flag, value): """ Set or clear flag in ASPR :param flag: The flag to set :param value: If value evaulates to true, it is set, cleared otherwise :return: """ if flag == 'N': bit = 31 elif flag == 'Z': ...
python
def set_APSR_flag_to_value(self, flag, value): """ Set or clear flag in ASPR :param flag: The flag to set :param value: If value evaulates to true, it is set, cleared otherwise :return: """ if flag == 'N': bit = 31 elif flag == 'Z': ...
[ "def", "set_APSR_flag_to_value", "(", "self", ",", "flag", ",", "value", ")", ":", "if", "flag", "==", "'N'", ":", "bit", "=", "31", "elif", "flag", "==", "'Z'", ":", "bit", "=", "30", "elif", "flag", "==", "'C'", ":", "bit", "=", "29", "elif", "...
Set or clear flag in ASPR :param flag: The flag to set :param value: If value evaulates to true, it is set, cleared otherwise :return:
[ "Set", "or", "clear", "flag", "in", "ASPR", ":", "param", "flag", ":", "The", "flag", "to", "set", ":", "param", "value", ":", "If", "value", "evaulates", "to", "true", "it", "is", "set", "cleared", "otherwise", ":", "return", ":" ]
train
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/_meta.py#L306-L327
DeepHorizons/iarm
iarm/arm_instructions/_meta.py
_Meta.rule_special_registers
def rule_special_registers(self, arg): """Raises an exception if the register is not a special register""" # TODO is PSR supposed to be here? special_registers = "PSR APSR IPSR EPSR PRIMASK FAULTMASK BASEPRI CONTROL" if arg not in special_registers.split(): raise iarm.excepti...
python
def rule_special_registers(self, arg): """Raises an exception if the register is not a special register""" # TODO is PSR supposed to be here? special_registers = "PSR APSR IPSR EPSR PRIMASK FAULTMASK BASEPRI CONTROL" if arg not in special_registers.split(): raise iarm.excepti...
[ "def", "rule_special_registers", "(", "self", ",", "arg", ")", ":", "# TODO is PSR supposed to be here?", "special_registers", "=", "\"PSR APSR IPSR EPSR PRIMASK FAULTMASK BASEPRI CONTROL\"", "if", "arg", "not", "in", "special_registers", ".", "split", "(", ")", ":", "rai...
Raises an exception if the register is not a special register
[ "Raises", "an", "exception", "if", "the", "register", "is", "not", "a", "special", "register" ]
train
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/_meta.py#L329-L334
DeepHorizons/iarm
iarm/arm_instructions/_meta.py
_Meta.set_C_flag
def set_C_flag(self, oper_1, oper_2, result, type): """ Set C flag C flag is set if the unsigned number overflows This condition is obtained if: 1. In addition, the result is smaller than either of the operands 2. In subtraction, if the second operand is larger than the f...
python
def set_C_flag(self, oper_1, oper_2, result, type): """ Set C flag C flag is set if the unsigned number overflows This condition is obtained if: 1. In addition, the result is smaller than either of the operands 2. In subtraction, if the second operand is larger than the f...
[ "def", "set_C_flag", "(", "self", ",", "oper_1", ",", "oper_2", ",", "result", ",", "type", ")", ":", "# TODO is this correct?", "if", "type", "==", "'add'", ":", "if", "result", "<", "oper_1", ":", "self", ".", "set_APSR_flag_to_value", "(", "'C'", ",", ...
Set C flag C flag is set if the unsigned number overflows This condition is obtained if: 1. In addition, the result is smaller than either of the operands 2. In subtraction, if the second operand is larger than the first This should not be used for shifting as each shift will ne...
[ "Set", "C", "flag", "C", "flag", "is", "set", "if", "the", "unsigned", "number", "overflows", "This", "condition", "is", "obtained", "if", ":", "1", ".", "In", "addition", "the", "result", "is", "smaller", "than", "either", "of", "the", "operands", "2", ...
train
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/_meta.py#L352-L381
glomex/gcdt
gcdt/utils.py
version
def version(): """Output version of gcdt tools and plugins.""" log.info('gcdt version %s' % __version__) tools = get_plugin_versions('gcdttool10') if tools: log.info('gcdt tools:') for p, v in tools.items(): log.info(' * %s version %s' % (p, v)) log.info('gcdt plugins:') ...
python
def version(): """Output version of gcdt tools and plugins.""" log.info('gcdt version %s' % __version__) tools = get_plugin_versions('gcdttool10') if tools: log.info('gcdt tools:') for p, v in tools.items(): log.info(' * %s version %s' % (p, v)) log.info('gcdt plugins:') ...
[ "def", "version", "(", ")", ":", "log", ".", "info", "(", "'gcdt version %s'", "%", "__version__", ")", "tools", "=", "get_plugin_versions", "(", "'gcdttool10'", ")", "if", "tools", ":", "log", ".", "info", "(", "'gcdt tools:'", ")", "for", "p", ",", "v"...
Output version of gcdt tools and plugins.
[ "Output", "version", "of", "gcdt", "tools", "and", "plugins", "." ]
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L32-L47
glomex/gcdt
gcdt/utils.py
retries
def retries(max_tries, delay=1, backoff=2, exceptions=(Exception,), hook=None): """Function decorator implementing retrying logic. delay: Sleep this many seconds * backoff * try number after failure backoff: Multiply delay by this factor after each failure exceptions: A tuple of exception classes; defa...
python
def retries(max_tries, delay=1, backoff=2, exceptions=(Exception,), hook=None): """Function decorator implementing retrying logic. delay: Sleep this many seconds * backoff * try number after failure backoff: Multiply delay by this factor after each failure exceptions: A tuple of exception classes; defa...
[ "def", "retries", "(", "max_tries", ",", "delay", "=", "1", ",", "backoff", "=", "2", ",", "exceptions", "=", "(", "Exception", ",", ")", ",", "hook", "=", "None", ")", ":", "\"\"\"\n def example_hook(tries_remaining, exception, delay):\n '''Example except...
Function decorator implementing retrying logic. delay: Sleep this many seconds * backoff * try number after failure backoff: Multiply delay by this factor after each failure exceptions: A tuple of exception classes; default (Exception,) hook: A function with the signature: (tries_remaining, exception, ...
[ "Function", "decorator", "implementing", "retrying", "logic", "." ]
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L50-L102
glomex/gcdt
gcdt/utils.py
get_env
def get_env(): """ Read environment from ENV and mangle it to a (lower case) representation Note: gcdt.utils get_env() is used in many cloudformation.py templates :return: Environment as lower case string (or None if not matched) """ env = os.getenv('ENV', os.getenv('env', None)) if env: ...
python
def get_env(): """ Read environment from ENV and mangle it to a (lower case) representation Note: gcdt.utils get_env() is used in many cloudformation.py templates :return: Environment as lower case string (or None if not matched) """ env = os.getenv('ENV', os.getenv('env', None)) if env: ...
[ "def", "get_env", "(", ")", ":", "env", "=", "os", ".", "getenv", "(", "'ENV'", ",", "os", ".", "getenv", "(", "'env'", ",", "None", ")", ")", "if", "env", ":", "env", "=", "env", ".", "lower", "(", ")", "return", "env" ]
Read environment from ENV and mangle it to a (lower case) representation Note: gcdt.utils get_env() is used in many cloudformation.py templates :return: Environment as lower case string (or None if not matched)
[ "Read", "environment", "from", "ENV", "and", "mangle", "it", "to", "a", "(", "lower", "case", ")", "representation", "Note", ":", "gcdt", ".", "utils", "get_env", "()", "is", "used", "in", "many", "cloudformation", ".", "py", "templates", ":", "return", ...
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L109-L118
glomex/gcdt
gcdt/utils.py
get_context
def get_context(awsclient, env, tool, command, arguments=None): """This assembles the tool context. Private members are preceded by a '_'. :param tool: :param command: :return: dictionary containing the gcdt tool context """ # TODO: elapsed, artifact(stack, depl-grp, lambda, api) if argumen...
python
def get_context(awsclient, env, tool, command, arguments=None): """This assembles the tool context. Private members are preceded by a '_'. :param tool: :param command: :return: dictionary containing the gcdt tool context """ # TODO: elapsed, artifact(stack, depl-grp, lambda, api) if argumen...
[ "def", "get_context", "(", "awsclient", ",", "env", ",", "tool", ",", "command", ",", "arguments", "=", "None", ")", ":", "# TODO: elapsed, artifact(stack, depl-grp, lambda, api)", "if", "arguments", "is", "None", ":", "arguments", "=", "{", "}", "context", "=",...
This assembles the tool context. Private members are preceded by a '_'. :param tool: :param command: :return: dictionary containing the gcdt tool context
[ "This", "assembles", "the", "tool", "context", ".", "Private", "members", "are", "preceded", "by", "a", "_", "." ]
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L121-L142
glomex/gcdt
gcdt/utils.py
get_command
def get_command(arguments): """Extract the first argument from arguments parsed by docopt. :param arguments parsed by docopt: :return: command """ return [k for k, v in arguments.items() if not k.startswith('-') and v is True][0]
python
def get_command(arguments): """Extract the first argument from arguments parsed by docopt. :param arguments parsed by docopt: :return: command """ return [k for k, v in arguments.items() if not k.startswith('-') and v is True][0]
[ "def", "get_command", "(", "arguments", ")", ":", "return", "[", "k", "for", "k", ",", "v", "in", "arguments", ".", "items", "(", ")", "if", "not", "k", ".", "startswith", "(", "'-'", ")", "and", "v", "is", "True", "]", "[", "0", "]" ]
Extract the first argument from arguments parsed by docopt. :param arguments parsed by docopt: :return: command
[ "Extract", "the", "first", "argument", "from", "arguments", "parsed", "by", "docopt", "." ]
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L145-L152
glomex/gcdt
gcdt/utils.py
check_gcdt_update
def check_gcdt_update(): """Check whether a newer gcdt is available and output a warning. """ try: inst_version, latest_version = get_package_versions('gcdt') if inst_version < latest_version: log.warn('Please consider an update to gcdt version: %s' % ...
python
def check_gcdt_update(): """Check whether a newer gcdt is available and output a warning. """ try: inst_version, latest_version = get_package_versions('gcdt') if inst_version < latest_version: log.warn('Please consider an update to gcdt version: %s' % ...
[ "def", "check_gcdt_update", "(", ")", ":", "try", ":", "inst_version", ",", "latest_version", "=", "get_package_versions", "(", "'gcdt'", ")", "if", "inst_version", "<", "latest_version", ":", "log", ".", "warn", "(", "'Please consider an update to gcdt version: %s'",...
Check whether a newer gcdt is available and output a warning.
[ "Check", "whether", "a", "newer", "gcdt", "is", "available", "and", "output", "a", "warning", "." ]
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L173-L185
glomex/gcdt
gcdt/utils.py
dict_selective_merge
def dict_selective_merge(a, b, selection, path=None): """Conditionally merges b into a if b's keys are contained in selection :param a: :param b: :param selection: limit merge to these top-level keys :param path: :return: """ if path is None: path = [] for key in b: ...
python
def dict_selective_merge(a, b, selection, path=None): """Conditionally merges b into a if b's keys are contained in selection :param a: :param b: :param selection: limit merge to these top-level keys :param path: :return: """ if path is None: path = [] for key in b: ...
[ "def", "dict_selective_merge", "(", "a", ",", "b", ",", "selection", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "[", "]", "for", "key", "in", "b", ":", "if", "key", "in", "selection", ":", "if", "key", "in",...
Conditionally merges b into a if b's keys are contained in selection :param a: :param b: :param selection: limit merge to these top-level keys :param path: :return:
[ "Conditionally", "merges", "b", "into", "a", "if", "b", "s", "keys", "are", "contained", "in", "selection" ]
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L190-L211
glomex/gcdt
gcdt/utils.py
dict_merge
def dict_merge(a, b, path=None): """merges b into a""" return dict_selective_merge(a, b, b.keys(), path)
python
def dict_merge(a, b, path=None): """merges b into a""" return dict_selective_merge(a, b, b.keys(), path)
[ "def", "dict_merge", "(", "a", ",", "b", ",", "path", "=", "None", ")", ":", "return", "dict_selective_merge", "(", "a", ",", "b", ",", "b", ".", "keys", "(", ")", ",", "path", ")" ]
merges b into a
[ "merges", "b", "into", "a" ]
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L214-L216
glomex/gcdt
gcdt/utils.py
are_credentials_still_valid
def are_credentials_still_valid(awsclient): """Check whether the credentials have expired. :param awsclient: :return: exit_code """ client = awsclient.get_client('lambda') try: client.list_functions() except GracefulExit: raise except Exception as e: log.debug(e)...
python
def are_credentials_still_valid(awsclient): """Check whether the credentials have expired. :param awsclient: :return: exit_code """ client = awsclient.get_client('lambda') try: client.list_functions() except GracefulExit: raise except Exception as e: log.debug(e)...
[ "def", "are_credentials_still_valid", "(", "awsclient", ")", ":", "client", "=", "awsclient", ".", "get_client", "(", "'lambda'", ")", "try", ":", "client", ".", "list_functions", "(", ")", "except", "GracefulExit", ":", "raise", "except", "Exception", "as", "...
Check whether the credentials have expired. :param awsclient: :return: exit_code
[ "Check", "whether", "the", "credentials", "have", "expired", "." ]
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L222-L237
glomex/gcdt
gcdt/utils.py
flatten
def flatten(lis): """Given a list, possibly nested to any level, return it flattened.""" new_lis = [] for item in lis: if isinstance(item, collections.Sequence) and not isinstance(item, basestring): new_lis.extend(flatten(item)) else: new_lis.append(item) return n...
python
def flatten(lis): """Given a list, possibly nested to any level, return it flattened.""" new_lis = [] for item in lis: if isinstance(item, collections.Sequence) and not isinstance(item, basestring): new_lis.extend(flatten(item)) else: new_lis.append(item) return n...
[ "def", "flatten", "(", "lis", ")", ":", "new_lis", "=", "[", "]", "for", "item", "in", "lis", ":", "if", "isinstance", "(", "item", ",", "collections", ".", "Sequence", ")", "and", "not", "isinstance", "(", "item", ",", "basestring", ")", ":", "new_l...
Given a list, possibly nested to any level, return it flattened.
[ "Given", "a", "list", "possibly", "nested", "to", "any", "level", "return", "it", "flattened", "." ]
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L241-L249
glomex/gcdt
gcdt/utils.py
signal_handler
def signal_handler(signum, frame): """ handle signals. example: 'signal.signal(signal.SIGTERM, signal_handler)' """ # signals are CONSTANTS so there is no mapping from signum to description # so please add to the mapping in case you use more signals! description = '%d' % signum if signum...
python
def signal_handler(signum, frame): """ handle signals. example: 'signal.signal(signal.SIGTERM, signal_handler)' """ # signals are CONSTANTS so there is no mapping from signum to description # so please add to the mapping in case you use more signals! description = '%d' % signum if signum...
[ "def", "signal_handler", "(", "signum", ",", "frame", ")", ":", "# signals are CONSTANTS so there is no mapping from signum to description", "# so please add to the mapping in case you use more signals!", "description", "=", "'%d'", "%", "signum", "if", "signum", "==", "2", ":"...
handle signals. example: 'signal.signal(signal.SIGTERM, signal_handler)'
[ "handle", "signals", ".", "example", ":", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", "signal_handler", ")" ]
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L260-L272
glomex/gcdt
gcdt/utils.py
json2table
def json2table(json): """This does format a dictionary into a table. Note this expects a dictionary (not a json string!) :param json: :return: """ filter_terms = ['ResponseMetadata'] table = [] try: for k in filter(lambda k: k not in filter_terms, json.keys()): table...
python
def json2table(json): """This does format a dictionary into a table. Note this expects a dictionary (not a json string!) :param json: :return: """ filter_terms = ['ResponseMetadata'] table = [] try: for k in filter(lambda k: k not in filter_terms, json.keys()): table...
[ "def", "json2table", "(", "json", ")", ":", "filter_terms", "=", "[", "'ResponseMetadata'", "]", "table", "=", "[", "]", "try", ":", "for", "k", "in", "filter", "(", "lambda", "k", ":", "k", "not", "in", "filter_terms", ",", "json", ".", "keys", "(",...
This does format a dictionary into a table. Note this expects a dictionary (not a json string!) :param json: :return:
[ "This", "does", "format", "a", "dictionary", "into", "a", "table", ".", "Note", "this", "expects", "a", "dictionary", "(", "not", "a", "json", "string!", ")" ]
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L275-L293
glomex/gcdt
gcdt/utils.py
random_string
def random_string(length=6): """Create a random 6 character string. note: in case you use this function in a test during test together with an awsclient then this function is altered so you get reproducible results that will work with your recorded placebo json files (see helpers_aws.py). """ r...
python
def random_string(length=6): """Create a random 6 character string. note: in case you use this function in a test during test together with an awsclient then this function is altered so you get reproducible results that will work with your recorded placebo json files (see helpers_aws.py). """ r...
[ "def", "random_string", "(", "length", "=", "6", ")", ":", "return", "''", ".", "join", "(", "[", "random", ".", "choice", "(", "string", ".", "ascii_lowercase", ")", "for", "i", "in", "range", "(", "length", ")", "]", ")" ]
Create a random 6 character string. note: in case you use this function in a test during test together with an awsclient then this function is altered so you get reproducible results that will work with your recorded placebo json files (see helpers_aws.py).
[ "Create", "a", "random", "6", "character", "string", "." ]
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L316-L323
glomex/gcdt
gcdt/utils.py
all_pages
def all_pages(method, request, accessor, cond=None): """Helper to process all pages using botocore service methods (exhausts NextToken). note: `cond` is optional... you can use it to make filtering more explicit if you like. Alternatively you can do the filtering in the `accessor` which is perfectly fin...
python
def all_pages(method, request, accessor, cond=None): """Helper to process all pages using botocore service methods (exhausts NextToken). note: `cond` is optional... you can use it to make filtering more explicit if you like. Alternatively you can do the filtering in the `accessor` which is perfectly fin...
[ "def", "all_pages", "(", "method", ",", "request", ",", "accessor", ",", "cond", "=", "None", ")", ":", "if", "cond", "is", "None", ":", "cond", "=", "lambda", "x", ":", "True", "result", "=", "[", "]", "next_token", "=", "None", "while", "True", "...
Helper to process all pages using botocore service methods (exhausts NextToken). note: `cond` is optional... you can use it to make filtering more explicit if you like. Alternatively you can do the filtering in the `accessor` which is perfectly fine, too Note: lambda uses a slightly different mechanism ...
[ "Helper", "to", "process", "all", "pages", "using", "botocore", "service", "methods", "(", "exhausts", "NextToken", ")", ".", "note", ":", "cond", "is", "optional", "...", "you", "can", "use", "it", "to", "make", "filtering", "more", "explicit", "if", "you...
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L336-L369
clarkperkins/click-shell
click_shell/core.py
get_invoke
def get_invoke(command): """ Get the Cmd main method from the click command :param command: The click Command object :return: the do_* method for Cmd :rtype: function """ assert isinstance(command, click.Command) def invoke_(self, arg): # pylint: disable=unused-argument try: ...
python
def get_invoke(command): """ Get the Cmd main method from the click command :param command: The click Command object :return: the do_* method for Cmd :rtype: function """ assert isinstance(command, click.Command) def invoke_(self, arg): # pylint: disable=unused-argument try: ...
[ "def", "get_invoke", "(", "command", ")", ":", "assert", "isinstance", "(", "command", ",", "click", ".", "Command", ")", "def", "invoke_", "(", "self", ",", "arg", ")", ":", "# pylint: disable=unused-argument", "try", ":", "command", ".", "main", "(", "ar...
Get the Cmd main method from the click command :param command: The click Command object :return: the do_* method for Cmd :rtype: function
[ "Get", "the", "Cmd", "main", "method", "from", "the", "click", "command", ":", "param", "command", ":", "The", "click", "Command", "object", ":", "return", ":", "the", "do_", "*", "method", "for", "Cmd", ":", "rtype", ":", "function" ]
train
https://github.com/clarkperkins/click-shell/blob/8d6e1a492176bc79e029d714f19d3156409656ea/click_shell/core.py#L21-L56
clarkperkins/click-shell
click_shell/core.py
get_help
def get_help(command): """ Get the Cmd help function from the click command :param command: The click Command object :return: the help_* method for Cmd :rtype: function """ assert isinstance(command, click.Command) def help_(self): # pylint: disable=unused-argument extra = {} ...
python
def get_help(command): """ Get the Cmd help function from the click command :param command: The click Command object :return: the help_* method for Cmd :rtype: function """ assert isinstance(command, click.Command) def help_(self): # pylint: disable=unused-argument extra = {} ...
[ "def", "get_help", "(", "command", ")", ":", "assert", "isinstance", "(", "command", ",", "click", ".", "Command", ")", "def", "help_", "(", "self", ")", ":", "# pylint: disable=unused-argument", "extra", "=", "{", "}", "for", "key", ",", "value", "in", ...
Get the Cmd help function from the click command :param command: The click Command object :return: the help_* method for Cmd :rtype: function
[ "Get", "the", "Cmd", "help", "function", "from", "the", "click", "command", ":", "param", "command", ":", "The", "click", "Command", "object", ":", "return", ":", "the", "help_", "*", "method", "for", "Cmd", ":", "rtype", ":", "function" ]
train
https://github.com/clarkperkins/click-shell/blob/8d6e1a492176bc79e029d714f19d3156409656ea/click_shell/core.py#L59-L79
clarkperkins/click-shell
click_shell/core.py
get_complete
def get_complete(command): """ Get the Cmd complete function for the click command :param command: The click Command object :return: the complete_* method for Cmd :rtype: function """ assert isinstance(command, click.Command) def complete_(self, text, line, begidx, endidx): # pylint: ...
python
def get_complete(command): """ Get the Cmd complete function for the click command :param command: The click Command object :return: the complete_* method for Cmd :rtype: function """ assert isinstance(command, click.Command) def complete_(self, text, line, begidx, endidx): # pylint: ...
[ "def", "get_complete", "(", "command", ")", ":", "assert", "isinstance", "(", "command", ",", "click", ".", "Command", ")", "def", "complete_", "(", "self", ",", "text", ",", "line", ",", "begidx", ",", "endidx", ")", ":", "# pylint: disable=unused-argument"...
Get the Cmd complete function for the click command :param command: The click Command object :return: the complete_* method for Cmd :rtype: function
[ "Get", "the", "Cmd", "complete", "function", "for", "the", "click", "command", ":", "param", "command", ":", "The", "click", "Command", "object", ":", "return", ":", "the", "complete_", "*", "method", "for", "Cmd", ":", "rtype", ":", "function" ]
train
https://github.com/clarkperkins/click-shell/blob/8d6e1a492176bc79e029d714f19d3156409656ea/click_shell/core.py#L82-L102
glomex/gcdt
gcdt/kumo_main.py
load_template
def load_template(): """Bail out if template is not found. """ cloudformation, found = load_cloudformation_template() if not found: print(colored.red('could not load cloudformation.py, bailing out...')) sys.exit(1) return cloudformation
python
def load_template(): """Bail out if template is not found. """ cloudformation, found = load_cloudformation_template() if not found: print(colored.red('could not load cloudformation.py, bailing out...')) sys.exit(1) return cloudformation
[ "def", "load_template", "(", ")", ":", "cloudformation", ",", "found", "=", "load_cloudformation_template", "(", ")", "if", "not", "found", ":", "print", "(", "colored", ".", "red", "(", "'could not load cloudformation.py, bailing out...'", ")", ")", "sys", ".", ...
Bail out if template is not found.
[ "Bail", "out", "if", "template", "is", "not", "found", "." ]
train
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/kumo_main.py#L49-L56
ramses-tech/nefertari
nefertari/engine.py
_import_public_names
def _import_public_names(module): "Import public names from module into this module, like import *" self = sys.modules[__name__] for name in module.__all__: if hasattr(self, name): # don't overwrite existing names continue setattr(self, name, getattr(module, name))
python
def _import_public_names(module): "Import public names from module into this module, like import *" self = sys.modules[__name__] for name in module.__all__: if hasattr(self, name): # don't overwrite existing names continue setattr(self, name, getattr(module, name))
[ "def", "_import_public_names", "(", "module", ")", ":", "self", "=", "sys", ".", "modules", "[", "__name__", "]", "for", "name", "in", "module", ".", "__all__", ":", "if", "hasattr", "(", "self", ",", "name", ")", ":", "# don't overwrite existing names", "...
Import public names from module into this module, like import *
[ "Import", "public", "names", "from", "module", "into", "this", "module", "like", "import", "*" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/engine.py#L59-L66
scalative/haas
haas/haas_application.py
create_argument_parser
def create_argument_parser(): """Creates the argument parser for haas. """ parser = argparse.ArgumentParser(prog='haas') parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(haas.__version__)) verbosity = parser.add_mutually_exclusive_group() ...
python
def create_argument_parser(): """Creates the argument parser for haas. """ parser = argparse.ArgumentParser(prog='haas') parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(haas.__version__)) verbosity = parser.add_mutually_exclusive_group() ...
[ "def", "create_argument_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'haas'", ")", "parser", ".", "add_argument", "(", "'--version'", ",", "action", "=", "'version'", ",", "version", "=", "'%(prog)s {0}'", ".", ...
Creates the argument parser for haas.
[ "Creates", "the", "argument", "parser", "for", "haas", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/haas_application.py#L20-L50
scalative/haas
haas/haas_application.py
HaasApplication.run
def run(self, plugin_manager=None): """Run the haas test runner. This will load and configure the selected plugins, set up the environment and begin test discovery, loading and running. Parameters ---------- plugin_manager : haas.plugin_manager.PluginManager ...
python
def run(self, plugin_manager=None): """Run the haas test runner. This will load and configure the selected plugins, set up the environment and begin test discovery, loading and running. Parameters ---------- plugin_manager : haas.plugin_manager.PluginManager ...
[ "def", "run", "(", "self", ",", "plugin_manager", "=", "None", ")", ":", "if", "plugin_manager", "is", "None", ":", "plugin_manager", "=", "PluginManager", "(", ")", "plugin_manager", ".", "add_plugin_arguments", "(", "self", ".", "parser", ")", "args", "=",...
Run the haas test runner. This will load and configure the selected plugins, set up the environment and begin test discovery, loading and running. Parameters ---------- plugin_manager : haas.plugin_manager.PluginManager [Optional] Override the use of the default plu...
[ "Run", "the", "haas", "test", "runner", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/haas_application.py#L83-L133
ramses-tech/nefertari
nefertari/authentication/models.py
encrypt_password
def encrypt_password(**kwargs): """ Crypt :new_value: if it's not crypted yet. """ new_value = kwargs['new_value'] field = kwargs['field'] min_length = field.params['min_length'] if len(new_value) < min_length: raise ValueError( '`{}`: Value length must be more than {}'.format( ...
python
def encrypt_password(**kwargs): """ Crypt :new_value: if it's not crypted yet. """ new_value = kwargs['new_value'] field = kwargs['field'] min_length = field.params['min_length'] if len(new_value) < min_length: raise ValueError( '`{}`: Value length must be more than {}'.format( ...
[ "def", "encrypt_password", "(", "*", "*", "kwargs", ")", ":", "new_value", "=", "kwargs", "[", "'new_value'", "]", "field", "=", "kwargs", "[", "'field'", "]", "min_length", "=", "field", ".", "params", "[", "'min_length'", "]", "if", "len", "(", "new_va...
Crypt :new_value: if it's not crypted yet.
[ "Crypt", ":", "new_value", ":", "if", "it", "s", "not", "crypted", "yet", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L159-L171
ramses-tech/nefertari
nefertari/authentication/models.py
create_apikey_model
def create_apikey_model(user_model): """ Generate ApiKey model class and connect it with :user_model:. ApiKey is generated with relationship to user model class :user_model: as a One-to-One relationship with a backreference. ApiKey is set up to be auto-generated when a new :user_model: is created. ...
python
def create_apikey_model(user_model): """ Generate ApiKey model class and connect it with :user_model:. ApiKey is generated with relationship to user model class :user_model: as a One-to-One relationship with a backreference. ApiKey is set up to be auto-generated when a new :user_model: is created. ...
[ "def", "create_apikey_model", "(", "user_model", ")", ":", "try", ":", "return", "engine", ".", "get_document_cls", "(", "'ApiKey'", ")", "except", "ValueError", ":", "pass", "fk_kwargs", "=", "{", "'ref_column'", ":", "None", ",", "}", "if", "hasattr", "(",...
Generate ApiKey model class and connect it with :user_model:. ApiKey is generated with relationship to user model class :user_model: as a One-to-One relationship with a backreference. ApiKey is set up to be auto-generated when a new :user_model: is created. Returns ApiKey document class. If ApiKey is ...
[ "Generate", "ApiKey", "model", "class", "and", "connect", "it", "with", ":", "user_model", ":", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L195-L243
ramses-tech/nefertari
nefertari/authentication/models.py
cache_request_user
def cache_request_user(user_cls, request, user_id): """ Helper function to cache currently logged in user. User is cached at `request._user`. Caching happens only only if user is not already cached or if cached user's pk does not match `user_id`. :param user_cls: User model class to use for user l...
python
def cache_request_user(user_cls, request, user_id): """ Helper function to cache currently logged in user. User is cached at `request._user`. Caching happens only only if user is not already cached or if cached user's pk does not match `user_id`. :param user_cls: User model class to use for user l...
[ "def", "cache_request_user", "(", "user_cls", ",", "request", ",", "user_id", ")", ":", "pk_field", "=", "user_cls", ".", "pk_field", "(", ")", "user", "=", "getattr", "(", "request", ",", "'_user'", ",", "None", ")", "if", "user", "is", "None", "or", ...
Helper function to cache currently logged in user. User is cached at `request._user`. Caching happens only only if user is not already cached or if cached user's pk does not match `user_id`. :param user_cls: User model class to use for user lookup. :param request: Pyramid Request instance. :us...
[ "Helper", "function", "to", "cache", "currently", "logged", "in", "user", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L246-L260
ramses-tech/nefertari
nefertari/authentication/models.py
AuthModelMethodsMixin.get_token_credentials
def get_token_credentials(cls, username, request): """ Get api token for user with username of :username: Used by Token-based auth as `credentials_callback` kwarg. """ try: user = cls.get_item(username=username) except Exception as ex: log.error(str(ex)) ...
python
def get_token_credentials(cls, username, request): """ Get api token for user with username of :username: Used by Token-based auth as `credentials_callback` kwarg. """ try: user = cls.get_item(username=username) except Exception as ex: log.error(str(ex)) ...
[ "def", "get_token_credentials", "(", "cls", ",", "username", ",", "request", ")", ":", "try", ":", "user", "=", "cls", ".", "get_item", "(", "username", "=", "username", ")", "except", "Exception", "as", "ex", ":", "log", ".", "error", "(", "str", "(",...
Get api token for user with username of :username: Used by Token-based auth as `credentials_callback` kwarg.
[ "Get", "api", "token", "for", "user", "with", "username", "of", ":", "username", ":" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L42-L54
ramses-tech/nefertari
nefertari/authentication/models.py
AuthModelMethodsMixin.get_groups_by_token
def get_groups_by_token(cls, username, token, request): """ Get user's groups if user with :username: exists and their api key token equals :token: Used by Token-based authentication as `check` kwarg. """ try: user = cls.get_item(username=username) except Exc...
python
def get_groups_by_token(cls, username, token, request): """ Get user's groups if user with :username: exists and their api key token equals :token: Used by Token-based authentication as `check` kwarg. """ try: user = cls.get_item(username=username) except Exc...
[ "def", "get_groups_by_token", "(", "cls", ",", "username", ",", "token", ",", "request", ")", ":", "try", ":", "user", "=", "cls", ".", "get_item", "(", "username", "=", "username", ")", "except", "Exception", "as", "ex", ":", "log", ".", "error", "(",...
Get user's groups if user with :username: exists and their api key token equals :token: Used by Token-based authentication as `check` kwarg.
[ "Get", "user", "s", "groups", "if", "user", "with", ":", "username", ":", "exists", "and", "their", "api", "key", "token", "equals", ":", "token", ":" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L57-L71
ramses-tech/nefertari
nefertari/authentication/models.py
AuthModelMethodsMixin.authenticate_by_password
def authenticate_by_password(cls, params): """ Authenticate user with login and password from :params: Used both by Token and Ticket-based auths (called from views). """ def verify_password(user, password): return crypt.check(user.password, password) success = False...
python
def authenticate_by_password(cls, params): """ Authenticate user with login and password from :params: Used both by Token and Ticket-based auths (called from views). """ def verify_password(user, password): return crypt.check(user.password, password) success = False...
[ "def", "authenticate_by_password", "(", "cls", ",", "params", ")", ":", "def", "verify_password", "(", "user", ",", "password", ")", ":", "return", "crypt", ".", "check", "(", "user", ".", "password", ",", "password", ")", "success", "=", "False", "user", ...
Authenticate user with login and password from :params: Used both by Token and Ticket-based auths (called from views).
[ "Authenticate", "user", "with", "login", "and", "password", "from", ":", "params", ":" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L74-L94
ramses-tech/nefertari
nefertari/authentication/models.py
AuthModelMethodsMixin.get_groups_by_userid
def get_groups_by_userid(cls, userid, request): """ Return group identifiers of user with id :userid: Used by Ticket-based auth as `callback` kwarg. """ try: cache_request_user(cls, request, userid) except Exception as ex: log.error(str(ex)) f...
python
def get_groups_by_userid(cls, userid, request): """ Return group identifiers of user with id :userid: Used by Ticket-based auth as `callback` kwarg. """ try: cache_request_user(cls, request, userid) except Exception as ex: log.error(str(ex)) f...
[ "def", "get_groups_by_userid", "(", "cls", ",", "userid", ",", "request", ")", ":", "try", ":", "cache_request_user", "(", "cls", ",", "request", ",", "userid", ")", "except", "Exception", "as", "ex", ":", "log", ".", "error", "(", "str", "(", "ex", ")...
Return group identifiers of user with id :userid: Used by Ticket-based auth as `callback` kwarg.
[ "Return", "group", "identifiers", "of", "user", "with", "id", ":", "userid", ":" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L97-L109
ramses-tech/nefertari
nefertari/authentication/models.py
AuthModelMethodsMixin.create_account
def create_account(cls, params): """ Create auth user instance with data from :params:. Used by both Token and Ticket-based auths to register a user ( called from views). """ user_params = dictset(params).subset( ['username', 'email', 'password']) try: ...
python
def create_account(cls, params): """ Create auth user instance with data from :params:. Used by both Token and Ticket-based auths to register a user ( called from views). """ user_params = dictset(params).subset( ['username', 'email', 'password']) try: ...
[ "def", "create_account", "(", "cls", ",", "params", ")", ":", "user_params", "=", "dictset", "(", "params", ")", ".", "subset", "(", "[", "'username'", ",", "'email'", ",", "'password'", "]", ")", "try", ":", "return", "cls", ".", "get_or_create", "(", ...
Create auth user instance with data from :params:. Used by both Token and Ticket-based auths to register a user ( called from views).
[ "Create", "auth", "user", "instance", "with", "data", "from", ":", "params", ":", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L112-L125
ramses-tech/nefertari
nefertari/authentication/models.py
AuthModelMethodsMixin.get_authuser_by_userid
def get_authuser_by_userid(cls, request): """ Get user by ID. Used by Ticket-based auth. Is added as request method to populate `request.user`. """ userid = authenticated_userid(request) if userid: cache_request_user(cls, request, userid) return r...
python
def get_authuser_by_userid(cls, request): """ Get user by ID. Used by Ticket-based auth. Is added as request method to populate `request.user`. """ userid = authenticated_userid(request) if userid: cache_request_user(cls, request, userid) return r...
[ "def", "get_authuser_by_userid", "(", "cls", ",", "request", ")", ":", "userid", "=", "authenticated_userid", "(", "request", ")", "if", "userid", ":", "cache_request_user", "(", "cls", ",", "request", ",", "userid", ")", "return", "request", ".", "_user" ]
Get user by ID. Used by Ticket-based auth. Is added as request method to populate `request.user`.
[ "Get", "user", "by", "ID", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L128-L137
ramses-tech/nefertari
nefertari/authentication/models.py
AuthModelMethodsMixin.get_authuser_by_name
def get_authuser_by_name(cls, request): """ Get user by username Used by Token-based auth. Is added as request method to populate `request.user`. """ username = authenticated_userid(request) if username: return cls.get_item(username=username)
python
def get_authuser_by_name(cls, request): """ Get user by username Used by Token-based auth. Is added as request method to populate `request.user`. """ username = authenticated_userid(request) if username: return cls.get_item(username=username)
[ "def", "get_authuser_by_name", "(", "cls", ",", "request", ")", ":", "username", "=", "authenticated_userid", "(", "request", ")", "if", "username", ":", "return", "cls", ".", "get_item", "(", "username", "=", "username", ")" ]
Get user by username Used by Token-based auth. Is added as request method to populate `request.user`.
[ "Get", "user", "by", "username" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/models.py#L140-L148
tsileo/dirtools
dirtools.py
Dir.walk
def walk(self): """ Walk the directory like os.path (yields a 3-tuple (dirpath, dirnames, filenames) except it exclude all files/directories on the fly. """ for root, dirs, files in os.walk(self.path, topdown=True): # TODO relative walk, recursive call if root excluder found?...
python
def walk(self): """ Walk the directory like os.path (yields a 3-tuple (dirpath, dirnames, filenames) except it exclude all files/directories on the fly. """ for root, dirs, files in os.walk(self.path, topdown=True): # TODO relative walk, recursive call if root excluder found?...
[ "def", "walk", "(", "self", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "self", ".", "path", ",", "topdown", "=", "True", ")", ":", "# TODO relative walk, recursive call if root excluder found???", "#root_excluder = get_root...
Walk the directory like os.path (yields a 3-tuple (dirpath, dirnames, filenames) except it exclude all files/directories on the fly.
[ "Walk", "the", "directory", "like", "os", ".", "path", "(", "yields", "a", "3", "-", "tuple", "(", "dirpath", "dirnames", "filenames", ")", "except", "it", "exclude", "all", "files", "/", "directories", "on", "the", "fly", "." ]
train
https://github.com/tsileo/dirtools/blob/34be55b20b4ef506869487b5fa5c6ea020604f80/dirtools.py#L245-L265
ramses-tech/nefertari
nefertari/authentication/__init__.py
includeme
def includeme(config): """ Set up event subscribers. """ from .models import ( AuthUserMixin, random_uuid, lower_strip, encrypt_password, ) add_proc = config.add_field_processors add_proc( [random_uuid, lower_strip], model=AuthUserMixin, field='usernam...
python
def includeme(config): """ Set up event subscribers. """ from .models import ( AuthUserMixin, random_uuid, lower_strip, encrypt_password, ) add_proc = config.add_field_processors add_proc( [random_uuid, lower_strip], model=AuthUserMixin, field='usernam...
[ "def", "includeme", "(", "config", ")", ":", "from", ".", "models", "import", "(", "AuthUserMixin", ",", "random_uuid", ",", "lower_strip", ",", "encrypt_password", ",", ")", "add_proc", "=", "config", ".", "add_field_processors", "add_proc", "(", "[", "random...
Set up event subscribers.
[ "Set", "up", "event", "subscribers", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/__init__.py#L1-L14
loisaidasam/pyslack
pyslack/__init__.py
SlackClient._make_request
def _make_request(self, method, params): """Make request to API endpoint Note: Ignoring SSL cert validation due to intermittent failures http://requests.readthedocs.org/en/latest/user/advanced/#ssl-cert-verification """ if self.blocked_until is not None and \ dat...
python
def _make_request(self, method, params): """Make request to API endpoint Note: Ignoring SSL cert validation due to intermittent failures http://requests.readthedocs.org/en/latest/user/advanced/#ssl-cert-verification """ if self.blocked_until is not None and \ dat...
[ "def", "_make_request", "(", "self", ",", "method", ",", "params", ")", ":", "if", "self", ".", "blocked_until", "is", "not", "None", "and", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "<", "self", ".", "blocked_until", ":", "raise", "SlackErro...
Make request to API endpoint Note: Ignoring SSL cert validation due to intermittent failures http://requests.readthedocs.org/en/latest/user/advanced/#ssl-cert-verification
[ "Make", "request", "to", "API", "endpoint" ]
train
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L23-L49
loisaidasam/pyslack
pyslack/__init__.py
SlackClient.channels_list
def channels_list(self, exclude_archived=True, **params): """channels.list This method returns a list of all channels in the team. This includes channels the caller is in, channels they are not currently in, and archived channels. The number of (non-deactivated) members in each ...
python
def channels_list(self, exclude_archived=True, **params): """channels.list This method returns a list of all channels in the team. This includes channels the caller is in, channels they are not currently in, and archived channels. The number of (non-deactivated) members in each ...
[ "def", "channels_list", "(", "self", ",", "exclude_archived", "=", "True", ",", "*", "*", "params", ")", ":", "method", "=", "'channels.list'", "params", ".", "update", "(", "{", "'exclude_archived'", ":", "exclude_archived", "and", "1", "or", "0", "}", ")...
channels.list This method returns a list of all channels in the team. This includes channels the caller is in, channels they are not currently in, and archived channels. The number of (non-deactivated) members in each channel is also returned. https://api.slack.com/methods/chan...
[ "channels", ".", "list" ]
train
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L51-L63
loisaidasam/pyslack
pyslack/__init__.py
SlackClient.channel_name_to_id
def channel_name_to_id(self, channel_name, force_lookup=False): """Helper name for getting a channel's id from its name """ if force_lookup or not self.channel_name_id_map: channels = self.channels_list()['channels'] self.channel_name_id_map = {channel['name']: channel['i...
python
def channel_name_to_id(self, channel_name, force_lookup=False): """Helper name for getting a channel's id from its name """ if force_lookup or not self.channel_name_id_map: channels = self.channels_list()['channels'] self.channel_name_id_map = {channel['name']: channel['i...
[ "def", "channel_name_to_id", "(", "self", ",", "channel_name", ",", "force_lookup", "=", "False", ")", ":", "if", "force_lookup", "or", "not", "self", ".", "channel_name_id_map", ":", "channels", "=", "self", ".", "channels_list", "(", ")", "[", "'channels'", ...
Helper name for getting a channel's id from its name
[ "Helper", "name", "for", "getting", "a", "channel", "s", "id", "from", "its", "name" ]
train
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L65-L72
loisaidasam/pyslack
pyslack/__init__.py
SlackClient.chat_post_message
def chat_post_message(self, channel, text, **params): """chat.postMessage This method posts a message to a channel. https://api.slack.com/methods/chat.postMessage """ method = 'chat.postMessage' params.update({ 'channel': channel, 'text': text, ...
python
def chat_post_message(self, channel, text, **params): """chat.postMessage This method posts a message to a channel. https://api.slack.com/methods/chat.postMessage """ method = 'chat.postMessage' params.update({ 'channel': channel, 'text': text, ...
[ "def", "chat_post_message", "(", "self", ",", "channel", ",", "text", ",", "*", "*", "params", ")", ":", "method", "=", "'chat.postMessage'", "params", ".", "update", "(", "{", "'channel'", ":", "channel", ",", "'text'", ":", "text", ",", "}", ")", "re...
chat.postMessage This method posts a message to a channel. https://api.slack.com/methods/chat.postMessage
[ "chat", ".", "postMessage" ]
train
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L74-L86
loisaidasam/pyslack
pyslack/__init__.py
SlackClient.chat_update_message
def chat_update_message(self, channel, text, timestamp, **params): """chat.update This method updates a message. Required parameters: `channel`: Channel containing the message to be updated. (e.g: "C1234567890") `text`: New text for the message, using the default format...
python
def chat_update_message(self, channel, text, timestamp, **params): """chat.update This method updates a message. Required parameters: `channel`: Channel containing the message to be updated. (e.g: "C1234567890") `text`: New text for the message, using the default format...
[ "def", "chat_update_message", "(", "self", ",", "channel", ",", "text", ",", "timestamp", ",", "*", "*", "params", ")", ":", "method", "=", "'chat.update'", "if", "self", ".", "_channel_is_name", "(", "channel", ")", ":", "# chat.update only takes channel ids (n...
chat.update This method updates a message. Required parameters: `channel`: Channel containing the message to be updated. (e.g: "C1234567890") `text`: New text for the message, using the default formatting rules. (e.g: "Hello world") `timestamp`: Timestamp of the me...
[ "chat", ".", "update" ]
train
https://github.com/loisaidasam/pyslack/blob/bce0dcbe830b95ba548b58c7ceea07923589a8ec/pyslack/__init__.py#L88-L109
ramses-tech/nefertari
nefertari/polymorphic.py
includeme
def includeme(config): """ Connect view to route that catches all URIs like 'something,something,...' """ root = config.get_root_resource() root.add('nef_polymorphic', '{collections:.+,.+}', view=PolymorphicESView, factory=PolymorphicACL)
python
def includeme(config): """ Connect view to route that catches all URIs like 'something,something,...' """ root = config.get_root_resource() root.add('nef_polymorphic', '{collections:.+,.+}', view=PolymorphicESView, factory=PolymorphicACL)
[ "def", "includeme", "(", "config", ")", ":", "root", "=", "config", ".", "get_root_resource", "(", ")", "root", ".", "add", "(", "'nef_polymorphic'", ",", "'{collections:.+,.+}'", ",", "view", "=", "PolymorphicESView", ",", "factory", "=", "PolymorphicACL", ")...
Connect view to route that catches all URIs like 'something,something,...'
[ "Connect", "view", "to", "route", "that", "catches", "all", "URIs", "like", "something", "something", "..." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L37-L44
ramses-tech/nefertari
nefertari/polymorphic.py
PolymorphicHelperMixin.get_collections
def get_collections(self): """ Get names of collections from request matchdict. :return: Names of collections :rtype: list of str """ collections = self.request.matchdict['collections'].split('/')[0] collections = [coll.strip() for coll in collections.split(',')] ...
python
def get_collections(self): """ Get names of collections from request matchdict. :return: Names of collections :rtype: list of str """ collections = self.request.matchdict['collections'].split('/')[0] collections = [coll.strip() for coll in collections.split(',')] ...
[ "def", "get_collections", "(", "self", ")", ":", "collections", "=", "self", ".", "request", ".", "matchdict", "[", "'collections'", "]", ".", "split", "(", "'/'", ")", "[", "0", "]", "collections", "=", "[", "coll", ".", "strip", "(", ")", "for", "c...
Get names of collections from request matchdict. :return: Names of collections :rtype: list of str
[ "Get", "names", "of", "collections", "from", "request", "matchdict", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L52-L60
ramses-tech/nefertari
nefertari/polymorphic.py
PolymorphicHelperMixin.get_resources
def get_resources(self, collections): """ Get resources that correspond to values from :collections:. :param collections: Collection names for which resources should be gathered :type collections: list of str :return: Gathered resources :rtype: list of Resource insta...
python
def get_resources(self, collections): """ Get resources that correspond to values from :collections:. :param collections: Collection names for which resources should be gathered :type collections: list of str :return: Gathered resources :rtype: list of Resource insta...
[ "def", "get_resources", "(", "self", ",", "collections", ")", ":", "res_map", "=", "self", ".", "request", ".", "registry", ".", "_model_collections", "resources", "=", "[", "res", "for", "res", "in", "res_map", ".", "values", "(", ")", "if", "res", ".",...
Get resources that correspond to values from :collections:. :param collections: Collection names for which resources should be gathered :type collections: list of str :return: Gathered resources :rtype: list of Resource instances
[ "Get", "resources", "that", "correspond", "to", "values", "from", ":", "collections", ":", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L62-L75
ramses-tech/nefertari
nefertari/polymorphic.py
PolymorphicACL._get_least_permissions_aces
def _get_least_permissions_aces(self, resources): """ Get ACEs with the least permissions that fit all resources. To have access to polymorph on N collections, user MUST have access to all of them. If this is true, ACEs are returned, that allows 'view' permissions to current request pri...
python
def _get_least_permissions_aces(self, resources): """ Get ACEs with the least permissions that fit all resources. To have access to polymorph on N collections, user MUST have access to all of them. If this is true, ACEs are returned, that allows 'view' permissions to current request pri...
[ "def", "_get_least_permissions_aces", "(", "self", ",", "resources", ")", ":", "factories", "=", "[", "res", ".", "view", ".", "_factory", "for", "res", "in", "resources", "]", "contexts", "=", "[", "factory", "(", "self", ".", "request", ")", "for", "fa...
Get ACEs with the least permissions that fit all resources. To have access to polymorph on N collections, user MUST have access to all of them. If this is true, ACEs are returned, that allows 'view' permissions to current request principals. Otherwise None is returned thus blocking all...
[ "Get", "ACEs", "with", "the", "least", "permissions", "that", "fit", "all", "resources", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L89-L113
ramses-tech/nefertari
nefertari/polymorphic.py
PolymorphicACL.set_collections_acl
def set_collections_acl(self): """ Calculate and set ACL valid for requested collections. DENY_ALL is added to ACL to make sure no access rules are inherited. """ acl = [(Allow, 'g:admin', ALL_PERMISSIONS)] collections = self.get_collections() resources = self.ge...
python
def set_collections_acl(self): """ Calculate and set ACL valid for requested collections. DENY_ALL is added to ACL to make sure no access rules are inherited. """ acl = [(Allow, 'g:admin', ALL_PERMISSIONS)] collections = self.get_collections() resources = self.ge...
[ "def", "set_collections_acl", "(", "self", ")", ":", "acl", "=", "[", "(", "Allow", ",", "'g:admin'", ",", "ALL_PERMISSIONS", ")", "]", "collections", "=", "self", ".", "get_collections", "(", ")", "resources", "=", "self", ".", "get_resources", "(", "coll...
Calculate and set ACL valid for requested collections. DENY_ALL is added to ACL to make sure no access rules are inherited.
[ "Calculate", "and", "set", "ACL", "valid", "for", "requested", "collections", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L115-L129
ramses-tech/nefertari
nefertari/polymorphic.py
PolymorphicESView.determine_types
def determine_types(self): """ Determine ES type names from request data. In particular `request.matchdict['collections']` is used to determine types names. Its value is comma-separated sequence of collection names under which views have been registered. """ from neferta...
python
def determine_types(self): """ Determine ES type names from request data. In particular `request.matchdict['collections']` is used to determine types names. Its value is comma-separated sequence of collection names under which views have been registered. """ from neferta...
[ "def", "determine_types", "(", "self", ")", ":", "from", "nefertari", ".", "elasticsearch", "import", "ES", "collections", "=", "self", ".", "get_collections", "(", ")", "resources", "=", "self", ".", "get_resources", "(", "collections", ")", "models", "=", ...
Determine ES type names from request data. In particular `request.matchdict['collections']` is used to determine types names. Its value is comma-separated sequence of collection names under which views have been registered.
[ "Determine", "ES", "type", "names", "from", "request", "data", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/polymorphic.py#L155-L169
asyne/cproto
cproto/domains/factory.py
get_command
def get_command(domain_name, command_name): """Returns a closure function that dispatches message to the WebSocket.""" def send_command(self, **kwargs): return self.ws.send_message( '{0}.{1}'.format(domain_name, command_name), kwargs ) return send_command
python
def get_command(domain_name, command_name): """Returns a closure function that dispatches message to the WebSocket.""" def send_command(self, **kwargs): return self.ws.send_message( '{0}.{1}'.format(domain_name, command_name), kwargs ) return send_command
[ "def", "get_command", "(", "domain_name", ",", "command_name", ")", ":", "def", "send_command", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "ws", ".", "send_message", "(", "'{0}.{1}'", ".", "format", "(", "domain_name", ",", "c...
Returns a closure function that dispatches message to the WebSocket.
[ "Returns", "a", "closure", "function", "that", "dispatches", "message", "to", "the", "WebSocket", "." ]
train
https://github.com/asyne/cproto/blob/9c5cf5b8565fe5f8369b06e21d1dd069b9322e4b/cproto/domains/factory.py#L5-L13
asyne/cproto
cproto/domains/factory.py
DomainFactory
def DomainFactory(domain_name, cmds): """Dynamically create Domain class and set it's methods.""" klass = type(str(domain_name), (BaseDomain,), {}) for c in cmds: command = get_command(domain_name, c['name']) setattr(klass, c['name'], classmethod(command)) return klass
python
def DomainFactory(domain_name, cmds): """Dynamically create Domain class and set it's methods.""" klass = type(str(domain_name), (BaseDomain,), {}) for c in cmds: command = get_command(domain_name, c['name']) setattr(klass, c['name'], classmethod(command)) return klass
[ "def", "DomainFactory", "(", "domain_name", ",", "cmds", ")", ":", "klass", "=", "type", "(", "str", "(", "domain_name", ")", ",", "(", "BaseDomain", ",", ")", ",", "{", "}", ")", "for", "c", "in", "cmds", ":", "command", "=", "get_command", "(", "...
Dynamically create Domain class and set it's methods.
[ "Dynamically", "create", "Domain", "class", "and", "set", "it", "s", "methods", "." ]
train
https://github.com/asyne/cproto/blob/9c5cf5b8565fe5f8369b06e21d1dd069b9322e4b/cproto/domains/factory.py#L16-L24
ucsb-cs-education/hairball
hairball/__init__.py
main
def main(): """The entrypoint for the hairball command installed via setup.py.""" description = ('PATH can be either the path to a scratch file, or a ' 'directory containing scratch files. Multiple PATH ' 'arguments can be provided.') parser = OptionParser(usage='%prog ...
python
def main(): """The entrypoint for the hairball command installed via setup.py.""" description = ('PATH can be either the path to a scratch file, or a ' 'directory containing scratch files. Multiple PATH ' 'arguments can be provided.') parser = OptionParser(usage='%prog ...
[ "def", "main", "(", ")", ":", "description", "=", "(", "'PATH can be either the path to a scratch file, or a '", "'directory containing scratch files. Multiple PATH '", "'arguments can be provided.'", ")", "parser", "=", "OptionParser", "(", "usage", "=", "'%prog -p PLUGIN_NAME [...
The entrypoint for the hairball command installed via setup.py.
[ "The", "entrypoint", "for", "the", "hairball", "command", "installed", "via", "setup", ".", "py", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L238-L281
ucsb-cs-education/hairball
hairball/__init__.py
KurtCache.path_to_key
def path_to_key(filepath): """Return the sha1sum (key) belonging to the file at filepath.""" tmp, last = os.path.split(filepath) tmp, middle = os.path.split(tmp) return '{}{}{}'.format(os.path.basename(tmp), middle, os.path.splitext(last)[0])
python
def path_to_key(filepath): """Return the sha1sum (key) belonging to the file at filepath.""" tmp, last = os.path.split(filepath) tmp, middle = os.path.split(tmp) return '{}{}{}'.format(os.path.basename(tmp), middle, os.path.splitext(last)[0])
[ "def", "path_to_key", "(", "filepath", ")", ":", "tmp", ",", "last", "=", "os", ".", "path", ".", "split", "(", "filepath", ")", "tmp", ",", "middle", "=", "os", ".", "path", ".", "split", "(", "tmp", ")", "return", "'{}{}{}'", ".", "format", "(", ...
Return the sha1sum (key) belonging to the file at filepath.
[ "Return", "the", "sha1sum", "(", "key", ")", "belonging", "to", "the", "file", "at", "filepath", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L29-L34
ucsb-cs-education/hairball
hairball/__init__.py
KurtCache.key_to_path
def key_to_path(self, key): """Return the fullpath to the file with sha1sum key.""" return os.path.join(self.cache_dir, key[:2], key[2:4], key[4:] + '.pkl')
python
def key_to_path(self, key): """Return the fullpath to the file with sha1sum key.""" return os.path.join(self.cache_dir, key[:2], key[2:4], key[4:] + '.pkl')
[ "def", "key_to_path", "(", "self", ",", "key", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "cache_dir", ",", "key", "[", ":", "2", "]", ",", "key", "[", "2", ":", "4", "]", ",", "key", "[", "4", ":", "]", "+", "'.p...
Return the fullpath to the file with sha1sum key.
[ "Return", "the", "fullpath", "to", "the", "file", "with", "sha1sum", "key", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L53-L56
ucsb-cs-education/hairball
hairball/__init__.py
KurtCache.load
def load(self, filename): """Optimized load and return the parsed version of filename. Uses the on-disk parse cache if the file is located in it. """ # Compute sha1 hash (key) with open(filename) as fp: key = sha1(fp.read()).hexdigest() path = self.key_to_pa...
python
def load(self, filename): """Optimized load and return the parsed version of filename. Uses the on-disk parse cache if the file is located in it. """ # Compute sha1 hash (key) with open(filename) as fp: key = sha1(fp.read()).hexdigest() path = self.key_to_pa...
[ "def", "load", "(", "self", ",", "filename", ")", ":", "# Compute sha1 hash (key)", "with", "open", "(", "filename", ")", "as", "fp", ":", "key", "=", "sha1", "(", "fp", ".", "read", "(", ")", ")", ".", "hexdigest", "(", ")", "path", "=", "self", "...
Optimized load and return the parsed version of filename. Uses the on-disk parse cache if the file is located in it.
[ "Optimized", "load", "and", "return", "the", "parsed", "version", "of", "filename", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L58-L91
ucsb-cs-education/hairball
hairball/__init__.py
Hairball.hairball_files
def hairball_files(self, paths, extensions): """Yield filepath to files with the proper extension within paths.""" def add_file(filename): return os.path.splitext(filename)[1] in extensions while paths: arg_path = paths.pop(0) if os.path.isdir(arg_path): ...
python
def hairball_files(self, paths, extensions): """Yield filepath to files with the proper extension within paths.""" def add_file(filename): return os.path.splitext(filename)[1] in extensions while paths: arg_path = paths.pop(0) if os.path.isdir(arg_path): ...
[ "def", "hairball_files", "(", "self", ",", "paths", ",", "extensions", ")", ":", "def", "add_file", "(", "filename", ")", ":", "return", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", "in", "extensions", "while", "paths", ":",...
Yield filepath to files with the proper extension within paths.
[ "Yield", "filepath", "to", "files", "with", "the", "proper", "extension", "within", "paths", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L136-L158
ucsb-cs-education/hairball
hairball/__init__.py
Hairball.initialize_plugins
def initialize_plugins(self): """Attempt to Load and initialize all the plugins. Any issues loading plugins will be output to stderr. """ for plugin_name in self.options.plugin: parts = plugin_name.split('.') if len(parts) > 1: module_name = '.'....
python
def initialize_plugins(self): """Attempt to Load and initialize all the plugins. Any issues loading plugins will be output to stderr. """ for plugin_name in self.options.plugin: parts = plugin_name.split('.') if len(parts) > 1: module_name = '.'....
[ "def", "initialize_plugins", "(", "self", ")", ":", "for", "plugin_name", "in", "self", ".", "options", ".", "plugin", ":", "parts", "=", "plugin_name", ".", "split", "(", "'.'", ")", "if", "len", "(", "parts", ")", ">", "1", ":", "module_name", "=", ...
Attempt to Load and initialize all the plugins. Any issues loading plugins will be output to stderr.
[ "Attempt", "to", "Load", "and", "initialize", "all", "the", "plugins", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L170-L212
ucsb-cs-education/hairball
hairball/__init__.py
Hairball.process
def process(self): """Run the analysis across all files found in the given paths. Each file is loaded once and all plugins are run against it before loading the next file. """ for filename in self.hairball_files(self.paths, self.extensions): if not self.options.quie...
python
def process(self): """Run the analysis across all files found in the given paths. Each file is loaded once and all plugins are run against it before loading the next file. """ for filename in self.hairball_files(self.paths, self.extensions): if not self.options.quie...
[ "def", "process", "(", "self", ")", ":", "for", "filename", "in", "self", ".", "hairball_files", "(", "self", ".", "paths", ",", "self", ".", "extensions", ")", ":", "if", "not", "self", ".", "options", ".", "quiet", ":", "print", "(", "filename", ")...
Run the analysis across all files found in the given paths. Each file is loaded once and all plugins are run against it before loading the next file.
[ "Run", "the", "analysis", "across", "all", "files", "found", "in", "the", "given", "paths", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/__init__.py#L214-L234
ramses-tech/nefertari
nefertari/utils/utils.py
maybe_dotted
def maybe_dotted(module, throw=True): """ If ``module`` is a dotted string pointing to the module, imports and returns the module object. """ try: return Configurator().maybe_dotted(module) except ImportError as e: err = '%s not found. %s' % (module, e) if throw: ...
python
def maybe_dotted(module, throw=True): """ If ``module`` is a dotted string pointing to the module, imports and returns the module object. """ try: return Configurator().maybe_dotted(module) except ImportError as e: err = '%s not found. %s' % (module, e) if throw: ...
[ "def", "maybe_dotted", "(", "module", ",", "throw", "=", "True", ")", ":", "try", ":", "return", "Configurator", "(", ")", ".", "maybe_dotted", "(", "module", ")", "except", "ImportError", "as", "e", ":", "err", "=", "'%s not found. %s'", "%", "(", "modu...
If ``module`` is a dotted string pointing to the module, imports and returns the module object.
[ "If", "module", "is", "a", "dotted", "string", "pointing", "to", "the", "module", "imports", "and", "returns", "the", "module", "object", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L95-L107
ramses-tech/nefertari
nefertari/utils/utils.py
issequence
def issequence(arg): """Return True if `arg` acts as a list and does not look like a string.""" string_behaviour = ( isinstance(arg, six.string_types) or isinstance(arg, six.text_type)) list_behaviour = hasattr(arg, '__getitem__') or hasattr(arg, '__iter__') return not string_behaviour a...
python
def issequence(arg): """Return True if `arg` acts as a list and does not look like a string.""" string_behaviour = ( isinstance(arg, six.string_types) or isinstance(arg, six.text_type)) list_behaviour = hasattr(arg, '__getitem__') or hasattr(arg, '__iter__') return not string_behaviour a...
[ "def", "issequence", "(", "arg", ")", ":", "string_behaviour", "=", "(", "isinstance", "(", "arg", ",", "six", ".", "string_types", ")", "or", "isinstance", "(", "arg", ",", "six", ".", "text_type", ")", ")", "list_behaviour", "=", "hasattr", "(", "arg",...
Return True if `arg` acts as a list and does not look like a string.
[ "Return", "True", "if", "arg", "acts", "as", "a", "list", "and", "does", "not", "look", "like", "a", "string", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L127-L133
ramses-tech/nefertari
nefertari/utils/utils.py
merge_dicts
def merge_dicts(a, b, path=None): """ Merge dict :b: into dict :a: Code snippet from http://stackoverflow.com/a/7205107 """ if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge_dicts(a[key]...
python
def merge_dicts(a, b, path=None): """ Merge dict :b: into dict :a: Code snippet from http://stackoverflow.com/a/7205107 """ if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge_dicts(a[key]...
[ "def", "merge_dicts", "(", "a", ",", "b", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "[", "]", "for", "key", "in", "b", ":", "if", "key", "in", "a", ":", "if", "isinstance", "(", "a", "[", "key", "]", ...
Merge dict :b: into dict :a: Code snippet from http://stackoverflow.com/a/7205107
[ "Merge", "dict", ":", "b", ":", "into", "dict", ":", "a", ":" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L136-L155
ramses-tech/nefertari
nefertari/utils/utils.py
str2dict
def str2dict(dotted_str, value=None, separator='.'): """ Convert dotted string to dict splitting by :separator: """ dict_ = {} parts = dotted_str.split(separator) d, prev = dict_, None for part in parts: prev = d d = d.setdefault(part, {}) else: if value is not None: ...
python
def str2dict(dotted_str, value=None, separator='.'): """ Convert dotted string to dict splitting by :separator: """ dict_ = {} parts = dotted_str.split(separator) d, prev = dict_, None for part in parts: prev = d d = d.setdefault(part, {}) else: if value is not None: ...
[ "def", "str2dict", "(", "dotted_str", ",", "value", "=", "None", ",", "separator", "=", "'.'", ")", ":", "dict_", "=", "{", "}", "parts", "=", "dotted_str", ".", "split", "(", "separator", ")", "d", ",", "prev", "=", "dict_", ",", "None", "for", "p...
Convert dotted string to dict splitting by :separator:
[ "Convert", "dotted", "string", "to", "dict", "splitting", "by", ":", "separator", ":" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L158-L169
ramses-tech/nefertari
nefertari/utils/utils.py
validate_data_privacy
def validate_data_privacy(request, data, wrapper_kw=None): """ Validate :data: contains only data allowed by privacy settings. :param request: Pyramid Request instance :param data: Dict containing request/response data which should be validated """ from nefertari import wrappers if wrap...
python
def validate_data_privacy(request, data, wrapper_kw=None): """ Validate :data: contains only data allowed by privacy settings. :param request: Pyramid Request instance :param data: Dict containing request/response data which should be validated """ from nefertari import wrappers if wrap...
[ "def", "validate_data_privacy", "(", "request", ",", "data", ",", "wrapper_kw", "=", "None", ")", ":", "from", "nefertari", "import", "wrappers", "if", "wrapper_kw", "is", "None", ":", "wrapper_kw", "=", "{", "}", "wrapper", "=", "wrappers", ".", "apply_priv...
Validate :data: contains only data allowed by privacy settings. :param request: Pyramid Request instance :param data: Dict containing request/response data which should be validated
[ "Validate", ":", "data", ":", "contains", "only", "data", "allowed", "by", "privacy", "settings", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L172-L190
ramses-tech/nefertari
nefertari/utils/utils.py
drop_reserved_params
def drop_reserved_params(params): """ Drops reserved params """ from nefertari import RESERVED_PARAMS params = params.copy() for reserved_param in RESERVED_PARAMS: if reserved_param in params: params.pop(reserved_param) return params
python
def drop_reserved_params(params): """ Drops reserved params """ from nefertari import RESERVED_PARAMS params = params.copy() for reserved_param in RESERVED_PARAMS: if reserved_param in params: params.pop(reserved_param) return params
[ "def", "drop_reserved_params", "(", "params", ")", ":", "from", "nefertari", "import", "RESERVED_PARAMS", "params", "=", "params", ".", "copy", "(", ")", "for", "reserved_param", "in", "RESERVED_PARAMS", ":", "if", "reserved_param", "in", "params", ":", "params"...
Drops reserved params
[ "Drops", "reserved", "params" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L193-L200
jmoore987/sharp_aquos_rc
sharp_aquos_rc/tv.py
TV._send_command_raw
def _send_command_raw(self, command, opt=''): """ Description: The TV doesn't handle long running connections very well, so we open a new connection every time. There might be a better way to do this, but it's pretty quick and resilient. Returns:...
python
def _send_command_raw(self, command, opt=''): """ Description: The TV doesn't handle long running connections very well, so we open a new connection every time. There might be a better way to do this, but it's pretty quick and resilient. Returns:...
[ "def", "_send_command_raw", "(", "self", ",", "command", ",", "opt", "=", "''", ")", ":", "# According to the documentation:", "# http://files.sharpusa.com/Downloads/ForHome/", "# HomeEntertainment/LCDTVs/Manuals/tel_man_LC40_46_52_60LE830U.pdf", "# Page 58 - Communication conditions f...
Description: The TV doesn't handle long running connections very well, so we open a new connection every time. There might be a better way to do this, but it's pretty quick and resilient. Returns: If a value is being requested ( opt2 is "?" ), ...
[ "Description", ":" ]
train
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L37-L95
jmoore987/sharp_aquos_rc
sharp_aquos_rc/tv.py
TV.info
def info(self): """ Description: Returns dict of information about the TV name, model, version """ return {"name": self._send_command('name'), "model": self._send_command('model'), "version": self._send_command('version'), ...
python
def info(self): """ Description: Returns dict of information about the TV name, model, version """ return {"name": self._send_command('name'), "model": self._send_command('model'), "version": self._send_command('version'), ...
[ "def", "info", "(", "self", ")", ":", "return", "{", "\"name\"", ":", "self", ".", "_send_command", "(", "'name'", ")", ",", "\"model\"", ":", "self", ".", "_send_command", "(", "'model'", ")", ",", "\"version\"", ":", "self", ".", "_send_command", "(", ...
Description: Returns dict of information about the TV name, model, version
[ "Description", ":" ]
train
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L115-L127
jmoore987/sharp_aquos_rc
sharp_aquos_rc/tv.py
TV.get_input_list
def get_input_list(self): """ Description: Get input list Returns an ordered list of all available input keys and names """ inputs = [' '] * len(self.command['input']) for key in self.command['input']: inputs[self.command['input'][key]['order...
python
def get_input_list(self): """ Description: Get input list Returns an ordered list of all available input keys and names """ inputs = [' '] * len(self.command['input']) for key in self.command['input']: inputs[self.command['input'][key]['order...
[ "def", "get_input_list", "(", "self", ")", ":", "inputs", "=", "[", "' '", "]", "*", "len", "(", "self", ".", "command", "[", "'input'", "]", ")", "for", "key", "in", "self", ".", "command", "[", "'input'", "]", ":", "inputs", "[", "self", ".", "...
Description: Get input list Returns an ordered list of all available input keys and names
[ "Description", ":" ]
train
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L158-L169
jmoore987/sharp_aquos_rc
sharp_aquos_rc/tv.py
TV.input
def input(self, opt): """ Description: Set the input Call with no arguments to get current setting Arguments: opt: string Name provided from input list or key from yaml ("HDMI 1" or "hdmi_1") """ for key in self.command['inpu...
python
def input(self, opt): """ Description: Set the input Call with no arguments to get current setting Arguments: opt: string Name provided from input list or key from yaml ("HDMI 1" or "hdmi_1") """ for key in self.command['inpu...
[ "def", "input", "(", "self", ",", "opt", ")", ":", "for", "key", "in", "self", ".", "command", "[", "'input'", "]", ":", "if", "(", "key", "==", "opt", ")", "or", "(", "self", ".", "command", "[", "'input'", "]", "[", "key", "]", "[", "'name'",...
Description: Set the input Call with no arguments to get current setting Arguments: opt: string Name provided from input list or key from yaml ("HDMI 1" or "hdmi_1")
[ "Description", ":" ]
train
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L171-L186
jmoore987/sharp_aquos_rc
sharp_aquos_rc/tv.py
TV.digital_channel_air
def digital_channel_air(self, opt1='?', opt2='?'): """ Description: Change Channel (Digital) Pass Channels "XX.YY" as TV.digital_channel_air(XX, YY) Arguments: opt1: integer 1-99: Major Channel opt2: integer (optional) ...
python
def digital_channel_air(self, opt1='?', opt2='?'): """ Description: Change Channel (Digital) Pass Channels "XX.YY" as TV.digital_channel_air(XX, YY) Arguments: opt1: integer 1-99: Major Channel opt2: integer (optional) ...
[ "def", "digital_channel_air", "(", "self", ",", "opt1", "=", "'?'", ",", "opt2", "=", "'?'", ")", ":", "if", "opt1", "==", "'?'", ":", "parameter", "=", "'?'", "elif", "opt2", "==", "'?'", ":", "parameter", "=", "str", "(", "opt1", ")", ".", "rjust...
Description: Change Channel (Digital) Pass Channels "XX.YY" as TV.digital_channel_air(XX, YY) Arguments: opt1: integer 1-99: Major Channel opt2: integer (optional) 1-99: Minor Channel
[ "Description", ":" ]
train
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L330-L349
jmoore987/sharp_aquos_rc
sharp_aquos_rc/tv.py
TV.digital_channel_cable
def digital_channel_cable(self, opt1='?', opt2=0): """ Description: Change Channel (Digital) Pass Channels "XXX.YYY" as TV.digital_channel_cable(XXX, YYY) Arguments: opt1: integer 1-999: Major Channel opt2: integer (optional) ...
python
def digital_channel_cable(self, opt1='?', opt2=0): """ Description: Change Channel (Digital) Pass Channels "XXX.YYY" as TV.digital_channel_cable(XXX, YYY) Arguments: opt1: integer 1-999: Major Channel opt2: integer (optional) ...
[ "def", "digital_channel_cable", "(", "self", ",", "opt1", "=", "'?'", ",", "opt2", "=", "0", ")", ":", "if", "opt1", "==", "'?'", ":", "parameter", "=", "'?'", "elif", "self", ".", "command", "[", "'digital_channel_cable_minor'", "]", "==", "''", ":", ...
Description: Change Channel (Digital) Pass Channels "XXX.YYY" as TV.digital_channel_cable(XXX, YYY) Arguments: opt1: integer 1-999: Major Channel opt2: integer (optional) 0-999: Minor Channel
[ "Description", ":" ]
train
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L351-L371
jmoore987/sharp_aquos_rc
sharp_aquos_rc/tv.py
TV.get_remote_button_list
def get_remote_button_list(self): """ Description: Get remote button list Returns an list of all available remote buttons """ remote_buttons = [] for key in self.command['remote']: if self.command['remote'][key] != '': remote_...
python
def get_remote_button_list(self): """ Description: Get remote button list Returns an list of all available remote buttons """ remote_buttons = [] for key in self.command['remote']: if self.command['remote'][key] != '': remote_...
[ "def", "get_remote_button_list", "(", "self", ")", ":", "remote_buttons", "=", "[", "]", "for", "key", "in", "self", ".", "command", "[", "'remote'", "]", ":", "if", "self", ".", "command", "[", "'remote'", "]", "[", "key", "]", "!=", "''", ":", "rem...
Description: Get remote button list Returns an list of all available remote buttons
[ "Description", ":" ]
train
https://github.com/jmoore987/sharp_aquos_rc/blob/9a5a1140241a866150dea2d26555680dc8e7f057/sharp_aquos_rc/tv.py#L387-L399
ucsb-cs-education/hairball
hairball/plugins/checks.py
Animation.check_results
def check_results(tmp_): """Return a 3 tuple for something.""" # TODO: Fix this to work with more meaningful names if tmp_['t'] > 0: if tmp_['l'] > 0: if tmp_['rr'] > 0 or tmp_['ra'] > 1: print 1, 3, tmp_ return 3 ...
python
def check_results(tmp_): """Return a 3 tuple for something.""" # TODO: Fix this to work with more meaningful names if tmp_['t'] > 0: if tmp_['l'] > 0: if tmp_['rr'] > 0 or tmp_['ra'] > 1: print 1, 3, tmp_ return 3 ...
[ "def", "check_results", "(", "tmp_", ")", ":", "# TODO: Fix this to work with more meaningful names", "if", "tmp_", "[", "'t'", "]", ">", "0", ":", "if", "tmp_", "[", "'l'", "]", ">", "0", ":", "if", "tmp_", "[", "'rr'", "]", ">", "0", "or", "tmp_", "[...
Return a 3 tuple for something.
[ "Return", "a", "3", "tuple", "for", "something", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L28-L62
ucsb-cs-education/hairball
hairball/plugins/checks.py
Animation._check_animation
def _check_animation(self, last, last_level, gen): """Internal helper function to check the animation.""" tmp_ = Counter() results = Counter() name, level, block = last, last_level, last others = False while name in self.ANIMATION and level >= last_level: if n...
python
def _check_animation(self, last, last_level, gen): """Internal helper function to check the animation.""" tmp_ = Counter() results = Counter() name, level, block = last, last_level, last others = False while name in self.ANIMATION and level >= last_level: if n...
[ "def", "_check_animation", "(", "self", ",", "last", ",", "last_level", ",", "gen", ")", ":", "tmp_", "=", "Counter", "(", ")", "results", "=", "Counter", "(", ")", "name", ",", "level", ",", "block", "=", "last", ",", "last_level", ",", "last", "oth...
Internal helper function to check the animation.
[ "Internal", "helper", "function", "to", "check", "the", "animation", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L64-L99
ucsb-cs-education/hairball
hairball/plugins/checks.py
Animation.analyze
def analyze(self, scratch, **kwargs): """Run and return the results from the Animation plugin.""" results = Counter() for script in self.iter_scripts(scratch): gen = self.iter_blocks(script.blocks) name = 'start' level = None while name != '': ...
python
def analyze(self, scratch, **kwargs): """Run and return the results from the Animation plugin.""" results = Counter() for script in self.iter_scripts(scratch): gen = self.iter_blocks(script.blocks) name = 'start' level = None while name != '': ...
[ "def", "analyze", "(", "self", ",", "scratch", ",", "*", "*", "kwargs", ")", ":", "results", "=", "Counter", "(", ")", "for", "script", "in", "self", ".", "iter_scripts", "(", "scratch", ")", ":", "gen", "=", "self", ".", "iter_blocks", "(", "script"...
Run and return the results from the Animation plugin.
[ "Run", "and", "return", "the", "results", "from", "the", "Animation", "plugin", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L101-L113
ucsb-cs-education/hairball
hairball/plugins/checks.py
BroadcastReceive.get_receive
def get_receive(self, script_list): """Return a list of received events contained in script_list.""" events = defaultdict(set) for script in script_list: if self.script_start_type(script) == self.HAT_WHEN_I_RECEIVE: event = script.blocks[0].args[0].lower() ...
python
def get_receive(self, script_list): """Return a list of received events contained in script_list.""" events = defaultdict(set) for script in script_list: if self.script_start_type(script) == self.HAT_WHEN_I_RECEIVE: event = script.blocks[0].args[0].lower() ...
[ "def", "get_receive", "(", "self", ",", "script_list", ")", ":", "events", "=", "defaultdict", "(", "set", ")", "for", "script", "in", "script_list", ":", "if", "self", ".", "script_start_type", "(", "script", ")", "==", "self", ".", "HAT_WHEN_I_RECEIVE", ...
Return a list of received events contained in script_list.
[ "Return", "a", "list", "of", "received", "events", "contained", "in", "script_list", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L120-L127
ucsb-cs-education/hairball
hairball/plugins/checks.py
BroadcastReceive.analyze
def analyze(self, scratch, **kwargs): """Run and return the results from the BroadcastReceive plugin.""" all_scripts = list(self.iter_scripts(scratch)) results = defaultdict(set) broadcast = dict((x, self.get_broadcast_events(x)) # Events by script for x in all_...
python
def analyze(self, scratch, **kwargs): """Run and return the results from the BroadcastReceive plugin.""" all_scripts = list(self.iter_scripts(scratch)) results = defaultdict(set) broadcast = dict((x, self.get_broadcast_events(x)) # Events by script for x in all_...
[ "def", "analyze", "(", "self", ",", "scratch", ",", "*", "*", "kwargs", ")", ":", "all_scripts", "=", "list", "(", "self", ".", "iter_scripts", "(", "scratch", ")", ")", "results", "=", "defaultdict", "(", "set", ")", "broadcast", "=", "dict", "(", "...
Run and return the results from the BroadcastReceive plugin.
[ "Run", "and", "return", "the", "results", "from", "the", "BroadcastReceive", "plugin", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L129-L175
ucsb-cs-education/hairball
hairball/plugins/checks.py
SaySoundSync.analyze
def analyze(self, scratch, **kwargs): """Categorize instances of attempted say and sound synchronization.""" errors = Counter() for script in self.iter_scripts(scratch): prev_name, prev_depth, prev_block = '', 0, script.blocks[0] gen = self.iter_blocks(script.blocks) ...
python
def analyze(self, scratch, **kwargs): """Categorize instances of attempted say and sound synchronization.""" errors = Counter() for script in self.iter_scripts(scratch): prev_name, prev_depth, prev_block = '', 0, script.blocks[0] gen = self.iter_blocks(script.blocks) ...
[ "def", "analyze", "(", "self", ",", "scratch", ",", "*", "*", "kwargs", ")", ":", "errors", "=", "Counter", "(", ")", "for", "script", "in", "self", ".", "iter_scripts", "(", "scratch", ")", ":", "prev_name", ",", "prev_depth", ",", "prev_block", "=", ...
Categorize instances of attempted say and sound synchronization.
[ "Categorize", "instances", "of", "attempted", "say", "and", "sound", "synchronization", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L203-L233
ucsb-cs-education/hairball
hairball/plugins/checks.py
SaySoundSync.check
def check(self, gen): """Check that the last part of the chain matches. TODO: Fix to handle the following situation that appears to not work say 'message 1' play sound until done say 'message 2' say 'message 3' play sound until done say '' """ ...
python
def check(self, gen): """Check that the last part of the chain matches. TODO: Fix to handle the following situation that appears to not work say 'message 1' play sound until done say 'message 2' say 'message 3' play sound until done say '' """ ...
[ "def", "check", "(", "self", ",", "gen", ")", ":", "retval", "=", "Counter", "(", ")", "name", ",", "_", ",", "block", "=", "next", "(", "gen", ",", "(", "''", ",", "0", ",", "''", ")", ")", "if", "name", "in", "self", ".", "SAY_THINK", ":", ...
Check that the last part of the chain matches. TODO: Fix to handle the following situation that appears to not work say 'message 1' play sound until done say 'message 2' say 'message 3' play sound until done say ''
[ "Check", "that", "the", "last", "part", "of", "the", "chain", "matches", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L235-L265
scalative/haas
haas/result.py
_format_exception
def _format_exception(err, is_failure, stdout=None, stderr=None): """Converts a sys.exc_info()-style tuple of values into a string.""" exctype, value, tb = err # Skip test runner traceback levels while tb and _is_relevant_tb_level(tb): tb = tb.tb_next if is_failure: # Skip assert*()...
python
def _format_exception(err, is_failure, stdout=None, stderr=None): """Converts a sys.exc_info()-style tuple of values into a string.""" exctype, value, tb = err # Skip test runner traceback levels while tb and _is_relevant_tb_level(tb): tb = tb.tb_next if is_failure: # Skip assert*()...
[ "def", "_format_exception", "(", "err", ",", "is_failure", ",", "stdout", "=", "None", ",", "stderr", "=", "None", ")", ":", "exctype", ",", "value", ",", "tb", "=", "err", "# Skip test runner traceback levels", "while", "tb", "and", "_is_relevant_tb_level", "...
Converts a sys.exc_info()-style tuple of values into a string.
[ "Converts", "a", "sys", ".", "exc_info", "()", "-", "style", "tuple", "of", "values", "into", "a", "string", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L76-L101
scalative/haas
haas/result.py
ResultCollector._setup_stdout
def _setup_stdout(self): """Hook stdout and stderr if buffering is enabled. """ if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = StringIO() self._stdout_buffer = StringIO() sys.stdout = self._stdout_buffer ...
python
def _setup_stdout(self): """Hook stdout and stderr if buffering is enabled. """ if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = StringIO() self._stdout_buffer = StringIO() sys.stdout = self._stdout_buffer ...
[ "def", "_setup_stdout", "(", "self", ")", ":", "if", "self", ".", "buffer", ":", "if", "self", ".", "_stderr_buffer", "is", "None", ":", "self", ".", "_stderr_buffer", "=", "StringIO", "(", ")", "self", ".", "_stdout_buffer", "=", "StringIO", "(", ")", ...
Hook stdout and stderr if buffering is enabled.
[ "Hook", "stdout", "and", "stderr", "if", "buffering", "is", "enabled", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L365-L374
scalative/haas
haas/result.py
ResultCollector._restore_stdout
def _restore_stdout(self): """Unhook stdout and stderr if buffering is enabled. """ if self.buffer: if self._mirror_output: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endsw...
python
def _restore_stdout(self): """Unhook stdout and stderr if buffering is enabled. """ if self.buffer: if self._mirror_output: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endsw...
[ "def", "_restore_stdout", "(", "self", ")", ":", "if", "self", ".", "buffer", ":", "if", "self", ".", "_mirror_output", ":", "output", "=", "sys", ".", "stdout", ".", "getvalue", "(", ")", "error", "=", "sys", ".", "stderr", ".", "getvalue", "(", ")"...
Unhook stdout and stderr if buffering is enabled.
[ "Unhook", "stdout", "and", "stderr", "if", "buffering", "is", "enabled", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L376-L398
scalative/haas
haas/result.py
ResultCollector.add_result_handler
def add_result_handler(self, handler): """Register a new result handler. """ self._result_handlers.append(handler) # Reset sorted handlers if self._sorted_handlers: self._sorted_handlers = None
python
def add_result_handler(self, handler): """Register a new result handler. """ self._result_handlers.append(handler) # Reset sorted handlers if self._sorted_handlers: self._sorted_handlers = None
[ "def", "add_result_handler", "(", "self", ",", "handler", ")", ":", "self", ".", "_result_handlers", ".", "append", "(", "handler", ")", "# Reset sorted handlers", "if", "self", ".", "_sorted_handlers", ":", "self", ".", "_sorted_handlers", "=", "None" ]
Register a new result handler.
[ "Register", "a", "new", "result", "handler", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L404-L411
scalative/haas
haas/result.py
ResultCollector.add_result
def add_result(self, result): """Add an already-constructed :class:`~.TestResult` to this :class:`~.ResultCollector`. This may be used when collecting results created by other ResultCollectors (e.g. in subprocesses). """ for handler in self._handlers: handle...
python
def add_result(self, result): """Add an already-constructed :class:`~.TestResult` to this :class:`~.ResultCollector`. This may be used when collecting results created by other ResultCollectors (e.g. in subprocesses). """ for handler in self._handlers: handle...
[ "def", "add_result", "(", "self", ",", "result", ")", ":", "for", "handler", "in", "self", ".", "_handlers", ":", "handler", "(", "result", ")", "if", "self", ".", "_successful", "and", "result", ".", "status", "not", "in", "_successful_results", ":", "s...
Add an already-constructed :class:`~.TestResult` to this :class:`~.ResultCollector`. This may be used when collecting results created by other ResultCollectors (e.g. in subprocesses).
[ "Add", "an", "already", "-", "constructed", ":", "class", ":", "~", ".", "TestResult", "to", "this", ":", "class", ":", "~", ".", "ResultCollector", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L462-L473
scalative/haas
haas/result.py
ResultCollector._handle_result
def _handle_result(self, test, status, exception=None, message=None): """Create a :class:`~.TestResult` and add it to this :class:`~ResultCollector`. Parameters ---------- test : unittest.TestCase The test that this result will represent. status : haas.result...
python
def _handle_result(self, test, status, exception=None, message=None): """Create a :class:`~.TestResult` and add it to this :class:`~ResultCollector`. Parameters ---------- test : unittest.TestCase The test that this result will represent. status : haas.result...
[ "def", "_handle_result", "(", "self", ",", "test", ",", "status", ",", "exception", "=", "None", ",", "message", "=", "None", ")", ":", "if", "self", ".", "buffer", ":", "stderr", "=", "self", ".", "_stderr_buffer", ".", "getvalue", "(", ")", "stdout",...
Create a :class:`~.TestResult` and add it to this :class:`~ResultCollector`. Parameters ---------- test : unittest.TestCase The test that this result will represent. status : haas.result.TestCompletionStatus The status of the test. exception : tup...
[ "Create", "a", ":", "class", ":", "~", ".", "TestResult", "and", "add", "it", "to", "this", ":", "class", ":", "~ResultCollector", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L475-L518
scalative/haas
haas/result.py
ResultCollector.addError
def addError(self, test, exception): """Register that a test ended in an error. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = se...
python
def addError(self, test, exception): """Register that a test ended in an error. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result = se...
[ "def", "addError", "(", "self", ",", "test", ",", "exception", ")", ":", "result", "=", "self", ".", "_handle_result", "(", "test", ",", "TestCompletionStatus", ".", "error", ",", "exception", "=", "exception", ")", "self", ".", "errors", ".", "append", ...
Register that a test ended in an error. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``.
[ "Register", "that", "a", "test", "ended", "in", "an", "error", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L521-L535
scalative/haas
haas/result.py
ResultCollector.addFailure
def addFailure(self, test, exception): """Register that a test ended with a failure. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result...
python
def addFailure(self, test, exception): """Register that a test ended with a failure. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. """ result...
[ "def", "addFailure", "(", "self", ",", "test", ",", "exception", ")", ":", "result", "=", "self", ".", "_handle_result", "(", "test", ",", "TestCompletionStatus", ".", "failure", ",", "exception", "=", "exception", ")", "self", ".", "failures", ".", "appen...
Register that a test ended with a failure. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``.
[ "Register", "that", "a", "test", "ended", "with", "a", "failure", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L538-L552
scalative/haas
haas/result.py
ResultCollector.addSkip
def addSkip(self, test, reason): """Register that a test that was skipped. Parameters ---------- test : unittest.TestCase The test that has completed. reason : str The reason the test was skipped. """ result = self._handle_result( ...
python
def addSkip(self, test, reason): """Register that a test that was skipped. Parameters ---------- test : unittest.TestCase The test that has completed. reason : str The reason the test was skipped. """ result = self._handle_result( ...
[ "def", "addSkip", "(", "self", ",", "test", ",", "reason", ")", ":", "result", "=", "self", ".", "_handle_result", "(", "test", ",", "TestCompletionStatus", ".", "skipped", ",", "message", "=", "reason", ")", "self", ".", "skipped", ".", "append", "(", ...
Register that a test that was skipped. Parameters ---------- test : unittest.TestCase The test that has completed. reason : str The reason the test was skipped.
[ "Register", "that", "a", "test", "that", "was", "skipped", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L565-L578
scalative/haas
haas/result.py
ResultCollector.addExpectedFailure
def addExpectedFailure(self, test, exception): """Register that a test that failed and was expected to fail. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. ...
python
def addExpectedFailure(self, test, exception): """Register that a test that failed and was expected to fail. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``. ...
[ "def", "addExpectedFailure", "(", "self", ",", "test", ",", "exception", ")", ":", "result", "=", "self", ".", "_handle_result", "(", "test", ",", "TestCompletionStatus", ".", "expected_failure", ",", "exception", "=", "exception", ")", "self", ".", "expectedF...
Register that a test that failed and was expected to fail. Parameters ---------- test : unittest.TestCase The test that has completed. exception : tuple ``exc_info`` tuple ``(type, value, traceback)``.
[ "Register", "that", "a", "test", "that", "failed", "and", "was", "expected", "to", "fail", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L580-L593
scalative/haas
haas/result.py
ResultCollector.addUnexpectedSuccess
def addUnexpectedSuccess(self, test): """Register a test that passed unexpectedly. Parameters ---------- test : unittest.TestCase The test that has completed. """ result = self._handle_result( test, TestCompletionStatus.unexpected_success) ...
python
def addUnexpectedSuccess(self, test): """Register a test that passed unexpectedly. Parameters ---------- test : unittest.TestCase The test that has completed. """ result = self._handle_result( test, TestCompletionStatus.unexpected_success) ...
[ "def", "addUnexpectedSuccess", "(", "self", ",", "test", ")", ":", "result", "=", "self", ".", "_handle_result", "(", "test", ",", "TestCompletionStatus", ".", "unexpected_success", ")", "self", ".", "unexpectedSuccesses", ".", "append", "(", "result", ")" ]
Register a test that passed unexpectedly. Parameters ---------- test : unittest.TestCase The test that has completed.
[ "Register", "a", "test", "that", "passed", "unexpectedly", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/result.py#L596-L607