id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
37,600
VikParuchuri/percept
percept/workflows/datastores.py
BaseStore.load
def load(self, id_code): """ Loads a workflow identified by id_code id_code - unique identifier, previously must have called save with same id_code """ filestream = open('{0}/{1}'.format(self.data_path, id_code), 'rb') workflow = pickle.load(filestream) return wor...
python
def load(self, id_code): """ Loads a workflow identified by id_code id_code - unique identifier, previously must have called save with same id_code """ filestream = open('{0}/{1}'.format(self.data_path, id_code), 'rb') workflow = pickle.load(filestream) return wor...
[ "def", "load", "(", "self", ",", "id_code", ")", ":", "filestream", "=", "open", "(", "'{0}/{1}'", ".", "format", "(", "self", ".", "data_path", ",", "id_code", ")", ",", "'rb'", ")", "workflow", "=", "pickle", ".", "load", "(", "filestream", ")", "r...
Loads a workflow identified by id_code id_code - unique identifier, previously must have called save with same id_code
[ "Loads", "a", "workflow", "identified", "by", "id_code", "id_code", "-", "unique", "identifier", "previously", "must", "have", "called", "save", "with", "same", "id_code" ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/workflows/datastores.py#L29-L36
37,601
smarie/python-parsyfiles
parsyfiles/plugins_base/support_for_objects.py
read_object_from_pickle
def read_object_from_pickle(desired_type: Type[T], file_path: str, encoding: str, fix_imports: bool = True, errors: str = 'strict', *args, **kwargs) -> Any: """ Parses a pickle file. :param desired_type: :param file_path: :param encoding: :param fix_imports: :par...
python
def read_object_from_pickle(desired_type: Type[T], file_path: str, encoding: str, fix_imports: bool = True, errors: str = 'strict', *args, **kwargs) -> Any: """ Parses a pickle file. :param desired_type: :param file_path: :param encoding: :param fix_imports: :par...
[ "def", "read_object_from_pickle", "(", "desired_type", ":", "Type", "[", "T", "]", ",", "file_path", ":", "str", ",", "encoding", ":", "str", ",", "fix_imports", ":", "bool", "=", "True", ",", "errors", ":", "str", "=", "'strict'", ",", "*", "args", ",...
Parses a pickle file. :param desired_type: :param file_path: :param encoding: :param fix_imports: :param errors: :param args: :param kwargs: :return:
[ "Parses", "a", "pickle", "file", "." ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_base/support_for_objects.py#L21-L40
37,602
smarie/python-parsyfiles
parsyfiles/plugins_base/support_for_objects.py
should_display_warnings_for
def should_display_warnings_for(to_type): """ Central method where we control whether warnings should be displayed """ if not hasattr(to_type, '__module__'): return True elif to_type.__module__ in {'builtins'} or to_type.__module__.startswith('parsyfiles') \ or to_type.__name__ in {'Data...
python
def should_display_warnings_for(to_type): """ Central method where we control whether warnings should be displayed """ if not hasattr(to_type, '__module__'): return True elif to_type.__module__ in {'builtins'} or to_type.__module__.startswith('parsyfiles') \ or to_type.__name__ in {'Data...
[ "def", "should_display_warnings_for", "(", "to_type", ")", ":", "if", "not", "hasattr", "(", "to_type", ",", "'__module__'", ")", ":", "return", "True", "elif", "to_type", ".", "__module__", "in", "{", "'builtins'", "}", "or", "to_type", ".", "__module__", "...
Central method where we control whether warnings should be displayed
[ "Central", "method", "where", "we", "control", "whether", "warnings", "should", "be", "displayed" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_base/support_for_objects.py#L191-L202
37,603
smarie/python-parsyfiles
parsyfiles/plugins_base/support_for_objects.py
print_dict
def print_dict(dict_name, dict_value, logger: Logger = None): """ Utility method to print a named dictionary :param dict_name: :param dict_value: :return: """ if logger is None: print(dict_name + ' = ') try: from pprint import pprint pprint(dict_value...
python
def print_dict(dict_name, dict_value, logger: Logger = None): """ Utility method to print a named dictionary :param dict_name: :param dict_value: :return: """ if logger is None: print(dict_name + ' = ') try: from pprint import pprint pprint(dict_value...
[ "def", "print_dict", "(", "dict_name", ",", "dict_value", ",", "logger", ":", "Logger", "=", "None", ")", ":", "if", "logger", "is", "None", ":", "print", "(", "dict_name", "+", "' = '", ")", "try", ":", "from", "pprint", "import", "pprint", "pprint", ...
Utility method to print a named dictionary :param dict_name: :param dict_value: :return:
[ "Utility", "method", "to", "print", "a", "named", "dictionary" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_base/support_for_objects.py#L485-L506
37,604
smarie/python-parsyfiles
parsyfiles/plugins_base/support_for_objects.py
MultifileObjectParser.is_able_to_parse_detailed
def is_able_to_parse_detailed(self, desired_type: Type[Any], desired_ext: str, strict: bool): """ Explicitly declare that we are not able to parse collections :param desired_type: :param desired_ext: :param strict: :return: """ if not _is_valid_for_dict_...
python
def is_able_to_parse_detailed(self, desired_type: Type[Any], desired_ext: str, strict: bool): """ Explicitly declare that we are not able to parse collections :param desired_type: :param desired_ext: :param strict: :return: """ if not _is_valid_for_dict_...
[ "def", "is_able_to_parse_detailed", "(", "self", ",", "desired_type", ":", "Type", "[", "Any", "]", ",", "desired_ext", ":", "str", ",", "strict", ":", "bool", ")", ":", "if", "not", "_is_valid_for_dict_to_object_conversion", "(", "strict", ",", "None", ",", ...
Explicitly declare that we are not able to parse collections :param desired_type: :param desired_ext: :param strict: :return:
[ "Explicitly", "declare", "that", "we", "are", "not", "able", "to", "parse", "collections" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_base/support_for_objects.py#L562-L575
37,605
smarie/python-parsyfiles
parsyfiles/global_config.py
parsyfiles_global_config
def parsyfiles_global_config(multiple_errors_tb_limit: int = None, full_paths_in_logs: bool = None, dict_to_object_subclass_limit: int = None): """ This is the method you should use to configure the parsyfiles library :param multiple_errors_tb_limit: the traceback size (defaul...
python
def parsyfiles_global_config(multiple_errors_tb_limit: int = None, full_paths_in_logs: bool = None, dict_to_object_subclass_limit: int = None): """ This is the method you should use to configure the parsyfiles library :param multiple_errors_tb_limit: the traceback size (defaul...
[ "def", "parsyfiles_global_config", "(", "multiple_errors_tb_limit", ":", "int", "=", "None", ",", "full_paths_in_logs", ":", "bool", "=", "None", ",", "dict_to_object_subclass_limit", ":", "int", "=", "None", ")", ":", "if", "multiple_errors_tb_limit", "is", "not", ...
This is the method you should use to configure the parsyfiles library :param multiple_errors_tb_limit: the traceback size (default is 3) of individual parsers exceptions displayed when parsyfiles tries several parsing chains and all of them fail. :param full_paths_in_logs: if True, full file paths will be ...
[ "This", "is", "the", "method", "you", "should", "use", "to", "configure", "the", "parsyfiles", "library" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/global_config.py#L17-L35
37,606
frascoweb/frasco
frasco/actions/core.py
Action.is_valid
def is_valid(self, context): """Checks through the previous_actions iterable if required actions have been executed """ if self.requires: for r in self.requires: if not r in context.executed_actions: raise RequirementMissingError("Action '%...
python
def is_valid(self, context): """Checks through the previous_actions iterable if required actions have been executed """ if self.requires: for r in self.requires: if not r in context.executed_actions: raise RequirementMissingError("Action '%...
[ "def", "is_valid", "(", "self", ",", "context", ")", ":", "if", "self", ".", "requires", ":", "for", "r", "in", "self", ".", "requires", ":", "if", "not", "r", "in", "context", ".", "executed_actions", ":", "raise", "RequirementMissingError", "(", "\"Act...
Checks through the previous_actions iterable if required actions have been executed
[ "Checks", "through", "the", "previous_actions", "iterable", "if", "required", "actions", "have", "been", "executed" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/actions/core.py#L50-L58
37,607
nikcub/floyd
setup.py
get_file_contents
def get_file_contents(file_path): """Get the context of the file using full path name""" full_path = os.path.join(package_dir, file_path) return open(full_path, 'r').read()
python
def get_file_contents(file_path): """Get the context of the file using full path name""" full_path = os.path.join(package_dir, file_path) return open(full_path, 'r').read()
[ "def", "get_file_contents", "(", "file_path", ")", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "package_dir", ",", "file_path", ")", "return", "open", "(", "full_path", ",", "'r'", ")", ".", "read", "(", ")" ]
Get the context of the file using full path name
[ "Get", "the", "context", "of", "the", "file", "using", "full", "path", "name" ]
5772d0047efb11c9ce5f7d234a9da4576ce24edc
https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/setup.py#L33-L36
37,608
majuss/lupupy
lupupy/devices/__init__.py
LupusecDevice.refresh
def refresh(self): """Refresh a device""" # new_device = {} if self.type in CONST.BINARY_SENSOR_TYPES: response = self._lupusec.get_sensors() for device in response: if device['device_id'] == self._device_id: self.update(device) ...
python
def refresh(self): """Refresh a device""" # new_device = {} if self.type in CONST.BINARY_SENSOR_TYPES: response = self._lupusec.get_sensors() for device in response: if device['device_id'] == self._device_id: self.update(device) ...
[ "def", "refresh", "(", "self", ")", ":", "# new_device = {}", "if", "self", ".", "type", "in", "CONST", ".", "BINARY_SENSOR_TYPES", ":", "response", "=", "self", ".", "_lupusec", ".", "get_sensors", "(", ")", "for", "device", "in", "response", ":", "if", ...
Refresh a device
[ "Refresh", "a", "device" ]
71af6c397837ffc393c7b8122be175602638d3c6
https://github.com/majuss/lupupy/blob/71af6c397837ffc393c7b8122be175602638d3c6/lupupy/devices/__init__.py#L34-L55
37,609
majuss/lupupy
lupupy/devices/__init__.py
LupusecDevice.desc
def desc(self): """Get a short description of the device.""" return '{0} (ID: {1}) - {2} - {3}'.format( self.name, self.device_id, self.type, self.status)
python
def desc(self): """Get a short description of the device.""" return '{0} (ID: {1}) - {2} - {3}'.format( self.name, self.device_id, self.type, self.status)
[ "def", "desc", "(", "self", ")", ":", "return", "'{0} (ID: {1}) - {2} - {3}'", ".", "format", "(", "self", ".", "name", ",", "self", ".", "device_id", ",", "self", ".", "type", ",", "self", ".", "status", ")" ]
Get a short description of the device.
[ "Get", "a", "short", "description", "of", "the", "device", "." ]
71af6c397837ffc393c7b8122be175602638d3c6
https://github.com/majuss/lupupy/blob/71af6c397837ffc393c7b8122be175602638d3c6/lupupy/devices/__init__.py#L124-L127
37,610
inveniosoftware/invenio-queues
invenio_queues/cli.py
list
def list(declared, undeclared): """List configured queues.""" queues = current_queues.queues.values() if declared: queues = filter(lambda queue: queue.exists, queues) elif undeclared: queues = filter(lambda queue: not queue.exists, queues) queue_names = [queue.routing_key for queue i...
python
def list(declared, undeclared): """List configured queues.""" queues = current_queues.queues.values() if declared: queues = filter(lambda queue: queue.exists, queues) elif undeclared: queues = filter(lambda queue: not queue.exists, queues) queue_names = [queue.routing_key for queue i...
[ "def", "list", "(", "declared", ",", "undeclared", ")", ":", "queues", "=", "current_queues", ".", "queues", ".", "values", "(", ")", "if", "declared", ":", "queues", "=", "filter", "(", "lambda", "queue", ":", "queue", ".", "exists", ",", "queues", ")...
List configured queues.
[ "List", "configured", "queues", "." ]
1dd9112d7c5fe72a428c86f21f6d02cdb0595921
https://github.com/inveniosoftware/invenio-queues/blob/1dd9112d7c5fe72a428c86f21f6d02cdb0595921/invenio_queues/cli.py#L46-L56
37,611
inveniosoftware/invenio-queues
invenio_queues/cli.py
declare
def declare(queues): """Initialize the given queues.""" current_queues.declare(queues=queues) click.secho( 'Queues {} have been declared.'.format( queues or current_queues.queues.keys()), fg='green' )
python
def declare(queues): """Initialize the given queues.""" current_queues.declare(queues=queues) click.secho( 'Queues {} have been declared.'.format( queues or current_queues.queues.keys()), fg='green' )
[ "def", "declare", "(", "queues", ")", ":", "current_queues", ".", "declare", "(", "queues", "=", "queues", ")", "click", ".", "secho", "(", "'Queues {} have been declared.'", ".", "format", "(", "queues", "or", "current_queues", ".", "queues", ".", "keys", "...
Initialize the given queues.
[ "Initialize", "the", "given", "queues", "." ]
1dd9112d7c5fe72a428c86f21f6d02cdb0595921
https://github.com/inveniosoftware/invenio-queues/blob/1dd9112d7c5fe72a428c86f21f6d02cdb0595921/invenio_queues/cli.py#L62-L69
37,612
inveniosoftware/invenio-queues
invenio_queues/cli.py
purge_queues
def purge_queues(queues=None): """Purge the given queues.""" current_queues.purge(queues=queues) click.secho( 'Queues {} have been purged.'.format( queues or current_queues.queues.keys()), fg='green' )
python
def purge_queues(queues=None): """Purge the given queues.""" current_queues.purge(queues=queues) click.secho( 'Queues {} have been purged.'.format( queues or current_queues.queues.keys()), fg='green' )
[ "def", "purge_queues", "(", "queues", "=", "None", ")", ":", "current_queues", ".", "purge", "(", "queues", "=", "queues", ")", "click", ".", "secho", "(", "'Queues {} have been purged.'", ".", "format", "(", "queues", "or", "current_queues", ".", "queues", ...
Purge the given queues.
[ "Purge", "the", "given", "queues", "." ]
1dd9112d7c5fe72a428c86f21f6d02cdb0595921
https://github.com/inveniosoftware/invenio-queues/blob/1dd9112d7c5fe72a428c86f21f6d02cdb0595921/invenio_queues/cli.py#L75-L82
37,613
inveniosoftware/invenio-queues
invenio_queues/cli.py
delete_queue
def delete_queue(queues): """Delete the given queues.""" current_queues.delete(queues=queues) click.secho( 'Queues {} have been deleted.'.format( queues or current_queues.queues.keys()), fg='green' )
python
def delete_queue(queues): """Delete the given queues.""" current_queues.delete(queues=queues) click.secho( 'Queues {} have been deleted.'.format( queues or current_queues.queues.keys()), fg='green' )
[ "def", "delete_queue", "(", "queues", ")", ":", "current_queues", ".", "delete", "(", "queues", "=", "queues", ")", "click", ".", "secho", "(", "'Queues {} have been deleted.'", ".", "format", "(", "queues", "or", "current_queues", ".", "queues", ".", "keys", ...
Delete the given queues.
[ "Delete", "the", "given", "queues", "." ]
1dd9112d7c5fe72a428c86f21f6d02cdb0595921
https://github.com/inveniosoftware/invenio-queues/blob/1dd9112d7c5fe72a428c86f21f6d02cdb0595921/invenio_queues/cli.py#L88-L95
37,614
VikParuchuri/percept
percept/utils/models.py
find_needed_formatter
def find_needed_formatter(input_format, output_format): """ Find a data formatter given an input and output format input_format - needed input format. see utils.input.dataformats output_format - needed output format. see utils.input.dataformats """ #Only take the formatters in the registry ...
python
def find_needed_formatter(input_format, output_format): """ Find a data formatter given an input and output format input_format - needed input format. see utils.input.dataformats output_format - needed output format. see utils.input.dataformats """ #Only take the formatters in the registry ...
[ "def", "find_needed_formatter", "(", "input_format", ",", "output_format", ")", ":", "#Only take the formatters in the registry", "selected_registry", "=", "[", "re", ".", "cls", "for", "re", "in", "registry", "if", "re", ".", "category", "==", "RegistryCategories", ...
Find a data formatter given an input and output format input_format - needed input format. see utils.input.dataformats output_format - needed output format. see utils.input.dataformats
[ "Find", "a", "data", "formatter", "given", "an", "input", "and", "output", "format", "input_format", "-", "needed", "input", "format", ".", "see", "utils", ".", "input", ".", "dataformats", "output_format", "-", "needed", "output", "format", ".", "see", "uti...
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/models.py#L24-L40
37,615
VikParuchuri/percept
percept/utils/models.py
find_needed_input
def find_needed_input(input_format): """ Find a needed input class input_format - needed input format, see utils.input.dataformats """ needed_inputs = [re.cls for re in registry if re.category==RegistryCategories.inputs and re.cls.input_format == input_format] if len(needed_inputs)>0: re...
python
def find_needed_input(input_format): """ Find a needed input class input_format - needed input format, see utils.input.dataformats """ needed_inputs = [re.cls for re in registry if re.category==RegistryCategories.inputs and re.cls.input_format == input_format] if len(needed_inputs)>0: re...
[ "def", "find_needed_input", "(", "input_format", ")", ":", "needed_inputs", "=", "[", "re", ".", "cls", "for", "re", "in", "registry", "if", "re", ".", "category", "==", "RegistryCategories", ".", "inputs", "and", "re", ".", "cls", ".", "input_format", "==...
Find a needed input class input_format - needed input format, see utils.input.dataformats
[ "Find", "a", "needed", "input", "class", "input_format", "-", "needed", "input", "format", "see", "utils", ".", "input", ".", "dataformats" ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/models.py#L42-L50
37,616
VikParuchuri/percept
percept/utils/models.py
exists_in_registry
def exists_in_registry(category, namespace, name): """ See if a given category, namespace, name combination exists in the registry category - See registrycategories. Type of module namespace - Namespace of the module, defined in settings name - the lowercase name of the module """ selected_...
python
def exists_in_registry(category, namespace, name): """ See if a given category, namespace, name combination exists in the registry category - See registrycategories. Type of module namespace - Namespace of the module, defined in settings name - the lowercase name of the module """ selected_...
[ "def", "exists_in_registry", "(", "category", ",", "namespace", ",", "name", ")", ":", "selected_registry", "=", "[", "re", "for", "re", "in", "registry", "if", "re", ".", "category", "==", "category", "and", "re", ".", "namespace", "==", "namespace", "and...
See if a given category, namespace, name combination exists in the registry category - See registrycategories. Type of module namespace - Namespace of the module, defined in settings name - the lowercase name of the module
[ "See", "if", "a", "given", "category", "namespace", "name", "combination", "exists", "in", "the", "registry", "category", "-", "See", "registrycategories", ".", "Type", "of", "module", "namespace", "-", "Namespace", "of", "the", "module", "defined", "in", "set...
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/models.py#L52-L62
37,617
VikParuchuri/percept
percept/utils/models.py
register
def register(cls): """ Register a given model in the registry """ registry_entry = RegistryEntry(category = cls.category, namespace = cls.namespace, name = cls.name, cls=cls) if registry_entry not in registry and not exists_in_registry(cls.category, cls.namespace, cls.name): registry.append(...
python
def register(cls): """ Register a given model in the registry """ registry_entry = RegistryEntry(category = cls.category, namespace = cls.namespace, name = cls.name, cls=cls) if registry_entry not in registry and not exists_in_registry(cls.category, cls.namespace, cls.name): registry.append(...
[ "def", "register", "(", "cls", ")", ":", "registry_entry", "=", "RegistryEntry", "(", "category", "=", "cls", ".", "category", ",", "namespace", "=", "cls", ".", "namespace", ",", "name", "=", "cls", ".", "name", ",", "cls", "=", "cls", ")", "if", "r...
Register a given model in the registry
[ "Register", "a", "given", "model", "in", "the", "registry" ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/models.py#L81-L89
37,618
VikParuchuri/percept
percept/utils/models.py
FieldModel._set_fields
def _set_fields(self): """ Initialize the fields for data caching. """ self.fields = [] self.required_input = [] for member_name, member_object in inspect.getmembers(self.__class__): if inspect.isdatadescriptor(member_object) and not member_name.startswith("__...
python
def _set_fields(self): """ Initialize the fields for data caching. """ self.fields = [] self.required_input = [] for member_name, member_object in inspect.getmembers(self.__class__): if inspect.isdatadescriptor(member_object) and not member_name.startswith("__...
[ "def", "_set_fields", "(", "self", ")", ":", "self", ".", "fields", "=", "[", "]", "self", ".", "required_input", "=", "[", "]", "for", "member_name", ",", "member_object", "in", "inspect", ".", "getmembers", "(", "self", ".", "__class__", ")", ":", "i...
Initialize the fields for data caching.
[ "Initialize", "the", "fields", "for", "data", "caching", "." ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/utils/models.py#L119-L129
37,619
supercoderz/pyzmq-wrapper
zmqwrapper/subscribers.py
subscriber
def subscriber(address,topics,callback,message_type): """ Creates a subscriber binding to the given address and subscribe the given topics. The callback is invoked for every message received. Args: - address: the address to bind the PUB socket to. - topics: the topics t...
python
def subscriber(address,topics,callback,message_type): """ Creates a subscriber binding to the given address and subscribe the given topics. The callback is invoked for every message received. Args: - address: the address to bind the PUB socket to. - topics: the topics t...
[ "def", "subscriber", "(", "address", ",", "topics", ",", "callback", ",", "message_type", ")", ":", "return", "Subscriber", "(", "address", ",", "topics", ",", "callback", ",", "message_type", ")" ]
Creates a subscriber binding to the given address and subscribe the given topics. The callback is invoked for every message received. Args: - address: the address to bind the PUB socket to. - topics: the topics to subscribe - callback: the callback to invoke for eve...
[ "Creates", "a", "subscriber", "binding", "to", "the", "given", "address", "and", "subscribe", "the", "given", "topics", ".", "The", "callback", "is", "invoked", "for", "every", "message", "received", "." ]
b16c0313dd10febd5060ee0589285025a09fa26a
https://github.com/supercoderz/pyzmq-wrapper/blob/b16c0313dd10febd5060ee0589285025a09fa26a/zmqwrapper/subscribers.py#L6-L18
37,620
supercoderz/pyzmq-wrapper
zmqwrapper/subscribers.py
Subscriber.start
def start(self): """ Start a thread that consumes the messages and invokes the callback """ t=threading.Thread(target=self._consume) t.start()
python
def start(self): """ Start a thread that consumes the messages and invokes the callback """ t=threading.Thread(target=self._consume) t.start()
[ "def", "start", "(", "self", ")", ":", "t", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_consume", ")", "t", ".", "start", "(", ")" ]
Start a thread that consumes the messages and invokes the callback
[ "Start", "a", "thread", "that", "consumes", "the", "messages", "and", "invokes", "the", "callback" ]
b16c0313dd10febd5060ee0589285025a09fa26a
https://github.com/supercoderz/pyzmq-wrapper/blob/b16c0313dd10febd5060ee0589285025a09fa26a/zmqwrapper/subscribers.py#L51-L56
37,621
helto4real/python-packages
smhi/smhi/smhi_lib.py
SmhiAPI.get_forecast_api
def get_forecast_api(self, longitude: str, latitude: str) -> {}: """gets data from API""" api_url = APIURL_TEMPLATE.format(longitude, latitude) response = urlopen(api_url) data = response.read().decode('utf-8') json_data = json.loads(data) return json_data
python
def get_forecast_api(self, longitude: str, latitude: str) -> {}: """gets data from API""" api_url = APIURL_TEMPLATE.format(longitude, latitude) response = urlopen(api_url) data = response.read().decode('utf-8') json_data = json.loads(data) return json_data
[ "def", "get_forecast_api", "(", "self", ",", "longitude", ":", "str", ",", "latitude", ":", "str", ")", "->", "{", "}", ":", "api_url", "=", "APIURL_TEMPLATE", ".", "format", "(", "longitude", ",", "latitude", ")", "response", "=", "urlopen", "(", "api_u...
gets data from API
[ "gets", "data", "from", "API" ]
8b65342eea34e370ea6fc5abdcb55e544c51fec5
https://github.com/helto4real/python-packages/blob/8b65342eea34e370ea6fc5abdcb55e544c51fec5/smhi/smhi/smhi_lib.py#L197-L205
37,622
helto4real/python-packages
smhi/smhi/smhi_lib.py
SmhiAPI.async_get_forecast_api
async def async_get_forecast_api(self, longitude: str, latitude: str) -> {}: """gets data from API asyncronious""" api_url = APIURL_TEMPLATE.format(longitude, latitude) if self.session is None: self.session = aiohttp.ClientSession() ...
python
async def async_get_forecast_api(self, longitude: str, latitude: str) -> {}: """gets data from API asyncronious""" api_url = APIURL_TEMPLATE.format(longitude, latitude) if self.session is None: self.session = aiohttp.ClientSession() ...
[ "async", "def", "async_get_forecast_api", "(", "self", ",", "longitude", ":", "str", ",", "latitude", ":", "str", ")", "->", "{", "}", ":", "api_url", "=", "APIURL_TEMPLATE", ".", "format", "(", "longitude", ",", "latitude", ")", "if", "self", ".", "sess...
gets data from API asyncronious
[ "gets", "data", "from", "API", "asyncronious" ]
8b65342eea34e370ea6fc5abdcb55e544c51fec5
https://github.com/helto4real/python-packages/blob/8b65342eea34e370ea6fc5abdcb55e544c51fec5/smhi/smhi/smhi_lib.py#L207-L222
37,623
wearpants/instrument
instrument/__init__.py
all
def all(iterable = None, *, name = None, metric = call_default): """Measure total time and item count for consuming an iterable :arg iterable: any iterable :arg function metric: f(name, count, total_time) :arg str name: name for the metric """ if iterable is None: return _iter_decorator...
python
def all(iterable = None, *, name = None, metric = call_default): """Measure total time and item count for consuming an iterable :arg iterable: any iterable :arg function metric: f(name, count, total_time) :arg str name: name for the metric """ if iterable is None: return _iter_decorator...
[ "def", "all", "(", "iterable", "=", "None", ",", "*", ",", "name", "=", "None", ",", "metric", "=", "call_default", ")", ":", "if", "iterable", "is", "None", ":", "return", "_iter_decorator", "(", "name", ",", "metric", ")", "else", ":", "return", "_...
Measure total time and item count for consuming an iterable :arg iterable: any iterable :arg function metric: f(name, count, total_time) :arg str name: name for the metric
[ "Measure", "total", "time", "and", "item", "count", "for", "consuming", "an", "iterable" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/__init__.py#L111-L121
37,624
wearpants/instrument
instrument/__init__.py
each
def each(iterable = None, *, name = None, metric = call_default): """Measure time elapsed to produce each item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric """ if iterable is None: return _each_decorator(name, metri...
python
def each(iterable = None, *, name = None, metric = call_default): """Measure time elapsed to produce each item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric """ if iterable is None: return _each_decorator(name, metri...
[ "def", "each", "(", "iterable", "=", "None", ",", "*", ",", "name", "=", "None", ",", "metric", "=", "call_default", ")", ":", "if", "iterable", "is", "None", ":", "return", "_each_decorator", "(", "name", ",", "metric", ")", "else", ":", "return", "...
Measure time elapsed to produce each item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric
[ "Measure", "time", "elapsed", "to", "produce", "each", "item", "of", "an", "iterable" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/__init__.py#L124-L134
37,625
wearpants/instrument
instrument/__init__.py
first
def first(iterable = None, *, name = None, metric = call_default): """Measure time elapsed to produce first item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric """ if iterable is None: return _first_decorator(name, me...
python
def first(iterable = None, *, name = None, metric = call_default): """Measure time elapsed to produce first item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric """ if iterable is None: return _first_decorator(name, me...
[ "def", "first", "(", "iterable", "=", "None", ",", "*", ",", "name", "=", "None", ",", "metric", "=", "call_default", ")", ":", "if", "iterable", "is", "None", ":", "return", "_first_decorator", "(", "name", ",", "metric", ")", "else", ":", "return", ...
Measure time elapsed to produce first item of an iterable :arg iterable: any iterable :arg function metric: f(name, 1, time) :arg str name: name for the metric
[ "Measure", "time", "elapsed", "to", "produce", "first", "item", "of", "an", "iterable" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/__init__.py#L137-L147
37,626
wearpants/instrument
instrument/__init__.py
reducer
def reducer(*, name = None, metric = call_default): """Decorator to measure a function that consumes many items. The wrapped ``func`` should take either a single ``iterable`` argument or ``*args`` (plus keyword arguments). :arg function metric: f(name, count, total_time) :arg str name: name for th...
python
def reducer(*, name = None, metric = call_default): """Decorator to measure a function that consumes many items. The wrapped ``func`` should take either a single ``iterable`` argument or ``*args`` (plus keyword arguments). :arg function metric: f(name, count, total_time) :arg str name: name for th...
[ "def", "reducer", "(", "*", ",", "name", "=", "None", ",", "metric", "=", "call_default", ")", ":", "class", "instrument_reducer_decorator", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "func", ")", ":", "self", ".", "orig_func", "=", ...
Decorator to measure a function that consumes many items. The wrapped ``func`` should take either a single ``iterable`` argument or ``*args`` (plus keyword arguments). :arg function metric: f(name, count, total_time) :arg str name: name for the metric
[ "Decorator", "to", "measure", "a", "function", "that", "consumes", "many", "items", "." ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/__init__.py#L190-L244
37,627
wearpants/instrument
instrument/__init__.py
producer
def producer(*, name = None, metric = call_default): """Decorator to measure a function that produces many items. The function should return an object that supports ``__len__`` (ie, a list). If the function returns an iterator, use :func:`all` instead. :arg function metric: f(name, count, total_time) ...
python
def producer(*, name = None, metric = call_default): """Decorator to measure a function that produces many items. The function should return an object that supports ``__len__`` (ie, a list). If the function returns an iterator, use :func:`all` instead. :arg function metric: f(name, count, total_time) ...
[ "def", "producer", "(", "*", ",", "name", "=", "None", ",", "metric", "=", "call_default", ")", ":", "def", "wrapper", "(", "func", ")", ":", "def", "instrumenter", "(", "name_", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "t", "=", "tim...
Decorator to measure a function that produces many items. The function should return an object that supports ``__len__`` (ie, a list). If the function returns an iterator, use :func:`all` instead. :arg function metric: f(name, count, total_time) :arg str name: name for the metric
[ "Decorator", "to", "measure", "a", "function", "that", "produces", "many", "items", "." ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/__init__.py#L246-L285
37,628
wearpants/instrument
instrument/__init__.py
block
def block(*, name = None, metric = call_default, count = 1): """Context manager to measure execution time of a block :arg function metric: f(name, 1, time) :arg str name: name for the metric :arg int count: user-supplied number of items, defaults to 1 """ t = time.time() try: yield ...
python
def block(*, name = None, metric = call_default, count = 1): """Context manager to measure execution time of a block :arg function metric: f(name, 1, time) :arg str name: name for the metric :arg int count: user-supplied number of items, defaults to 1 """ t = time.time() try: yield ...
[ "def", "block", "(", "*", ",", "name", "=", "None", ",", "metric", "=", "call_default", ",", "count", "=", "1", ")", ":", "t", "=", "time", ".", "time", "(", ")", "try", ":", "yield", "finally", ":", "metric", "(", "name", ",", "count", ",", "t...
Context manager to measure execution time of a block :arg function metric: f(name, 1, time) :arg str name: name for the metric :arg int count: user-supplied number of items, defaults to 1
[ "Context", "manager", "to", "measure", "execution", "time", "of", "a", "block" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/__init__.py#L319-L330
37,629
toumorokoshi/sprinter
sprinter/formula/package.py
PackageFormula.__get_package_manager
def __get_package_manager(self): """ Installs and verifies package manager """ package_manager = "" args = "" sudo_required = True if system.is_osx(): package_manager = "brew" sudo_required = False args = " install" elif...
python
def __get_package_manager(self): """ Installs and verifies package manager """ package_manager = "" args = "" sudo_required = True if system.is_osx(): package_manager = "brew" sudo_required = False args = " install" elif...
[ "def", "__get_package_manager", "(", "self", ")", ":", "package_manager", "=", "\"\"", "args", "=", "\"\"", "sudo_required", "=", "True", "if", "system", ".", "is_osx", "(", ")", ":", "package_manager", "=", "\"brew\"", "sudo_required", "=", "False", "args", ...
Installs and verifies package manager
[ "Installs", "and", "verifies", "package", "manager" ]
846697a7a087e69c61d075232e754d6975a64152
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/package.py#L56-L82
37,630
thewca/wca-regulations-compiler
wrc/parse/parser.py
WCAParser.parse
def parse(self, data, doctype): ''' Parse an input string, and return an AST doctype must have WCADocument as a baseclass ''' self.doctype = doctype self.lexer.lineno = 0 del self.errors[:] del self.warnings[:] self.lexer.lexerror = False a...
python
def parse(self, data, doctype): ''' Parse an input string, and return an AST doctype must have WCADocument as a baseclass ''' self.doctype = doctype self.lexer.lineno = 0 del self.errors[:] del self.warnings[:] self.lexer.lexerror = False a...
[ "def", "parse", "(", "self", ",", "data", ",", "doctype", ")", ":", "self", ".", "doctype", "=", "doctype", "self", ".", "lexer", ".", "lineno", "=", "0", "del", "self", ".", "errors", "[", ":", "]", "del", "self", ".", "warnings", "[", ":", "]",...
Parse an input string, and return an AST doctype must have WCADocument as a baseclass
[ "Parse", "an", "input", "string", "and", "return", "an", "AST", "doctype", "must", "have", "WCADocument", "as", "a", "baseclass" ]
3ebbd8fe8fec7c9167296f59b2677696fe61a954
https://github.com/thewca/wca-regulations-compiler/blob/3ebbd8fe8fec7c9167296f59b2677696fe61a954/wrc/parse/parser.py#L41-L63
37,631
thewca/wca-regulations-compiler
wrc/parse/parser.py
WCAParser.p_error
def p_error(self, elem): '''Handle syntax error''' self.errors.append("Syntax error on line " + str(self.lexer.lineno) + ". Got unexpected token " + elem.type)
python
def p_error(self, elem): '''Handle syntax error''' self.errors.append("Syntax error on line " + str(self.lexer.lineno) + ". Got unexpected token " + elem.type)
[ "def", "p_error", "(", "self", ",", "elem", ")", ":", "self", ".", "errors", ".", "append", "(", "\"Syntax error on line \"", "+", "str", "(", "self", ".", "lexer", ".", "lineno", ")", "+", "\". Got unexpected token \"", "+", "elem", ".", "type", ")" ]
Handle syntax error
[ "Handle", "syntax", "error" ]
3ebbd8fe8fec7c9167296f59b2677696fe61a954
https://github.com/thewca/wca-regulations-compiler/blob/3ebbd8fe8fec7c9167296f59b2677696fe61a954/wrc/parse/parser.py#L251-L254
37,632
mailund/statusbar
statusbar/__init__.py
ProgressBar.set_progress_brackets
def set_progress_brackets(self, start, end): """Set brackets to set around a progress bar.""" self.sep_start = start self.sep_end = end
python
def set_progress_brackets(self, start, end): """Set brackets to set around a progress bar.""" self.sep_start = start self.sep_end = end
[ "def", "set_progress_brackets", "(", "self", ",", "start", ",", "end", ")", ":", "self", ".", "sep_start", "=", "start", "self", ".", "sep_end", "=", "end" ]
Set brackets to set around a progress bar.
[ "Set", "brackets", "to", "set", "around", "a", "progress", "bar", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L43-L46
37,633
mailund/statusbar
statusbar/__init__.py
ProgressBar.format_progress
def format_progress(self, width): """Create the formatted string that displays the progress.""" chunk_widths = self._get_chunk_sizes(width) progress_chunks = [chunk.format_chunk(chunk_width) for (chunk, chunk_width) in zip(self._progress_chun...
python
def format_progress(self, width): """Create the formatted string that displays the progress.""" chunk_widths = self._get_chunk_sizes(width) progress_chunks = [chunk.format_chunk(chunk_width) for (chunk, chunk_width) in zip(self._progress_chun...
[ "def", "format_progress", "(", "self", ",", "width", ")", ":", "chunk_widths", "=", "self", ".", "_get_chunk_sizes", "(", "width", ")", "progress_chunks", "=", "[", "chunk", ".", "format_chunk", "(", "chunk_width", ")", "for", "(", "chunk", ",", "chunk_width...
Create the formatted string that displays the progress.
[ "Create", "the", "formatted", "string", "that", "displays", "the", "progress", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L83-L93
37,634
mailund/statusbar
statusbar/__init__.py
ProgressBar.summary_width
def summary_width(self): """Calculate how long a string is needed to show a summary string. This is not simply the length of the formatted summary string since that string might contain ANSI codes. """ chunk_counts = [chunk.count for chunk in self._progress_chunks] numbe...
python
def summary_width(self): """Calculate how long a string is needed to show a summary string. This is not simply the length of the formatted summary string since that string might contain ANSI codes. """ chunk_counts = [chunk.count for chunk in self._progress_chunks] numbe...
[ "def", "summary_width", "(", "self", ")", ":", "chunk_counts", "=", "[", "chunk", ".", "count", "for", "chunk", "in", "self", ".", "_progress_chunks", "]", "numbers_width", "=", "sum", "(", "max", "(", "1", ",", "ceil", "(", "log10", "(", "count", "+",...
Calculate how long a string is needed to show a summary string. This is not simply the length of the formatted summary string since that string might contain ANSI codes.
[ "Calculate", "how", "long", "a", "string", "is", "needed", "to", "show", "a", "summary", "string", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L95-L105
37,635
mailund/statusbar
statusbar/__init__.py
ProgressBar.format_summary
def format_summary(self): """Generate a summary string for the progress bar.""" chunks = [chunk.format_chunk_summary() for chunk in self._progress_chunks] return "/".join(chunks)
python
def format_summary(self): """Generate a summary string for the progress bar.""" chunks = [chunk.format_chunk_summary() for chunk in self._progress_chunks] return "/".join(chunks)
[ "def", "format_summary", "(", "self", ")", ":", "chunks", "=", "[", "chunk", ".", "format_chunk_summary", "(", ")", "for", "chunk", "in", "self", ".", "_progress_chunks", "]", "return", "\"/\"", ".", "join", "(", "chunks", ")" ]
Generate a summary string for the progress bar.
[ "Generate", "a", "summary", "string", "for", "the", "progress", "bar", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L107-L111
37,636
mailund/statusbar
statusbar/__init__.py
StatusBar.format_status
def format_status(self, width=None, label_width=None, progress_width=None, summary_width=None): """Generate the formatted status bar string.""" if width is None: # pragma: no cover width = shutil.get_terminal_size()[0] ...
python
def format_status(self, width=None, label_width=None, progress_width=None, summary_width=None): """Generate the formatted status bar string.""" if width is None: # pragma: no cover width = shutil.get_terminal_size()[0] ...
[ "def", "format_status", "(", "self", ",", "width", "=", "None", ",", "label_width", "=", "None", ",", "progress_width", "=", "None", ",", "summary_width", "=", "None", ")", ":", "if", "width", "is", "None", ":", "# pragma: no cover", "width", "=", "shutil"...
Generate the formatted status bar string.
[ "Generate", "the", "formatted", "status", "bar", "string", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L153-L188
37,637
mailund/statusbar
statusbar/__init__.py
StatusTable.add_status_line
def add_status_line(self, label): """Add a status bar line to the table. This function returns the status bar and it can be modified from this return value. """ status_line = StatusBar(label, self._sep_start, self._sep_end, ...
python
def add_status_line(self, label): """Add a status bar line to the table. This function returns the status bar and it can be modified from this return value. """ status_line = StatusBar(label, self._sep_start, self._sep_end, ...
[ "def", "add_status_line", "(", "self", ",", "label", ")", ":", "status_line", "=", "StatusBar", "(", "label", ",", "self", ".", "_sep_start", ",", "self", ".", "_sep_end", ",", "self", ".", "_fill_char", ")", "self", ".", "_lines", ".", "append", "(", ...
Add a status bar line to the table. This function returns the status bar and it can be modified from this return value.
[ "Add", "a", "status", "bar", "line", "to", "the", "table", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L203-L213
37,638
mailund/statusbar
statusbar/__init__.py
StatusTable.calculate_field_widths
def calculate_field_widths(self, width=None, min_label_width=10, min_progress_width=10): """Calculate how wide each field should be so we can align them. We always find room for the summaries since these are short and packed with inf...
python
def calculate_field_widths(self, width=None, min_label_width=10, min_progress_width=10): """Calculate how wide each field should be so we can align them. We always find room for the summaries since these are short and packed with inf...
[ "def", "calculate_field_widths", "(", "self", ",", "width", "=", "None", ",", "min_label_width", "=", "10", ",", "min_progress_width", "=", "10", ")", ":", "if", "width", "is", "None", ":", "# pragma: no cover", "width", "=", "shutil", ".", "get_terminal_size"...
Calculate how wide each field should be so we can align them. We always find room for the summaries since these are short and packed with information. If possible, we will also find room for labels, but if this would make the progress bar width shorter than the specified minium then we ...
[ "Calculate", "how", "wide", "each", "field", "should", "be", "so", "we", "can", "align", "them", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L231-L260
37,639
mailund/statusbar
statusbar/__init__.py
StatusTable.format_table
def format_table(self, width=None, min_label_width=10, min_progress_width=10): """Format the entire table of progress bars. The function first computes the widths of the fields so they can be aligned across lines and then returns formatted lines as a list of strings...
python
def format_table(self, width=None, min_label_width=10, min_progress_width=10): """Format the entire table of progress bars. The function first computes the widths of the fields so they can be aligned across lines and then returns formatted lines as a list of strings...
[ "def", "format_table", "(", "self", ",", "width", "=", "None", ",", "min_label_width", "=", "10", ",", "min_progress_width", "=", "10", ")", ":", "# handle the special case of an empty table.", "if", "len", "(", "self", ".", "_lines", ")", "==", "0", ":", "r...
Format the entire table of progress bars. The function first computes the widths of the fields so they can be aligned across lines and then returns formatted lines as a list of strings.
[ "Format", "the", "entire", "table", "of", "progress", "bars", "." ]
e42ac88cdaae281d47318dd8dcf156bfff2a7b2a
https://github.com/mailund/statusbar/blob/e42ac88cdaae281d47318dd8dcf156bfff2a7b2a/statusbar/__init__.py#L262-L291
37,640
jsmits/django-logutils
django_logutils/middleware.py
create_log_dict
def create_log_dict(request, response): """ Create a dictionary with logging data. """ remote_addr = request.META.get('REMOTE_ADDR') if remote_addr in getattr(settings, 'INTERNAL_IPS', []): remote_addr = request.META.get( 'HTTP_X_FORWARDED_FOR') or remote_addr user_email = "...
python
def create_log_dict(request, response): """ Create a dictionary with logging data. """ remote_addr = request.META.get('REMOTE_ADDR') if remote_addr in getattr(settings, 'INTERNAL_IPS', []): remote_addr = request.META.get( 'HTTP_X_FORWARDED_FOR') or remote_addr user_email = "...
[ "def", "create_log_dict", "(", "request", ",", "response", ")", ":", "remote_addr", "=", "request", ".", "META", ".", "get", "(", "'REMOTE_ADDR'", ")", "if", "remote_addr", "in", "getattr", "(", "settings", ",", "'INTERNAL_IPS'", ",", "[", "]", ")", ":", ...
Create a dictionary with logging data.
[ "Create", "a", "dictionary", "with", "logging", "data", "." ]
e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88
https://github.com/jsmits/django-logutils/blob/e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88/django_logutils/middleware.py#L17-L46
37,641
jsmits/django-logutils
django_logutils/middleware.py
create_log_message
def create_log_message(log_dict, use_sql_info=False, fmt=True): """ Create the logging message string. """ log_msg = ( "%(remote_address)s %(user_email)s %(method)s %(url)s %(status)d " "%(content_length)d (%(request_time).2f seconds)" ) if use_sql_info: sql_time = sum( ...
python
def create_log_message(log_dict, use_sql_info=False, fmt=True): """ Create the logging message string. """ log_msg = ( "%(remote_address)s %(user_email)s %(method)s %(url)s %(status)d " "%(content_length)d (%(request_time).2f seconds)" ) if use_sql_info: sql_time = sum( ...
[ "def", "create_log_message", "(", "log_dict", ",", "use_sql_info", "=", "False", ",", "fmt", "=", "True", ")", ":", "log_msg", "=", "(", "\"%(remote_address)s %(user_email)s %(method)s %(url)s %(status)d \"", "\"%(content_length)d (%(request_time).2f seconds)\"", ")", "if", ...
Create the logging message string.
[ "Create", "the", "logging", "message", "string", "." ]
e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88
https://github.com/jsmits/django-logutils/blob/e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88/django_logutils/middleware.py#L49-L65
37,642
jsmits/django-logutils
django_logutils/middleware.py
LoggingMiddleware.process_response
def process_response(self, request, response): """ Create the logging message.. """ try: log_dict = create_log_dict(request, response) # add the request time to the log_dict; if no start time is # available, use -1 as NA value request_time...
python
def process_response(self, request, response): """ Create the logging message.. """ try: log_dict = create_log_dict(request, response) # add the request time to the log_dict; if no start time is # available, use -1 as NA value request_time...
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "try", ":", "log_dict", "=", "create_log_dict", "(", "request", ",", "response", ")", "# add the request time to the log_dict; if no start time is", "# available, use -1 as NA value", "requ...
Create the logging message..
[ "Create", "the", "logging", "message", ".." ]
e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88
https://github.com/jsmits/django-logutils/blob/e88f6e0a08c6f3df9e61f96cfb6cd79bc5ea8a88/django_logutils/middleware.py#L102-L129
37,643
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
as_completed
def as_completed(jobs): ''' Generator function that yields the jobs in order of their completion. Attaches a new listener to each job. ''' jobs = tuple(jobs) event = threading.Event() callback = lambda f, ev: event.set() [job.add_listener(Job.SUCCESS, callback, once=True) for job in jobs] [job.add_listen...
python
def as_completed(jobs): ''' Generator function that yields the jobs in order of their completion. Attaches a new listener to each job. ''' jobs = tuple(jobs) event = threading.Event() callback = lambda f, ev: event.set() [job.add_listener(Job.SUCCESS, callback, once=True) for job in jobs] [job.add_listen...
[ "def", "as_completed", "(", "jobs", ")", ":", "jobs", "=", "tuple", "(", "jobs", ")", "event", "=", "threading", ".", "Event", "(", ")", "callback", "=", "lambda", "f", ",", "ev", ":", "event", ".", "set", "(", ")", "[", "job", ".", "add_listener",...
Generator function that yields the jobs in order of their completion. Attaches a new listener to each job.
[ "Generator", "function", "that", "yields", "the", "jobs", "in", "order", "of", "their", "completion", ".", "Attaches", "a", "new", "listener", "to", "each", "job", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L682-L698
37,644
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
reraise
def reraise(tpe, value, tb=None): " Reraise an exception from an exception info tuple. " Py3 = (sys.version_info[0] == 3) if value is None: value = tpe() if Py3: if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value else: exec('raise tpe, value, tb')
python
def reraise(tpe, value, tb=None): " Reraise an exception from an exception info tuple. " Py3 = (sys.version_info[0] == 3) if value is None: value = tpe() if Py3: if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value else: exec('raise tpe, value, tb')
[ "def", "reraise", "(", "tpe", ",", "value", ",", "tb", "=", "None", ")", ":", "Py3", "=", "(", "sys", ".", "version_info", "[", "0", "]", "==", "3", ")", "if", "value", "is", "None", ":", "value", "=", "tpe", "(", ")", "if", "Py3", ":", "if",...
Reraise an exception from an exception info tuple.
[ "Reraise", "an", "exception", "from", "an", "exception", "info", "tuple", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L1280-L1291
37,645
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
Job.finished
def finished(self): """ True if the job run and finished. There is no difference if the job finished successfully or errored. """ return self.__state in (Job.ERROR, Job.SUCCESS, Job.CANCELLED)
python
def finished(self): """ True if the job run and finished. There is no difference if the job finished successfully or errored. """ return self.__state in (Job.ERROR, Job.SUCCESS, Job.CANCELLED)
[ "def", "finished", "(", "self", ")", ":", "return", "self", ".", "__state", "in", "(", "Job", ".", "ERROR", ",", "Job", ".", "SUCCESS", ",", "Job", ".", "CANCELLED", ")" ]
True if the job run and finished. There is no difference if the job finished successfully or errored.
[ "True", "if", "the", "job", "run", "and", "finished", ".", "There", "is", "no", "difference", "if", "the", "job", "finished", "successfully", "or", "errored", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L423-L429
37,646
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
Job._trigger_event
def _trigger_event(self, event): """ Private. Triggers and event and removes all one-off listeners for that event. """ if event is None or event not in self.__listeners: raise ValueError('invalid event type: {0!r}'.format(event)) # Check the event has not already been triggered, then mark ...
python
def _trigger_event(self, event): """ Private. Triggers and event and removes all one-off listeners for that event. """ if event is None or event not in self.__listeners: raise ValueError('invalid event type: {0!r}'.format(event)) # Check the event has not already been triggered, then mark ...
[ "def", "_trigger_event", "(", "self", ",", "event", ")", ":", "if", "event", "is", "None", "or", "event", "not", "in", "self", ".", "__listeners", ":", "raise", "ValueError", "(", "'invalid event type: {0!r}'", ".", "format", "(", "event", ")", ")", "# Che...
Private. Triggers and event and removes all one-off listeners for that event.
[ "Private", ".", "Triggers", "and", "event", "and", "removes", "all", "one", "-", "off", "listeners", "for", "that", "event", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L475-L497
37,647
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
Job.wait
def wait(self, timeout=None): """ Waits for the job to finish and returns the result. # Arguments timeout (number, None): A number of seconds to wait for the result before raising a #Timeout exception. # Raises Timeout: If the timeout limit is exceeded. """ def cond(self): ...
python
def wait(self, timeout=None): """ Waits for the job to finish and returns the result. # Arguments timeout (number, None): A number of seconds to wait for the result before raising a #Timeout exception. # Raises Timeout: If the timeout limit is exceeded. """ def cond(self): ...
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "def", "cond", "(", "self", ")", ":", "return", "self", ".", "__state", "not", "in", "(", "Job", ".", "PENDING", ",", "Job", ".", "RUNNING", ")", "or", "self", ".", "__cancelled", ...
Waits for the job to finish and returns the result. # Arguments timeout (number, None): A number of seconds to wait for the result before raising a #Timeout exception. # Raises Timeout: If the timeout limit is exceeded.
[ "Waits", "for", "the", "job", "to", "finish", "and", "returns", "the", "result", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L535-L551
37,648
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
Job.factory
def factory(start_immediately=True): """ This is a decorator function that creates new `Job`s with the wrapped function as the target. # Example ```python @Job.factory() def some_longish_function(job, seconds): time.sleep(seconds) return 42 job = some_longish_function(2) ...
python
def factory(start_immediately=True): """ This is a decorator function that creates new `Job`s with the wrapped function as the target. # Example ```python @Job.factory() def some_longish_function(job, seconds): time.sleep(seconds) return 42 job = some_longish_function(2) ...
[ "def", "factory", "(", "start_immediately", "=", "True", ")", ":", "def", "decorator", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "job", "=", "Job", "(", "task", "=", "lambda", "j", ":", "func", ...
This is a decorator function that creates new `Job`s with the wrapped function as the target. # Example ```python @Job.factory() def some_longish_function(job, seconds): time.sleep(seconds) return 42 job = some_longish_function(2) print(job.wait()) ``` # Arguments ...
[ "This", "is", "a", "decorator", "function", "that", "creates", "new", "Job", "s", "with", "the", "wrapped", "function", "as", "the", "target", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L651-L679
37,649
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
ThreadPool.wait
def wait(self, timeout=None): """ Block until all jobs in the ThreadPool are finished. Beware that this can make the program run into a deadlock if another thread adds new jobs to the pool! # Raises Timeout: If the timeout is exceeded. """ if not self.__running: raise RuntimeErro...
python
def wait(self, timeout=None): """ Block until all jobs in the ThreadPool are finished. Beware that this can make the program run into a deadlock if another thread adds new jobs to the pool! # Raises Timeout: If the timeout is exceeded. """ if not self.__running: raise RuntimeErro...
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "not", "self", ".", "__running", ":", "raise", "RuntimeError", "(", "\"ThreadPool ain't running\"", ")", "self", ".", "__queue", ".", "wait", "(", "timeout", ")" ]
Block until all jobs in the ThreadPool are finished. Beware that this can make the program run into a deadlock if another thread adds new jobs to the pool! # Raises Timeout: If the timeout is exceeded.
[ "Block", "until", "all", "jobs", "in", "the", "ThreadPool", "are", "finished", ".", "Beware", "that", "this", "can", "make", "the", "program", "run", "into", "a", "deadlock", "if", "another", "thread", "adds", "new", "jobs", "to", "the", "pool!" ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L894-L906
37,650
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
ThreadPool.shutdown
def shutdown(self, wait=True): """ Shut down the ThreadPool. # Arguments wait (bool): If #True, wait until all worker threads end. Note that pending jobs are still executed. If you want to cancel any pending jobs, use the #clear() or #cancel_all() methods. """ if self.__running: ...
python
def shutdown(self, wait=True): """ Shut down the ThreadPool. # Arguments wait (bool): If #True, wait until all worker threads end. Note that pending jobs are still executed. If you want to cancel any pending jobs, use the #clear() or #cancel_all() methods. """ if self.__running: ...
[ "def", "shutdown", "(", "self", ",", "wait", "=", "True", ")", ":", "if", "self", ".", "__running", ":", "# Add a Non-entry for every worker thread we have.", "for", "thread", "in", "self", ".", "__threads", ":", "assert", "thread", ".", "isAlive", "(", ")", ...
Shut down the ThreadPool. # Arguments wait (bool): If #True, wait until all worker threads end. Note that pending jobs are still executed. If you want to cancel any pending jobs, use the #clear() or #cancel_all() methods.
[ "Shut", "down", "the", "ThreadPool", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L908-L928
37,651
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
EventQueue.new_event_type
def new_event_type(self, name, mergeable=False): ''' Declare a new event. May overwrite an existing entry. ''' self.event_types[name] = self.EventType(name, mergeable)
python
def new_event_type(self, name, mergeable=False): ''' Declare a new event. May overwrite an existing entry. ''' self.event_types[name] = self.EventType(name, mergeable)
[ "def", "new_event_type", "(", "self", ",", "name", ",", "mergeable", "=", "False", ")", ":", "self", ".", "event_types", "[", "name", "]", "=", "self", ".", "EventType", "(", "name", ",", "mergeable", ")" ]
Declare a new event. May overwrite an existing entry.
[ "Declare", "a", "new", "event", ".", "May", "overwrite", "an", "existing", "entry", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L994-L997
37,652
NiklasRosenstein-Python/nr-deprecated
nr/concurrency.py
EventQueue.pop_event
def pop_event(self): ''' Pop the next queued event from the queue. :raise ValueError: If there is no event queued. ''' with self.lock: if not self.events: raise ValueError('no events queued') return self.events.popleft()
python
def pop_event(self): ''' Pop the next queued event from the queue. :raise ValueError: If there is no event queued. ''' with self.lock: if not self.events: raise ValueError('no events queued') return self.events.popleft()
[ "def", "pop_event", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "not", "self", ".", "events", ":", "raise", "ValueError", "(", "'no events queued'", ")", "return", "self", ".", "events", ".", "popleft", "(", ")" ]
Pop the next queued event from the queue. :raise ValueError: If there is no event queued.
[ "Pop", "the", "next", "queued", "event", "from", "the", "queue", "." ]
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/concurrency.py#L1025-L1035
37,653
ludeeus/pytautulli
pytautulli/__init__.py
logger
def logger(message, level=10): """Handle logging.""" logging.getLogger(__name__).log(level, str(message))
python
def logger(message, level=10): """Handle logging.""" logging.getLogger(__name__).log(level, str(message))
[ "def", "logger", "(", "message", ",", "level", "=", "10", ")", ":", "logging", ".", "getLogger", "(", "__name__", ")", ".", "log", "(", "level", ",", "str", "(", "message", ")", ")" ]
Handle logging.
[ "Handle", "logging", "." ]
0cf602f6720a105abb2311c8fbc8c6b2f9581276
https://github.com/ludeeus/pytautulli/blob/0cf602f6720a105abb2311c8fbc8c6b2f9581276/pytautulli/__init__.py#L196-L198
37,654
ludeeus/pytautulli
pytautulli/__init__.py
Tautulli.get_data
async def get_data(self): """Get Tautulli data.""" try: await self.get_session_data() await self.get_home_data() await self.get_users() await self.get_user_data() except (asyncio.TimeoutError, aiohttp.ClientError, socket.gaierror): msg ...
python
async def get_data(self): """Get Tautulli data.""" try: await self.get_session_data() await self.get_home_data() await self.get_users() await self.get_user_data() except (asyncio.TimeoutError, aiohttp.ClientError, socket.gaierror): msg ...
[ "async", "def", "get_data", "(", "self", ")", ":", "try", ":", "await", "self", ".", "get_session_data", "(", ")", "await", "self", ".", "get_home_data", "(", ")", "await", "self", ".", "get_users", "(", ")", "await", "self", ".", "get_user_data", "(", ...
Get Tautulli data.
[ "Get", "Tautulli", "data", "." ]
0cf602f6720a105abb2311c8fbc8c6b2f9581276
https://github.com/ludeeus/pytautulli/blob/0cf602f6720a105abb2311c8fbc8c6b2f9581276/pytautulli/__init__.py#L61-L70
37,655
ludeeus/pytautulli
pytautulli/__init__.py
Tautulli.get_session_data
async def get_session_data(self): """Get Tautulli sessions.""" cmd = 'get_activity' url = self.base_url + cmd try: async with async_timeout.timeout(8, loop=self._loop): response = await self._session.get(url) logger("Status from Tautulli: " + str(...
python
async def get_session_data(self): """Get Tautulli sessions.""" cmd = 'get_activity' url = self.base_url + cmd try: async with async_timeout.timeout(8, loop=self._loop): response = await self._session.get(url) logger("Status from Tautulli: " + str(...
[ "async", "def", "get_session_data", "(", "self", ")", ":", "cmd", "=", "'get_activity'", "url", "=", "self", ".", "base_url", "+", "cmd", "try", ":", "async", "with", "async_timeout", ".", "timeout", "(", "8", ",", "loop", "=", "self", ".", "_loop", ")...
Get Tautulli sessions.
[ "Get", "Tautulli", "sessions", "." ]
0cf602f6720a105abb2311c8fbc8c6b2f9581276
https://github.com/ludeeus/pytautulli/blob/0cf602f6720a105abb2311c8fbc8c6b2f9581276/pytautulli/__init__.py#L72-L87
37,656
ludeeus/pytautulli
pytautulli/__init__.py
Tautulli.get_home_data
async def get_home_data(self): """Get Tautulli home stats.""" cmd = 'get_home_stats' url = self.base_url + cmd data = {} try: async with async_timeout.timeout(8, loop=self._loop): request = await self._session.get(url) response = await ...
python
async def get_home_data(self): """Get Tautulli home stats.""" cmd = 'get_home_stats' url = self.base_url + cmd data = {} try: async with async_timeout.timeout(8, loop=self._loop): request = await self._session.get(url) response = await ...
[ "async", "def", "get_home_data", "(", "self", ")", ":", "cmd", "=", "'get_home_stats'", "url", "=", "self", ".", "base_url", "+", "cmd", "data", "=", "{", "}", "try", ":", "async", "with", "async_timeout", ".", "timeout", "(", "8", ",", "loop", "=", ...
Get Tautulli home stats.
[ "Get", "Tautulli", "home", "stats", "." ]
0cf602f6720a105abb2311c8fbc8c6b2f9581276
https://github.com/ludeeus/pytautulli/blob/0cf602f6720a105abb2311c8fbc8c6b2f9581276/pytautulli/__init__.py#L89-L124
37,657
ludeeus/pytautulli
pytautulli/__init__.py
Tautulli.get_users
async def get_users(self): """Get Tautulli users.""" cmd = 'get_users' url = self.base_url + cmd users = [] try: async with async_timeout.timeout(8, loop=self._loop): response = await self._session.get(url) logger("Status from Tautulli: " ...
python
async def get_users(self): """Get Tautulli users.""" cmd = 'get_users' url = self.base_url + cmd users = [] try: async with async_timeout.timeout(8, loop=self._loop): response = await self._session.get(url) logger("Status from Tautulli: " ...
[ "async", "def", "get_users", "(", "self", ")", ":", "cmd", "=", "'get_users'", "url", "=", "self", ".", "base_url", "+", "cmd", "users", "=", "[", "]", "try", ":", "async", "with", "async_timeout", ".", "timeout", "(", "8", ",", "loop", "=", "self", ...
Get Tautulli users.
[ "Get", "Tautulli", "users", "." ]
0cf602f6720a105abb2311c8fbc8c6b2f9581276
https://github.com/ludeeus/pytautulli/blob/0cf602f6720a105abb2311c8fbc8c6b2f9581276/pytautulli/__init__.py#L126-L146
37,658
ludeeus/pytautulli
pytautulli/__init__.py
Tautulli.get_user_data
async def get_user_data(self): """Get Tautulli userdata.""" userdata = {} sessions = self.session_data.get('sessions', {}) try: async with async_timeout.timeout(8, loop=self._loop): for username in self.tautulli_users: userdata[username] = ...
python
async def get_user_data(self): """Get Tautulli userdata.""" userdata = {} sessions = self.session_data.get('sessions', {}) try: async with async_timeout.timeout(8, loop=self._loop): for username in self.tautulli_users: userdata[username] = ...
[ "async", "def", "get_user_data", "(", "self", ")", ":", "userdata", "=", "{", "}", "sessions", "=", "self", ".", "session_data", ".", "get", "(", "'sessions'", ",", "{", "}", ")", "try", ":", "async", "with", "async_timeout", ".", "timeout", "(", "8", ...
Get Tautulli userdata.
[ "Get", "Tautulli", "userdata", "." ]
0cf602f6720a105abb2311c8fbc8c6b2f9581276
https://github.com/ludeeus/pytautulli/blob/0cf602f6720a105abb2311c8fbc8c6b2f9581276/pytautulli/__init__.py#L148-L168
37,659
frascoweb/frasco
frasco/utils.py
find_classes_in_module
def find_classes_in_module(module, clstypes): """Find classes of clstypes in module """ classes = [] for item in dir(module): item = getattr(module, item) try: for cls in clstypes: if issubclass(item, cls) and item != cls: classes.append(it...
python
def find_classes_in_module(module, clstypes): """Find classes of clstypes in module """ classes = [] for item in dir(module): item = getattr(module, item) try: for cls in clstypes: if issubclass(item, cls) and item != cls: classes.append(it...
[ "def", "find_classes_in_module", "(", "module", ",", "clstypes", ")", ":", "classes", "=", "[", "]", "for", "item", "in", "dir", "(", "module", ")", ":", "item", "=", "getattr", "(", "module", ",", "item", ")", "try", ":", "for", "cls", "in", "clstyp...
Find classes of clstypes in module
[ "Find", "classes", "of", "clstypes", "in", "module" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/utils.py#L82-L94
37,660
frascoweb/frasco
frasco/utils.py
remove_yaml_frontmatter
def remove_yaml_frontmatter(source, return_frontmatter=False): """If there's one, remove the YAML front-matter from the source """ if source.startswith("---\n"): frontmatter_end = source.find("\n---\n", 4) if frontmatter_end == -1: frontmatter = source source = "" ...
python
def remove_yaml_frontmatter(source, return_frontmatter=False): """If there's one, remove the YAML front-matter from the source """ if source.startswith("---\n"): frontmatter_end = source.find("\n---\n", 4) if frontmatter_end == -1: frontmatter = source source = "" ...
[ "def", "remove_yaml_frontmatter", "(", "source", ",", "return_frontmatter", "=", "False", ")", ":", "if", "source", ".", "startswith", "(", "\"---\\n\"", ")", ":", "frontmatter_end", "=", "source", ".", "find", "(", "\"\\n---\\n\"", ",", "4", ")", "if", "fro...
If there's one, remove the YAML front-matter from the source
[ "If", "there", "s", "one", "remove", "the", "YAML", "front", "-", "matter", "from", "the", "source" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/utils.py#L97-L113
37,661
frascoweb/frasco
frasco/utils.py
populate_obj
def populate_obj(obj, attrs): """Populates an object's attributes using the provided dict """ for k, v in attrs.iteritems(): setattr(obj, k, v)
python
def populate_obj(obj, attrs): """Populates an object's attributes using the provided dict """ for k, v in attrs.iteritems(): setattr(obj, k, v)
[ "def", "populate_obj", "(", "obj", ",", "attrs", ")", ":", "for", "k", ",", "v", "in", "attrs", ".", "iteritems", "(", ")", ":", "setattr", "(", "obj", ",", "k", ",", "v", ")" ]
Populates an object's attributes using the provided dict
[ "Populates", "an", "object", "s", "attributes", "using", "the", "provided", "dict" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/utils.py#L123-L127
37,662
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
ParserFinder.build_parser_for_fileobject_and_desiredtype
def build_parser_for_fileobject_and_desiredtype(self, obj_on_filesystem: PersistedObject, object_type: Type[T], logger: Logger = None) -> Parser: """ Returns the most appropriate parser to use to parse object obj_on_filesystem as an object of type obje...
python
def build_parser_for_fileobject_and_desiredtype(self, obj_on_filesystem: PersistedObject, object_type: Type[T], logger: Logger = None) -> Parser: """ Returns the most appropriate parser to use to parse object obj_on_filesystem as an object of type obje...
[ "def", "build_parser_for_fileobject_and_desiredtype", "(", "self", ",", "obj_on_filesystem", ":", "PersistedObject", ",", "object_type", ":", "Type", "[", "T", "]", ",", "logger", ":", "Logger", "=", "None", ")", "->", "Parser", ":", "pass" ]
Returns the most appropriate parser to use to parse object obj_on_filesystem as an object of type object_type :param obj_on_filesystem: the filesystem object to parse :param object_type: the type of object that the parser is expected to produce :param logger: :return:
[ "Returns", "the", "most", "appropriate", "parser", "to", "use", "to", "parse", "object", "obj_on_filesystem", "as", "an", "object", "of", "type", "object_type" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L29-L39
37,663
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
AbstractParserCache.get_capabilities_by_type
def get_capabilities_by_type(self, strict_type_matching: bool = False) -> Dict[Type, Dict[str, Dict[str, Parser]]]: """ For all types that are supported, lists all extensions that can be parsed into such a type. For each extension, provides the list of parsers supported. The order is "mo...
python
def get_capabilities_by_type(self, strict_type_matching: bool = False) -> Dict[Type, Dict[str, Dict[str, Parser]]]: """ For all types that are supported, lists all extensions that can be parsed into such a type. For each extension, provides the list of parsers supported. The order is "mo...
[ "def", "get_capabilities_by_type", "(", "self", ",", "strict_type_matching", ":", "bool", "=", "False", ")", "->", "Dict", "[", "Type", ",", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Parser", "]", "]", "]", ":", "check_var", "(", "strict_type_ma...
For all types that are supported, lists all extensions that can be parsed into such a type. For each extension, provides the list of parsers supported. The order is "most pertinent first" This method is for monitoring and debug, so we prefer to not rely on the cache, but rather on the query eng...
[ "For", "all", "types", "that", "are", "supported", "lists", "all", "extensions", "that", "can", "be", "parsed", "into", "such", "a", "type", ".", "For", "each", "extension", "provides", "the", "list", "of", "parsers", "supported", ".", "The", "order", "is"...
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L279-L300
37,664
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
AbstractParserCache.get_capabilities_by_ext
def get_capabilities_by_ext(self, strict_type_matching: bool = False) -> Dict[str, Dict[Type, Dict[str, Parser]]]: """ For all extensions that are supported, lists all types that can be parsed from this extension. For each type, provide the list of parsers supported. The order is "most p...
python
def get_capabilities_by_ext(self, strict_type_matching: bool = False) -> Dict[str, Dict[Type, Dict[str, Parser]]]: """ For all extensions that are supported, lists all types that can be parsed from this extension. For each type, provide the list of parsers supported. The order is "most p...
[ "def", "get_capabilities_by_ext", "(", "self", ",", "strict_type_matching", ":", "bool", "=", "False", ")", "->", "Dict", "[", "str", ",", "Dict", "[", "Type", ",", "Dict", "[", "str", ",", "Parser", "]", "]", "]", ":", "check_var", "(", "strict_type_mat...
For all extensions that are supported, lists all types that can be parsed from this extension. For each type, provide the list of parsers supported. The order is "most pertinent first" This method is for monitoring and debug, so we prefer to not rely on the cache, but rather on the query engine...
[ "For", "all", "extensions", "that", "are", "supported", "lists", "all", "types", "that", "can", "be", "parsed", "from", "this", "extension", ".", "For", "each", "type", "provide", "the", "list", "of", "parsers", "supported", ".", "The", "order", "is", "mos...
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L337-L356
37,665
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
AbstractParserCache.get_capabilities_for_ext
def get_capabilities_for_ext(self, ext, strict_type_matching: bool = False) -> Dict[Type, Dict[str, Parser]]: """ Utility method to return, for a given file extension, all known ways to parse a file with this extension, organized by target object type. :param ext: :param strict_...
python
def get_capabilities_for_ext(self, ext, strict_type_matching: bool = False) -> Dict[Type, Dict[str, Parser]]: """ Utility method to return, for a given file extension, all known ways to parse a file with this extension, organized by target object type. :param ext: :param strict_...
[ "def", "get_capabilities_for_ext", "(", "self", ",", "ext", ",", "strict_type_matching", ":", "bool", "=", "False", ")", "->", "Dict", "[", "Type", ",", "Dict", "[", "str", ",", "Parser", "]", "]", ":", "r", "=", "dict", "(", ")", "# List all types that ...
Utility method to return, for a given file extension, all known ways to parse a file with this extension, organized by target object type. :param ext: :param strict_type_matching: :return:
[ "Utility", "method", "to", "return", "for", "a", "given", "file", "extension", "all", "known", "ways", "to", "parse", "a", "file", "with", "this", "extension", "organized", "by", "target", "object", "type", "." ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L361-L391
37,666
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
ParserCache.get_all_supported_types_for_ext
def get_all_supported_types_for_ext(self, ext_to_match: str, strict_type_matching: bool = False) -> Set[Type]: """ Utility method to return the set of all supported types that may be parsed from files with the given extension. ext=JOKER is a joker that means all extensions :param ext_to...
python
def get_all_supported_types_for_ext(self, ext_to_match: str, strict_type_matching: bool = False) -> Set[Type]: """ Utility method to return the set of all supported types that may be parsed from files with the given extension. ext=JOKER is a joker that means all extensions :param ext_to...
[ "def", "get_all_supported_types_for_ext", "(", "self", ",", "ext_to_match", ":", "str", ",", "strict_type_matching", ":", "bool", "=", "False", ")", "->", "Set", "[", "Type", "]", ":", "matching", "=", "self", ".", "find_all_matching_parsers", "(", "required_ext...
Utility method to return the set of all supported types that may be parsed from files with the given extension. ext=JOKER is a joker that means all extensions :param ext_to_match: :param strict_type_matching: :return:
[ "Utility", "method", "to", "return", "the", "set", "of", "all", "supported", "types", "that", "may", "be", "parsed", "from", "files", "with", "the", "given", "extension", ".", "ext", "=", "JOKER", "is", "a", "joker", "that", "means", "all", "extensions" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L505-L516
37,667
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
ParserCache.get_all_supported_exts_for_type
def get_all_supported_exts_for_type(self, type_to_match: Type[Any], strict: bool) -> Set[str]: """ Utility method to return the set of all supported file extensions that may be converted to objects of the given type. type=JOKER is a joker that means all types :param type_to_match: ...
python
def get_all_supported_exts_for_type(self, type_to_match: Type[Any], strict: bool) -> Set[str]: """ Utility method to return the set of all supported file extensions that may be converted to objects of the given type. type=JOKER is a joker that means all types :param type_to_match: ...
[ "def", "get_all_supported_exts_for_type", "(", "self", ",", "type_to_match", ":", "Type", "[", "Any", "]", ",", "strict", ":", "bool", ")", "->", "Set", "[", "str", "]", ":", "matching", "=", "self", ".", "find_all_matching_parsers", "(", "desired_type", "="...
Utility method to return the set of all supported file extensions that may be converted to objects of the given type. type=JOKER is a joker that means all types :param type_to_match: :param strict: :return:
[ "Utility", "method", "to", "return", "the", "set", "of", "all", "supported", "file", "extensions", "that", "may", "be", "converted", "to", "objects", "of", "the", "given", "type", ".", "type", "=", "JOKER", "is", "a", "joker", "that", "means", "all", "ty...
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L518-L529
37,668
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
ParserCache.find_all_matching_parsers
def find_all_matching_parsers(self, strict: bool, desired_type: Type[Any] = JOKER, required_ext: str = JOKER) \ -> Tuple[Tuple[List[Parser], List[Parser], List[Parser]], List[Parser], List[Parser], List[Parser]]: """ Implementation of the parent method by lookin into the...
python
def find_all_matching_parsers(self, strict: bool, desired_type: Type[Any] = JOKER, required_ext: str = JOKER) \ -> Tuple[Tuple[List[Parser], List[Parser], List[Parser]], List[Parser], List[Parser], List[Parser]]: """ Implementation of the parent method by lookin into the...
[ "def", "find_all_matching_parsers", "(", "self", ",", "strict", ":", "bool", ",", "desired_type", ":", "Type", "[", "Any", "]", "=", "JOKER", ",", "required_ext", ":", "str", "=", "JOKER", ")", "->", "Tuple", "[", "Tuple", "[", "List", "[", "Parser", "...
Implementation of the parent method by lookin into the registry to find the most appropriate parsers to use in order :param strict: :param desired_type: the desired type, or 'JOKER' for a wildcard :param required_ext: :return: match=(matching_parsers_generic, matching_parsers_ap...
[ "Implementation", "of", "the", "parent", "method", "by", "lookin", "into", "the", "registry", "to", "find", "the", "most", "appropriate", "parsers", "to", "use", "in", "order" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L531-L621
37,669
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
ParserRegistry._build_parser_for_fileobject_and_desiredtype
def _build_parser_for_fileobject_and_desiredtype(self, obj_on_filesystem: PersistedObject, object_typ: Type[T], logger: Logger = None) -> Dict[Type, Parser]: """ Builds a parser for each subtype of object_typ :param obj_on_filesystem: ...
python
def _build_parser_for_fileobject_and_desiredtype(self, obj_on_filesystem: PersistedObject, object_typ: Type[T], logger: Logger = None) -> Dict[Type, Parser]: """ Builds a parser for each subtype of object_typ :param obj_on_filesystem: ...
[ "def", "_build_parser_for_fileobject_and_desiredtype", "(", "self", ",", "obj_on_filesystem", ":", "PersistedObject", ",", "object_typ", ":", "Type", "[", "T", "]", ",", "logger", ":", "Logger", "=", "None", ")", "->", "Dict", "[", "Type", ",", "Parser", "]", ...
Builds a parser for each subtype of object_typ :param obj_on_filesystem: :param object_typ: :param logger: :return:
[ "Builds", "a", "parser", "for", "each", "subtype", "of", "object_typ" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L717-L770
37,670
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
ConversionFinder.get_all_conversion_chains_to_type
def get_all_conversion_chains_to_type(self, to_type: Type[Any])\ -> Tuple[List[Converter], List[Converter], List[Converter]]: """ Utility method to find all converters to a given type :param to_type: :return: """ return self.get_all_conversion_chains(to_type=...
python
def get_all_conversion_chains_to_type(self, to_type: Type[Any])\ -> Tuple[List[Converter], List[Converter], List[Converter]]: """ Utility method to find all converters to a given type :param to_type: :return: """ return self.get_all_conversion_chains(to_type=...
[ "def", "get_all_conversion_chains_to_type", "(", "self", ",", "to_type", ":", "Type", "[", "Any", "]", ")", "->", "Tuple", "[", "List", "[", "Converter", "]", ",", "List", "[", "Converter", "]", ",", "List", "[", "Converter", "]", "]", ":", "return", "...
Utility method to find all converters to a given type :param to_type: :return:
[ "Utility", "method", "to", "find", "all", "converters", "to", "a", "given", "type" ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L922-L930
37,671
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
ConversionFinder.get_all_conversion_chains_from_type
def get_all_conversion_chains_from_type(self, from_type: Type[Any]) \ -> Tuple[List[Converter], List[Converter], List[Converter]]: """ Utility method to find all converters from a given type. :param from_type: :return: """ return self.get_all_conversion_chain...
python
def get_all_conversion_chains_from_type(self, from_type: Type[Any]) \ -> Tuple[List[Converter], List[Converter], List[Converter]]: """ Utility method to find all converters from a given type. :param from_type: :return: """ return self.get_all_conversion_chain...
[ "def", "get_all_conversion_chains_from_type", "(", "self", ",", "from_type", ":", "Type", "[", "Any", "]", ")", "->", "Tuple", "[", "List", "[", "Converter", "]", ",", "List", "[", "Converter", "]", ",", "List", "[", "Converter", "]", "]", ":", "return",...
Utility method to find all converters from a given type. :param from_type: :return:
[ "Utility", "method", "to", "find", "all", "converters", "from", "a", "given", "type", "." ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L932-L940
37,672
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
ConversionFinder.get_all_conversion_chains
def get_all_conversion_chains(self, from_type: Type[Any] = JOKER, to_type: Type[Any] = JOKER)\ -> Tuple[List[Converter], List[Converter], List[Converter]]: """ Utility method to find all converters or conversion chains matching the provided query. :param from_type: a required type o...
python
def get_all_conversion_chains(self, from_type: Type[Any] = JOKER, to_type: Type[Any] = JOKER)\ -> Tuple[List[Converter], List[Converter], List[Converter]]: """ Utility method to find all converters or conversion chains matching the provided query. :param from_type: a required type o...
[ "def", "get_all_conversion_chains", "(", "self", ",", "from_type", ":", "Type", "[", "Any", "]", "=", "JOKER", ",", "to_type", ":", "Type", "[", "Any", "]", "=", "JOKER", ")", "->", "Tuple", "[", "List", "[", "Converter", "]", ",", "List", "[", "Conv...
Utility method to find all converters or conversion chains matching the provided query. :param from_type: a required type of input object, or JOKER for 'wildcard'(*) . WARNING: "from_type=AnyObject/object/Any" means "all converters able to source from anything", which is different from "from_ty...
[ "Utility", "method", "to", "find", "all", "converters", "or", "conversion", "chains", "matching", "the", "provided", "query", "." ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L943-L958
37,673
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
ConverterCache.get_all_conversion_chains
def get_all_conversion_chains(self, from_type: Type[Any] = JOKER, to_type: Type[Any] = JOKER) \ -> Tuple[List[Converter], List[Converter], List[Converter]]: """ Utility method to find matching converters or conversion chains. :param from_type: a required type of input object, or JOK...
python
def get_all_conversion_chains(self, from_type: Type[Any] = JOKER, to_type: Type[Any] = JOKER) \ -> Tuple[List[Converter], List[Converter], List[Converter]]: """ Utility method to find matching converters or conversion chains. :param from_type: a required type of input object, or JOK...
[ "def", "get_all_conversion_chains", "(", "self", ",", "from_type", ":", "Type", "[", "Any", "]", "=", "JOKER", ",", "to_type", ":", "Type", "[", "Any", "]", "=", "JOKER", ")", "->", "Tuple", "[", "List", "[", "Converter", "]", ",", "List", "[", "Conv...
Utility method to find matching converters or conversion chains. :param from_type: a required type of input object, or JOKER for 'wildcard'(*) . WARNING: "from_type=AnyObject/object/Any" means "all converters able to source from anything", which is different from "from_type=JOKER" which means "...
[ "Utility", "method", "to", "find", "matching", "converters", "or", "conversion", "chains", "." ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L1351-L1413
37,674
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
ParserRegistryWithConverters.find_all_matching_parsers
def find_all_matching_parsers(self, strict: bool, desired_type: Type[Any] = JOKER, required_ext: str = JOKER) \ -> Tuple[Tuple[List[Parser], List[Parser], List[Parser]], List[Parser], List[Parser], List[Parser]]: """ Overrides the parent method to find parsers appropriate to a g...
python
def find_all_matching_parsers(self, strict: bool, desired_type: Type[Any] = JOKER, required_ext: str = JOKER) \ -> Tuple[Tuple[List[Parser], List[Parser], List[Parser]], List[Parser], List[Parser], List[Parser]]: """ Overrides the parent method to find parsers appropriate to a g...
[ "def", "find_all_matching_parsers", "(", "self", ",", "strict", ":", "bool", ",", "desired_type", ":", "Type", "[", "Any", "]", "=", "JOKER", ",", "required_ext", ":", "str", "=", "JOKER", ")", "->", "Tuple", "[", "Tuple", "[", "List", "[", "Parser", "...
Overrides the parent method to find parsers appropriate to a given extension and type. This leverages both the parser registry and the converter registry to propose parsing chains in a relevant order :param strict: :param desired_type: the type of object to match. :param required_ext: t...
[ "Overrides", "the", "parent", "method", "to", "find", "parsers", "appropriate", "to", "a", "given", "extension", "and", "type", ".", "This", "leverages", "both", "the", "parser", "registry", "and", "the", "converter", "registry", "to", "propose", "parsing", "c...
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L1440-L1530
37,675
smarie/python-parsyfiles
parsyfiles/parsing_registries.py
ParserRegistryWithConverters._complete_parsers_with_converters
def _complete_parsers_with_converters(self, parser, parser_supported_type, desired_type, matching_c_generic_to_type, matching_c_approx_to_type, matching_c_exact_to_type): """ Internal method to create parsing chains made of a parser and converters from the provi...
python
def _complete_parsers_with_converters(self, parser, parser_supported_type, desired_type, matching_c_generic_to_type, matching_c_approx_to_type, matching_c_exact_to_type): """ Internal method to create parsing chains made of a parser and converters from the provi...
[ "def", "_complete_parsers_with_converters", "(", "self", ",", "parser", ",", "parser_supported_type", ",", "desired_type", ",", "matching_c_generic_to_type", ",", "matching_c_approx_to_type", ",", "matching_c_exact_to_type", ")", ":", "matching_p_generic", ",", "matching_p_ge...
Internal method to create parsing chains made of a parser and converters from the provided lists. Once again a JOKER for a type means 'joker' here. :param parser: :param parser_supported_type: :param desired_type: :param matching_c_generic_to_type: :param matching_c_appr...
[ "Internal", "method", "to", "create", "parsing", "chains", "made", "of", "a", "parser", "and", "converters", "from", "the", "provided", "lists", ".", "Once", "again", "a", "JOKER", "for", "a", "type", "means", "joker", "here", "." ]
344b37e1151e8d4e7c2ee49ae09d6568715ae64e
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L1532-L1632
37,676
NiklasRosenstein-Python/nr-deprecated
nr/tools/versionupgrade.py
get_changed_files
def get_changed_files(include_staged=False): """ Returns a list of the files that changed in the Git repository. This is used to check if the files that are supposed to be upgraded have changed. If so, the upgrade will be prevented. """ process = subprocess.Popen(['git', 'status', '--porcelain'], stdou...
python
def get_changed_files(include_staged=False): """ Returns a list of the files that changed in the Git repository. This is used to check if the files that are supposed to be upgraded have changed. If so, the upgrade will be prevented. """ process = subprocess.Popen(['git', 'status', '--porcelain'], stdou...
[ "def", "get_changed_files", "(", "include_staged", "=", "False", ")", ":", "process", "=", "subprocess", ".", "Popen", "(", "[", "'git'", ",", "'status'", ",", "'--porcelain'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subpro...
Returns a list of the files that changed in the Git repository. This is used to check if the files that are supposed to be upgraded have changed. If so, the upgrade will be prevented.
[ "Returns", "a", "list", "of", "the", "files", "that", "changed", "in", "the", "Git", "repository", ".", "This", "is", "used", "to", "check", "if", "the", "files", "that", "are", "supposed", "to", "be", "upgraded", "have", "changed", ".", "If", "so", "t...
f9f8b89ea1b084841a8ab65784eaf68852686b2a
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/tools/versionupgrade.py#L126-L144
37,677
ponty/entrypoint2
entrypoint2/__init__.py
_parse_doc
def _parse_doc(docs): """ Converts a well-formed docstring into documentation to be fed into argparse. See signature_parser for details. shorts: (-k for --keyword -k, or "from" for "frm/from") metavars: (FILE for --input=FILE) helps: (docs for --keyword: docs) ...
python
def _parse_doc(docs): """ Converts a well-formed docstring into documentation to be fed into argparse. See signature_parser for details. shorts: (-k for --keyword -k, or "from" for "frm/from") metavars: (FILE for --input=FILE) helps: (docs for --keyword: docs) ...
[ "def", "_parse_doc", "(", "docs", ")", ":", "name", "=", "\"(?:[a-zA-Z][a-zA-Z0-9-_]*)\"", "re_var", "=", "re", ".", "compile", "(", "r\"^ *(%s)(?: */(%s))? *:(.*)$\"", "%", "(", "name", ",", "name", ")", ")", "re_opt", "=", "re", ".", "compile", "(", "r\"^ ...
Converts a well-formed docstring into documentation to be fed into argparse. See signature_parser for details. shorts: (-k for --keyword -k, or "from" for "frm/from") metavars: (FILE for --input=FILE) helps: (docs for --keyword: docs) description: the stuff before ...
[ "Converts", "a", "well", "-", "formed", "docstring", "into", "documentation", "to", "be", "fed", "into", "argparse", "." ]
d355dd1a6e0cabdd6751fc2f6016aee20755d332
https://github.com/ponty/entrypoint2/blob/d355dd1a6e0cabdd6751fc2f6016aee20755d332/entrypoint2/__init__.py#L125-L206
37,678
scraperwiki/dumptruck
dumptruck/convert.py
quote
def quote(text): 'Handle quote characters' # Convert to unicode. if not isinstance(text, unicode): text = text.decode('utf-8') # Look for quote characters. Keep the text as is if it's already quoted. for qp in QUOTEPAIRS: if text[0] == qp[0] and text[-1] == qp[-1] and len(text) >= 2: return te...
python
def quote(text): 'Handle quote characters' # Convert to unicode. if not isinstance(text, unicode): text = text.decode('utf-8') # Look for quote characters. Keep the text as is if it's already quoted. for qp in QUOTEPAIRS: if text[0] == qp[0] and text[-1] == qp[-1] and len(text) >= 2: return te...
[ "def", "quote", "(", "text", ")", ":", "# Convert to unicode.", "if", "not", "isinstance", "(", "text", ",", "unicode", ")", ":", "text", "=", "text", ".", "decode", "(", "'utf-8'", ")", "# Look for quote characters. Keep the text as is if it's already quoted.", "fo...
Handle quote characters
[ "Handle", "quote", "characters" ]
ac5855e34d4dffc7e53a13ff925ccabda19604fc
https://github.com/scraperwiki/dumptruck/blob/ac5855e34d4dffc7e53a13ff925ccabda19604fc/dumptruck/convert.py#L72-L90
37,679
bniemczyk/automata
automata/automata.py
NFA.reltags
def reltags(self, src, cache=None): ''' returns all the tags that are relevant at this state cache should be a dictionary and it is updated by the function ''' if not self._tag_assocs: return set() # fucking python and it's terrible support for recursion makes this # far more comp...
python
def reltags(self, src, cache=None): ''' returns all the tags that are relevant at this state cache should be a dictionary and it is updated by the function ''' if not self._tag_assocs: return set() # fucking python and it's terrible support for recursion makes this # far more comp...
[ "def", "reltags", "(", "self", ",", "src", ",", "cache", "=", "None", ")", ":", "if", "not", "self", ".", "_tag_assocs", ":", "return", "set", "(", ")", "# fucking python and it's terrible support for recursion makes this", "# far more complicated than it needs to be", ...
returns all the tags that are relevant at this state cache should be a dictionary and it is updated by the function
[ "returns", "all", "the", "tags", "that", "are", "relevant", "at", "this", "state", "cache", "should", "be", "a", "dictionary", "and", "it", "is", "updated", "by", "the", "function" ]
b4e21ba8b881f2cb1a07a813a4011209a3f1e017
https://github.com/bniemczyk/automata/blob/b4e21ba8b881f2cb1a07a813a4011209a3f1e017/automata/automata.py#L60-L95
37,680
wearpants/instrument
instrument/output/logging.py
make_log_metric
def make_log_metric(level=logging.INFO, msg="%d items in %.2f seconds"): """Make a new metric function that logs at the given level :arg int level: logging level, defaults to ``logging.INFO`` :arg string msg: logging message format string, taking ``count`` and ``elapsed`` :rtype: function """ d...
python
def make_log_metric(level=logging.INFO, msg="%d items in %.2f seconds"): """Make a new metric function that logs at the given level :arg int level: logging level, defaults to ``logging.INFO`` :arg string msg: logging message format string, taking ``count`` and ``elapsed`` :rtype: function """ d...
[ "def", "make_log_metric", "(", "level", "=", "logging", ".", "INFO", ",", "msg", "=", "\"%d items in %.2f seconds\"", ")", ":", "def", "log_metric", "(", "name", ",", "count", ",", "elapsed", ")", ":", "log_name", "=", "'instrument.{}'", ".", "format", "(", ...
Make a new metric function that logs at the given level :arg int level: logging level, defaults to ``logging.INFO`` :arg string msg: logging message format string, taking ``count`` and ``elapsed`` :rtype: function
[ "Make", "a", "new", "metric", "function", "that", "logs", "at", "the", "given", "level" ]
a0f6103574ab58a82361a951e5e56b69aedfe294
https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/output/logging.py#L4-L14
37,681
memphis-iis/GLUDB
gludb/simple.py
DBObject
def DBObject(table_name, versioning=VersioningTypes.NONE): """Classes annotated with DBObject gain persistence methods.""" def wrapped(cls): field_names = set() all_fields = [] for name in dir(cls): fld = getattr(cls, name) if fld and isinstance(fld, Field): ...
python
def DBObject(table_name, versioning=VersioningTypes.NONE): """Classes annotated with DBObject gain persistence methods.""" def wrapped(cls): field_names = set() all_fields = [] for name in dir(cls): fld = getattr(cls, name) if fld and isinstance(fld, Field): ...
[ "def", "DBObject", "(", "table_name", ",", "versioning", "=", "VersioningTypes", ".", "NONE", ")", ":", "def", "wrapped", "(", "cls", ")", ":", "field_names", "=", "set", "(", ")", "all_fields", "=", "[", "]", "for", "name", "in", "dir", "(", "cls", ...
Classes annotated with DBObject gain persistence methods.
[ "Classes", "annotated", "with", "DBObject", "gain", "persistence", "methods", "." ]
25692528ff6fe8184a3570f61f31f1a90088a388
https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/simple.py#L188-L253
37,682
VikParuchuri/percept
percept/tasks/validate.py
Validate.train
def train(self, data, target, **kwargs): """ Used in the training phase. Override. """ non_predictors = [i.replace(" ", "_").lower() for i in list(set(data['team']))] + ["team", "next_year_wins"] self.column_names = [l for l in list(data.columns) if l not in non_predictors] ...
python
def train(self, data, target, **kwargs): """ Used in the training phase. Override. """ non_predictors = [i.replace(" ", "_").lower() for i in list(set(data['team']))] + ["team", "next_year_wins"] self.column_names = [l for l in list(data.columns) if l not in non_predictors] ...
[ "def", "train", "(", "self", ",", "data", ",", "target", ",", "*", "*", "kwargs", ")", ":", "non_predictors", "=", "[", "i", ".", "replace", "(", "\" \"", ",", "\"_\"", ")", ".", "lower", "(", ")", "for", "i", "in", "list", "(", "set", "(", "da...
Used in the training phase. Override.
[ "Used", "in", "the", "training", "phase", ".", "Override", "." ]
90304ba82053e2a9ad2bacaab3479403d3923bcf
https://github.com/VikParuchuri/percept/blob/90304ba82053e2a9ad2bacaab3479403d3923bcf/percept/tasks/validate.py#L78-L85
37,683
frascoweb/frasco
frasco/commands.py
CommandDecorator.as_command
def as_command(self): """Creates the click command wrapping the function """ try: params = self.unbound_func.__click_params__ params.reverse() del self.unbound_func.__click_params__ except AttributeError: params = [] help = inspect....
python
def as_command(self): """Creates the click command wrapping the function """ try: params = self.unbound_func.__click_params__ params.reverse() del self.unbound_func.__click_params__ except AttributeError: params = [] help = inspect....
[ "def", "as_command", "(", "self", ")", ":", "try", ":", "params", "=", "self", ".", "unbound_func", ".", "__click_params__", "params", ".", "reverse", "(", ")", "del", "self", ".", "unbound_func", ".", "__click_params__", "except", "AttributeError", ":", "pa...
Creates the click command wrapping the function
[ "Creates", "the", "click", "command", "wrapping", "the", "function" ]
ea519d69dd5ca6deaf3650175692ee4a1a02518f
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/commands.py#L76-L99
37,684
bioidiap/bob.ip.facedetect
bob/ip/facedetect/script/plot_froc.py
main
def main(command_line_arguments=None): """Reads score files, computes error measures and plots curves.""" args = command_line_options(command_line_arguments) # get some colors for plotting cmap = mpl.cm.get_cmap(name='hsv') count = len(args.files) + (len(args.baselines) if args.baselines else 0) colors = ...
python
def main(command_line_arguments=None): """Reads score files, computes error measures and plots curves.""" args = command_line_options(command_line_arguments) # get some colors for plotting cmap = mpl.cm.get_cmap(name='hsv') count = len(args.files) + (len(args.baselines) if args.baselines else 0) colors = ...
[ "def", "main", "(", "command_line_arguments", "=", "None", ")", ":", "args", "=", "command_line_options", "(", "command_line_arguments", ")", "# get some colors for plotting", "cmap", "=", "mpl", ".", "cm", ".", "get_cmap", "(", "name", "=", "'hsv'", ")", "count...
Reads score files, computes error measures and plots curves.
[ "Reads", "score", "files", "computes", "error", "measures", "and", "plots", "curves", "." ]
601da5141ca7302ad36424d1421b33190ba46779
https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/script/plot_froc.py#L168-L225
37,685
Robpol86/Flask-Statics-Helper
flask_statics/helpers.py
get_resources
def get_resources(minify=False): """Find all resources which subclass ResourceBase. Keyword arguments: minify -- select minified resources if available. Returns: Dictionary of available resources. Keys are resource names (part of the config variable names), values are dicts with css and js key...
python
def get_resources(minify=False): """Find all resources which subclass ResourceBase. Keyword arguments: minify -- select minified resources if available. Returns: Dictionary of available resources. Keys are resource names (part of the config variable names), values are dicts with css and js key...
[ "def", "get_resources", "(", "minify", "=", "False", ")", ":", "all_resources", "=", "dict", "(", ")", "subclasses", "=", "resource_base", ".", "ResourceBase", ".", "__subclasses__", "(", ")", "+", "resource_definitions", ".", "ResourceAngular", ".", "__subclass...
Find all resources which subclass ResourceBase. Keyword arguments: minify -- select minified resources if available. Returns: Dictionary of available resources. Keys are resource names (part of the config variable names), values are dicts with css and js keys, and tuples of resources as values.
[ "Find", "all", "resources", "which", "subclass", "ResourceBase", "." ]
b1771e65225f62b760b3ef841b710ff23ef6f83c
https://github.com/Robpol86/Flask-Statics-Helper/blob/b1771e65225f62b760b3ef841b710ff23ef6f83c/flask_statics/helpers.py#L23-L38
37,686
scieloorg/citedbyapi
citedby/client.py
ThriftClient.search
def search(self, dsl, params): """ Free queries to ES index. dsl (string): with DSL query params (list): [(key, value), (key, value)] where key is a query parameter, and value is the value required for parameter, ex: [('size', '0'), ('search_type', 'count')] """ ...
python
def search(self, dsl, params): """ Free queries to ES index. dsl (string): with DSL query params (list): [(key, value), (key, value)] where key is a query parameter, and value is the value required for parameter, ex: [('size', '0'), ('search_type', 'count')] """ ...
[ "def", "search", "(", "self", ",", "dsl", ",", "params", ")", ":", "query_parameters", "=", "[", "]", "for", "key", ",", "value", "in", "params", ":", "query_parameters", ".", "append", "(", "self", ".", "CITEDBY_THRIFT", ".", "kwargs", "(", "str", "("...
Free queries to ES index. dsl (string): with DSL query params (list): [(key, value), (key, value)] where key is a query parameter, and value is the value required for parameter, ex: [('size', '0'), ('search_type', 'count')]
[ "Free", "queries", "to", "ES", "index", "." ]
c614d6d1a3c3a5aebd8d79c18bcab444fb351b90
https://github.com/scieloorg/citedbyapi/blob/c614d6d1a3c3a5aebd8d79c18bcab444fb351b90/citedby/client.py#L215-L236
37,687
nimbusproject/dashi
dashi/__init__.py
raise_error
def raise_error(error): """Intakes a dict of remote error information and raises a DashiError """ exc_type = error.get('exc_type') if exc_type and exc_type.startswith(ERROR_PREFIX): exc_type = exc_type[len(ERROR_PREFIX):] exc_cls = ERROR_TYPE_MAP.get(exc_type, DashiError) else: ...
python
def raise_error(error): """Intakes a dict of remote error information and raises a DashiError """ exc_type = error.get('exc_type') if exc_type and exc_type.startswith(ERROR_PREFIX): exc_type = exc_type[len(ERROR_PREFIX):] exc_cls = ERROR_TYPE_MAP.get(exc_type, DashiError) else: ...
[ "def", "raise_error", "(", "error", ")", ":", "exc_type", "=", "error", ".", "get", "(", "'exc_type'", ")", "if", "exc_type", "and", "exc_type", ".", "startswith", "(", "ERROR_PREFIX", ")", ":", "exc_type", "=", "exc_type", "[", "len", "(", "ERROR_PREFIX",...
Intakes a dict of remote error information and raises a DashiError
[ "Intakes", "a", "dict", "of", "remote", "error", "information", "and", "raises", "a", "DashiError" ]
368b3963ec8abd60aebe0f81915429b45cbf4b5a
https://github.com/nimbusproject/dashi/blob/368b3963ec8abd60aebe0f81915429b45cbf4b5a/dashi/__init__.py#L553-L563
37,688
nimbusproject/dashi
dashi/__init__.py
Dashi.fire
def fire(self, name, operation, args=None, **kwargs): """Send a message without waiting for a reply @param name: name of destination service queue @param operation: name of service operation to invoke @param args: dictionary of keyword args to pass to operation. Use...
python
def fire(self, name, operation, args=None, **kwargs): """Send a message without waiting for a reply @param name: name of destination service queue @param operation: name of service operation to invoke @param args: dictionary of keyword args to pass to operation. Use...
[ "def", "fire", "(", "self", ",", "name", ",", "operation", ",", "args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "args", ":", "if", "kwargs", ":", "raise", "TypeError", "(", "\"specify args dict or keyword arguments, not both\"", ")", "else", ...
Send a message without waiting for a reply @param name: name of destination service queue @param operation: name of service operation to invoke @param args: dictionary of keyword args to pass to operation. Use this OR kwargs. @param kwargs: additional args to pass t...
[ "Send", "a", "message", "without", "waiting", "for", "a", "reply" ]
368b3963ec8abd60aebe0f81915429b45cbf4b5a
https://github.com/nimbusproject/dashi/blob/368b3963ec8abd60aebe0f81915429b45cbf4b5a/dashi/__init__.py#L101-L131
37,689
nimbusproject/dashi
dashi/__init__.py
Dashi.call
def call(self, name, operation, timeout=10, args=None, **kwargs): """Send a message and wait for reply @param name: name of destination service queue @param operation: name of service operation to invoke @param timeout: RPC timeout to await a reply @param args: dictionary of key...
python
def call(self, name, operation, timeout=10, args=None, **kwargs): """Send a message and wait for reply @param name: name of destination service queue @param operation: name of service operation to invoke @param timeout: RPC timeout to await a reply @param args: dictionary of key...
[ "def", "call", "(", "self", ",", "name", ",", "operation", ",", "timeout", "=", "10", ",", "args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "args", ":", "if", "kwargs", ":", "raise", "TypeError", "(", "\"specify args dict or keyword argument...
Send a message and wait for reply @param name: name of destination service queue @param operation: name of service operation to invoke @param timeout: RPC timeout to await a reply @param args: dictionary of keyword args to pass to operation. Use this OR kwargs. ...
[ "Send", "a", "message", "and", "wait", "for", "reply" ]
368b3963ec8abd60aebe0f81915429b45cbf4b5a
https://github.com/nimbusproject/dashi/blob/368b3963ec8abd60aebe0f81915429b45cbf4b5a/dashi/__init__.py#L133-L204
37,690
nimbusproject/dashi
dashi/__init__.py
Dashi.handle
def handle(self, operation, operation_name=None, sender_kwarg=None): """Handle an operation using the specified function @param operation: function to call for this operation @param operation_name: operation name. if unspecified operation.__name__ is used @param sender_kwarg: optional k...
python
def handle(self, operation, operation_name=None, sender_kwarg=None): """Handle an operation using the specified function @param operation: function to call for this operation @param operation_name: operation name. if unspecified operation.__name__ is used @param sender_kwarg: optional k...
[ "def", "handle", "(", "self", ",", "operation", ",", "operation_name", "=", "None", ",", "sender_kwarg", "=", "None", ")", ":", "if", "not", "self", ".", "_consumer", ":", "self", ".", "_consumer", "=", "DashiConsumer", "(", "self", ",", "self", ".", "...
Handle an operation using the specified function @param operation: function to call for this operation @param operation_name: operation name. if unspecified operation.__name__ is used @param sender_kwarg: optional keyword arg on operation to feed in sender name
[ "Handle", "an", "operation", "using", "the", "specified", "function" ]
368b3963ec8abd60aebe0f81915429b45cbf4b5a
https://github.com/nimbusproject/dashi/blob/368b3963ec8abd60aebe0f81915429b45cbf4b5a/dashi/__init__.py#L276-L287
37,691
nimbusproject/dashi
dashi/__init__.py
Dashi.link_exceptions
def link_exceptions(self, custom_exception=None, dashi_exception=None): """Link a custom exception thrown on the receiver to a dashi exception """ if custom_exception is None: raise ValueError("custom_exception must be set") if dashi_exception is None: raise Value...
python
def link_exceptions(self, custom_exception=None, dashi_exception=None): """Link a custom exception thrown on the receiver to a dashi exception """ if custom_exception is None: raise ValueError("custom_exception must be set") if dashi_exception is None: raise Value...
[ "def", "link_exceptions", "(", "self", ",", "custom_exception", "=", "None", ",", "dashi_exception", "=", "None", ")", ":", "if", "custom_exception", "is", "None", ":", "raise", "ValueError", "(", "\"custom_exception must be set\"", ")", "if", "dashi_exception", "...
Link a custom exception thrown on the receiver to a dashi exception
[ "Link", "a", "custom", "exception", "thrown", "on", "the", "receiver", "to", "a", "dashi", "exception" ]
368b3963ec8abd60aebe0f81915429b45cbf4b5a
https://github.com/nimbusproject/dashi/blob/368b3963ec8abd60aebe0f81915429b45cbf4b5a/dashi/__init__.py#L313-L321
37,692
nimbusproject/dashi
dashi/__init__.py
Dashi.ensure
def ensure(self, connection, func, *args, **kwargs): """Perform an operation until success Repeats in the face of connection errors, pursuant to retry policy. """ channel = None while 1: try: if channel is None: channel = connectio...
python
def ensure(self, connection, func, *args, **kwargs): """Perform an operation until success Repeats in the face of connection errors, pursuant to retry policy. """ channel = None while 1: try: if channel is None: channel = connectio...
[ "def", "ensure", "(", "self", ",", "connection", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "channel", "=", "None", "while", "1", ":", "try", ":", "if", "channel", "is", "None", ":", "channel", "=", "connection", ".", "channe...
Perform an operation until success Repeats in the face of connection errors, pursuant to retry policy.
[ "Perform", "an", "operation", "until", "success" ]
368b3963ec8abd60aebe0f81915429b45cbf4b5a
https://github.com/nimbusproject/dashi/blob/368b3963ec8abd60aebe0f81915429b45cbf4b5a/dashi/__init__.py#L379-L393
37,693
cwoebker/pen
pen/edit.py
re_tab
def re_tab(s): """Return a tabbed string from an expanded one.""" l = [] p = 0 for i in range(8, len(s), 8): if s[i - 2:i] == " ": # collapse two or more spaces into a tab l.append(s[p:i].rstrip() + "\t") p = i if p == 0: return s else: ...
python
def re_tab(s): """Return a tabbed string from an expanded one.""" l = [] p = 0 for i in range(8, len(s), 8): if s[i - 2:i] == " ": # collapse two or more spaces into a tab l.append(s[p:i].rstrip() + "\t") p = i if p == 0: return s else: ...
[ "def", "re_tab", "(", "s", ")", ":", "l", "=", "[", "]", "p", "=", "0", "for", "i", "in", "range", "(", "8", ",", "len", "(", "s", ")", ",", "8", ")", ":", "if", "s", "[", "i", "-", "2", ":", "i", "]", "==", "\" \"", ":", "# collapse t...
Return a tabbed string from an expanded one.
[ "Return", "a", "tabbed", "string", "from", "an", "expanded", "one", "." ]
996dfcdc018f2fc14a376835a2622fb4a7230a2f
https://github.com/cwoebker/pen/blob/996dfcdc018f2fc14a376835a2622fb4a7230a2f/pen/edit.py#L187-L201
37,694
cwoebker/pen
pen/edit.py
LineWalker.read_next_line
def read_next_line(self): """Read another line from the file.""" next_line = self.file.readline() if not next_line or next_line[-1:] != '\n': # no newline on last line of file self.file = None else: # trim newline characters next_line = n...
python
def read_next_line(self): """Read another line from the file.""" next_line = self.file.readline() if not next_line or next_line[-1:] != '\n': # no newline on last line of file self.file = None else: # trim newline characters next_line = n...
[ "def", "read_next_line", "(", "self", ")", ":", "next_line", "=", "self", ".", "file", ".", "readline", "(", ")", "if", "not", "next_line", "or", "next_line", "[", "-", "1", ":", "]", "!=", "'\\n'", ":", "# no newline on last line of file", "self", ".", ...
Read another line from the file.
[ "Read", "another", "line", "from", "the", "file", "." ]
996dfcdc018f2fc14a376835a2622fb4a7230a2f
https://github.com/cwoebker/pen/blob/996dfcdc018f2fc14a376835a2622fb4a7230a2f/pen/edit.py#L31-L50
37,695
cwoebker/pen
pen/edit.py
LineWalker._get_at_pos
def _get_at_pos(self, pos): """Return a widget for the line number passed.""" if pos < 0: # line 0 is the start of the file, no more above return None, None if len(self.lines) > pos: # we have that line so return it return self.lines[pos], pos ...
python
def _get_at_pos(self, pos): """Return a widget for the line number passed.""" if pos < 0: # line 0 is the start of the file, no more above return None, None if len(self.lines) > pos: # we have that line so return it return self.lines[pos], pos ...
[ "def", "_get_at_pos", "(", "self", ",", "pos", ")", ":", "if", "pos", "<", "0", ":", "# line 0 is the start of the file, no more above", "return", "None", ",", "None", "if", "len", "(", "self", ".", "lines", ")", ">", "pos", ":", "# we have that line so return...
Return a widget for the line number passed.
[ "Return", "a", "widget", "for", "the", "line", "number", "passed", "." ]
996dfcdc018f2fc14a376835a2622fb4a7230a2f
https://github.com/cwoebker/pen/blob/996dfcdc018f2fc14a376835a2622fb4a7230a2f/pen/edit.py#L52-L71
37,696
cwoebker/pen
pen/edit.py
LineWalker.split_focus
def split_focus(self): """Divide the focus edit widget at the cursor location.""" focus = self.lines[self.focus] pos = focus.edit_pos edit = urwid.Edit("", focus.edit_text[pos:], allow_tab=True) edit.original_text = "" focus.set_edit_text(focus.edit_text[:pos]) e...
python
def split_focus(self): """Divide the focus edit widget at the cursor location.""" focus = self.lines[self.focus] pos = focus.edit_pos edit = urwid.Edit("", focus.edit_text[pos:], allow_tab=True) edit.original_text = "" focus.set_edit_text(focus.edit_text[:pos]) e...
[ "def", "split_focus", "(", "self", ")", ":", "focus", "=", "self", ".", "lines", "[", "self", ".", "focus", "]", "pos", "=", "focus", ".", "edit_pos", "edit", "=", "urwid", ".", "Edit", "(", "\"\"", ",", "focus", ".", "edit_text", "[", "pos", ":", ...
Divide the focus edit widget at the cursor location.
[ "Divide", "the", "focus", "edit", "widget", "at", "the", "cursor", "location", "." ]
996dfcdc018f2fc14a376835a2622fb4a7230a2f
https://github.com/cwoebker/pen/blob/996dfcdc018f2fc14a376835a2622fb4a7230a2f/pen/edit.py#L73-L82
37,697
cwoebker/pen
pen/edit.py
LineWalker.combine_focus_with_prev
def combine_focus_with_prev(self): """Combine the focus edit widget with the one above.""" above, ignore = self.get_prev(self.focus) if above is None: # already at the top return focus = self.lines[self.focus] above.set_edit_pos(len(above.edit_text)) ...
python
def combine_focus_with_prev(self): """Combine the focus edit widget with the one above.""" above, ignore = self.get_prev(self.focus) if above is None: # already at the top return focus = self.lines[self.focus] above.set_edit_pos(len(above.edit_text)) ...
[ "def", "combine_focus_with_prev", "(", "self", ")", ":", "above", ",", "ignore", "=", "self", ".", "get_prev", "(", "self", ".", "focus", ")", "if", "above", "is", "None", ":", "# already at the top", "return", "focus", "=", "self", ".", "lines", "[", "s...
Combine the focus edit widget with the one above.
[ "Combine", "the", "focus", "edit", "widget", "with", "the", "one", "above", "." ]
996dfcdc018f2fc14a376835a2622fb4a7230a2f
https://github.com/cwoebker/pen/blob/996dfcdc018f2fc14a376835a2622fb4a7230a2f/pen/edit.py#L84-L96
37,698
cwoebker/pen
pen/edit.py
LineWalker.combine_focus_with_next
def combine_focus_with_next(self): """Combine the focus edit widget with the one below.""" below, ignore = self.get_next(self.focus) if below is None: # already at bottom return focus = self.lines[self.focus] focus.set_edit_text(focus.edit_text + below.e...
python
def combine_focus_with_next(self): """Combine the focus edit widget with the one below.""" below, ignore = self.get_next(self.focus) if below is None: # already at bottom return focus = self.lines[self.focus] focus.set_edit_text(focus.edit_text + below.e...
[ "def", "combine_focus_with_next", "(", "self", ")", ":", "below", ",", "ignore", "=", "self", ".", "get_next", "(", "self", ".", "focus", ")", "if", "below", "is", "None", ":", "# already at bottom", "return", "focus", "=", "self", ".", "lines", "[", "se...
Combine the focus edit widget with the one below.
[ "Combine", "the", "focus", "edit", "widget", "with", "the", "one", "below", "." ]
996dfcdc018f2fc14a376835a2622fb4a7230a2f
https://github.com/cwoebker/pen/blob/996dfcdc018f2fc14a376835a2622fb4a7230a2f/pen/edit.py#L98-L108
37,699
cwoebker/pen
pen/edit.py
EditDisplay.handle_keypress
def handle_keypress(self, k): """Last resort for keypresses.""" if k == "esc": self.save_file() raise urwid.ExitMainLoop() elif k == "delete": # delete at end of line self.walker.combine_focus_with_next() elif k == "backspace": ...
python
def handle_keypress(self, k): """Last resort for keypresses.""" if k == "esc": self.save_file() raise urwid.ExitMainLoop() elif k == "delete": # delete at end of line self.walker.combine_focus_with_next() elif k == "backspace": ...
[ "def", "handle_keypress", "(", "self", ",", "k", ")", ":", "if", "k", "==", "\"esc\"", ":", "self", ".", "save_file", "(", ")", "raise", "urwid", ".", "ExitMainLoop", "(", ")", "elif", "k", "==", "\"delete\"", ":", "# delete at end of line", "self", ".",...
Last resort for keypresses.
[ "Last", "resort", "for", "keypresses", "." ]
996dfcdc018f2fc14a376835a2622fb4a7230a2f
https://github.com/cwoebker/pen/blob/996dfcdc018f2fc14a376835a2622fb4a7230a2f/pen/edit.py#L134-L150