repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
smarie/python-parsyfiles
parsyfiles/parsing_combining_parsers.py
print_error_to_io_stream
def print_error_to_io_stream(err: Exception, io: TextIOBase, print_big_traceback : bool = True): """ Utility method to print an exception's content to a stream :param err: :param io: :param print_big_traceback: :return: """ if print_big_traceback: traceback.print_tb(err.__traceback__, file=io, limit=-GLOBAL_CONFIG.multiple_errors_tb_limit) else: traceback.print_tb(err.__traceback__, file=io, limit=-1) io.writelines(' ' + str(err.__class__.__name__) + ' : ' + str(err))
python
def print_error_to_io_stream(err: Exception, io: TextIOBase, print_big_traceback : bool = True): """ Utility method to print an exception's content to a stream :param err: :param io: :param print_big_traceback: :return: """ if print_big_traceback: traceback.print_tb(err.__traceback__, file=io, limit=-GLOBAL_CONFIG.multiple_errors_tb_limit) else: traceback.print_tb(err.__traceback__, file=io, limit=-1) io.writelines(' ' + str(err.__class__.__name__) + ' : ' + str(err))
[ "def", "print_error_to_io_stream", "(", "err", ":", "Exception", ",", "io", ":", "TextIOBase", ",", "print_big_traceback", ":", "bool", "=", "True", ")", ":", "if", "print_big_traceback", ":", "traceback", ".", "print_tb", "(", "err", ".", "__traceback__", ","...
Utility method to print an exception's content to a stream :param err: :param io: :param print_big_traceback: :return:
[ "Utility", "method", "to", "print", "an", "exception", "s", "content", "to", "a", "stream" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_combining_parsers.py#L82-L95
train
55,000
smarie/python-parsyfiles
parsyfiles/parsing_combining_parsers.py
should_hide_traceback
def should_hide_traceback(e): """ Returns True if we can hide the error traceback in the warnings messages """ if type(e) in {WrongTypeCreatedError, CascadeError, TypeInformationRequiredError}: return True elif type(e).__name__ in {'InvalidAttributeNameForConstructorError', 'MissingMandatoryAttributeFiles'}: return True else: return False
python
def should_hide_traceback(e): """ Returns True if we can hide the error traceback in the warnings messages """ if type(e) in {WrongTypeCreatedError, CascadeError, TypeInformationRequiredError}: return True elif type(e).__name__ in {'InvalidAttributeNameForConstructorError', 'MissingMandatoryAttributeFiles'}: return True else: return False
[ "def", "should_hide_traceback", "(", "e", ")", ":", "if", "type", "(", "e", ")", "in", "{", "WrongTypeCreatedError", ",", "CascadeError", ",", "TypeInformationRequiredError", "}", ":", "return", "True", "elif", "type", "(", "e", ")", ".", "__name__", "in", ...
Returns True if we can hide the error traceback in the warnings messages
[ "Returns", "True", "if", "we", "can", "hide", "the", "error", "traceback", "in", "the", "warnings", "messages" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_combining_parsers.py#L165-L172
train
55,001
smarie/python-parsyfiles
parsyfiles/parsing_combining_parsers.py
CascadingParser._create_parsing_plan
def _create_parsing_plan(self, desired_type: Type[T], filesystem_object: PersistedObject, logger: Logger, log_only_last: bool = False) -> ParsingPlan[T]: """ Creates a parsing plan to parse the given filesystem object into the given desired_type. This overrides the method in AnyParser, in order to provide a 'cascading' parsing plan :param desired_type: :param filesystem_object: :param logger: :param log_only_last: a flag to only log the last part of the file path (default False) :return: """ # build the parsing plan logger.debug('(B) ' + get_parsing_plan_log_str(filesystem_object, desired_type, log_only_last=log_only_last, parser=self)) return CascadingParser.CascadingParsingPlan(desired_type, filesystem_object, self, self._parsers_list, logger=logger)
python
def _create_parsing_plan(self, desired_type: Type[T], filesystem_object: PersistedObject, logger: Logger, log_only_last: bool = False) -> ParsingPlan[T]: """ Creates a parsing plan to parse the given filesystem object into the given desired_type. This overrides the method in AnyParser, in order to provide a 'cascading' parsing plan :param desired_type: :param filesystem_object: :param logger: :param log_only_last: a flag to only log the last part of the file path (default False) :return: """ # build the parsing plan logger.debug('(B) ' + get_parsing_plan_log_str(filesystem_object, desired_type, log_only_last=log_only_last, parser=self)) return CascadingParser.CascadingParsingPlan(desired_type, filesystem_object, self, self._parsers_list, logger=logger)
[ "def", "_create_parsing_plan", "(", "self", ",", "desired_type", ":", "Type", "[", "T", "]", ",", "filesystem_object", ":", "PersistedObject", ",", "logger", ":", "Logger", ",", "log_only_last", ":", "bool", "=", "False", ")", "->", "ParsingPlan", "[", "T", ...
Creates a parsing plan to parse the given filesystem object into the given desired_type. This overrides the method in AnyParser, in order to provide a 'cascading' parsing plan :param desired_type: :param filesystem_object: :param logger: :param log_only_last: a flag to only log the last part of the file path (default False) :return:
[ "Creates", "a", "parsing", "plan", "to", "parse", "the", "given", "filesystem", "object", "into", "the", "given", "desired_type", ".", "This", "overrides", "the", "method", "in", "AnyParser", "in", "order", "to", "provide", "a", "cascading", "parsing", "plan" ...
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_combining_parsers.py#L479-L495
train
55,002
smarie/python-parsyfiles
parsyfiles/parsing_combining_parsers.py
ParsingChain.are_worth_chaining
def are_worth_chaining(base_parser: Parser, to_type: Type[S], converter: Converter[S,T]) -> bool: """ Utility method to check if it makes sense to chain this parser configured with the given to_type, with this converter. It is an extension of ConverterChain.are_worth_chaining :param base_parser: :param to_type: :param converter: :return: """ if isinstance(converter, ConversionChain): for conv in converter._converters_list: if not Parser.are_worth_chaining(base_parser, to_type, conv): return False # all good return True else: return Parser.are_worth_chaining(base_parser, to_type, converter)
python
def are_worth_chaining(base_parser: Parser, to_type: Type[S], converter: Converter[S,T]) -> bool: """ Utility method to check if it makes sense to chain this parser configured with the given to_type, with this converter. It is an extension of ConverterChain.are_worth_chaining :param base_parser: :param to_type: :param converter: :return: """ if isinstance(converter, ConversionChain): for conv in converter._converters_list: if not Parser.are_worth_chaining(base_parser, to_type, conv): return False # all good return True else: return Parser.are_worth_chaining(base_parser, to_type, converter)
[ "def", "are_worth_chaining", "(", "base_parser", ":", "Parser", ",", "to_type", ":", "Type", "[", "S", "]", ",", "converter", ":", "Converter", "[", "S", ",", "T", "]", ")", "->", "bool", ":", "if", "isinstance", "(", "converter", ",", "ConversionChain",...
Utility method to check if it makes sense to chain this parser configured with the given to_type, with this converter. It is an extension of ConverterChain.are_worth_chaining :param base_parser: :param to_type: :param converter: :return:
[ "Utility", "method", "to", "check", "if", "it", "makes", "sense", "to", "chain", "this", "parser", "configured", "with", "the", "given", "to_type", "with", "this", "converter", ".", "It", "is", "an", "extension", "of", "ConverterChain", ".", "are_worth_chainin...
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_combining_parsers.py#L623-L640
train
55,003
majuss/lupupy
lupupy/devices/alarm.py
LupusecAlarm.set_mode
def set_mode(self, mode): """Set Lupusec alarm mode.""" _LOGGER.debug('State change called from alarm device') if not mode: _LOGGER.info('No mode supplied') elif mode not in CONST.ALL_MODES: _LOGGER.warning('Invalid mode') response_object = self._lupusec.set_mode(CONST.MODE_TRANSLATION[mode]) if response_object['result'] != 1: _LOGGER.warning('Mode setting unsuccessful') self._json_state['mode'] = mode _LOGGER.info('Mode set to: %s', mode) return True
python
def set_mode(self, mode): """Set Lupusec alarm mode.""" _LOGGER.debug('State change called from alarm device') if not mode: _LOGGER.info('No mode supplied') elif mode not in CONST.ALL_MODES: _LOGGER.warning('Invalid mode') response_object = self._lupusec.set_mode(CONST.MODE_TRANSLATION[mode]) if response_object['result'] != 1: _LOGGER.warning('Mode setting unsuccessful') self._json_state['mode'] = mode _LOGGER.info('Mode set to: %s', mode) return True
[ "def", "set_mode", "(", "self", ",", "mode", ")", ":", "_LOGGER", ".", "debug", "(", "'State change called from alarm device'", ")", "if", "not", "mode", ":", "_LOGGER", ".", "info", "(", "'No mode supplied'", ")", "elif", "mode", "not", "in", "CONST", ".", ...
Set Lupusec alarm mode.
[ "Set", "Lupusec", "alarm", "mode", "." ]
71af6c397837ffc393c7b8122be175602638d3c6
https://github.com/majuss/lupupy/blob/71af6c397837ffc393c7b8122be175602638d3c6/lupupy/devices/alarm.py#L24-L37
train
55,004
nikcub/floyd
floyd/util/unicode.py
to_utf8
def to_utf8(value): """Returns a string encoded using UTF-8. This function comes from `Tornado`_. :param value: A unicode or string to be encoded. :returns: The encoded string. """ if isinstance(value, unicode): return value.encode('utf-8') assert isinstance(value, str) return value
python
def to_utf8(value): """Returns a string encoded using UTF-8. This function comes from `Tornado`_. :param value: A unicode or string to be encoded. :returns: The encoded string. """ if isinstance(value, unicode): return value.encode('utf-8') assert isinstance(value, str) return value
[ "def", "to_utf8", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "unicode", ")", ":", "return", "value", ".", "encode", "(", "'utf-8'", ")", "assert", "isinstance", "(", "value", ",", "str", ")", "return", "value" ]
Returns a string encoded using UTF-8. This function comes from `Tornado`_. :param value: A unicode or string to be encoded. :returns: The encoded string.
[ "Returns", "a", "string", "encoded", "using", "UTF", "-", "8", "." ]
5772d0047efb11c9ce5f7d234a9da4576ce24edc
https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/floyd/util/unicode.py#L42-L56
train
55,005
nikcub/floyd
floyd/util/unicode.py
to_unicode
def to_unicode(value): """Returns a unicode string from a string, using UTF-8 to decode if needed. This function comes from `Tornado`_. :param value: A unicode or string to be decoded. :returns: The decoded string. """ if isinstance(value, str): return value.decode('utf-8') assert isinstance(value, unicode) return value
python
def to_unicode(value): """Returns a unicode string from a string, using UTF-8 to decode if needed. This function comes from `Tornado`_. :param value: A unicode or string to be decoded. :returns: The decoded string. """ if isinstance(value, str): return value.decode('utf-8') assert isinstance(value, unicode) return value
[ "def", "to_unicode", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "return", "value", ".", "decode", "(", "'utf-8'", ")", "assert", "isinstance", "(", "value", ",", "unicode", ")", "return", "value" ]
Returns a unicode string from a string, using UTF-8 to decode if needed. This function comes from `Tornado`_. :param value: A unicode or string to be decoded. :returns: The decoded string.
[ "Returns", "a", "unicode", "string", "from", "a", "string", "using", "UTF", "-", "8", "to", "decode", "if", "needed", "." ]
5772d0047efb11c9ce5f7d234a9da4576ce24edc
https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/floyd/util/unicode.py#L59-L73
train
55,006
VikParuchuri/percept
percept/management/base.py
get_commands
def get_commands(): """ Get all valid commands return - all valid commands in dictionary form """ commands = {} #Try to load the settings file (settings can be specified on the command line) and get the INSTALLED_APPS try: from percept.conf.base import settings apps = settings.INSTALLED_APPS except KeyError: apps = [] #For each app, try to find the command module (command folder in the app) #Then, try to load all commands in the directory for app_name in apps: try: path = find_commands_module(app_name) commands.update(dict([(name, app_name) for name in find_all_commands(path)])) except ImportError as e: pass return commands
python
def get_commands(): """ Get all valid commands return - all valid commands in dictionary form """ commands = {} #Try to load the settings file (settings can be specified on the command line) and get the INSTALLED_APPS try: from percept.conf.base import settings apps = settings.INSTALLED_APPS except KeyError: apps = [] #For each app, try to find the command module (command folder in the app) #Then, try to load all commands in the directory for app_name in apps: try: path = find_commands_module(app_name) commands.update(dict([(name, app_name) for name in find_all_commands(path)])) except ImportError as e: pass return commands
[ "def", "get_commands", "(", ")", ":", "commands", "=", "{", "}", "#Try to load the settings file (settings can be specified on the command line) and get the INSTALLED_APPS", "try", ":", "from", "percept", ".", "conf", ".", "base", "import", "settings", "apps", "=", "setti...
Get all valid commands return - all valid commands in dictionary form
[ "Get", "all", "valid", "commands", "return", "-", "all", "valid", "commands", "in", "dictionary", "form" ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/management/base.py#L62-L85
train
55,007
VikParuchuri/percept
percept/management/base.py
Management.execute
def execute(self): """ Run the command with the command line arguments """ #Initialize the option parser parser = LaxOptionParser( usage="%prog subcommand [options] [args]", option_list=BaseCommand.option_list #This will define what is allowed input to the parser (ie --settings=) ) #Parse the options options, args = parser.parse_args(self.argv) #Handle --settings and --pythonpath properly options = handle_default_options(options) try: #Get the name of the subcommand subcommand = self.argv[1] except IndexError: #If the subcommand name cannot be found, set it to help subcommand = 'help' #If the subcommand is help, print the usage of the parser, and available command names if subcommand == 'help': if len(args) <= 2: parser.print_help() sys.stdout.write(self.help_text + '\n') else: #Otherwise, run the given command self.fetch_command(subcommand).run_from_argv(self.argv)
python
def execute(self): """ Run the command with the command line arguments """ #Initialize the option parser parser = LaxOptionParser( usage="%prog subcommand [options] [args]", option_list=BaseCommand.option_list #This will define what is allowed input to the parser (ie --settings=) ) #Parse the options options, args = parser.parse_args(self.argv) #Handle --settings and --pythonpath properly options = handle_default_options(options) try: #Get the name of the subcommand subcommand = self.argv[1] except IndexError: #If the subcommand name cannot be found, set it to help subcommand = 'help' #If the subcommand is help, print the usage of the parser, and available command names if subcommand == 'help': if len(args) <= 2: parser.print_help() sys.stdout.write(self.help_text + '\n') else: #Otherwise, run the given command self.fetch_command(subcommand).run_from_argv(self.argv)
[ "def", "execute", "(", "self", ")", ":", "#Initialize the option parser", "parser", "=", "LaxOptionParser", "(", "usage", "=", "\"%prog subcommand [options] [args]\"", ",", "option_list", "=", "BaseCommand", ".", "option_list", "#This will define what is allowed input to the ...
Run the command with the command line arguments
[ "Run", "the", "command", "with", "the", "command", "line", "arguments" ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/management/base.py#L133-L162
train
55,008
VikParuchuri/percept
percept/management/base.py
Management.help_text
def help_text(self): """ Formats and prints the help text from the command list """ help_text = '\n'.join(sorted(get_commands().keys())) help_text = "\nCommands:\n" + help_text return help_text
python
def help_text(self): """ Formats and prints the help text from the command list """ help_text = '\n'.join(sorted(get_commands().keys())) help_text = "\nCommands:\n" + help_text return help_text
[ "def", "help_text", "(", "self", ")", ":", "help_text", "=", "'\\n'", ".", "join", "(", "sorted", "(", "get_commands", "(", ")", ".", "keys", "(", ")", ")", ")", "help_text", "=", "\"\\nCommands:\\n\"", "+", "help_text", "return", "help_text" ]
Formats and prints the help text from the command list
[ "Formats", "and", "prints", "the", "help", "text", "from", "the", "command", "list" ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/management/base.py#L165-L171
train
55,009
rbccps-iisc/ideam-python-sdk
ideam/entity.py
Entity.register
def register(self): """ Registers a new device with the name entity_id. This device has permissions for services like subscribe, publish and access historical data. """ register_url = self.base_url + "api/0.1.0/register" register_headers = { "apikey": str(self.owner_api_key), "resourceID": str(self.entity_id), "serviceType": "publish,subscribe,historicData" } with self.no_ssl_verification(): r = requests.get(register_url, {}, headers=register_headers) response = r.content.decode("utf-8") if "APIKey" in str(r.content.decode("utf-8")): response = json.loads(response[:-331] + "}") # Temporary fix to a middleware bug, should be removed in future response["Registration"] = "success" else: response = json.loads(response) response["Registration"] = "failure" return response
python
def register(self): """ Registers a new device with the name entity_id. This device has permissions for services like subscribe, publish and access historical data. """ register_url = self.base_url + "api/0.1.0/register" register_headers = { "apikey": str(self.owner_api_key), "resourceID": str(self.entity_id), "serviceType": "publish,subscribe,historicData" } with self.no_ssl_verification(): r = requests.get(register_url, {}, headers=register_headers) response = r.content.decode("utf-8") if "APIKey" in str(r.content.decode("utf-8")): response = json.loads(response[:-331] + "}") # Temporary fix to a middleware bug, should be removed in future response["Registration"] = "success" else: response = json.loads(response) response["Registration"] = "failure" return response
[ "def", "register", "(", "self", ")", ":", "register_url", "=", "self", ".", "base_url", "+", "\"api/0.1.0/register\"", "register_headers", "=", "{", "\"apikey\"", ":", "str", "(", "self", ".", "owner_api_key", ")", ",", "\"resourceID\"", ":", "str", "(", "se...
Registers a new device with the name entity_id. This device has permissions for services like subscribe, publish and access historical data.
[ "Registers", "a", "new", "device", "with", "the", "name", "entity_id", ".", "This", "device", "has", "permissions", "for", "services", "like", "subscribe", "publish", "and", "access", "historical", "data", "." ]
fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98
https://github.com/rbccps-iisc/ideam-python-sdk/blob/fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98/ideam/entity.py#L44-L64
train
55,010
rbccps-iisc/ideam-python-sdk
ideam/entity.py
Entity.no_ssl_verification
def no_ssl_verification(self): """ Requests module fails due to lets encrypt ssl encryption. Will be fixed in the future release.""" try: from functools import partialmethod except ImportError: # Python 2 fallback: https://gist.github.com/carymrobbins/8940382 from functools import partial class partialmethod(partial): def __get__(self, instance, owner): if instance is None: return self return partial(self.func, instance, *(self.args or ()), **(self.keywords or {})) old_request = requests.Session.request requests.Session.request = partialmethod(old_request, verify=False) warnings.filterwarnings('ignore', 'Unverified HTTPS request') yield warnings.resetwarnings() requests.Session.request = old_request
python
def no_ssl_verification(self): """ Requests module fails due to lets encrypt ssl encryption. Will be fixed in the future release.""" try: from functools import partialmethod except ImportError: # Python 2 fallback: https://gist.github.com/carymrobbins/8940382 from functools import partial class partialmethod(partial): def __get__(self, instance, owner): if instance is None: return self return partial(self.func, instance, *(self.args or ()), **(self.keywords or {})) old_request = requests.Session.request requests.Session.request = partialmethod(old_request, verify=False) warnings.filterwarnings('ignore', 'Unverified HTTPS request') yield warnings.resetwarnings() requests.Session.request = old_request
[ "def", "no_ssl_verification", "(", "self", ")", ":", "try", ":", "from", "functools", "import", "partialmethod", "except", "ImportError", ":", "# Python 2 fallback: https://gist.github.com/carymrobbins/8940382", "from", "functools", "import", "partial", "class", "partialmet...
Requests module fails due to lets encrypt ssl encryption. Will be fixed in the future release.
[ "Requests", "module", "fails", "due", "to", "lets", "encrypt", "ssl", "encryption", ".", "Will", "be", "fixed", "in", "the", "future", "release", "." ]
fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98
https://github.com/rbccps-iisc/ideam-python-sdk/blob/fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98/ideam/entity.py#L67-L87
train
55,011
rbccps-iisc/ideam-python-sdk
ideam/entity.py
Entity.publish
def publish(self, data): """ This function allows an entity to publish data to the middleware. Args: data (string): contents to be published by this entity. """ if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} publish_url = self.base_url + "api/0.1.0/publish" publish_headers = {"apikey": self.entity_api_key} publish_data = { "exchange": "amq.topic", "key": str(self.entity_id), "body": str(data) } with self.no_ssl_verification(): r = requests.post(publish_url, json.dumps(publish_data), headers=publish_headers) response = dict() if "No API key" in str(r.content.decode("utf-8")): response["status"] = "failure" r = json.loads(r.content.decode("utf-8"))['message'] elif 'publish message ok' in str(r.content.decode("utf-8")): response["status"] = "success" r = r.content.decode("utf-8") else: response["status"] = "failure" r = r.content.decode("utf-8") response["response"] = str(r) return response
python
def publish(self, data): """ This function allows an entity to publish data to the middleware. Args: data (string): contents to be published by this entity. """ if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} publish_url = self.base_url + "api/0.1.0/publish" publish_headers = {"apikey": self.entity_api_key} publish_data = { "exchange": "amq.topic", "key": str(self.entity_id), "body": str(data) } with self.no_ssl_verification(): r = requests.post(publish_url, json.dumps(publish_data), headers=publish_headers) response = dict() if "No API key" in str(r.content.decode("utf-8")): response["status"] = "failure" r = json.loads(r.content.decode("utf-8"))['message'] elif 'publish message ok' in str(r.content.decode("utf-8")): response["status"] = "success" r = r.content.decode("utf-8") else: response["status"] = "failure" r = r.content.decode("utf-8") response["response"] = str(r) return response
[ "def", "publish", "(", "self", ",", "data", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "publish_url", "=", "self", ".", "base_ur...
This function allows an entity to publish data to the middleware. Args: data (string): contents to be published by this entity.
[ "This", "function", "allows", "an", "entity", "to", "publish", "data", "to", "the", "middleware", "." ]
fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98
https://github.com/rbccps-iisc/ideam-python-sdk/blob/fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98/ideam/entity.py#L89-L117
train
55,012
rbccps-iisc/ideam-python-sdk
ideam/entity.py
Entity.db
def db(self, entity, query_filters="size=10"): """ This function allows an entity to access the historic data. Args: entity (string): Name of the device to listen to query_filters (string): Elastic search response format string example, "pretty=true&size=10" """ if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} historic_url = self.base_url + "api/0.1.0/historicData?" + query_filters historic_headers = { "apikey": self.entity_api_key, "Content-Type": "application/json" } historic_query_data = json.dumps({ "query": { "match": { "key": entity } } }) with self.no_ssl_verification(): r = requests.get(historic_url, data=historic_query_data, headers=historic_headers) response = dict() if "No API key" in str(r.content.decode("utf-8")): response["status"] = "failure" else: r = r.content.decode("utf-8") response = r return response
python
def db(self, entity, query_filters="size=10"): """ This function allows an entity to access the historic data. Args: entity (string): Name of the device to listen to query_filters (string): Elastic search response format string example, "pretty=true&size=10" """ if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} historic_url = self.base_url + "api/0.1.0/historicData?" + query_filters historic_headers = { "apikey": self.entity_api_key, "Content-Type": "application/json" } historic_query_data = json.dumps({ "query": { "match": { "key": entity } } }) with self.no_ssl_verification(): r = requests.get(historic_url, data=historic_query_data, headers=historic_headers) response = dict() if "No API key" in str(r.content.decode("utf-8")): response["status"] = "failure" else: r = r.content.decode("utf-8") response = r return response
[ "def", "db", "(", "self", ",", "entity", ",", "query_filters", "=", "\"size=10\"", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "h...
This function allows an entity to access the historic data. Args: entity (string): Name of the device to listen to query_filters (string): Elastic search response format string example, "pretty=true&size=10"
[ "This", "function", "allows", "an", "entity", "to", "access", "the", "historic", "data", "." ]
fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98
https://github.com/rbccps-iisc/ideam-python-sdk/blob/fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98/ideam/entity.py#L119-L152
train
55,013
rbccps-iisc/ideam-python-sdk
ideam/entity.py
Entity.bind
def bind(self, devices_to_bind): """ This function allows an entity to list the devices to subscribe for data. This function must be called at least once, before doing a subscribe. Subscribe function will listen to devices that are bound here. Args: devices_to_bind (list): an array of devices to listen to. Example bind(["test100","testDemo"]) """ if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} url = self.base_url + "api/0.1.0/subscribe/bind" headers = {"apikey": self.entity_api_key} data = { "exchange": "amq.topic", "keys": devices_to_bind, "queue": self.entity_id } with self.no_ssl_verification(): r = requests.post(url, json=data, headers=headers) response = dict() if "No API key" in str(r.content.decode("utf-8")): response["status"] = "failure" r = json.loads(r.content.decode("utf-8"))['message'] elif 'bind queue ok' in str(r.content.decode("utf-8")): response["status"] = "success" r = r.content.decode("utf-8") else: response["status"] = "failure" r = r.content.decode("utf-8") response["response"] = str(r) return response
python
def bind(self, devices_to_bind): """ This function allows an entity to list the devices to subscribe for data. This function must be called at least once, before doing a subscribe. Subscribe function will listen to devices that are bound here. Args: devices_to_bind (list): an array of devices to listen to. Example bind(["test100","testDemo"]) """ if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} url = self.base_url + "api/0.1.0/subscribe/bind" headers = {"apikey": self.entity_api_key} data = { "exchange": "amq.topic", "keys": devices_to_bind, "queue": self.entity_id } with self.no_ssl_verification(): r = requests.post(url, json=data, headers=headers) response = dict() if "No API key" in str(r.content.decode("utf-8")): response["status"] = "failure" r = json.loads(r.content.decode("utf-8"))['message'] elif 'bind queue ok' in str(r.content.decode("utf-8")): response["status"] = "success" r = r.content.decode("utf-8") else: response["status"] = "failure" r = r.content.decode("utf-8") response["response"] = str(r) return response
[ "def", "bind", "(", "self", ",", "devices_to_bind", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "url", "=", "self", ".", "base_ur...
This function allows an entity to list the devices to subscribe for data. This function must be called at least once, before doing a subscribe. Subscribe function will listen to devices that are bound here. Args: devices_to_bind (list): an array of devices to listen to. Example bind(["test100","testDemo"])
[ "This", "function", "allows", "an", "entity", "to", "list", "the", "devices", "to", "subscribe", "for", "data", ".", "This", "function", "must", "be", "called", "at", "least", "once", "before", "doing", "a", "subscribe", ".", "Subscribe", "function", "will",...
fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98
https://github.com/rbccps-iisc/ideam-python-sdk/blob/fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98/ideam/entity.py#L154-L186
train
55,014
rbccps-iisc/ideam-python-sdk
ideam/entity.py
Entity.unbind
def unbind(self, devices_to_unbind): """ This function allows an entity to unbound devices that are already bound. Args: devices_to_unbind (list): an array of devices that are to be unbound ( stop listening) Example unbind(["test10","testDemo105"]) """ if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} url = self.base_url + "api/0.1.0/subscribe/unbind" headers = {"apikey": self.entity_api_key} data = { "exchange": "amq.topic", "keys": devices_to_unbind, "queue": self.entity_id } with self.no_ssl_verification(): r = requests.delete(url, json=data, headers=headers) print(r) response = dict() if "No API key" in str(r.content.decode("utf-8")): response["status"] = "failure" r = json.loads(r.content.decode("utf-8"))['message'] elif 'unbind' in str(r.content.decode("utf-8")): response["status"] = "success" r = r.content.decode("utf-8") else: response["status"] = "failure" r = r.content.decode("utf-8") response["response"] = str(r) return response
python
def unbind(self, devices_to_unbind): """ This function allows an entity to unbound devices that are already bound. Args: devices_to_unbind (list): an array of devices that are to be unbound ( stop listening) Example unbind(["test10","testDemo105"]) """ if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} url = self.base_url + "api/0.1.0/subscribe/unbind" headers = {"apikey": self.entity_api_key} data = { "exchange": "amq.topic", "keys": devices_to_unbind, "queue": self.entity_id } with self.no_ssl_verification(): r = requests.delete(url, json=data, headers=headers) print(r) response = dict() if "No API key" in str(r.content.decode("utf-8")): response["status"] = "failure" r = json.loads(r.content.decode("utf-8"))['message'] elif 'unbind' in str(r.content.decode("utf-8")): response["status"] = "success" r = r.content.decode("utf-8") else: response["status"] = "failure" r = r.content.decode("utf-8") response["response"] = str(r) return response
[ "def", "unbind", "(", "self", ",", "devices_to_unbind", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "url", "=", "self", ".", "bas...
This function allows an entity to unbound devices that are already bound. Args: devices_to_unbind (list): an array of devices that are to be unbound ( stop listening) Example unbind(["test10","testDemo105"])
[ "This", "function", "allows", "an", "entity", "to", "unbound", "devices", "that", "are", "already", "bound", "." ]
fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98
https://github.com/rbccps-iisc/ideam-python-sdk/blob/fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98/ideam/entity.py#L188-L219
train
55,015
rbccps-iisc/ideam-python-sdk
ideam/entity.py
Entity.subscribe
def subscribe(self, devices_to_bind=[]): """ This function allows an entity to subscribe for data from the devices specified in the bind operation. It creates a thread with an event loop to manager the tasks created in start_subscribe_worker. Args: devices_to_bind (list): an array of devices to listen to """ if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} self.bind(devices_to_bind) loop = asyncio.new_event_loop() t1 = threading.Thread(target=self.start_subscribe_worker, args=(loop,)) t1.daemon = True t1.start()
python
def subscribe(self, devices_to_bind=[]): """ This function allows an entity to subscribe for data from the devices specified in the bind operation. It creates a thread with an event loop to manager the tasks created in start_subscribe_worker. Args: devices_to_bind (list): an array of devices to listen to """ if self.entity_api_key == "": return {'status': 'failure', 'response': 'No API key found in request'} self.bind(devices_to_bind) loop = asyncio.new_event_loop() t1 = threading.Thread(target=self.start_subscribe_worker, args=(loop,)) t1.daemon = True t1.start()
[ "def", "subscribe", "(", "self", ",", "devices_to_bind", "=", "[", "]", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "self", ".", ...
This function allows an entity to subscribe for data from the devices specified in the bind operation. It creates a thread with an event loop to manager the tasks created in start_subscribe_worker. Args: devices_to_bind (list): an array of devices to listen to
[ "This", "function", "allows", "an", "entity", "to", "subscribe", "for", "data", "from", "the", "devices", "specified", "in", "the", "bind", "operation", ".", "It", "creates", "a", "thread", "with", "an", "event", "loop", "to", "manager", "the", "tasks", "c...
fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98
https://github.com/rbccps-iisc/ideam-python-sdk/blob/fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98/ideam/entity.py#L221-L234
train
55,016
rbccps-iisc/ideam-python-sdk
ideam/entity.py
Entity.start_subscribe_worker
def start_subscribe_worker(self, loop): """ Switch to new event loop as a thread and run until complete. """ url = self.base_url + "api/0.1.0/subscribe" task = loop.create_task(self.asynchronously_get_data(url + "?name={0}".format(self.entity_id))) asyncio.set_event_loop(loop) loop.run_until_complete(task) self.event_loop = loop
python
def start_subscribe_worker(self, loop): """ Switch to new event loop as a thread and run until complete. """ url = self.base_url + "api/0.1.0/subscribe" task = loop.create_task(self.asynchronously_get_data(url + "?name={0}".format(self.entity_id))) asyncio.set_event_loop(loop) loop.run_until_complete(task) self.event_loop = loop
[ "def", "start_subscribe_worker", "(", "self", ",", "loop", ")", ":", "url", "=", "self", ".", "base_url", "+", "\"api/0.1.0/subscribe\"", "task", "=", "loop", ".", "create_task", "(", "self", ".", "asynchronously_get_data", "(", "url", "+", "\"?name={0}\"", "....
Switch to new event loop as a thread and run until complete.
[ "Switch", "to", "new", "event", "loop", "as", "a", "thread", "and", "run", "until", "complete", "." ]
fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98
https://github.com/rbccps-iisc/ideam-python-sdk/blob/fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98/ideam/entity.py#L237-L243
train
55,017
rbccps-iisc/ideam-python-sdk
ideam/entity.py
Entity.stop_subscribe
def stop_subscribe(self): """ This function is used to stop the event loop created when subscribe is called. But this function doesn't stop the thread and should be avoided until its completely developed. """ asyncio.gather(*asyncio.Task.all_tasks()).cancel() self.event_loop.stop() self.event_loop.close()
python
def stop_subscribe(self): """ This function is used to stop the event loop created when subscribe is called. But this function doesn't stop the thread and should be avoided until its completely developed. """ asyncio.gather(*asyncio.Task.all_tasks()).cancel() self.event_loop.stop() self.event_loop.close()
[ "def", "stop_subscribe", "(", "self", ")", ":", "asyncio", ".", "gather", "(", "*", "asyncio", ".", "Task", ".", "all_tasks", "(", ")", ")", ".", "cancel", "(", ")", "self", ".", "event_loop", ".", "stop", "(", ")", "self", ".", "event_loop", ".", ...
This function is used to stop the event loop created when subscribe is called. But this function doesn't stop the thread and should be avoided until its completely developed.
[ "This", "function", "is", "used", "to", "stop", "the", "event", "loop", "created", "when", "subscribe", "is", "called", ".", "But", "this", "function", "doesn", "t", "stop", "the", "thread", "and", "should", "be", "avoided", "until", "its", "completely", "...
fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98
https://github.com/rbccps-iisc/ideam-python-sdk/blob/fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98/ideam/entity.py#L272-L279
train
55,018
nikcub/floyd
floyd/util/timesince.py
timeuntil
def timeuntil(d, now=None): """ Like timesince, but returns a string measuring the time until the given time. """ if not now: if getattr(d, 'tzinfo', None): now = datetime.datetime.now(LocalTimezone(d)) else: now = datetime.datetime.now() return timesince(now, d)
python
def timeuntil(d, now=None): """ Like timesince, but returns a string measuring the time until the given time. """ if not now: if getattr(d, 'tzinfo', None): now = datetime.datetime.now(LocalTimezone(d)) else: now = datetime.datetime.now() return timesince(now, d)
[ "def", "timeuntil", "(", "d", ",", "now", "=", "None", ")", ":", "if", "not", "now", ":", "if", "getattr", "(", "d", ",", "'tzinfo'", ",", "None", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", "LocalTimezone", "(", "d", ")",...
Like timesince, but returns a string measuring the time until the given time.
[ "Like", "timesince", "but", "returns", "a", "string", "measuring", "the", "time", "until", "the", "given", "time", "." ]
5772d0047efb11c9ce5f7d234a9da4576ce24edc
https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/floyd/util/timesince.py#L59-L69
train
55,019
toumorokoshi/sprinter
sprinter/external/pippuppet.py
Pip.delete_all_eggs
def delete_all_eggs(self): """ delete all the eggs in the directory specified """ path_to_delete = os.path.join(self.egg_directory, "lib", "python") if os.path.exists(path_to_delete): shutil.rmtree(path_to_delete)
python
def delete_all_eggs(self): """ delete all the eggs in the directory specified """ path_to_delete = os.path.join(self.egg_directory, "lib", "python") if os.path.exists(path_to_delete): shutil.rmtree(path_to_delete)
[ "def", "delete_all_eggs", "(", "self", ")", ":", "path_to_delete", "=", "os", ".", "path", ".", "join", "(", "self", ".", "egg_directory", ",", "\"lib\"", ",", "\"python\"", ")", "if", "os", ".", "path", ".", "exists", "(", "path_to_delete", ")", ":", ...
delete all the eggs in the directory specified
[ "delete", "all", "the", "eggs", "in", "the", "directory", "specified" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/external/pippuppet.py#L50-L54
train
55,020
toumorokoshi/sprinter
sprinter/external/pippuppet.py
Pip.install_egg
def install_egg(self, egg_name): """ Install an egg into the egg directory """ if not os.path.exists(self.egg_directory): os.makedirs(self.egg_directory) self.requirement_set.add_requirement( InstallRequirement.from_line(egg_name, None)) try: self.requirement_set.prepare_files(self.finder) self.requirement_set.install(['--prefix=' + self.egg_directory], []) except DistributionNotFound: self.requirement_set.requirements._keys.remove(egg_name) raise PipException()
python
def install_egg(self, egg_name): """ Install an egg into the egg directory """ if not os.path.exists(self.egg_directory): os.makedirs(self.egg_directory) self.requirement_set.add_requirement( InstallRequirement.from_line(egg_name, None)) try: self.requirement_set.prepare_files(self.finder) self.requirement_set.install(['--prefix=' + self.egg_directory], []) except DistributionNotFound: self.requirement_set.requirements._keys.remove(egg_name) raise PipException()
[ "def", "install_egg", "(", "self", ",", "egg_name", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "egg_directory", ")", ":", "os", ".", "makedirs", "(", "self", ".", "egg_directory", ")", "self", ".", "requirement_set", "."...
Install an egg into the egg directory
[ "Install", "an", "egg", "into", "the", "egg", "directory" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/external/pippuppet.py#L56-L67
train
55,021
NiklasRosenstein-Python/nr-deprecated
nr/stream.py
stream.chunks
def chunks(cls, iterable, n, fill=None): """ Collects elements in fixed-length chunks. """ return cls(itertools.zip_longest(*[iter(iterable)] * n, fillvalue=fill))
python
def chunks(cls, iterable, n, fill=None): """ Collects elements in fixed-length chunks. """ return cls(itertools.zip_longest(*[iter(iterable)] * n, fillvalue=fill))
[ "def", "chunks", "(", "cls", ",", "iterable", ",", "n", ",", "fill", "=", "None", ")", ":", "return", "cls", "(", "itertools", ".", "zip_longest", "(", "*", "[", "iter", "(", "iterable", ")", "]", "*", "n", ",", "fillvalue", "=", "fill", ")", ")"...
Collects elements in fixed-length chunks.
[ "Collects", "elements", "in", "fixed", "-", "length", "chunks", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/stream.py#L88-L93
train
55,022
NiklasRosenstein-Python/nr-deprecated
nr/stream.py
stream.partition
def partition(cls, iterable, pred): """ Use a predicate to partition items into false and true entries. """ t1, t2 = itertools.tee(iterable) return cls(itertools.filterfalse(pred, t1), filter(pred, t2))
python
def partition(cls, iterable, pred): """ Use a predicate to partition items into false and true entries. """ t1, t2 = itertools.tee(iterable) return cls(itertools.filterfalse(pred, t1), filter(pred, t2))
[ "def", "partition", "(", "cls", ",", "iterable", ",", "pred", ")", ":", "t1", ",", "t2", "=", "itertools", ".", "tee", "(", "iterable", ")", "return", "cls", "(", "itertools", ".", "filterfalse", "(", "pred", ",", "t1", ")", ",", "filter", "(", "pr...
Use a predicate to partition items into false and true entries.
[ "Use", "a", "predicate", "to", "partition", "items", "into", "false", "and", "true", "entries", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/stream.py#L144-L150
train
55,023
NiklasRosenstein-Python/nr-deprecated
nr/stream.py
stream.count
def count(cls, iterable): """ Returns the number of items in an iterable. """ iterable = iter(iterable) count = 0 while True: try: next(iterable) except StopIteration: break count += 1 return count
python
def count(cls, iterable): """ Returns the number of items in an iterable. """ iterable = iter(iterable) count = 0 while True: try: next(iterable) except StopIteration: break count += 1 return count
[ "def", "count", "(", "cls", ",", "iterable", ")", ":", "iterable", "=", "iter", "(", "iterable", ")", "count", "=", "0", "while", "True", ":", "try", ":", "next", "(", "iterable", ")", "except", "StopIteration", ":", "break", "count", "+=", "1", "ret...
Returns the number of items in an iterable.
[ "Returns", "the", "number", "of", "items", "in", "an", "iterable", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/stream.py#L172-L185
train
55,024
scraperwiki/dumptruck
dumptruck/dumptruck.py
DumpTruck.column_names
def column_names(self, table): """An iterable of column names, for a particular table or view.""" table_info = self.execute( u'PRAGMA table_info(%s)' % quote(table)) return (column['name'] for column in table_info)
python
def column_names(self, table): """An iterable of column names, for a particular table or view.""" table_info = self.execute( u'PRAGMA table_info(%s)' % quote(table)) return (column['name'] for column in table_info)
[ "def", "column_names", "(", "self", ",", "table", ")", ":", "table_info", "=", "self", ".", "execute", "(", "u'PRAGMA table_info(%s)'", "%", "quote", "(", "table", ")", ")", "return", "(", "column", "[", "'name'", "]", "for", "column", "in", "table_info", ...
An iterable of column names, for a particular table or view.
[ "An", "iterable", "of", "column", "names", "for", "a", "particular", "table", "or", "view", "." ]
ac5855e34d4dffc7e53a13ff925ccabda19604fc
https://github.com/scraperwiki/dumptruck/blob/ac5855e34d4dffc7e53a13ff925ccabda19604fc/dumptruck/dumptruck.py#L110-L116
train
55,025
scraperwiki/dumptruck
dumptruck/dumptruck.py
DumpTruck.execute
def execute(self, sql, *args, **kwargs): ''' Run raw SQL on the database, and receive relaxing output. This is sort of the foundational method that most of the others build on. ''' try: self.cursor.execute(sql, *args) except self.sqlite3.InterfaceError, msg: raise self.sqlite3.InterfaceError(unicode(msg) + '\nTry converting types or pickling.') rows = self.cursor.fetchall() self.__commit_if_necessary(kwargs) if None == self.cursor.description: return None else: colnames = [d[0].decode('utf-8') for d in self.cursor.description] rawdata = [OrderedDict(zip(colnames,row)) for row in rows] return rawdata
python
def execute(self, sql, *args, **kwargs): ''' Run raw SQL on the database, and receive relaxing output. This is sort of the foundational method that most of the others build on. ''' try: self.cursor.execute(sql, *args) except self.sqlite3.InterfaceError, msg: raise self.sqlite3.InterfaceError(unicode(msg) + '\nTry converting types or pickling.') rows = self.cursor.fetchall() self.__commit_if_necessary(kwargs) if None == self.cursor.description: return None else: colnames = [d[0].decode('utf-8') for d in self.cursor.description] rawdata = [OrderedDict(zip(colnames,row)) for row in rows] return rawdata
[ "def", "execute", "(", "self", ",", "sql", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "cursor", ".", "execute", "(", "sql", ",", "*", "args", ")", "except", "self", ".", "sqlite3", ".", "InterfaceError", ",", "m...
Run raw SQL on the database, and receive relaxing output. This is sort of the foundational method that most of the others build on.
[ "Run", "raw", "SQL", "on", "the", "database", "and", "receive", "relaxing", "output", ".", "This", "is", "sort", "of", "the", "foundational", "method", "that", "most", "of", "the", "others", "build", "on", "." ]
ac5855e34d4dffc7e53a13ff925ccabda19604fc
https://github.com/scraperwiki/dumptruck/blob/ac5855e34d4dffc7e53a13ff925ccabda19604fc/dumptruck/dumptruck.py#L129-L148
train
55,026
scraperwiki/dumptruck
dumptruck/dumptruck.py
DumpTruck.create_table
def create_table(self, data, table_name, error_if_exists = False, **kwargs): 'Create a table based on the data, but don\'t insert anything.' converted_data = convert(data) if len(converted_data) == 0 or converted_data[0] == []: raise ValueError(u'You passed no sample values, or all the values you passed were null.') else: startdata = OrderedDict(converted_data[0]) # Select a non-null item for k, v in startdata.items(): if v != None: break else: v = None if_not_exists = u'' if error_if_exists else u'IF NOT EXISTS' # Do nothing if all items are null. if v != None: try: # This is vulnerable to injection. sql = u''' CREATE TABLE %s %s ( %s %s );''' % (if_not_exists, quote(table_name), quote(k), get_column_type(startdata[k])) self.execute(sql, commit = False) except: raise else: self.commit() for row in converted_data: self.__check_and_add_columns(table_name, row)
python
def create_table(self, data, table_name, error_if_exists = False, **kwargs): 'Create a table based on the data, but don\'t insert anything.' converted_data = convert(data) if len(converted_data) == 0 or converted_data[0] == []: raise ValueError(u'You passed no sample values, or all the values you passed were null.') else: startdata = OrderedDict(converted_data[0]) # Select a non-null item for k, v in startdata.items(): if v != None: break else: v = None if_not_exists = u'' if error_if_exists else u'IF NOT EXISTS' # Do nothing if all items are null. if v != None: try: # This is vulnerable to injection. sql = u''' CREATE TABLE %s %s ( %s %s );''' % (if_not_exists, quote(table_name), quote(k), get_column_type(startdata[k])) self.execute(sql, commit = False) except: raise else: self.commit() for row in converted_data: self.__check_and_add_columns(table_name, row)
[ "def", "create_table", "(", "self", ",", "data", ",", "table_name", ",", "error_if_exists", "=", "False", ",", "*", "*", "kwargs", ")", ":", "converted_data", "=", "convert", "(", "data", ")", "if", "len", "(", "converted_data", ")", "==", "0", "or", "...
Create a table based on the data, but don\'t insert anything.
[ "Create", "a", "table", "based", "on", "the", "data", "but", "don", "\\", "t", "insert", "anything", "." ]
ac5855e34d4dffc7e53a13ff925ccabda19604fc
https://github.com/scraperwiki/dumptruck/blob/ac5855e34d4dffc7e53a13ff925ccabda19604fc/dumptruck/dumptruck.py#L199-L232
train
55,027
scraperwiki/dumptruck
dumptruck/dumptruck.py
DumpTruck.get_var
def get_var(self, key): 'Retrieve one saved variable from the database.' vt = quote(self.__vars_table) data = self.execute(u'SELECT * FROM %s WHERE `key` = ?' % vt, [key], commit = False) if data == []: raise NameError(u'The DumpTruck variables table doesn\'t have a value for %s.' % key) else: tmp = quote(self.__vars_table_tmp) row = data[0] self.execute(u'DROP TABLE IF EXISTS %s' % tmp, commit = False) # This is vulnerable to injection self.execute(u'CREATE TEMPORARY TABLE %s (`value` %s)' % (tmp, row['type']), commit = False) # This is ugly self.execute(u'INSERT INTO %s (`value`) VALUES (?)' % tmp, [row['value']], commit = False) value = self.dump(tmp)[0]['value'] self.execute(u'DROP TABLE %s' % tmp, commit = False) return value
python
def get_var(self, key): 'Retrieve one saved variable from the database.' vt = quote(self.__vars_table) data = self.execute(u'SELECT * FROM %s WHERE `key` = ?' % vt, [key], commit = False) if data == []: raise NameError(u'The DumpTruck variables table doesn\'t have a value for %s.' % key) else: tmp = quote(self.__vars_table_tmp) row = data[0] self.execute(u'DROP TABLE IF EXISTS %s' % tmp, commit = False) # This is vulnerable to injection self.execute(u'CREATE TEMPORARY TABLE %s (`value` %s)' % (tmp, row['type']), commit = False) # This is ugly self.execute(u'INSERT INTO %s (`value`) VALUES (?)' % tmp, [row['value']], commit = False) value = self.dump(tmp)[0]['value'] self.execute(u'DROP TABLE %s' % tmp, commit = False) return value
[ "def", "get_var", "(", "self", ",", "key", ")", ":", "vt", "=", "quote", "(", "self", ".", "__vars_table", ")", "data", "=", "self", ".", "execute", "(", "u'SELECT * FROM %s WHERE `key` = ?'", "%", "vt", ",", "[", "key", "]", ",", "commit", "=", "False...
Retrieve one saved variable from the database.
[ "Retrieve", "one", "saved", "variable", "from", "the", "database", "." ]
ac5855e34d4dffc7e53a13ff925ccabda19604fc
https://github.com/scraperwiki/dumptruck/blob/ac5855e34d4dffc7e53a13ff925ccabda19604fc/dumptruck/dumptruck.py#L307-L327
train
55,028
scraperwiki/dumptruck
dumptruck/dumptruck.py
DumpTruck.save_var
def save_var(self, key, value, **kwargs): 'Save one variable to the database.' # Check whether Highwall's variables table exists self.__check_or_create_vars_table() column_type = get_column_type(value) tmp = quote(self.__vars_table_tmp) self.execute(u'DROP TABLE IF EXISTS %s' % tmp, commit = False) # This is vulnerable to injection self.execute(u'CREATE TABLE %s (`value` %s)' % (tmp, column_type), commit = False) # This is ugly self.execute(u'INSERT INTO %s (`value`) VALUES (?)' % tmp, [value], commit = False) table = (quote(self.__vars_table), tmp) params = [key, column_type] self.execute(u''' INSERT OR REPLACE INTO %s (`key`, `type`, `value`) SELECT ? AS key, ? AS type, value FROM %s ''' % table, params) self.execute(u'DROP TABLE %s' % tmp, commit = False) self.__commit_if_necessary(kwargs)
python
def save_var(self, key, value, **kwargs): 'Save one variable to the database.' # Check whether Highwall's variables table exists self.__check_or_create_vars_table() column_type = get_column_type(value) tmp = quote(self.__vars_table_tmp) self.execute(u'DROP TABLE IF EXISTS %s' % tmp, commit = False) # This is vulnerable to injection self.execute(u'CREATE TABLE %s (`value` %s)' % (tmp, column_type), commit = False) # This is ugly self.execute(u'INSERT INTO %s (`value`) VALUES (?)' % tmp, [value], commit = False) table = (quote(self.__vars_table), tmp) params = [key, column_type] self.execute(u''' INSERT OR REPLACE INTO %s (`key`, `type`, `value`) SELECT ? AS key, ? AS type, value FROM %s ''' % table, params) self.execute(u'DROP TABLE %s' % tmp, commit = False) self.__commit_if_necessary(kwargs)
[ "def", "save_var", "(", "self", ",", "key", ",", "value", ",", "*", "*", "kwargs", ")", ":", "# Check whether Highwall's variables table exists", "self", ".", "__check_or_create_vars_table", "(", ")", "column_type", "=", "get_column_type", "(", "value", ")", "tmp"...
Save one variable to the database.
[ "Save", "one", "variable", "to", "the", "database", "." ]
ac5855e34d4dffc7e53a13ff925ccabda19604fc
https://github.com/scraperwiki/dumptruck/blob/ac5855e34d4dffc7e53a13ff925ccabda19604fc/dumptruck/dumptruck.py#L329-L357
train
55,029
scraperwiki/dumptruck
dumptruck/dumptruck.py
DumpTruck.drop
def drop(self, table_name = 'dumptruck', if_exists = False, **kwargs): 'Drop a table.' return self.execute(u'DROP TABLE %s %s;' % ('IF EXISTS' if if_exists else '', quote(table_name)), **kwargs)
python
def drop(self, table_name = 'dumptruck', if_exists = False, **kwargs): 'Drop a table.' return self.execute(u'DROP TABLE %s %s;' % ('IF EXISTS' if if_exists else '', quote(table_name)), **kwargs)
[ "def", "drop", "(", "self", ",", "table_name", "=", "'dumptruck'", ",", "if_exists", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "execute", "(", "u'DROP TABLE %s %s;'", "%", "(", "'IF EXISTS'", "if", "if_exists", "else", "''", ...
Drop a table.
[ "Drop", "a", "table", "." ]
ac5855e34d4dffc7e53a13ff925ccabda19604fc
https://github.com/scraperwiki/dumptruck/blob/ac5855e34d4dffc7e53a13ff925ccabda19604fc/dumptruck/dumptruck.py#L372-L374
train
55,030
toumorokoshi/sprinter
sprinter/formula/perforce.py
PerforceFormula.__install_perforce
def __install_perforce(self, config): """ install perforce binary """ if not system.is_64_bit(): self.logger.warn("Perforce formula is only designed for 64 bit systems! Not install executables...") return False version = config.get('version', 'r13.2') key = 'osx' if system.is_osx() else 'linux' perforce_packages = package_dict[version][key] d = self.directory.install_directory(self.feature_name) if not os.path.exists(d): os.makedirs(d) self.logger.info("Downloading p4 executable...") with open(os.path.join(d, "p4"), 'wb+') as fh: fh.write(lib.cleaned_request('get', url_prefix + perforce_packages['p4']).content) self.directory.symlink_to_bin("p4", os.path.join(d, "p4")) self.p4_command = os.path.join(d, "p4") self.logger.info("Installing p4v...") if system.is_osx(): return self._install_p4v_osx(url_prefix + perforce_packages['p4v']) else: return self._install_p4v_linux(url_prefix + perforce_packages['p4v'])
python
def __install_perforce(self, config): """ install perforce binary """ if not system.is_64_bit(): self.logger.warn("Perforce formula is only designed for 64 bit systems! Not install executables...") return False version = config.get('version', 'r13.2') key = 'osx' if system.is_osx() else 'linux' perforce_packages = package_dict[version][key] d = self.directory.install_directory(self.feature_name) if not os.path.exists(d): os.makedirs(d) self.logger.info("Downloading p4 executable...") with open(os.path.join(d, "p4"), 'wb+') as fh: fh.write(lib.cleaned_request('get', url_prefix + perforce_packages['p4']).content) self.directory.symlink_to_bin("p4", os.path.join(d, "p4")) self.p4_command = os.path.join(d, "p4") self.logger.info("Installing p4v...") if system.is_osx(): return self._install_p4v_osx(url_prefix + perforce_packages['p4v']) else: return self._install_p4v_linux(url_prefix + perforce_packages['p4v'])
[ "def", "__install_perforce", "(", "self", ",", "config", ")", ":", "if", "not", "system", ".", "is_64_bit", "(", ")", ":", "self", ".", "logger", ".", "warn", "(", "\"Perforce formula is only designed for 64 bit systems! Not install executables...\"", ")", "return", ...
install perforce binary
[ "install", "perforce", "binary" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/perforce.py#L144-L164
train
55,031
toumorokoshi/sprinter
sprinter/formula/perforce.py
PerforceFormula._install_p4v_osx
def _install_p4v_osx(self, url, overwrite=False): """ Install perforce applications and binaries for mac """ package_exists = False root_dir = os.path.expanduser(os.path.join("~", "Applications")) package_exists = len([x for x in P4V_APPLICATIONS if os.path.exists(os.path.join(root_dir, x))]) if not package_exists or overwrite: lib.extract_dmg(url, root_dir) else: self.logger.warn("P4V exists already in %s! Not overwriting..." % root_dir) return True
python
def _install_p4v_osx(self, url, overwrite=False): """ Install perforce applications and binaries for mac """ package_exists = False root_dir = os.path.expanduser(os.path.join("~", "Applications")) package_exists = len([x for x in P4V_APPLICATIONS if os.path.exists(os.path.join(root_dir, x))]) if not package_exists or overwrite: lib.extract_dmg(url, root_dir) else: self.logger.warn("P4V exists already in %s! Not overwriting..." % root_dir) return True
[ "def", "_install_p4v_osx", "(", "self", ",", "url", ",", "overwrite", "=", "False", ")", ":", "package_exists", "=", "False", "root_dir", "=", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "\"~\"", ",", "\"Applications\"...
Install perforce applications and binaries for mac
[ "Install", "perforce", "applications", "and", "binaries", "for", "mac" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/perforce.py#L166-L175
train
55,032
toumorokoshi/sprinter
sprinter/formula/perforce.py
PerforceFormula._install_p4v_linux
def _install_p4v_linux(self, url): """ Install perforce applications and binaries for linux """ lib.extract_targz(url, self.directory.install_directory(self.feature_name), remove_common_prefix=True) bin_path = os.path.join(self.directory.install_directory(self.feature_name), 'bin') if os.path.exists(bin_path): for f in os.listdir(bin_path): self.directory.symlink_to_bin(f, os.path.join(bin_path, f)) return True
python
def _install_p4v_linux(self, url): """ Install perforce applications and binaries for linux """ lib.extract_targz(url, self.directory.install_directory(self.feature_name), remove_common_prefix=True) bin_path = os.path.join(self.directory.install_directory(self.feature_name), 'bin') if os.path.exists(bin_path): for f in os.listdir(bin_path): self.directory.symlink_to_bin(f, os.path.join(bin_path, f)) return True
[ "def", "_install_p4v_linux", "(", "self", ",", "url", ")", ":", "lib", ".", "extract_targz", "(", "url", ",", "self", ".", "directory", ".", "install_directory", "(", "self", ".", "feature_name", ")", ",", "remove_common_prefix", "=", "True", ")", "bin_path"...
Install perforce applications and binaries for linux
[ "Install", "perforce", "applications", "and", "binaries", "for", "linux" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/perforce.py#L177-L186
train
55,033
toumorokoshi/sprinter
sprinter/formula/perforce.py
PerforceFormula.__write_p4settings
def __write_p4settings(self, config): """ write perforce settings """ self.logger.info("Writing p4settings...") root_dir = os.path.expanduser(config.get('root_path')) p4settings_path = os.path.join(root_dir, ".p4settings") if os.path.exists(p4settings_path): if self.target.get('overwrite_p4settings', False): self.logger.info("Overwriting existing p4settings...") os.remove(p4settings_path) else: return with open(p4settings_path, "w+") as p4settings_file: p4settings_file.write(p4settings_template % config.to_dict()) if config.get('write_password_p4settings', 'no'): p4settings_file.write("\nP4PASSWD=%s" % config['password'])
python
def __write_p4settings(self, config): """ write perforce settings """ self.logger.info("Writing p4settings...") root_dir = os.path.expanduser(config.get('root_path')) p4settings_path = os.path.join(root_dir, ".p4settings") if os.path.exists(p4settings_path): if self.target.get('overwrite_p4settings', False): self.logger.info("Overwriting existing p4settings...") os.remove(p4settings_path) else: return with open(p4settings_path, "w+") as p4settings_file: p4settings_file.write(p4settings_template % config.to_dict()) if config.get('write_password_p4settings', 'no'): p4settings_file.write("\nP4PASSWD=%s" % config['password'])
[ "def", "__write_p4settings", "(", "self", ",", "config", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Writing p4settings...\"", ")", "root_dir", "=", "os", ".", "path", ".", "expanduser", "(", "config", ".", "get", "(", "'root_path'", ")", ")", ...
write perforce settings
[ "write", "perforce", "settings" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/perforce.py#L188-L202
train
55,034
toumorokoshi/sprinter
sprinter/formula/perforce.py
PerforceFormula.__configure_client
def __configure_client(self, config): """ write the perforce client """ self.logger.info("Configuring p4 client...") client_dict = config.to_dict() client_dict['root_path'] = os.path.expanduser(config.get('root_path')) os.chdir(client_dict['root_path']) client_dict['hostname'] = system.NODE client_dict['p4view'] = config['p4view'] % self.environment.target.get_context_dict() client = re.sub('//depot', ' //depot', p4client_template % client_dict) self.logger.info(lib.call("%s client -i" % self.p4_command, stdin=client, env=self.p4environ, cwd=client_dict['root_path']))
python
def __configure_client(self, config): """ write the perforce client """ self.logger.info("Configuring p4 client...") client_dict = config.to_dict() client_dict['root_path'] = os.path.expanduser(config.get('root_path')) os.chdir(client_dict['root_path']) client_dict['hostname'] = system.NODE client_dict['p4view'] = config['p4view'] % self.environment.target.get_context_dict() client = re.sub('//depot', ' //depot', p4client_template % client_dict) self.logger.info(lib.call("%s client -i" % self.p4_command, stdin=client, env=self.p4environ, cwd=client_dict['root_path']))
[ "def", "__configure_client", "(", "self", ",", "config", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Configuring p4 client...\"", ")", "client_dict", "=", "config", ".", "to_dict", "(", ")", "client_dict", "[", "'root_path'", "]", "=", "os", ".", ...
write the perforce client
[ "write", "the", "perforce", "client" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/perforce.py#L209-L221
train
55,035
toumorokoshi/sprinter
sprinter/formula/eggscript.py
EggscriptFormula.__install_eggs
def __install_eggs(self, config): """ Install eggs for a particular configuration """ egg_carton = (self.directory.install_directory(self.feature_name), 'requirements.txt') eggs = self.__gather_eggs(config) self.logger.debug("Installing eggs %s..." % eggs) self.__load_carton(egg_carton, eggs) self.__prepare_eggs(egg_carton, config)
python
def __install_eggs(self, config): """ Install eggs for a particular configuration """ egg_carton = (self.directory.install_directory(self.feature_name), 'requirements.txt') eggs = self.__gather_eggs(config) self.logger.debug("Installing eggs %s..." % eggs) self.__load_carton(egg_carton, eggs) self.__prepare_eggs(egg_carton, config)
[ "def", "__install_eggs", "(", "self", ",", "config", ")", ":", "egg_carton", "=", "(", "self", ".", "directory", ".", "install_directory", "(", "self", ".", "feature_name", ")", ",", "'requirements.txt'", ")", "eggs", "=", "self", ".", "__gather_eggs", "(", ...
Install eggs for a particular configuration
[ "Install", "eggs", "for", "a", "particular", "configuration" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/eggscript.py#L116-L125
train
55,036
toumorokoshi/sprinter
sprinter/formula/eggscript.py
EggscriptFormula.__add_paths
def __add_paths(self, config): """ add the proper resources into the environment """ bin_path = os.path.join(self.directory.install_directory(self.feature_name), 'bin') whitelist_executables = self._get_whitelisted_executables(config) for f in os.listdir(bin_path): for pattern in BLACKLISTED_EXECUTABLES: if re.match(pattern, f): continue if whitelist_executables and f not in whitelist_executables: continue self.directory.symlink_to_bin(f, os.path.join(bin_path, f))
python
def __add_paths(self, config): """ add the proper resources into the environment """ bin_path = os.path.join(self.directory.install_directory(self.feature_name), 'bin') whitelist_executables = self._get_whitelisted_executables(config) for f in os.listdir(bin_path): for pattern in BLACKLISTED_EXECUTABLES: if re.match(pattern, f): continue if whitelist_executables and f not in whitelist_executables: continue self.directory.symlink_to_bin(f, os.path.join(bin_path, f))
[ "def", "__add_paths", "(", "self", ",", "config", ")", ":", "bin_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "directory", ".", "install_directory", "(", "self", ".", "feature_name", ")", ",", "'bin'", ")", "whitelist_executables", "=", ...
add the proper resources into the environment
[ "add", "the", "proper", "resources", "into", "the", "environment" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/eggscript.py#L127-L137
train
55,037
inveniosoftware/kwalitee
kwalitee/cli/prepare.py
amended_commits
def amended_commits(commits): """Return those git commit sha1s that have been amended later.""" # which SHA1 are declared as amended later? amended_sha1s = [] for message in commits.values(): amended_sha1s.extend(re.findall(r'AMENDS\s([0-f]+)', message)) return amended_sha1s
python
def amended_commits(commits): """Return those git commit sha1s that have been amended later.""" # which SHA1 are declared as amended later? amended_sha1s = [] for message in commits.values(): amended_sha1s.extend(re.findall(r'AMENDS\s([0-f]+)', message)) return amended_sha1s
[ "def", "amended_commits", "(", "commits", ")", ":", "# which SHA1 are declared as amended later?", "amended_sha1s", "=", "[", "]", "for", "message", "in", "commits", ".", "values", "(", ")", ":", "amended_sha1s", ".", "extend", "(", "re", ".", "findall", "(", ...
Return those git commit sha1s that have been amended later.
[ "Return", "those", "git", "commit", "sha1s", "that", "have", "been", "amended", "later", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/cli/prepare.py#L90-L96
train
55,038
inveniosoftware/kwalitee
kwalitee/cli/prepare.py
enrich_git_log_dict
def enrich_git_log_dict(messages, labels): """Enrich git log with related information on tickets.""" for commit_sha1, message in messages.items(): # detect module and ticket numbers for each commit: component = None title = message.split('\n')[0] try: component, title = title.split(":", 1) component = component.strip() except ValueError: pass # noqa paragraphs = [analyse_body_paragraph(p, labels) for p in message.split('\n\n')] yield { 'sha1': commit_sha1, 'component': component, 'title': title.strip(), 'tickets': re.findall(r'\s(#\d+)', message), 'paragraphs': [ (label, remove_ticket_directives(message)) for label, message in paragraphs ], }
python
def enrich_git_log_dict(messages, labels): """Enrich git log with related information on tickets.""" for commit_sha1, message in messages.items(): # detect module and ticket numbers for each commit: component = None title = message.split('\n')[0] try: component, title = title.split(":", 1) component = component.strip() except ValueError: pass # noqa paragraphs = [analyse_body_paragraph(p, labels) for p in message.split('\n\n')] yield { 'sha1': commit_sha1, 'component': component, 'title': title.strip(), 'tickets': re.findall(r'\s(#\d+)', message), 'paragraphs': [ (label, remove_ticket_directives(message)) for label, message in paragraphs ], }
[ "def", "enrich_git_log_dict", "(", "messages", ",", "labels", ")", ":", "for", "commit_sha1", ",", "message", "in", "messages", ".", "items", "(", ")", ":", "# detect module and ticket numbers for each commit:", "component", "=", "None", "title", "=", "message", "...
Enrich git log with related information on tickets.
[ "Enrich", "git", "log", "with", "related", "information", "on", "tickets", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/cli/prepare.py#L99-L122
train
55,039
inveniosoftware/kwalitee
kwalitee/cli/prepare.py
release
def release(obj, commit='HEAD', components=False): """Generate release notes.""" options = obj.options repository = obj.repository try: sha = 'oid' commits = _pygit2_commits(commit, repository) except ImportError: try: sha = 'hexsha' commits = _git_commits(commit, repository) except ImportError: click.echo('To use this feature, please install pygit2. ' 'GitPython will also work but is not recommended ' '(python <= 2.7 only).', file=sys.stderr) return 2 messages = OrderedDict([(getattr(c, sha), c.message) for c in commits]) for commit_sha1 in amended_commits(messages): if commit_sha1 in messages: del messages[commit_sha1] full_messages = list( enrich_git_log_dict(messages, options.get('commit_msg_labels')) ) indent = ' ' if components else '' wrapper = textwrap.TextWrapper( width=70, initial_indent=indent + '- ', subsequent_indent=indent + ' ', ) for label, section in options.get('commit_msg_labels'): if section is None: continue bullets = [] for commit in full_messages: bullets += [ {'text': bullet, 'component': commit['component']} for lbl, bullet in commit['paragraphs'] if lbl == label and bullet is not None ] if len(bullets) > 0: click.echo(section) click.echo('~' * len(section)) click.echo() if components: def key(cmt): return cmt['component'] for component, bullets in itertools.groupby( sorted(bullets, key=key), key): bullets = list(bullets) if len(bullets) > 0: click.echo('+ {}'.format(component)) click.echo() for bullet in bullets: click.echo(wrapper.fill(bullet['text'])) click.echo() else: for bullet in bullets: click.echo(wrapper.fill(bullet['text'])) click.echo() return 0
python
def release(obj, commit='HEAD', components=False): """Generate release notes.""" options = obj.options repository = obj.repository try: sha = 'oid' commits = _pygit2_commits(commit, repository) except ImportError: try: sha = 'hexsha' commits = _git_commits(commit, repository) except ImportError: click.echo('To use this feature, please install pygit2. ' 'GitPython will also work but is not recommended ' '(python <= 2.7 only).', file=sys.stderr) return 2 messages = OrderedDict([(getattr(c, sha), c.message) for c in commits]) for commit_sha1 in amended_commits(messages): if commit_sha1 in messages: del messages[commit_sha1] full_messages = list( enrich_git_log_dict(messages, options.get('commit_msg_labels')) ) indent = ' ' if components else '' wrapper = textwrap.TextWrapper( width=70, initial_indent=indent + '- ', subsequent_indent=indent + ' ', ) for label, section in options.get('commit_msg_labels'): if section is None: continue bullets = [] for commit in full_messages: bullets += [ {'text': bullet, 'component': commit['component']} for lbl, bullet in commit['paragraphs'] if lbl == label and bullet is not None ] if len(bullets) > 0: click.echo(section) click.echo('~' * len(section)) click.echo() if components: def key(cmt): return cmt['component'] for component, bullets in itertools.groupby( sorted(bullets, key=key), key): bullets = list(bullets) if len(bullets) > 0: click.echo('+ {}'.format(component)) click.echo() for bullet in bullets: click.echo(wrapper.fill(bullet['text'])) click.echo() else: for bullet in bullets: click.echo(wrapper.fill(bullet['text'])) click.echo() return 0
[ "def", "release", "(", "obj", ",", "commit", "=", "'HEAD'", ",", "components", "=", "False", ")", ":", "options", "=", "obj", ".", "options", "repository", "=", "obj", ".", "repository", "try", ":", "sha", "=", "'oid'", "commits", "=", "_pygit2_commits",...
Generate release notes.
[ "Generate", "release", "notes", "." ]
9124f8f55b15547fef08c6c43cabced314e70674
https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/cli/prepare.py#L130-L196
train
55,040
frascoweb/frasco
frasco/actions/common.py
redirect
def redirect(view=None, url=None, **kwargs): """Redirects to the specified view or url """ if view: if url: kwargs["url"] = url url = flask.url_for(view, **kwargs) current_context.exit(flask.redirect(url))
python
def redirect(view=None, url=None, **kwargs): """Redirects to the specified view or url """ if view: if url: kwargs["url"] = url url = flask.url_for(view, **kwargs) current_context.exit(flask.redirect(url))
[ "def", "redirect", "(", "view", "=", "None", ",", "url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "view", ":", "if", "url", ":", "kwargs", "[", "\"url\"", "]", "=", "url", "url", "=", "flask", ".", "url_for", "(", "view", ",", "*",...
Redirects to the specified view or url
[ "Redirects", "to", "the", "specified", "view", "or", "url" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/actions/common.py#L150-L157
train
55,041
wearpants/instrument
instrument/output/statsd.py
statsd_metric
def statsd_metric(name, count, elapsed): """Metric that records to statsd & graphite""" with statsd.pipeline() as pipe: pipe.incr(name, count) pipe.timing(name, int(round(1000 * elapsed)))
python
def statsd_metric(name, count, elapsed): """Metric that records to statsd & graphite""" with statsd.pipeline() as pipe: pipe.incr(name, count) pipe.timing(name, int(round(1000 * elapsed)))
[ "def", "statsd_metric", "(", "name", ",", "count", ",", "elapsed", ")", ":", "with", "statsd", ".", "pipeline", "(", ")", "as", "pipe", ":", "pipe", ".", "incr", "(", "name", ",", "count", ")", "pipe", ".", "timing", "(", "name", ",", "int", "(", ...
Metric that records to statsd & graphite
[ "Metric", "that", "records", "to", "statsd", "&", "graphite" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/output/statsd.py#L8-L12
train
55,042
nikcub/floyd
floyd/templating/jinja.py
compile_file
def compile_file(env, src_path, dst_path, encoding='utf-8', base_dir=''): """Compiles a Jinja2 template to python code. :param env: a Jinja2 Environment instance. :param src_path: path to the source file. :param dst_path: path to the destination file. :param encoding: template encoding. :param base_dir: the base path to be removed from the compiled template filename. """ src_file = file(src_path, 'r') source = src_file.read().decode(encoding) name = src_path.replace(base_dir, '') raw = env.compile(source, name=name, filename=name, raw=True) src_file.close() dst_file = open(dst_path, 'w') dst_file.write(raw) dst_file.close()
python
def compile_file(env, src_path, dst_path, encoding='utf-8', base_dir=''): """Compiles a Jinja2 template to python code. :param env: a Jinja2 Environment instance. :param src_path: path to the source file. :param dst_path: path to the destination file. :param encoding: template encoding. :param base_dir: the base path to be removed from the compiled template filename. """ src_file = file(src_path, 'r') source = src_file.read().decode(encoding) name = src_path.replace(base_dir, '') raw = env.compile(source, name=name, filename=name, raw=True) src_file.close() dst_file = open(dst_path, 'w') dst_file.write(raw) dst_file.close()
[ "def", "compile_file", "(", "env", ",", "src_path", ",", "dst_path", ",", "encoding", "=", "'utf-8'", ",", "base_dir", "=", "''", ")", ":", "src_file", "=", "file", "(", "src_path", ",", "'r'", ")", "source", "=", "src_file", ".", "read", "(", ")", "...
Compiles a Jinja2 template to python code. :param env: a Jinja2 Environment instance. :param src_path: path to the source file. :param dst_path: path to the destination file. :param encoding: template encoding. :param base_dir: the base path to be removed from the compiled template filename.
[ "Compiles", "a", "Jinja2", "template", "to", "python", "code", "." ]
5772d0047efb11c9ce5f7d234a9da4576ce24edc
https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/floyd/templating/jinja.py#L242-L259
train
55,043
wearpants/instrument
instrument/output/plot.py
PlotMetric._pre_dump
def _pre_dump(cls): """Output all recorded stats""" shutil.rmtree(cls.outdir, ignore_errors=True) os.makedirs(cls.outdir) super(PlotMetric, cls)._pre_dump()
python
def _pre_dump(cls): """Output all recorded stats""" shutil.rmtree(cls.outdir, ignore_errors=True) os.makedirs(cls.outdir) super(PlotMetric, cls)._pre_dump()
[ "def", "_pre_dump", "(", "cls", ")", ":", "shutil", ".", "rmtree", "(", "cls", ".", "outdir", ",", "ignore_errors", "=", "True", ")", "os", ".", "makedirs", "(", "cls", ".", "outdir", ")", "super", "(", "PlotMetric", ",", "cls", ")", ".", "_pre_dump"...
Output all recorded stats
[ "Output", "all", "recorded", "stats" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/output/plot.py#L27-L31
train
55,044
wearpants/instrument
instrument/output/plot.py
PlotMetric._histogram
def _histogram(self, which, mu, sigma, data): """plot a histogram. For internal use only""" weights = np.ones_like(data)/len(data) # make bar heights sum to 100% n, bins, patches = plt.hist(data, bins=25, weights=weights, facecolor='blue', alpha=0.5) plt.title(r'%s %s: $\mu=%.2f$, $\sigma=%.2f$' % (self.name, which.capitalize(), mu, sigma)) plt.xlabel('Items' if which == 'count' else 'Seconds') plt.ylabel('Frequency') plt.gca().yaxis.set_major_formatter(FuncFormatter(lambda y, position: "{:.1f}%".format(y*100)))
python
def _histogram(self, which, mu, sigma, data): """plot a histogram. For internal use only""" weights = np.ones_like(data)/len(data) # make bar heights sum to 100% n, bins, patches = plt.hist(data, bins=25, weights=weights, facecolor='blue', alpha=0.5) plt.title(r'%s %s: $\mu=%.2f$, $\sigma=%.2f$' % (self.name, which.capitalize(), mu, sigma)) plt.xlabel('Items' if which == 'count' else 'Seconds') plt.ylabel('Frequency') plt.gca().yaxis.set_major_formatter(FuncFormatter(lambda y, position: "{:.1f}%".format(y*100)))
[ "def", "_histogram", "(", "self", ",", "which", ",", "mu", ",", "sigma", ",", "data", ")", ":", "weights", "=", "np", ".", "ones_like", "(", "data", ")", "/", "len", "(", "data", ")", "# make bar heights sum to 100%", "n", ",", "bins", ",", "patches", ...
plot a histogram. For internal use only
[ "plot", "a", "histogram", ".", "For", "internal", "use", "only" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/output/plot.py#L51-L60
train
55,045
wearpants/instrument
instrument/output/plot.py
PlotMetric._scatter
def _scatter(self): """plot a scatter plot of count vs. elapsed. For internal use only""" plt.scatter(self.count_arr, self.elapsed_arr) plt.title('{}: Count vs. Elapsed'.format(self.name)) plt.xlabel('Items') plt.ylabel('Seconds')
python
def _scatter(self): """plot a scatter plot of count vs. elapsed. For internal use only""" plt.scatter(self.count_arr, self.elapsed_arr) plt.title('{}: Count vs. Elapsed'.format(self.name)) plt.xlabel('Items') plt.ylabel('Seconds')
[ "def", "_scatter", "(", "self", ")", ":", "plt", ".", "scatter", "(", "self", ".", "count_arr", ",", "self", ".", "elapsed_arr", ")", "plt", ".", "title", "(", "'{}: Count vs. Elapsed'", ".", "format", "(", "self", ".", "name", ")", ")", "plt", ".", ...
plot a scatter plot of count vs. elapsed. For internal use only
[ "plot", "a", "scatter", "plot", "of", "count", "vs", ".", "elapsed", ".", "For", "internal", "use", "only" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/output/plot.py#L62-L68
train
55,046
NiklasRosenstein-Python/nr-deprecated
nr/futures.py
Future.bind
def bind(self, __fun, *args, **kwargs): """ Bind a worker function to the future. This worker function will be executed when the future is executed. """ with self._lock: if self._running or self._completed or self._cancelled: raise RuntimeError('Future object can not be reused') if self._worker: raise RuntimeError('Future object is already bound') self._worker = functools.partial(__fun, *args, **kwargs) return self
python
def bind(self, __fun, *args, **kwargs): """ Bind a worker function to the future. This worker function will be executed when the future is executed. """ with self._lock: if self._running or self._completed or self._cancelled: raise RuntimeError('Future object can not be reused') if self._worker: raise RuntimeError('Future object is already bound') self._worker = functools.partial(__fun, *args, **kwargs) return self
[ "def", "bind", "(", "self", ",", "__fun", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "_lock", ":", "if", "self", ".", "_running", "or", "self", ".", "_completed", "or", "self", ".", "_cancelled", ":", "raise", "Runtim...
Bind a worker function to the future. This worker function will be executed when the future is executed.
[ "Bind", "a", "worker", "function", "to", "the", "future", ".", "This", "worker", "function", "will", "be", "executed", "when", "the", "future", "is", "executed", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/futures.py#L138-L150
train
55,047
NiklasRosenstein-Python/nr-deprecated
nr/futures.py
Future.set_result
def set_result(self, result): """ Allows you to set the result of the future without requiring the future to actually be executed. This can be used if the result is available before the future is run, allowing you to keep the future as the interface for retrieving the result data. :param result: The result of the future. :raise RuntimeError: If the future is already enqueued. """ with self._lock: if self._enqueued: raise RuntimeError('can not set result of enqueued Future') self._result = result self._completed = True callbacks = self._prepare_done_callbacks() callbacks()
python
def set_result(self, result): """ Allows you to set the result of the future without requiring the future to actually be executed. This can be used if the result is available before the future is run, allowing you to keep the future as the interface for retrieving the result data. :param result: The result of the future. :raise RuntimeError: If the future is already enqueued. """ with self._lock: if self._enqueued: raise RuntimeError('can not set result of enqueued Future') self._result = result self._completed = True callbacks = self._prepare_done_callbacks() callbacks()
[ "def", "set_result", "(", "self", ",", "result", ")", ":", "with", "self", ".", "_lock", ":", "if", "self", ".", "_enqueued", ":", "raise", "RuntimeError", "(", "'can not set result of enqueued Future'", ")", "self", ".", "_result", "=", "result", "self", "....
Allows you to set the result of the future without requiring the future to actually be executed. This can be used if the result is available before the future is run, allowing you to keep the future as the interface for retrieving the result data. :param result: The result of the future. :raise RuntimeError: If the future is already enqueued.
[ "Allows", "you", "to", "set", "the", "result", "of", "the", "future", "without", "requiring", "the", "future", "to", "actually", "be", "executed", ".", "This", "can", "be", "used", "if", "the", "result", "is", "available", "before", "the", "future", "is", ...
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/futures.py#L371-L388
train
55,048
NiklasRosenstein-Python/nr-deprecated
nr/futures.py
Future.set_exception
def set_exception(self, exc_info): """ This method allows you to set an exception in the future without requring that exception to be raised from the futures worker. This method can be called on an unbound future. :param exc_info: Either an exception info tuple or an exception value. In the latter case, the traceback will be automatically generated from the parent frame. :raise RuntimeError: If the future is already enqueued. """ if not isinstance(exc_info, tuple): if not isinstance(exc_info, BaseException): raise TypeError('expected BaseException instance') try: # TODO: Filld the traceback so it appears as if the exception # was actually raised by the caller? (Not sure if possible) raise exc_info except: exc_info = sys.exc_info() exc_info = (exc_info[0], exc_info[1], exc_info[2]) with self._lock: if self._enqueued: raise RuntimeError('can not set exception of enqueued Future') self._exc_info = exc_info self._completed = True callbacks = self._prepare_done_callbacks() callbacks()
python
def set_exception(self, exc_info): """ This method allows you to set an exception in the future without requring that exception to be raised from the futures worker. This method can be called on an unbound future. :param exc_info: Either an exception info tuple or an exception value. In the latter case, the traceback will be automatically generated from the parent frame. :raise RuntimeError: If the future is already enqueued. """ if not isinstance(exc_info, tuple): if not isinstance(exc_info, BaseException): raise TypeError('expected BaseException instance') try: # TODO: Filld the traceback so it appears as if the exception # was actually raised by the caller? (Not sure if possible) raise exc_info except: exc_info = sys.exc_info() exc_info = (exc_info[0], exc_info[1], exc_info[2]) with self._lock: if self._enqueued: raise RuntimeError('can not set exception of enqueued Future') self._exc_info = exc_info self._completed = True callbacks = self._prepare_done_callbacks() callbacks()
[ "def", "set_exception", "(", "self", ",", "exc_info", ")", ":", "if", "not", "isinstance", "(", "exc_info", ",", "tuple", ")", ":", "if", "not", "isinstance", "(", "exc_info", ",", "BaseException", ")", ":", "raise", "TypeError", "(", "'expected BaseExceptio...
This method allows you to set an exception in the future without requring that exception to be raised from the futures worker. This method can be called on an unbound future. :param exc_info: Either an exception info tuple or an exception value. In the latter case, the traceback will be automatically generated from the parent frame. :raise RuntimeError: If the future is already enqueued.
[ "This", "method", "allows", "you", "to", "set", "an", "exception", "in", "the", "future", "without", "requring", "that", "exception", "to", "be", "raised", "from", "the", "futures", "worker", ".", "This", "method", "can", "be", "called", "on", "an", "unbou...
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/futures.py#L390-L419
train
55,049
NiklasRosenstein-Python/nr-deprecated
nr/futures.py
ThreadPool.enqueue
def enqueue(self, future): """ Enqueue a future to be processed by one of the threads in the pool. The future must be bound to a worker and not have been started yet. """ future.enqueue() with self._lock: if self._shutdown: raise RuntimeError('ThreadPool has been shut down and can no ' 'longer accept futures.') self._queue.append(future) if len(self._running) == len(self._workers): self._new_worker() self._lock.notify_all()
python
def enqueue(self, future): """ Enqueue a future to be processed by one of the threads in the pool. The future must be bound to a worker and not have been started yet. """ future.enqueue() with self._lock: if self._shutdown: raise RuntimeError('ThreadPool has been shut down and can no ' 'longer accept futures.') self._queue.append(future) if len(self._running) == len(self._workers): self._new_worker() self._lock.notify_all()
[ "def", "enqueue", "(", "self", ",", "future", ")", ":", "future", ".", "enqueue", "(", ")", "with", "self", ".", "_lock", ":", "if", "self", ".", "_shutdown", ":", "raise", "RuntimeError", "(", "'ThreadPool has been shut down and can no '", "'longer accept futur...
Enqueue a future to be processed by one of the threads in the pool. The future must be bound to a worker and not have been started yet.
[ "Enqueue", "a", "future", "to", "be", "processed", "by", "one", "of", "the", "threads", "in", "the", "pool", ".", "The", "future", "must", "be", "bound", "to", "a", "worker", "and", "not", "have", "been", "started", "yet", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/futures.py#L479-L493
train
55,050
NiklasRosenstein-Python/nr-deprecated
nr/futures.py
ThreadPool.submit
def submit(self, __fun, *args, **kwargs): """ Creates a new future and enqueues it. Returns the future. """ future = Future().bind(__fun, *args, **kwargs) self.enqueue(future) return future
python
def submit(self, __fun, *args, **kwargs): """ Creates a new future and enqueues it. Returns the future. """ future = Future().bind(__fun, *args, **kwargs) self.enqueue(future) return future
[ "def", "submit", "(", "self", ",", "__fun", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "future", "=", "Future", "(", ")", ".", "bind", "(", "__fun", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "enqueue", "(", "future"...
Creates a new future and enqueues it. Returns the future.
[ "Creates", "a", "new", "future", "and", "enqueues", "it", ".", "Returns", "the", "future", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/futures.py#L495-L502
train
55,051
romaryd/python-awesome-decorators
awesomedecorators/timez.py
timeit
def timeit(func): """ Returns the number of seconds that a function took along with the result """ @wraps(func) def timer_wrapper(*args, **kwargs): """ Inner function that uses the Timer context object """ with Timer() as timer: result = func(*args, **kwargs) return result, timer return timer_wrapper
python
def timeit(func): """ Returns the number of seconds that a function took along with the result """ @wraps(func) def timer_wrapper(*args, **kwargs): """ Inner function that uses the Timer context object """ with Timer() as timer: result = func(*args, **kwargs) return result, timer return timer_wrapper
[ "def", "timeit", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "timer_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Inner function that uses the Timer context object\n \"\"\"", "with", "Timer", "(", ")", "...
Returns the number of seconds that a function took along with the result
[ "Returns", "the", "number", "of", "seconds", "that", "a", "function", "took", "along", "with", "the", "result" ]
8c83784149338ab69a25797e1097b214d33a5958
https://github.com/romaryd/python-awesome-decorators/blob/8c83784149338ab69a25797e1097b214d33a5958/awesomedecorators/timez.py#L18-L33
train
55,052
romaryd/python-awesome-decorators
awesomedecorators/timez.py
timeout
def timeout(seconds): """ Raises a TimeoutError if a function does not terminate within specified seconds. """ def _timeout_error(signal, frame): raise TimeoutError("Operation did not finish within \ {} seconds".format(seconds)) def timeout_decorator(func): @wraps(func) def timeout_wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _timeout_error) signal.alarm(seconds) try: return func(*args, **kwargs) finally: signal.alarm(0) return timeout_wrapper return timeout_decorator
python
def timeout(seconds): """ Raises a TimeoutError if a function does not terminate within specified seconds. """ def _timeout_error(signal, frame): raise TimeoutError("Operation did not finish within \ {} seconds".format(seconds)) def timeout_decorator(func): @wraps(func) def timeout_wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _timeout_error) signal.alarm(seconds) try: return func(*args, **kwargs) finally: signal.alarm(0) return timeout_wrapper return timeout_decorator
[ "def", "timeout", "(", "seconds", ")", ":", "def", "_timeout_error", "(", "signal", ",", "frame", ")", ":", "raise", "TimeoutError", "(", "\"Operation did not finish within \\\n {} seconds\"", ".", "format", "(", "seconds", ")", ")", "def", "timeout_decorator...
Raises a TimeoutError if a function does not terminate within specified seconds.
[ "Raises", "a", "TimeoutError", "if", "a", "function", "does", "not", "terminate", "within", "specified", "seconds", "." ]
8c83784149338ab69a25797e1097b214d33a5958
https://github.com/romaryd/python-awesome-decorators/blob/8c83784149338ab69a25797e1097b214d33a5958/awesomedecorators/timez.py#L36-L58
train
55,053
smarie/python-parsyfiles
parsyfiles/filesystem_mapping.py
FileMappingConfiguration.create_persisted_object
def create_persisted_object(self, location: str, logger: Logger) -> PersistedObject: """ Creates a PersistedObject representing the object at location 'location', and recursively creates all of its children :param location: :param logger: :return: """ #print('Checking all files under ' + location) logger.debug('Checking all files under [{loc}]'.format(loc=location)) obj = FileMappingConfiguration.RecursivePersistedObject(location=location, file_mapping_conf=self, logger=logger) #print('File checks done') logger.debug('File checks done') return obj
python
def create_persisted_object(self, location: str, logger: Logger) -> PersistedObject: """ Creates a PersistedObject representing the object at location 'location', and recursively creates all of its children :param location: :param logger: :return: """ #print('Checking all files under ' + location) logger.debug('Checking all files under [{loc}]'.format(loc=location)) obj = FileMappingConfiguration.RecursivePersistedObject(location=location, file_mapping_conf=self, logger=logger) #print('File checks done') logger.debug('File checks done') return obj
[ "def", "create_persisted_object", "(", "self", ",", "location", ":", "str", ",", "logger", ":", "Logger", ")", "->", "PersistedObject", ":", "#print('Checking all files under ' + location)", "logger", ".", "debug", "(", "'Checking all files under [{loc}]'", ".", "format...
Creates a PersistedObject representing the object at location 'location', and recursively creates all of its children :param location: :param logger: :return:
[ "Creates", "a", "PersistedObject", "representing", "the", "object", "at", "location", "location", "and", "recursively", "creates", "all", "of", "its", "children" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/filesystem_mapping.py#L476-L491
train
55,054
smarie/python-parsyfiles
parsyfiles/filesystem_mapping.py
WrappedFileMappingConfiguration.is_multifile_object_without_children
def is_multifile_object_without_children(self, location: str) -> bool: """ Returns True if an item with this location is present as a multifile object without children. For this implementation, this means that there is a folder without any files in it :param location: :return: """ return isdir(location) and len(self.find_multifile_object_children(location)) == 0
python
def is_multifile_object_without_children(self, location: str) -> bool: """ Returns True if an item with this location is present as a multifile object without children. For this implementation, this means that there is a folder without any files in it :param location: :return: """ return isdir(location) and len(self.find_multifile_object_children(location)) == 0
[ "def", "is_multifile_object_without_children", "(", "self", ",", "location", ":", "str", ")", "->", "bool", ":", "return", "isdir", "(", "location", ")", "and", "len", "(", "self", ".", "find_multifile_object_children", "(", "location", ")", ")", "==", "0" ]
Returns True if an item with this location is present as a multifile object without children. For this implementation, this means that there is a folder without any files in it :param location: :return:
[ "Returns", "True", "if", "an", "item", "with", "this", "location", "is", "present", "as", "a", "multifile", "object", "without", "children", ".", "For", "this", "implementation", "this", "means", "that", "there", "is", "a", "folder", "without", "any", "files...
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/filesystem_mapping.py#L549-L557
train
55,055
smarie/python-parsyfiles
parsyfiles/filesystem_mapping.py
WrappedFileMappingConfiguration.get_multifile_object_child_location
def get_multifile_object_child_location(self, parent_item_prefix: str, child_name: str) -> str: """ Implementation of the parent abstract method. In this mode the attribute is a file inside the parent object folder :param parent_item_prefix: the absolute file prefix of the parent item. :return: the file prefix for this attribute """ check_var(parent_item_prefix, var_types=str, var_name='parent_item_prefix') check_var(child_name, var_types=str, var_name='item_name') # assert that folder_path is a folder if not isdir(parent_item_prefix): raise ValueError( 'Cannot get attribute item in non-flat mode, parent item path is not a folder : ' + parent_item_prefix) return join(parent_item_prefix, child_name)
python
def get_multifile_object_child_location(self, parent_item_prefix: str, child_name: str) -> str: """ Implementation of the parent abstract method. In this mode the attribute is a file inside the parent object folder :param parent_item_prefix: the absolute file prefix of the parent item. :return: the file prefix for this attribute """ check_var(parent_item_prefix, var_types=str, var_name='parent_item_prefix') check_var(child_name, var_types=str, var_name='item_name') # assert that folder_path is a folder if not isdir(parent_item_prefix): raise ValueError( 'Cannot get attribute item in non-flat mode, parent item path is not a folder : ' + parent_item_prefix) return join(parent_item_prefix, child_name)
[ "def", "get_multifile_object_child_location", "(", "self", ",", "parent_item_prefix", ":", "str", ",", "child_name", ":", "str", ")", "->", "str", ":", "check_var", "(", "parent_item_prefix", ",", "var_types", "=", "str", ",", "var_name", "=", "'parent_item_prefix...
Implementation of the parent abstract method. In this mode the attribute is a file inside the parent object folder :param parent_item_prefix: the absolute file prefix of the parent item. :return: the file prefix for this attribute
[ "Implementation", "of", "the", "parent", "abstract", "method", ".", "In", "this", "mode", "the", "attribute", "is", "a", "file", "inside", "the", "parent", "object", "folder" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/filesystem_mapping.py#L559-L574
train
55,056
smarie/python-parsyfiles
parsyfiles/filesystem_mapping.py
FlatFileMappingConfiguration.is_multifile_object_without_children
def is_multifile_object_without_children(self, location: str) -> bool: """ Returns True if an item with this location is present as a multifile object without children. For this implementation, this means that there is a file with the appropriate name but without extension :param location: :return: """ # (1) Find the base directory and base name if isdir(location): # special case: parent location is the root folder where all the files are. return len(self.find_multifile_object_children(location)) == 0 else: # TODO same comment than in find_multifile_object_children if exists(location): # location is a file without extension. We can accept that as being a multifile object without children return True else: return False
python
def is_multifile_object_without_children(self, location: str) -> bool: """ Returns True if an item with this location is present as a multifile object without children. For this implementation, this means that there is a file with the appropriate name but without extension :param location: :return: """ # (1) Find the base directory and base name if isdir(location): # special case: parent location is the root folder where all the files are. return len(self.find_multifile_object_children(location)) == 0 else: # TODO same comment than in find_multifile_object_children if exists(location): # location is a file without extension. We can accept that as being a multifile object without children return True else: return False
[ "def", "is_multifile_object_without_children", "(", "self", ",", "location", ":", "str", ")", "->", "bool", ":", "# (1) Find the base directory and base name", "if", "isdir", "(", "location", ")", ":", "# special case: parent location is the root folder where all the files are....
Returns True if an item with this location is present as a multifile object without children. For this implementation, this means that there is a file with the appropriate name but without extension :param location: :return:
[ "Returns", "True", "if", "an", "item", "with", "this", "location", "is", "present", "as", "a", "multifile", "object", "without", "children", ".", "For", "this", "implementation", "this", "means", "that", "there", "is", "a", "file", "with", "the", "appropriat...
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/filesystem_mapping.py#L691-L708
train
55,057
thewca/wca-regulations-compiler
wrc/codegen/cghtml.py
special_links_replace
def special_links_replace(text, urls): ''' Replace simplified Regulations and Guidelines links into actual links. 'urls' dictionary is expected to provide actual links to the targeted Regulations and Guidelines, as well as to the PDF file. ''' match_number = r'([A-Za-z0-9]+)' + r'(\+*)' reference_list = [(r'regulations:article:' + match_number, urls['regulations']), (r'regulations:regulation:' + match_number, urls['regulations']), (r'guidelines:article:' + match_number, urls['guidelines']), (r'guidelines:guideline:' + match_number, urls['guidelines']), ] anchor_list = [(r'regulations:contents', urls['regulations'] + r'#contents'), (r'guidelines:contents', urls['guidelines'] + r'#contents'), (r'regulations:top', urls['regulations'] + r'#'), (r'guidelines:top', urls['guidelines'] + r'#'), (r'link:pdf', urls['pdf'] + '.pdf'), ] retval = text for match, repl in reference_list: retval = re.sub(match, repl + r'#\1\2', retval) for match, repl in anchor_list: retval = re.sub(match, repl, retval) return retval
python
def special_links_replace(text, urls): ''' Replace simplified Regulations and Guidelines links into actual links. 'urls' dictionary is expected to provide actual links to the targeted Regulations and Guidelines, as well as to the PDF file. ''' match_number = r'([A-Za-z0-9]+)' + r'(\+*)' reference_list = [(r'regulations:article:' + match_number, urls['regulations']), (r'regulations:regulation:' + match_number, urls['regulations']), (r'guidelines:article:' + match_number, urls['guidelines']), (r'guidelines:guideline:' + match_number, urls['guidelines']), ] anchor_list = [(r'regulations:contents', urls['regulations'] + r'#contents'), (r'guidelines:contents', urls['guidelines'] + r'#contents'), (r'regulations:top', urls['regulations'] + r'#'), (r'guidelines:top', urls['guidelines'] + r'#'), (r'link:pdf', urls['pdf'] + '.pdf'), ] retval = text for match, repl in reference_list: retval = re.sub(match, repl + r'#\1\2', retval) for match, repl in anchor_list: retval = re.sub(match, repl, retval) return retval
[ "def", "special_links_replace", "(", "text", ",", "urls", ")", ":", "match_number", "=", "r'([A-Za-z0-9]+)'", "+", "r'(\\+*)'", "reference_list", "=", "[", "(", "r'regulations:article:'", "+", "match_number", ",", "urls", "[", "'regulations'", "]", ")", ",", "("...
Replace simplified Regulations and Guidelines links into actual links. 'urls' dictionary is expected to provide actual links to the targeted Regulations and Guidelines, as well as to the PDF file.
[ "Replace", "simplified", "Regulations", "and", "Guidelines", "links", "into", "actual", "links", ".", "urls", "dictionary", "is", "expected", "to", "provide", "actual", "links", "to", "the", "targeted", "Regulations", "and", "Guidelines", "as", "well", "as", "to...
3ebbd8fe8fec7c9167296f59b2677696fe61a954
https://github.com/thewca/wca-regulations-compiler/blob/3ebbd8fe8fec7c9167296f59b2677696fe61a954/wrc/codegen/cghtml.py#L30-L53
train
55,058
thewca/wca-regulations-compiler
wrc/codegen/cghtml.py
link2html
def link2html(text): ''' Turns md links to html ''' match = r'\[([^\]]+)\]\(([^)]+)\)' replace = r'<a href="\2">\1</a>' return re.sub(match, replace, text)
python
def link2html(text): ''' Turns md links to html ''' match = r'\[([^\]]+)\]\(([^)]+)\)' replace = r'<a href="\2">\1</a>' return re.sub(match, replace, text)
[ "def", "link2html", "(", "text", ")", ":", "match", "=", "r'\\[([^\\]]+)\\]\\(([^)]+)\\)'", "replace", "=", "r'<a href=\"\\2\">\\1</a>'", "return", "re", ".", "sub", "(", "match", ",", "replace", ",", "text", ")" ]
Turns md links to html
[ "Turns", "md", "links", "to", "html" ]
3ebbd8fe8fec7c9167296f59b2677696fe61a954
https://github.com/thewca/wca-regulations-compiler/blob/3ebbd8fe8fec7c9167296f59b2677696fe61a954/wrc/codegen/cghtml.py#L70-L74
train
55,059
thewca/wca-regulations-compiler
wrc/codegen/cghtml.py
simple_md2html
def simple_md2html(text, urls): ''' Convert a text from md to html ''' retval = special_links_replace(text, urls) # Create a par break for double newlines retval = re.sub(r'\n\n', r'</p><p>', retval) # Create a visual br for every new line retval = re.sub(r'\n', r'<br />\n', retval) # Do we really need this ? Help reduce the diff to only '\n' diff. retval = re.sub(r'"', r'&quot;', retval) retval = list2html(retval) return link2html(retval)
python
def simple_md2html(text, urls): ''' Convert a text from md to html ''' retval = special_links_replace(text, urls) # Create a par break for double newlines retval = re.sub(r'\n\n', r'</p><p>', retval) # Create a visual br for every new line retval = re.sub(r'\n', r'<br />\n', retval) # Do we really need this ? Help reduce the diff to only '\n' diff. retval = re.sub(r'"', r'&quot;', retval) retval = list2html(retval) return link2html(retval)
[ "def", "simple_md2html", "(", "text", ",", "urls", ")", ":", "retval", "=", "special_links_replace", "(", "text", ",", "urls", ")", "# Create a par break for double newlines", "retval", "=", "re", ".", "sub", "(", "r'\\n\\n'", ",", "r'</p><p>'", ",", "retval", ...
Convert a text from md to html
[ "Convert", "a", "text", "from", "md", "to", "html" ]
3ebbd8fe8fec7c9167296f59b2677696fe61a954
https://github.com/thewca/wca-regulations-compiler/blob/3ebbd8fe8fec7c9167296f59b2677696fe61a954/wrc/codegen/cghtml.py#L76-L86
train
55,060
thewca/wca-regulations-compiler
wrc/codegen/cghtml.py
WCADocumentHtml.generate_ul
def generate_ul(self, a_list): ''' Determines if we should generate th 'ul' around the list 'a_list' ''' return len(a_list) > 0 and (isinstance(a_list[0], Rule) or isinstance(a_list[0], LabelDecl))
python
def generate_ul(self, a_list): ''' Determines if we should generate th 'ul' around the list 'a_list' ''' return len(a_list) > 0 and (isinstance(a_list[0], Rule) or isinstance(a_list[0], LabelDecl))
[ "def", "generate_ul", "(", "self", ",", "a_list", ")", ":", "return", "len", "(", "a_list", ")", ">", "0", "and", "(", "isinstance", "(", "a_list", "[", "0", "]", ",", "Rule", ")", "or", "isinstance", "(", "a_list", "[", "0", "]", ",", "LabelDecl",...
Determines if we should generate th 'ul' around the list 'a_list'
[ "Determines", "if", "we", "should", "generate", "th", "ul", "around", "the", "list", "a_list" ]
3ebbd8fe8fec7c9167296f59b2677696fe61a954
https://github.com/thewca/wca-regulations-compiler/blob/3ebbd8fe8fec7c9167296f59b2677696fe61a954/wrc/codegen/cghtml.py#L126-L129
train
55,061
mdickinson/refcycle
setup.py
get_version_info
def get_version_info(): """Extract version information as a dictionary from version.py.""" version_info = {} with open(os.path.join("refcycle", "version.py"), 'r') as f: version_code = compile(f.read(), "version.py", 'exec') exec(version_code, version_info) return version_info
python
def get_version_info(): """Extract version information as a dictionary from version.py.""" version_info = {} with open(os.path.join("refcycle", "version.py"), 'r') as f: version_code = compile(f.read(), "version.py", 'exec') exec(version_code, version_info) return version_info
[ "def", "get_version_info", "(", ")", ":", "version_info", "=", "{", "}", "with", "open", "(", "os", ".", "path", ".", "join", "(", "\"refcycle\"", ",", "\"version.py\"", ")", ",", "'r'", ")", "as", "f", ":", "version_code", "=", "compile", "(", "f", ...
Extract version information as a dictionary from version.py.
[ "Extract", "version", "information", "as", "a", "dictionary", "from", "version", ".", "py", "." ]
627fad74c74efc601209c96405f8118cd99b2241
https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/setup.py#L22-L28
train
55,062
bryanwweber/thermohw
thermohw/filters.py
div_filter
def div_filter(key: str, value: list, format: str, meta: Any) -> Optional[list]: """Filter the JSON ``value`` for alert divs. Arguments --------- key Key of the structure value Values in the structure format Output format of the processing meta Meta information """ if key != "Div" or format != "latex": return None [[_, classes, _], contents] = value try: alert_type = [name.split("-")[1] for name in classes if "-" in name][0] except IndexError: return None if alert_type not in ALLOWED_ALERT_TYPES.__members__: return None filtered = [RawBlock("latex", rf"\begin{{{alert_type}box}}")] filtered.extend(contents) filtered.append(RawBlock("latex", rf"\end{{{alert_type}box}}")) return filtered
python
def div_filter(key: str, value: list, format: str, meta: Any) -> Optional[list]: """Filter the JSON ``value`` for alert divs. Arguments --------- key Key of the structure value Values in the structure format Output format of the processing meta Meta information """ if key != "Div" or format != "latex": return None [[_, classes, _], contents] = value try: alert_type = [name.split("-")[1] for name in classes if "-" in name][0] except IndexError: return None if alert_type not in ALLOWED_ALERT_TYPES.__members__: return None filtered = [RawBlock("latex", rf"\begin{{{alert_type}box}}")] filtered.extend(contents) filtered.append(RawBlock("latex", rf"\end{{{alert_type}box}}")) return filtered
[ "def", "div_filter", "(", "key", ":", "str", ",", "value", ":", "list", ",", "format", ":", "str", ",", "meta", ":", "Any", ")", "->", "Optional", "[", "list", "]", ":", "if", "key", "!=", "\"Div\"", "or", "format", "!=", "\"latex\"", ":", "return"...
Filter the JSON ``value`` for alert divs. Arguments --------- key Key of the structure value Values in the structure format Output format of the processing meta Meta information
[ "Filter", "the", "JSON", "value", "for", "alert", "divs", "." ]
b6be276c14f8adf6ae23f5498065de74f868ccaa
https://github.com/bryanwweber/thermohw/blob/b6be276c14f8adf6ae23f5498065de74f868ccaa/thermohw/filters.py#L25-L54
train
55,063
bryanwweber/thermohw
thermohw/filters.py
convert_div
def convert_div(text: str, format: Optional[str] = None) -> "applyJSONFilters": """Apply the `dev_filter` action to the text.""" return applyJSONFilters([div_filter], text, format=format)
python
def convert_div(text: str, format: Optional[str] = None) -> "applyJSONFilters": """Apply the `dev_filter` action to the text.""" return applyJSONFilters([div_filter], text, format=format)
[ "def", "convert_div", "(", "text", ":", "str", ",", "format", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "\"applyJSONFilters\"", ":", "return", "applyJSONFilters", "(", "[", "div_filter", "]", ",", "text", ",", "format", "=", "format", ")"...
Apply the `dev_filter` action to the text.
[ "Apply", "the", "dev_filter", "action", "to", "the", "text", "." ]
b6be276c14f8adf6ae23f5498065de74f868ccaa
https://github.com/bryanwweber/thermohw/blob/b6be276c14f8adf6ae23f5498065de74f868ccaa/thermohw/filters.py#L57-L59
train
55,064
bryanwweber/thermohw
thermohw/filters.py
raw_html_filter
def raw_html_filter(key: str, value: list, format: str, meta: Any) -> Optional[list]: """Filter the JSON ``value`` for raw html to convert to LaTeX. Arguments --------- key Key of the structure value Values in the structure format Output format of the processing meta Meta information """ if key == "RawInline" and format == "latex" and value[0] == "html": if value[1] == "<sup>": filtered = [RawInline("latex", r"\textsuperscript{")] elif value[1] == "</sup>": filtered = [RawInline("latex", "}")] elif value[1] == "<sub>": filtered = [RawInline("latex", r"\textsubscript{")] elif value[1] == "</sub>": filtered = [RawInline("latex", "}")] else: return None return filtered return None
python
def raw_html_filter(key: str, value: list, format: str, meta: Any) -> Optional[list]: """Filter the JSON ``value`` for raw html to convert to LaTeX. Arguments --------- key Key of the structure value Values in the structure format Output format of the processing meta Meta information """ if key == "RawInline" and format == "latex" and value[0] == "html": if value[1] == "<sup>": filtered = [RawInline("latex", r"\textsuperscript{")] elif value[1] == "</sup>": filtered = [RawInline("latex", "}")] elif value[1] == "<sub>": filtered = [RawInline("latex", r"\textsubscript{")] elif value[1] == "</sub>": filtered = [RawInline("latex", "}")] else: return None return filtered return None
[ "def", "raw_html_filter", "(", "key", ":", "str", ",", "value", ":", "list", ",", "format", ":", "str", ",", "meta", ":", "Any", ")", "->", "Optional", "[", "list", "]", ":", "if", "key", "==", "\"RawInline\"", "and", "format", "==", "\"latex\"", "an...
Filter the JSON ``value`` for raw html to convert to LaTeX. Arguments --------- key Key of the structure value Values in the structure format Output format of the processing meta Meta information
[ "Filter", "the", "JSON", "value", "for", "raw", "html", "to", "convert", "to", "LaTeX", "." ]
b6be276c14f8adf6ae23f5498065de74f868ccaa
https://github.com/bryanwweber/thermohw/blob/b6be276c14f8adf6ae23f5498065de74f868ccaa/thermohw/filters.py#L62-L89
train
55,065
bryanwweber/thermohw
thermohw/filters.py
convert_raw_html
def convert_raw_html(text: str, format: Optional[str] = None) -> "applyJSONFilters": """Apply the `raw_html_filter` action to the text.""" return applyJSONFilters([raw_html_filter], text, format=format)
python
def convert_raw_html(text: str, format: Optional[str] = None) -> "applyJSONFilters": """Apply the `raw_html_filter` action to the text.""" return applyJSONFilters([raw_html_filter], text, format=format)
[ "def", "convert_raw_html", "(", "text", ":", "str", ",", "format", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "\"applyJSONFilters\"", ":", "return", "applyJSONFilters", "(", "[", "raw_html_filter", "]", ",", "text", ",", "format", "=", "form...
Apply the `raw_html_filter` action to the text.
[ "Apply", "the", "raw_html_filter", "action", "to", "the", "text", "." ]
b6be276c14f8adf6ae23f5498065de74f868ccaa
https://github.com/bryanwweber/thermohw/blob/b6be276c14f8adf6ae23f5498065de74f868ccaa/thermohw/filters.py#L92-L94
train
55,066
mdickinson/refcycle
refcycle/element_transform_set.py
ElementTransformSet.add
def add(self, element): """Add an element to this set.""" key = self._transform(element) if key not in self._elements: self._elements[key] = element
python
def add(self, element): """Add an element to this set.""" key = self._transform(element) if key not in self._elements: self._elements[key] = element
[ "def", "add", "(", "self", ",", "element", ")", ":", "key", "=", "self", ".", "_transform", "(", "element", ")", "if", "key", "not", "in", "self", ".", "_elements", ":", "self", ".", "_elements", "[", "key", "]", "=", "element" ]
Add an element to this set.
[ "Add", "an", "element", "to", "this", "set", "." ]
627fad74c74efc601209c96405f8118cd99b2241
https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/element_transform_set.py#L47-L51
train
55,067
jsmits/django-logutils
django_logutils/utils.py
add_items_to_message
def add_items_to_message(msg, log_dict): """Utility function to add dictionary items to a log message.""" out = msg for key, value in log_dict.items(): out += " {}={}".format(key, value) return out
python
def add_items_to_message(msg, log_dict): """Utility function to add dictionary items to a log message.""" out = msg for key, value in log_dict.items(): out += " {}={}".format(key, value) return out
[ "def", "add_items_to_message", "(", "msg", ",", "log_dict", ")", ":", "out", "=", "msg", "for", "key", ",", "value", "in", "log_dict", ".", "items", "(", ")", ":", "out", "+=", "\" {}={}\"", ".", "format", "(", "key", ",", "value", ")", "return", "ou...
Utility function to add dictionary items to a log message.
[ "Utility", "function", "to", "add", "dictionary", "items", "to", "a", "log", "message", "." ]
e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88
https://github.com/jsmits/django-logutils/blob/e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88/django_logutils/utils.py#L8-L13
train
55,068
wearpants/instrument
instrument/output/csv.py
CSVDirMetric.metric
def metric(cls, name, count, elapsed): """A metric function that writes multiple CSV files :arg str name: name of the metric :arg int count: number of items :arg float elapsed: time in seconds """ if name is None: warnings.warn("Ignoring unnamed metric", stacklevel=3) return with cls.lock: if not cls.instances: # first call shutil.rmtree(cls.outdir, ignore_errors=True) os.makedirs(cls.outdir) if cls.dump_atexit: atexit.register(cls.dump) try: self = cls.instances[name] except KeyError: self = cls.instances[name] = cls(name) self.writer.writerow((count, "%f"%elapsed))
python
def metric(cls, name, count, elapsed): """A metric function that writes multiple CSV files :arg str name: name of the metric :arg int count: number of items :arg float elapsed: time in seconds """ if name is None: warnings.warn("Ignoring unnamed metric", stacklevel=3) return with cls.lock: if not cls.instances: # first call shutil.rmtree(cls.outdir, ignore_errors=True) os.makedirs(cls.outdir) if cls.dump_atexit: atexit.register(cls.dump) try: self = cls.instances[name] except KeyError: self = cls.instances[name] = cls(name) self.writer.writerow((count, "%f"%elapsed))
[ "def", "metric", "(", "cls", ",", "name", ",", "count", ",", "elapsed", ")", ":", "if", "name", "is", "None", ":", "warnings", ".", "warn", "(", "\"Ignoring unnamed metric\"", ",", "stacklevel", "=", "3", ")", "return", "with", "cls", ".", "lock", ":",...
A metric function that writes multiple CSV files :arg str name: name of the metric :arg int count: number of items :arg float elapsed: time in seconds
[ "A", "metric", "function", "that", "writes", "multiple", "CSV", "files" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/output/csv.py#L38-L63
train
55,069
wearpants/instrument
instrument/output/csv.py
CSVFileMetric.metric
def metric(self, name, count, elapsed): """A metric function that writes a single CSV file :arg str name: name of the metric :arg int count: number of items :arg float elapsed: time in seconds """ if name is None: warnings.warn("Ignoring unnamed metric", stacklevel=3) return with self.lock: self.writer.writerow((name, count, "%f"%elapsed))
python
def metric(self, name, count, elapsed): """A metric function that writes a single CSV file :arg str name: name of the metric :arg int count: number of items :arg float elapsed: time in seconds """ if name is None: warnings.warn("Ignoring unnamed metric", stacklevel=3) return with self.lock: self.writer.writerow((name, count, "%f"%elapsed))
[ "def", "metric", "(", "self", ",", "name", ",", "count", ",", "elapsed", ")", ":", "if", "name", "is", "None", ":", "warnings", ".", "warn", "(", "\"Ignoring unnamed metric\"", ",", "stacklevel", "=", "3", ")", "return", "with", "self", ".", "lock", ":...
A metric function that writes a single CSV file :arg str name: name of the metric :arg int count: number of items :arg float elapsed: time in seconds
[ "A", "metric", "function", "that", "writes", "a", "single", "CSV", "file" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/output/csv.py#L102-L115
train
55,070
Cadasta/cadasta-workertoolbox
setup.py
read
def read(parts): """ Build an absolute path from parts array and and return the contents of the resulting file. Assume UTF-8 encoding. """ cur_dir = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(cur_dir, *parts), "rb", "utf-8") as f: return f.read()
python
def read(parts): """ Build an absolute path from parts array and and return the contents of the resulting file. Assume UTF-8 encoding. """ cur_dir = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(cur_dir, *parts), "rb", "utf-8") as f: return f.read()
[ "def", "read", "(", "parts", ")", ":", "cur_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "with", "codecs", ".", "open", "(", "os", ".", "path", ".", "join", "(", "cur_dir", ",", ...
Build an absolute path from parts array and and return the contents of the resulting file. Assume UTF-8 encoding.
[ "Build", "an", "absolute", "path", "from", "parts", "array", "and", "and", "return", "the", "contents", "of", "the", "resulting", "file", ".", "Assume", "UTF", "-", "8", "encoding", "." ]
e17cf376538cee0b32c7a21afd5319e3549b954f
https://github.com/Cadasta/cadasta-workertoolbox/blob/e17cf376538cee0b32c7a21afd5319e3549b954f/setup.py#L28-L35
train
55,071
Cadasta/cadasta-workertoolbox
setup.py
ensure_clean_git
def ensure_clean_git(operation='operation'): """ Verify that git has no uncommitted changes """ if os.system('git diff-index --quiet HEAD --'): print("Unstaged or uncommitted changes detected. {} aborted.".format( operation.capitalize())) sys.exit()
python
def ensure_clean_git(operation='operation'): """ Verify that git has no uncommitted changes """ if os.system('git diff-index --quiet HEAD --'): print("Unstaged or uncommitted changes detected. {} aborted.".format( operation.capitalize())) sys.exit()
[ "def", "ensure_clean_git", "(", "operation", "=", "'operation'", ")", ":", "if", "os", ".", "system", "(", "'git diff-index --quiet HEAD --'", ")", ":", "print", "(", "\"Unstaged or uncommitted changes detected. {} aborted.\"", ".", "format", "(", "operation", ".", "c...
Verify that git has no uncommitted changes
[ "Verify", "that", "git", "has", "no", "uncommitted", "changes" ]
e17cf376538cee0b32c7a21afd5319e3549b954f
https://github.com/Cadasta/cadasta-workertoolbox/blob/e17cf376538cee0b32c7a21afd5319e3549b954f/setup.py#L54-L59
train
55,072
nikcub/floyd
floyd/util/object.py
hasmethod
def hasmethod(obj, meth): """ Checks if an object, obj, has a callable method, meth return True or False """ if hasattr(obj, meth): return callable(getattr(obj,meth)) return False
python
def hasmethod(obj, meth): """ Checks if an object, obj, has a callable method, meth return True or False """ if hasattr(obj, meth): return callable(getattr(obj,meth)) return False
[ "def", "hasmethod", "(", "obj", ",", "meth", ")", ":", "if", "hasattr", "(", "obj", ",", "meth", ")", ":", "return", "callable", "(", "getattr", "(", "obj", ",", "meth", ")", ")", "return", "False" ]
Checks if an object, obj, has a callable method, meth return True or False
[ "Checks", "if", "an", "object", "obj", "has", "a", "callable", "method", "meth", "return", "True", "or", "False" ]
5772d0047efb11c9ce5f7d234a9da4576ce24edc
https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/floyd/util/object.py#L19-L27
train
55,073
nikcub/floyd
floyd/util/object.py
hasvar
def hasvar(obj, var): """ Checks if object, obj has a variable var return True or False """ if hasattr(obj, var): return not callable(getattr(obj, var)) return False
python
def hasvar(obj, var): """ Checks if object, obj has a variable var return True or False """ if hasattr(obj, var): return not callable(getattr(obj, var)) return False
[ "def", "hasvar", "(", "obj", ",", "var", ")", ":", "if", "hasattr", "(", "obj", ",", "var", ")", ":", "return", "not", "callable", "(", "getattr", "(", "obj", ",", "var", ")", ")", "return", "False" ]
Checks if object, obj has a variable var return True or False
[ "Checks", "if", "object", "obj", "has", "a", "variable", "var", "return", "True", "or", "False" ]
5772d0047efb11c9ce5f7d234a9da4576ce24edc
https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/floyd/util/object.py#L29-L37
train
55,074
nikcub/floyd
floyd/util/object.py
getmethattr
def getmethattr(obj, meth): """ Returns either the variable value or method invocation """ if hasmethod(obj, meth): return getattr(obj, meth)() elif hasvar(obj, meth): return getattr(obj, meth) return None
python
def getmethattr(obj, meth): """ Returns either the variable value or method invocation """ if hasmethod(obj, meth): return getattr(obj, meth)() elif hasvar(obj, meth): return getattr(obj, meth) return None
[ "def", "getmethattr", "(", "obj", ",", "meth", ")", ":", "if", "hasmethod", "(", "obj", ",", "meth", ")", ":", "return", "getattr", "(", "obj", ",", "meth", ")", "(", ")", "elif", "hasvar", "(", "obj", ",", "meth", ")", ":", "return", "getattr", ...
Returns either the variable value or method invocation
[ "Returns", "either", "the", "variable", "value", "or", "method", "invocation" ]
5772d0047efb11c9ce5f7d234a9da4576ce24edc
https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/floyd/util/object.py#L39-L47
train
55,075
nikcub/floyd
floyd/util/object.py
assure_obj_child_dict
def assure_obj_child_dict(obj, var): """Assure the object has the specified child dict """ if not var in obj or type(obj[var]) != type({}): obj[var] = {} return obj
python
def assure_obj_child_dict(obj, var): """Assure the object has the specified child dict """ if not var in obj or type(obj[var]) != type({}): obj[var] = {} return obj
[ "def", "assure_obj_child_dict", "(", "obj", ",", "var", ")", ":", "if", "not", "var", "in", "obj", "or", "type", "(", "obj", "[", "var", "]", ")", "!=", "type", "(", "{", "}", ")", ":", "obj", "[", "var", "]", "=", "{", "}", "return", "obj" ]
Assure the object has the specified child dict
[ "Assure", "the", "object", "has", "the", "specified", "child", "dict" ]
5772d0047efb11c9ce5f7d234a9da4576ce24edc
https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/floyd/util/object.py#L50-L55
train
55,076
toumorokoshi/sprinter
sprinter/environment.py
warmup
def warmup(f): """ Decorator to run warmup before running a command """ @wraps(f) def wrapped(self, *args, **kwargs): if not self.warmed_up: self.warmup() return f(self, *args, **kwargs) return wrapped
python
def warmup(f): """ Decorator to run warmup before running a command """ @wraps(f) def wrapped(self, *args, **kwargs): if not self.warmed_up: self.warmup() return f(self, *args, **kwargs) return wrapped
[ "def", "warmup", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapped", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "warmed_up", ":", "self", ".", "warmup", "(", ")", "return", "f", ...
Decorator to run warmup before running a command
[ "Decorator", "to", "run", "warmup", "before", "running", "a", "command" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L20-L28
train
55,077
toumorokoshi/sprinter
sprinter/environment.py
install_required
def install_required(f): """ Return an exception if the namespace is not already installed """ @wraps(f) def wrapped(self, *args, **kwargs): if self.directory.new: raise SprinterException("Namespace %s is not yet installed!" % self.namespace) return f(self, *args, **kwargs) return wrapped
python
def install_required(f): """ Return an exception if the namespace is not already installed """ @wraps(f) def wrapped(self, *args, **kwargs): if self.directory.new: raise SprinterException("Namespace %s is not yet installed!" % self.namespace) return f(self, *args, **kwargs) return wrapped
[ "def", "install_required", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapped", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "directory", ".", "new", ":", "raise", "SprinterException", "(", "\"N...
Return an exception if the namespace is not already installed
[ "Return", "an", "exception", "if", "the", "namespace", "is", "not", "already", "installed" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L31-L39
train
55,078
toumorokoshi/sprinter
sprinter/environment.py
Environment.install
def install(self): """ Install the environment """ self.phase = PHASE.INSTALL if not self.directory.new: self.logger.info("Namespace %s directory already exists!" % self.namespace) self.source = load_manifest(self.directory.manifest_path) return self.update() try: self.logger.info("Installing environment %s..." % self.namespace) self.directory.initialize() self.install_sandboxes() self.instantiate_features() self.grab_inputs() self._specialize() for feature in self.features.run_order: self.run_action(feature, 'sync') self.inject_environment_config() self._finalize() except Exception: self.logger.debug("", exc_info=sys.exc_info()) self.logger.info("An error occured during installation!") if not self.ignore_errors: self.clear_all() self.logger.info("Removing installation %s..." % self.namespace) self.directory.remove() et, ei, tb = sys.exc_info() reraise(et, ei, tb)
python
def install(self): """ Install the environment """ self.phase = PHASE.INSTALL if not self.directory.new: self.logger.info("Namespace %s directory already exists!" % self.namespace) self.source = load_manifest(self.directory.manifest_path) return self.update() try: self.logger.info("Installing environment %s..." % self.namespace) self.directory.initialize() self.install_sandboxes() self.instantiate_features() self.grab_inputs() self._specialize() for feature in self.features.run_order: self.run_action(feature, 'sync') self.inject_environment_config() self._finalize() except Exception: self.logger.debug("", exc_info=sys.exc_info()) self.logger.info("An error occured during installation!") if not self.ignore_errors: self.clear_all() self.logger.info("Removing installation %s..." % self.namespace) self.directory.remove() et, ei, tb = sys.exc_info() reraise(et, ei, tb)
[ "def", "install", "(", "self", ")", ":", "self", ".", "phase", "=", "PHASE", ".", "INSTALL", "if", "not", "self", ".", "directory", ".", "new", ":", "self", ".", "logger", ".", "info", "(", "\"Namespace %s directory already exists!\"", "%", "self", ".", ...
Install the environment
[ "Install", "the", "environment" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L128-L154
train
55,079
toumorokoshi/sprinter
sprinter/environment.py
Environment.update
def update(self, reconfigure=False): """ update the environment """ try: self.phase = PHASE.UPDATE self.logger.info("Updating environment %s..." % self.namespace) self.install_sandboxes() self.instantiate_features() # We don't grab inputs, only on install # updates inputs are grabbed on demand # self.grab_inputs(reconfigure=reconfigure) if reconfigure: self.grab_inputs(reconfigure=True) else: self._copy_source_to_target() self._specialize(reconfigure=reconfigure) for feature in self.features.run_order: self.run_action(feature, 'sync') self.inject_environment_config() self._finalize() except Exception: self.logger.debug("", exc_info=sys.exc_info()) et, ei, tb = sys.exc_info() reraise(et, ei, tb)
python
def update(self, reconfigure=False): """ update the environment """ try: self.phase = PHASE.UPDATE self.logger.info("Updating environment %s..." % self.namespace) self.install_sandboxes() self.instantiate_features() # We don't grab inputs, only on install # updates inputs are grabbed on demand # self.grab_inputs(reconfigure=reconfigure) if reconfigure: self.grab_inputs(reconfigure=True) else: self._copy_source_to_target() self._specialize(reconfigure=reconfigure) for feature in self.features.run_order: self.run_action(feature, 'sync') self.inject_environment_config() self._finalize() except Exception: self.logger.debug("", exc_info=sys.exc_info()) et, ei, tb = sys.exc_info() reraise(et, ei, tb)
[ "def", "update", "(", "self", ",", "reconfigure", "=", "False", ")", ":", "try", ":", "self", ".", "phase", "=", "PHASE", ".", "UPDATE", "self", ".", "logger", ".", "info", "(", "\"Updating environment %s...\"", "%", "self", ".", "namespace", ")", "self"...
update the environment
[ "update", "the", "environment" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L158-L180
train
55,080
toumorokoshi/sprinter
sprinter/environment.py
Environment.remove
def remove(self): """ remove the environment """ try: self.phase = PHASE.REMOVE self.logger.info("Removing environment %s..." % self.namespace) self.instantiate_features() self._specialize() for feature in self.features.run_order: try: self.run_action(feature, 'sync') except FormulaException: # continue trying to remove any remaining features. pass self.clear_all() self.directory.remove() self.injections.commit() if self.error_occured: self.logger.error(warning_template) self.logger.error(REMOVE_WARNING) except Exception: self.logger.debug("", exc_info=sys.exc_info()) et, ei, tb = sys.exc_info() reraise(et, ei, tb)
python
def remove(self): """ remove the environment """ try: self.phase = PHASE.REMOVE self.logger.info("Removing environment %s..." % self.namespace) self.instantiate_features() self._specialize() for feature in self.features.run_order: try: self.run_action(feature, 'sync') except FormulaException: # continue trying to remove any remaining features. pass self.clear_all() self.directory.remove() self.injections.commit() if self.error_occured: self.logger.error(warning_template) self.logger.error(REMOVE_WARNING) except Exception: self.logger.debug("", exc_info=sys.exc_info()) et, ei, tb = sys.exc_info() reraise(et, ei, tb)
[ "def", "remove", "(", "self", ")", ":", "try", ":", "self", ".", "phase", "=", "PHASE", ".", "REMOVE", "self", ".", "logger", ".", "info", "(", "\"Removing environment %s...\"", "%", "self", ".", "namespace", ")", "self", ".", "instantiate_features", "(", ...
remove the environment
[ "remove", "the", "environment" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L184-L206
train
55,081
toumorokoshi/sprinter
sprinter/environment.py
Environment.deactivate
def deactivate(self): """ deactivate the environment """ try: self.phase = PHASE.DEACTIVATE self.logger.info("Deactivating environment %s..." % self.namespace) self.directory.rewrite_config = False self.instantiate_features() self._specialize() for feature in self.features.run_order: self.logger.info("Deactivating %s..." % feature[0]) self.run_action(feature, 'deactivate') self.clear_all() self._finalize() except Exception: self.logger.debug("", exc_info=sys.exc_info()) et, ei, tb = sys.exc_info() reraise(et, ei, tb)
python
def deactivate(self): """ deactivate the environment """ try: self.phase = PHASE.DEACTIVATE self.logger.info("Deactivating environment %s..." % self.namespace) self.directory.rewrite_config = False self.instantiate_features() self._specialize() for feature in self.features.run_order: self.logger.info("Deactivating %s..." % feature[0]) self.run_action(feature, 'deactivate') self.clear_all() self._finalize() except Exception: self.logger.debug("", exc_info=sys.exc_info()) et, ei, tb = sys.exc_info() reraise(et, ei, tb)
[ "def", "deactivate", "(", "self", ")", ":", "try", ":", "self", ".", "phase", "=", "PHASE", ".", "DEACTIVATE", "self", ".", "logger", ".", "info", "(", "\"Deactivating environment %s...\"", "%", "self", ".", "namespace", ")", "self", ".", "directory", ".",...
deactivate the environment
[ "deactivate", "the", "environment" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L210-L226
train
55,082
toumorokoshi/sprinter
sprinter/environment.py
Environment.validate
def validate(self): """ Validate the target environment """ self.phase = PHASE.VALIDATE self.logger.info("Validating %s..." % self.namespace) self.instantiate_features() context_dict = {} if self.target: for s in self.target.formula_sections(): context_dict["%s:root_dir" % s] = self.directory.install_directory(s) context_dict['config:root_dir'] = self.directory.root_dir context_dict['config:node'] = system.NODE self.target.add_additional_context(context_dict) for feature in self.features.run_order: self.run_action(feature, 'validate', run_if_error=True)
python
def validate(self): """ Validate the target environment """ self.phase = PHASE.VALIDATE self.logger.info("Validating %s..." % self.namespace) self.instantiate_features() context_dict = {} if self.target: for s in self.target.formula_sections(): context_dict["%s:root_dir" % s] = self.directory.install_directory(s) context_dict['config:root_dir'] = self.directory.root_dir context_dict['config:node'] = system.NODE self.target.add_additional_context(context_dict) for feature in self.features.run_order: self.run_action(feature, 'validate', run_if_error=True)
[ "def", "validate", "(", "self", ")", ":", "self", ".", "phase", "=", "PHASE", ".", "VALIDATE", "self", ".", "logger", ".", "info", "(", "\"Validating %s...\"", "%", "self", ".", "namespace", ")", "self", ".", "instantiate_features", "(", ")", "context_dict...
Validate the target environment
[ "Validate", "the", "target", "environment" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L249-L262
train
55,083
toumorokoshi/sprinter
sprinter/environment.py
Environment.clear_all
def clear_all(self): """ clear all files that were to be injected """ self.injections.clear_all() for config_file in CONFIG_FILES: self.injections.clear(os.path.join("~", config_file))
python
def clear_all(self): """ clear all files that were to be injected """ self.injections.clear_all() for config_file in CONFIG_FILES: self.injections.clear(os.path.join("~", config_file))
[ "def", "clear_all", "(", "self", ")", ":", "self", ".", "injections", ".", "clear_all", "(", ")", "for", "config_file", "in", "CONFIG_FILES", ":", "self", ".", "injections", ".", "clear", "(", "os", ".", "path", ".", "join", "(", "\"~\"", ",", "config_...
clear all files that were to be injected
[ "clear", "all", "files", "that", "were", "to", "be", "injected" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L299-L303
train
55,084
toumorokoshi/sprinter
sprinter/environment.py
Environment.write_debug_log
def write_debug_log(self, file_path): """ Write the debug log to a file """ with open(file_path, "wb+") as fh: fh.write(system.get_system_info().encode('utf-8')) # writing to debug stream self._debug_stream.seek(0) fh.write(self._debug_stream.read().encode('utf-8')) fh.write("The following errors occured:\n".encode('utf-8')) for error in self._errors: fh.write((error + "\n").encode('utf-8')) for k, v in self._error_dict.items(): if len(v) > 0: fh.write(("Error(s) in %s with formula %s:\n" % k).encode('utf-8')) for error in v: fh.write((error + "\n").encode('utf-8'))
python
def write_debug_log(self, file_path): """ Write the debug log to a file """ with open(file_path, "wb+") as fh: fh.write(system.get_system_info().encode('utf-8')) # writing to debug stream self._debug_stream.seek(0) fh.write(self._debug_stream.read().encode('utf-8')) fh.write("The following errors occured:\n".encode('utf-8')) for error in self._errors: fh.write((error + "\n").encode('utf-8')) for k, v in self._error_dict.items(): if len(v) > 0: fh.write(("Error(s) in %s with formula %s:\n" % k).encode('utf-8')) for error in v: fh.write((error + "\n").encode('utf-8'))
[ "def", "write_debug_log", "(", "self", ",", "file_path", ")", ":", "with", "open", "(", "file_path", ",", "\"wb+\"", ")", "as", "fh", ":", "fh", ".", "write", "(", "system", ".", "get_system_info", "(", ")", ".", "encode", "(", "'utf-8'", ")", ")", "...
Write the debug log to a file
[ "Write", "the", "debug", "log", "to", "a", "file" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L335-L349
train
55,085
toumorokoshi/sprinter
sprinter/environment.py
Environment.write_manifest
def write_manifest(self): """ Write the manifest to the file """ if os.path.exists(self.directory.manifest_path): self.main_manifest.write(open(self.directory.manifest_path, "w+"))
python
def write_manifest(self): """ Write the manifest to the file """ if os.path.exists(self.directory.manifest_path): self.main_manifest.write(open(self.directory.manifest_path, "w+"))
[ "def", "write_manifest", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "directory", ".", "manifest_path", ")", ":", "self", ".", "main_manifest", ".", "write", "(", "open", "(", "self", ".", "directory", ".", "manifes...
Write the manifest to the file
[ "Write", "the", "manifest", "to", "the", "file" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L351-L354
train
55,086
toumorokoshi/sprinter
sprinter/environment.py
Environment.message_failure
def message_failure(self): """ return a failure message, if one exists """ if not isinstance(self.main_manifest, Manifest): return None return self.main_manifest.get('config', 'message_failure', default=None)
python
def message_failure(self): """ return a failure message, if one exists """ if not isinstance(self.main_manifest, Manifest): return None return self.main_manifest.get('config', 'message_failure', default=None)
[ "def", "message_failure", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "main_manifest", ",", "Manifest", ")", ":", "return", "None", "return", "self", ".", "main_manifest", ".", "get", "(", "'config'", ",", "'message_failure'", ",", ...
return a failure message, if one exists
[ "return", "a", "failure", "message", "if", "one", "exists" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L356-L360
train
55,087
toumorokoshi/sprinter
sprinter/environment.py
Environment.warmup
def warmup(self): """ initialize variables necessary to perform a sprinter action """ self.logger.debug("Warming up...") try: if not isinstance(self.source, Manifest) and self.source: self.source = load_manifest(self.source) if not isinstance(self.target, Manifest) and self.target: self.target = load_manifest(self.target) self.main_manifest = self.target or self.source except lib.BadCredentialsException: e = sys.exc_info()[1] self.logger.error(str(e)) raise SprinterException("Fatal error! Bad credentials to grab manifest!") if not getattr(self, 'namespace', None): if self.target: self.namespace = self.target.namespace elif not self.namespace and self.source: self.namespace = self.source.namespace else: raise SprinterException("No environment name has been specified!") self.directory_root = self.custom_directory_root if not self.directory: if not self.directory_root: self.directory_root = os.path.join(self.root, self.namespace) self.directory = Directory(self.directory_root, shell_util_path=self.shell_util_path) if not self.injections: self.injections = Injections(wrapper="%s_%s" % (self.sprinter_namespace.upper(), self.namespace), override="SPRINTER_OVERRIDES") if not self.global_injections: self.global_injections = Injections(wrapper="%s" % self.sprinter_namespace.upper() + "GLOBALS", override="SPRINTER_OVERRIDES") # append the bin, in the case sandboxes are necessary to # execute commands further down the sprinter lifecycle os.environ['PATH'] = self.directory.bin_path() + ":" + os.environ['PATH'] self.warmed_up = True
python
def warmup(self): """ initialize variables necessary to perform a sprinter action """ self.logger.debug("Warming up...") try: if not isinstance(self.source, Manifest) and self.source: self.source = load_manifest(self.source) if not isinstance(self.target, Manifest) and self.target: self.target = load_manifest(self.target) self.main_manifest = self.target or self.source except lib.BadCredentialsException: e = sys.exc_info()[1] self.logger.error(str(e)) raise SprinterException("Fatal error! Bad credentials to grab manifest!") if not getattr(self, 'namespace', None): if self.target: self.namespace = self.target.namespace elif not self.namespace and self.source: self.namespace = self.source.namespace else: raise SprinterException("No environment name has been specified!") self.directory_root = self.custom_directory_root if not self.directory: if not self.directory_root: self.directory_root = os.path.join(self.root, self.namespace) self.directory = Directory(self.directory_root, shell_util_path=self.shell_util_path) if not self.injections: self.injections = Injections(wrapper="%s_%s" % (self.sprinter_namespace.upper(), self.namespace), override="SPRINTER_OVERRIDES") if not self.global_injections: self.global_injections = Injections(wrapper="%s" % self.sprinter_namespace.upper() + "GLOBALS", override="SPRINTER_OVERRIDES") # append the bin, in the case sandboxes are necessary to # execute commands further down the sprinter lifecycle os.environ['PATH'] = self.directory.bin_path() + ":" + os.environ['PATH'] self.warmed_up = True
[ "def", "warmup", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Warming up...\"", ")", "try", ":", "if", "not", "isinstance", "(", "self", ".", "source", ",", "Manifest", ")", "and", "self", ".", "source", ":", "self", ".", "sour...
initialize variables necessary to perform a sprinter action
[ "initialize", "variables", "necessary", "to", "perform", "a", "sprinter", "action" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L366-L408
train
55,088
toumorokoshi/sprinter
sprinter/environment.py
Environment._inject_config_source
def _inject_config_source(self, source_filename, files_to_inject): """ Inject existing environmental config with namespace sourcing. Returns a tuple of the first file name and path found. """ # src_path = os.path.join(self.directory.root_dir, source_filename) # src_exec = "[ -r %s ] && . %s" % (src_path, src_path) src_exec = "[ -r {0} ] && . {0}".format(os.path.join(self.directory.root_dir, source_filename)) # The ridiculous construction above is necessary to avoid failing tests(!) for config_file in files_to_inject: config_path = os.path.expanduser(os.path.join("~", config_file)) if os.path.exists(config_path): self.injections.inject(config_path, src_exec) break else: config_file = files_to_inject[0] config_path = os.path.expanduser(os.path.join("~", config_file)) self.logger.info("No config files found to source %s, creating ~/%s!" % (source_filename, config_file)) self.injections.inject(config_path, src_exec) return (config_file, config_path)
python
def _inject_config_source(self, source_filename, files_to_inject): """ Inject existing environmental config with namespace sourcing. Returns a tuple of the first file name and path found. """ # src_path = os.path.join(self.directory.root_dir, source_filename) # src_exec = "[ -r %s ] && . %s" % (src_path, src_path) src_exec = "[ -r {0} ] && . {0}".format(os.path.join(self.directory.root_dir, source_filename)) # The ridiculous construction above is necessary to avoid failing tests(!) for config_file in files_to_inject: config_path = os.path.expanduser(os.path.join("~", config_file)) if os.path.exists(config_path): self.injections.inject(config_path, src_exec) break else: config_file = files_to_inject[0] config_path = os.path.expanduser(os.path.join("~", config_file)) self.logger.info("No config files found to source %s, creating ~/%s!" % (source_filename, config_file)) self.injections.inject(config_path, src_exec) return (config_file, config_path)
[ "def", "_inject_config_source", "(", "self", ",", "source_filename", ",", "files_to_inject", ")", ":", "# src_path = os.path.join(self.directory.root_dir, source_filename)", "# src_exec = \"[ -r %s ] && . %s\" % (src_path, src_path)", "src_exec", "=", "\"[ -r {0} ] && . {0}\"", ".", ...
Inject existing environmental config with namespace sourcing. Returns a tuple of the first file name and path found.
[ "Inject", "existing", "environmental", "config", "with", "namespace", "sourcing", ".", "Returns", "a", "tuple", "of", "the", "first", "file", "name", "and", "path", "found", "." ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L410-L431
train
55,089
toumorokoshi/sprinter
sprinter/environment.py
Environment._finalize
def _finalize(self): """ command to run at the end of sprinter's run """ self.logger.info("Finalizing...") self.write_manifest() if self.directory.rewrite_config: # always ensure .rc is written (sourcing .env) self.directory.add_to_rc('') # prepend brew for global installs if system.is_osx() and self.main_manifest.is_affirmative('config', 'use_global_packagemanagers'): self.directory.add_to_env('__sprinter_prepend_path "%s" PATH' % '/usr/local/bin') self.directory.add_to_env('__sprinter_prepend_path "%s" PATH' % self.directory.bin_path()) self.directory.add_to_env('__sprinter_prepend_path "%s" LIBRARY_PATH' % self.directory.lib_path()) self.directory.add_to_env('__sprinter_prepend_path "%s" C_INCLUDE_PATH' % self.directory.include_path()) self.directory.finalize() self.injections.commit() self.global_injections.commit() if not os.path.exists(os.path.join(self.root, ".global")): self.logger.debug("Global directory doesn't exist! creating...") os.makedirs(os.path.join(self.root, ".global")) self.logger.debug("Writing shell util file...") with open(self.shell_util_path, 'w+') as fh: fh.write(shell_utils_template) if self.error_occured: raise SprinterException("Error occured!") if self.message_success(): self.logger.info(self.message_success()) self.logger.info("Done!") self.logger.info("NOTE: Please remember to open new shells/terminals to use the modified environment")
python
def _finalize(self): """ command to run at the end of sprinter's run """ self.logger.info("Finalizing...") self.write_manifest() if self.directory.rewrite_config: # always ensure .rc is written (sourcing .env) self.directory.add_to_rc('') # prepend brew for global installs if system.is_osx() and self.main_manifest.is_affirmative('config', 'use_global_packagemanagers'): self.directory.add_to_env('__sprinter_prepend_path "%s" PATH' % '/usr/local/bin') self.directory.add_to_env('__sprinter_prepend_path "%s" PATH' % self.directory.bin_path()) self.directory.add_to_env('__sprinter_prepend_path "%s" LIBRARY_PATH' % self.directory.lib_path()) self.directory.add_to_env('__sprinter_prepend_path "%s" C_INCLUDE_PATH' % self.directory.include_path()) self.directory.finalize() self.injections.commit() self.global_injections.commit() if not os.path.exists(os.path.join(self.root, ".global")): self.logger.debug("Global directory doesn't exist! creating...") os.makedirs(os.path.join(self.root, ".global")) self.logger.debug("Writing shell util file...") with open(self.shell_util_path, 'w+') as fh: fh.write(shell_utils_template) if self.error_occured: raise SprinterException("Error occured!") if self.message_success(): self.logger.info(self.message_success()) self.logger.info("Done!") self.logger.info("NOTE: Please remember to open new shells/terminals to use the modified environment")
[ "def", "_finalize", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Finalizing...\"", ")", "self", ".", "write_manifest", "(", ")", "if", "self", ".", "directory", ".", "rewrite_config", ":", "# always ensure .rc is written (sourcing .env)", "...
command to run at the end of sprinter's run
[ "command", "to", "run", "at", "the", "end", "of", "sprinter", "s", "run" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L433-L467
train
55,090
toumorokoshi/sprinter
sprinter/environment.py
Environment._build_logger
def _build_logger(self, level=logging.INFO): """ return a logger. if logger is none, generate a logger from stdout """ self._debug_stream = StringIO() logger = logging.getLogger('sprinter') # stdout log out_hdlr = logging.StreamHandler(sys.stdout) out_hdlr.setLevel(level) logger.addHandler(out_hdlr) # debug log debug_hdlr = logging.StreamHandler(self._debug_stream) debug_hdlr.setFormatter(logging.Formatter('%(asctime)s %(message)s')) debug_hdlr.setLevel(logging.DEBUG) logger.addHandler(debug_hdlr) logger.setLevel(logging.DEBUG) return logger
python
def _build_logger(self, level=logging.INFO): """ return a logger. if logger is none, generate a logger from stdout """ self._debug_stream = StringIO() logger = logging.getLogger('sprinter') # stdout log out_hdlr = logging.StreamHandler(sys.stdout) out_hdlr.setLevel(level) logger.addHandler(out_hdlr) # debug log debug_hdlr = logging.StreamHandler(self._debug_stream) debug_hdlr.setFormatter(logging.Formatter('%(asctime)s %(message)s')) debug_hdlr.setLevel(logging.DEBUG) logger.addHandler(debug_hdlr) logger.setLevel(logging.DEBUG) return logger
[ "def", "_build_logger", "(", "self", ",", "level", "=", "logging", ".", "INFO", ")", ":", "self", ".", "_debug_stream", "=", "StringIO", "(", ")", "logger", "=", "logging", ".", "getLogger", "(", "'sprinter'", ")", "# stdout log", "out_hdlr", "=", "logging...
return a logger. if logger is none, generate a logger from stdout
[ "return", "a", "logger", ".", "if", "logger", "is", "none", "generate", "a", "logger", "from", "stdout" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L475-L489
train
55,091
toumorokoshi/sprinter
sprinter/environment.py
Environment.run_action
def run_action(self, feature, action, run_if_error=False, raise_exception=True): """ Run an action, and log it's output in case of errors """ if len(self._error_dict[feature]) > 0 and not run_if_error: return error = None instance = self.features[feature] try: getattr(instance, action)() # catch a generic exception within a feature except Exception as e: e = sys.exc_info()[1] self.logger.info("An exception occurred with action %s in feature %s!" % (action, feature)) self.logger.debug("Exception", exc_info=sys.exc_info()) error = str(e) self.log_feature_error(feature, str(e)) # any error in a feature should fail immediately - unless it occurred # from the remove() method in which case continue the rest of the # feature removal from there if error is not None and raise_exception: exception_msg = "%s action failed for feature %s: %s" % (action, feature, error) if self.phase == PHASE.REMOVE: raise FormulaException(exception_msg) else: raise SprinterException(exception_msg) return error
python
def run_action(self, feature, action, run_if_error=False, raise_exception=True): """ Run an action, and log it's output in case of errors """ if len(self._error_dict[feature]) > 0 and not run_if_error: return error = None instance = self.features[feature] try: getattr(instance, action)() # catch a generic exception within a feature except Exception as e: e = sys.exc_info()[1] self.logger.info("An exception occurred with action %s in feature %s!" % (action, feature)) self.logger.debug("Exception", exc_info=sys.exc_info()) error = str(e) self.log_feature_error(feature, str(e)) # any error in a feature should fail immediately - unless it occurred # from the remove() method in which case continue the rest of the # feature removal from there if error is not None and raise_exception: exception_msg = "%s action failed for feature %s: %s" % (action, feature, error) if self.phase == PHASE.REMOVE: raise FormulaException(exception_msg) else: raise SprinterException(exception_msg) return error
[ "def", "run_action", "(", "self", ",", "feature", ",", "action", ",", "run_if_error", "=", "False", ",", "raise_exception", "=", "True", ")", ":", "if", "len", "(", "self", ".", "_error_dict", "[", "feature", "]", ")", ">", "0", "and", "not", "run_if_e...
Run an action, and log it's output in case of errors
[ "Run", "an", "action", "and", "log", "it", "s", "output", "in", "case", "of", "errors" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L509-L537
train
55,092
toumorokoshi/sprinter
sprinter/environment.py
Environment._specialize
def _specialize(self, reconfigure=False): """ Add variables and specialize contexts """ # add in the 'root_dir' directories to the context dictionaries for manifest in [self.source, self.target]: context_dict = {} if manifest: for s in manifest.formula_sections(): context_dict["%s:root_dir" % s] = self.directory.install_directory(s) context_dict['config:root_dir'] = self.directory.root_dir context_dict['config:node'] = system.NODE manifest.add_additional_context(context_dict) self._validate_manifest() for feature in self.features.run_order: if not reconfigure: self.run_action(feature, 'resolve') # if a target doesn't exist, no need to prompt. instance = self.features[feature] if instance.target: self.run_action(feature, 'prompt')
python
def _specialize(self, reconfigure=False): """ Add variables and specialize contexts """ # add in the 'root_dir' directories to the context dictionaries for manifest in [self.source, self.target]: context_dict = {} if manifest: for s in manifest.formula_sections(): context_dict["%s:root_dir" % s] = self.directory.install_directory(s) context_dict['config:root_dir'] = self.directory.root_dir context_dict['config:node'] = system.NODE manifest.add_additional_context(context_dict) self._validate_manifest() for feature in self.features.run_order: if not reconfigure: self.run_action(feature, 'resolve') # if a target doesn't exist, no need to prompt. instance = self.features[feature] if instance.target: self.run_action(feature, 'prompt')
[ "def", "_specialize", "(", "self", ",", "reconfigure", "=", "False", ")", ":", "# add in the 'root_dir' directories to the context dictionaries", "for", "manifest", "in", "[", "self", ".", "source", ",", "self", ".", "target", "]", ":", "context_dict", "=", "{", ...
Add variables and specialize contexts
[ "Add", "variables", "and", "specialize", "contexts" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L553-L571
train
55,093
toumorokoshi/sprinter
sprinter/environment.py
Environment._copy_source_to_target
def _copy_source_to_target(self): """ copy source user configuration to target """ if self.source and self.target: for k, v in self.source.items('config'): # always have source override target. self.target.set_input(k, v)
python
def _copy_source_to_target(self): """ copy source user configuration to target """ if self.source and self.target: for k, v in self.source.items('config'): # always have source override target. self.target.set_input(k, v)
[ "def", "_copy_source_to_target", "(", "self", ")", ":", "if", "self", ".", "source", "and", "self", ".", "target", ":", "for", "k", ",", "v", "in", "self", ".", "source", ".", "items", "(", "'config'", ")", ":", "# always have source override target.", "se...
copy source user configuration to target
[ "copy", "source", "user", "configuration", "to", "target" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L573-L578
train
55,094
toumorokoshi/sprinter
sprinter/environment.py
Environment.grab_inputs
def grab_inputs(self, reconfigure=False): """ Resolve the source and target config section """ self._copy_source_to_target() if self.target: self.target.grab_inputs(force=reconfigure)
python
def grab_inputs(self, reconfigure=False): """ Resolve the source and target config section """ self._copy_source_to_target() if self.target: self.target.grab_inputs(force=reconfigure)
[ "def", "grab_inputs", "(", "self", ",", "reconfigure", "=", "False", ")", ":", "self", ".", "_copy_source_to_target", "(", ")", "if", "self", ".", "target", ":", "self", ".", "target", ".", "grab_inputs", "(", "force", "=", "reconfigure", ")" ]
Resolve the source and target config section
[ "Resolve", "the", "source", "and", "target", "config", "section" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/environment.py#L580-L584
train
55,095
toumorokoshi/sprinter
sprinter/install.py
parse_domain
def parse_domain(url): """ parse the domain from the url """ domain_match = lib.DOMAIN_REGEX.match(url) if domain_match: return domain_match.group()
python
def parse_domain(url): """ parse the domain from the url """ domain_match = lib.DOMAIN_REGEX.match(url) if domain_match: return domain_match.group()
[ "def", "parse_domain", "(", "url", ")", ":", "domain_match", "=", "lib", ".", "DOMAIN_REGEX", ".", "match", "(", "url", ")", "if", "domain_match", ":", "return", "domain_match", ".", "group", "(", ")" ]
parse the domain from the url
[ "parse", "the", "domain", "from", "the", "url" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/install.py#L200-L204
train
55,096
toumorokoshi/sprinter
sprinter/install.py
get_credentials
def get_credentials(options, environment): """ Get credentials or prompt for them from options """ if options['--username'] or options['--auth']: if not options['--username']: options['<username>'] = lib.prompt("Please enter the username for %s..." % environment) if not options['--password']: options['<password>'] = lib.prompt("Please enter the password for %s..." % environment, secret=True) return options
python
def get_credentials(options, environment): """ Get credentials or prompt for them from options """ if options['--username'] or options['--auth']: if not options['--username']: options['<username>'] = lib.prompt("Please enter the username for %s..." % environment) if not options['--password']: options['<password>'] = lib.prompt("Please enter the password for %s..." % environment, secret=True) return options
[ "def", "get_credentials", "(", "options", ",", "environment", ")", ":", "if", "options", "[", "'--username'", "]", "or", "options", "[", "'--auth'", "]", ":", "if", "not", "options", "[", "'--username'", "]", ":", "options", "[", "'<username>'", "]", "=", ...
Get credentials or prompt for them from options
[ "Get", "credentials", "or", "prompt", "for", "them", "from", "options" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/install.py#L207-L214
train
55,097
NiklasRosenstein-Python/nr-deprecated
nr/tundras/field.py
Field.full_name
def full_name(self): """ The full name of the field. This is the field's entities name concatenated with the field's name. If the field is unnamed or not bound to an entity, the result respectively contains None. """ entity = self.entity.__name__ if self.entity is not None else None name = self.name if self.name is not None else None if entity and name: return entity + '.' + name elif entity: return entity + '.<unnamed>' elif name: return '<unbound>.' + name else: return '<unbound>.<unnamed>'
python
def full_name(self): """ The full name of the field. This is the field's entities name concatenated with the field's name. If the field is unnamed or not bound to an entity, the result respectively contains None. """ entity = self.entity.__name__ if self.entity is not None else None name = self.name if self.name is not None else None if entity and name: return entity + '.' + name elif entity: return entity + '.<unnamed>' elif name: return '<unbound>.' + name else: return '<unbound>.<unnamed>'
[ "def", "full_name", "(", "self", ")", ":", "entity", "=", "self", ".", "entity", ".", "__name__", "if", "self", ".", "entity", "is", "not", "None", "else", "None", "name", "=", "self", ".", "name", "if", "self", ".", "name", "is", "not", "None", "e...
The full name of the field. This is the field's entities name concatenated with the field's name. If the field is unnamed or not bound to an entity, the result respectively contains None.
[ "The", "full", "name", "of", "the", "field", ".", "This", "is", "the", "field", "s", "entities", "name", "concatenated", "with", "the", "field", "s", "name", ".", "If", "the", "field", "is", "unnamed", "or", "not", "bound", "to", "an", "entity", "the",...
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/tundras/field.py#L140-L156
train
55,098
NiklasRosenstein-Python/nr-deprecated
nr/tundras/field.py
Field.type_name
def type_name(self): """ Returns the full type identifier of the field. """ res = self.type.__name__ if self.type.__module__ not in ('__builtin__', 'builtins'): res = self.type.__module__ + '.' + res return res
python
def type_name(self): """ Returns the full type identifier of the field. """ res = self.type.__name__ if self.type.__module__ not in ('__builtin__', 'builtins'): res = self.type.__module__ + '.' + res return res
[ "def", "type_name", "(", "self", ")", ":", "res", "=", "self", ".", "type", ".", "__name__", "if", "self", ".", "type", ".", "__module__", "not", "in", "(", "'__builtin__'", ",", "'builtins'", ")", ":", "res", "=", "self", ".", "type", ".", "__module...
Returns the full type identifier of the field.
[ "Returns", "the", "full", "type", "identifier", "of", "the", "field", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/tundras/field.py#L159-L167
train
55,099