repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
corydodt/Crosscap
crosscap/openapi.py
representCleanOpenAPIOperation
def representCleanOpenAPIOperation(dumper, data): """ Unpack nonstandard attributes while representing an OpenAPIOperation """ dct = _orderedCleanDict(data) if '_extended' in dct: for k, ext in list(data._extended.items()): dct[k] = ext del dct['_extended'] return du...
python
def representCleanOpenAPIOperation(dumper, data): """ Unpack nonstandard attributes while representing an OpenAPIOperation """ dct = _orderedCleanDict(data) if '_extended' in dct: for k, ext in list(data._extended.items()): dct[k] = ext del dct['_extended'] return du...
[ "def", "representCleanOpenAPIOperation", "(", "dumper", ",", "data", ")", ":", "dct", "=", "_orderedCleanDict", "(", "data", ")", "if", "'_extended'", "in", "dct", ":", "for", "k", ",", "ext", "in", "list", "(", "data", ".", "_extended", ".", "items", "(...
Unpack nonstandard attributes while representing an OpenAPIOperation
[ "Unpack", "nonstandard", "attributes", "while", "representing", "an", "OpenAPIOperation" ]
train
https://github.com/corydodt/Crosscap/blob/388a2ec36b8aa85e8f1ed692bb6e43474ba76c8e/crosscap/openapi.py#L141-L151
corydodt/Crosscap
crosscap/openapi.py
representCleanOpenAPIPathItem
def representCleanOpenAPIPathItem(dumper, data): """ Unpack operation key/values before representing an OpenAPIPathItem """ dct = _orderedCleanDict(data) if '_operations' in dct: items = sorted(data._operations.items()) for k, op in items: dct[k] = op del dct['_op...
python
def representCleanOpenAPIPathItem(dumper, data): """ Unpack operation key/values before representing an OpenAPIPathItem """ dct = _orderedCleanDict(data) if '_operations' in dct: items = sorted(data._operations.items()) for k, op in items: dct[k] = op del dct['_op...
[ "def", "representCleanOpenAPIPathItem", "(", "dumper", ",", "data", ")", ":", "dct", "=", "_orderedCleanDict", "(", "data", ")", "if", "'_operations'", "in", "dct", ":", "items", "=", "sorted", "(", "data", ".", "_operations", ".", "items", "(", ")", ")", ...
Unpack operation key/values before representing an OpenAPIPathItem
[ "Unpack", "operation", "key", "/", "values", "before", "representing", "an", "OpenAPIPathItem" ]
train
https://github.com/corydodt/Crosscap/blob/388a2ec36b8aa85e8f1ed692bb6e43474ba76c8e/crosscap/openapi.py#L154-L165
corydodt/Crosscap
crosscap/openapi.py
representCleanOpenAPIParameter
def representCleanOpenAPIParameter(dumper, data): """ Rename python reserved keyword fields before representing an OpenAPIParameter """ dct = _orderedCleanDict(data) # We are using "in_" as a key for the "in" parameter, since in is a Python keyword. # To represent it correctly, we then have to s...
python
def representCleanOpenAPIParameter(dumper, data): """ Rename python reserved keyword fields before representing an OpenAPIParameter """ dct = _orderedCleanDict(data) # We are using "in_" as a key for the "in" parameter, since in is a Python keyword. # To represent it correctly, we then have to s...
[ "def", "representCleanOpenAPIParameter", "(", "dumper", ",", "data", ")", ":", "dct", "=", "_orderedCleanDict", "(", "data", ")", "# We are using \"in_\" as a key for the \"in\" parameter, since in is a Python keyword.", "# To represent it correctly, we then have to swap \"in_\" for \"...
Rename python reserved keyword fields before representing an OpenAPIParameter
[ "Rename", "python", "reserved", "keyword", "fields", "before", "representing", "an", "OpenAPIParameter" ]
train
https://github.com/corydodt/Crosscap/blob/388a2ec36b8aa85e8f1ed692bb6e43474ba76c8e/crosscap/openapi.py#L168-L184
corydodt/Crosscap
crosscap/openapi.py
representCleanOpenAPIObjects
def representCleanOpenAPIObjects(dumper, data): """ Produce a representation of an OpenAPI object, removing empty attributes """ dct = _orderedCleanDict(data) return dumper.yaml_representers[type(dct)](dumper, dct)
python
def representCleanOpenAPIObjects(dumper, data): """ Produce a representation of an OpenAPI object, removing empty attributes """ dct = _orderedCleanDict(data) return dumper.yaml_representers[type(dct)](dumper, dct)
[ "def", "representCleanOpenAPIObjects", "(", "dumper", ",", "data", ")", ":", "dct", "=", "_orderedCleanDict", "(", "data", ")", "return", "dumper", ".", "yaml_representers", "[", "type", "(", "dct", ")", "]", "(", "dumper", ",", "dct", ")" ]
Produce a representation of an OpenAPI object, removing empty attributes
[ "Produce", "a", "representation", "of", "an", "OpenAPI", "object", "removing", "empty", "attributes" ]
train
https://github.com/corydodt/Crosscap/blob/388a2ec36b8aa85e8f1ed692bb6e43474ba76c8e/crosscap/openapi.py#L187-L193
corydodt/Crosscap
crosscap/openapi.py
mediaTypeHelper
def mediaTypeHelper(mediaType): """ Return a function that creates a Responses object; """ def _innerHelper(data=None): """ Create a Responses object that contains a MediaType entry of the specified mediaType Convenience function for the most common cases where you need an insta...
python
def mediaTypeHelper(mediaType): """ Return a function that creates a Responses object; """ def _innerHelper(data=None): """ Create a Responses object that contains a MediaType entry of the specified mediaType Convenience function for the most common cases where you need an insta...
[ "def", "mediaTypeHelper", "(", "mediaType", ")", ":", "def", "_innerHelper", "(", "data", "=", "None", ")", ":", "\"\"\"\n Create a Responses object that contains a MediaType entry of the specified mediaType\n\n Convenience function for the most common cases where you need ...
Return a function that creates a Responses object;
[ "Return", "a", "function", "that", "creates", "a", "Responses", "object", ";" ]
train
https://github.com/corydodt/Crosscap/blob/388a2ec36b8aa85e8f1ed692bb6e43474ba76c8e/crosscap/openapi.py#L196-L211
etcher-be/elib_config
elib_config/_file/_config_file.py
_ensure_config_file_exists
def _ensure_config_file_exists(): """ Makes sure the config file exists. :raises: :class:`epab.core.new_config.exc.ConfigFileNotFoundError` """ config_file = Path(ELIBConfig.config_file_path).absolute() if not config_file.exists(): raise ConfigFileNotFoundError(ELIBConfig.config_file_pa...
python
def _ensure_config_file_exists(): """ Makes sure the config file exists. :raises: :class:`epab.core.new_config.exc.ConfigFileNotFoundError` """ config_file = Path(ELIBConfig.config_file_path).absolute() if not config_file.exists(): raise ConfigFileNotFoundError(ELIBConfig.config_file_pa...
[ "def", "_ensure_config_file_exists", "(", ")", ":", "config_file", "=", "Path", "(", "ELIBConfig", ".", "config_file_path", ")", ".", "absolute", "(", ")", "if", "not", "config_file", ".", "exists", "(", ")", ":", "raise", "ConfigFileNotFoundError", "(", "ELIB...
Makes sure the config file exists. :raises: :class:`epab.core.new_config.exc.ConfigFileNotFoundError`
[ "Makes", "sure", "the", "config", "file", "exists", "." ]
train
https://github.com/etcher-be/elib_config/blob/5d8c839e84d70126620ab0186dc1f717e5868bd0/elib_config/_file/_config_file.py#L21-L29
jenanwise/codequality
codequality/main.py
CodeQuality._relevant_checkers
def _relevant_checkers(self, path): """ Get set of checkers for the given path. TODO: currently this is based off the file extension. We would like to honor magic bits as well, so that python binaries, shell scripts, etc but we're not guaranteed that `path` currently exists on ...
python
def _relevant_checkers(self, path): """ Get set of checkers for the given path. TODO: currently this is based off the file extension. We would like to honor magic bits as well, so that python binaries, shell scripts, etc but we're not guaranteed that `path` currently exists on ...
[ "def", "_relevant_checkers", "(", "self", ",", "path", ")", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "ext", "=", "ext", ".", "lstrip", "(", "'.'", ")", "return", "checkers", ".", "checkers", ".", "get", "(", ...
Get set of checkers for the given path. TODO: currently this is based off the file extension. We would like to honor magic bits as well, so that python binaries, shell scripts, etc but we're not guaranteed that `path` currently exists on the filesystem -- e.g. when version control for ...
[ "Get", "set", "of", "checkers", "for", "the", "given", "path", "." ]
train
https://github.com/jenanwise/codequality/blob/8a2bd767fd73091c49a5318fdbfb2b4fff77533d/codequality/main.py#L139-L150
jenanwise/codequality
codequality/main.py
CodeQuality._resolve_paths
def _resolve_paths(self, *paths): """ Resolve paths into a set of filenames (no directories) to check. External tools will handle directories as arguments differently, so for consistency we just want to pass them filenames. This method will recursively walk all directories and ...
python
def _resolve_paths(self, *paths): """ Resolve paths into a set of filenames (no directories) to check. External tools will handle directories as arguments differently, so for consistency we just want to pass them filenames. This method will recursively walk all directories and ...
[ "def", "_resolve_paths", "(", "self", ",", "*", "paths", ")", ":", "result", "=", "set", "(", ")", "for", "path", "in", "paths", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "for", "dirpath", ",", "_", ",", "filenames", "in"...
Resolve paths into a set of filenames (no directories) to check. External tools will handle directories as arguments differently, so for consistency we just want to pass them filenames. This method will recursively walk all directories and filter out any paths that match self.options.i...
[ "Resolve", "paths", "into", "a", "set", "of", "filenames", "(", "no", "directories", ")", "to", "check", "." ]
train
https://github.com/jenanwise/codequality/blob/8a2bd767fd73091c49a5318fdbfb2b4fff77533d/codequality/main.py#L152-L174
jenanwise/codequality
codequality/main.py
CodeQuality._list_checkers
def _list_checkers(self): """ Print information about checkers and their external tools. Currently only works properly on systems with the `which` tool available. """ classes = set() for checker_group in checkers.checkers.itervalues(): for checker in ...
python
def _list_checkers(self): """ Print information about checkers and their external tools. Currently only works properly on systems with the `which` tool available. """ classes = set() for checker_group in checkers.checkers.itervalues(): for checker in ...
[ "def", "_list_checkers", "(", "self", ")", ":", "classes", "=", "set", "(", ")", "for", "checker_group", "in", "checkers", ".", "checkers", ".", "itervalues", "(", ")", ":", "for", "checker", "in", "checker_group", ":", "classes", ".", "add", "(", "check...
Print information about checkers and their external tools. Currently only works properly on systems with the `which` tool available.
[ "Print", "information", "about", "checkers", "and", "their", "external", "tools", "." ]
train
https://github.com/jenanwise/codequality/blob/8a2bd767fd73091c49a5318fdbfb2b4fff77533d/codequality/main.py#L176-L201
jenanwise/codequality
codequality/main.py
CodeQuality._should_ignore
def _should_ignore(self, path): """ Return True iff path should be ignored. """ for ignore in self.options.ignores: if fnmatch.fnmatch(path, ignore): return True return False
python
def _should_ignore(self, path): """ Return True iff path should be ignored. """ for ignore in self.options.ignores: if fnmatch.fnmatch(path, ignore): return True return False
[ "def", "_should_ignore", "(", "self", ",", "path", ")", ":", "for", "ignore", "in", "self", ".", "options", ".", "ignores", ":", "if", "fnmatch", ".", "fnmatch", "(", "path", ",", "ignore", ")", ":", "return", "True", "return", "False" ]
Return True iff path should be ignored.
[ "Return", "True", "iff", "path", "should", "be", "ignored", "." ]
train
https://github.com/jenanwise/codequality/blob/8a2bd767fd73091c49a5318fdbfb2b4fff77533d/codequality/main.py#L203-L210
knagra/farnsworth
legacy/views.py
legacy_notes_view
def legacy_notes_view(request): """ View to see legacy notes. """ notes = TeacherNote.objects.all() note_count = notes.count() paginator = Paginator(notes, 100) page = request.GET.get('page') try: notes = paginator.page(page) except PageNotAnInteger: notes = paginato...
python
def legacy_notes_view(request): """ View to see legacy notes. """ notes = TeacherNote.objects.all() note_count = notes.count() paginator = Paginator(notes, 100) page = request.GET.get('page') try: notes = paginator.page(page) except PageNotAnInteger: notes = paginato...
[ "def", "legacy_notes_view", "(", "request", ")", ":", "notes", "=", "TeacherNote", ".", "objects", ".", "all", "(", ")", "note_count", "=", "notes", ".", "count", "(", ")", "paginator", "=", "Paginator", "(", "notes", ",", "100", ")", "page", "=", "req...
View to see legacy notes.
[ "View", "to", "see", "legacy", "notes", "." ]
train
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/legacy/views.py#L69-L90
knagra/farnsworth
legacy/views.py
legacy_events_view
def legacy_events_view(request): """ View to see legacy events. """ events = TeacherEvent.objects.all() event_count = events.count() paginator = Paginator(events, 100) page = request.GET.get('page') try: events = paginator.page(page) except PageNotAnInteger: events =...
python
def legacy_events_view(request): """ View to see legacy events. """ events = TeacherEvent.objects.all() event_count = events.count() paginator = Paginator(events, 100) page = request.GET.get('page') try: events = paginator.page(page) except PageNotAnInteger: events =...
[ "def", "legacy_events_view", "(", "request", ")", ":", "events", "=", "TeacherEvent", ".", "objects", ".", "all", "(", ")", "event_count", "=", "events", ".", "count", "(", ")", "paginator", "=", "Paginator", "(", "events", ",", "100", ")", "page", "=", ...
View to see legacy events.
[ "View", "to", "see", "legacy", "events", "." ]
train
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/legacy/views.py#L93-L114
knagra/farnsworth
legacy/views.py
legacy_requests_view
def legacy_requests_view(request, rtype): """ View to see legacy requests of rtype request type, which should be either 'food' or 'maintenance'. """ if not rtype in ['food', 'maintenance']: raise Http404 requests_dict = [] # [(req, [req_responses]), (req2, [req2_responses]), ...] req...
python
def legacy_requests_view(request, rtype): """ View to see legacy requests of rtype request type, which should be either 'food' or 'maintenance'. """ if not rtype in ['food', 'maintenance']: raise Http404 requests_dict = [] # [(req, [req_responses]), (req2, [req2_responses]), ...] req...
[ "def", "legacy_requests_view", "(", "request", ",", "rtype", ")", ":", "if", "not", "rtype", "in", "[", "'food'", ",", "'maintenance'", "]", ":", "raise", "Http404", "requests_dict", "=", "[", "]", "# [(req, [req_responses]), (req2, [req2_responses]), ...]", "reques...
View to see legacy requests of rtype request type, which should be either 'food' or 'maintenance'.
[ "View", "to", "see", "legacy", "requests", "of", "rtype", "request", "type", "which", "should", "be", "either", "food", "or", "maintenance", "." ]
train
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/legacy/views.py#L117-L148
fstab50/metal
metal/bash_init.py
run_command_orig
def run_command_orig(cmd): """ No idea how th f to get this to work """ process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() if process.returncode == 0: os.killpg(os.getpgid(pro.pid), signal.SIGTERM) else: ...
python
def run_command_orig(cmd): """ No idea how th f to get this to work """ process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() if process.returncode == 0: os.killpg(os.getpgid(pro.pid), signal.SIGTERM) else: ...
[ "def", "run_command_orig", "(", "cmd", ")", ":", "process", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "stdout", ",", "stder...
No idea how th f to get this to work
[ "No", "idea", "how", "th", "f", "to", "get", "this", "to", "work" ]
train
https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/bash_init.py#L12-L20
tBaxter/django-fretboard
fretboard/models.py
Topic.get_short_url
def get_short_url(self): """ Returns short version of topic url (without page number) """ return reverse('post_short_url', args=(self.forum.slug, self.slug, self.id))
python
def get_short_url(self): """ Returns short version of topic url (without page number) """ return reverse('post_short_url', args=(self.forum.slug, self.slug, self.id))
[ "def", "get_short_url", "(", "self", ")", ":", "return", "reverse", "(", "'post_short_url'", ",", "args", "=", "(", "self", ".", "forum", ".", "slug", ",", "self", ".", "slug", ",", "self", ".", "id", ")", ")" ]
Returns short version of topic url (without page number)
[ "Returns", "short", "version", "of", "topic", "url", "(", "without", "page", "number", ")" ]
train
https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/models.py#L135-L137
tBaxter/django-fretboard
fretboard/models.py
Topic.page_count
def page_count(self): """ Get count of total pages """ postcount = self.post_set.count() max_pages = (postcount / get_paginate_by()) if postcount % get_paginate_by() != 0: max_pages += 1 return max_pages
python
def page_count(self): """ Get count of total pages """ postcount = self.post_set.count() max_pages = (postcount / get_paginate_by()) if postcount % get_paginate_by() != 0: max_pages += 1 return max_pages
[ "def", "page_count", "(", "self", ")", ":", "postcount", "=", "self", ".", "post_set", ".", "count", "(", ")", "max_pages", "=", "(", "postcount", "/", "get_paginate_by", "(", ")", ")", "if", "postcount", "%", "get_paginate_by", "(", ")", "!=", "0", ":...
Get count of total pages
[ "Get", "count", "of", "total", "pages" ]
train
https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/models.py#L167-L175
tBaxter/django-fretboard
fretboard/models.py
Topic.get_image
def get_image(self): """ Gets first image from post set. """ posts_with_images = self.post_set.filter(image__gt='') if posts_with_images: return posts_with_images[0].image
python
def get_image(self): """ Gets first image from post set. """ posts_with_images = self.post_set.filter(image__gt='') if posts_with_images: return posts_with_images[0].image
[ "def", "get_image", "(", "self", ")", ":", "posts_with_images", "=", "self", ".", "post_set", ".", "filter", "(", "image__gt", "=", "''", ")", "if", "posts_with_images", ":", "return", "posts_with_images", "[", "0", "]", ".", "image" ]
Gets first image from post set.
[ "Gets", "first", "image", "from", "post", "set", "." ]
train
https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/models.py#L192-L198
tBaxter/django-fretboard
fretboard/models.py
Post.post_url
def post_url(self): """ Determine which page this post lives on within the topic and return link to anchor within that page """ topic = self.topic topic_page = topic.post_set.filter(id__lt=self.id).count() / get_paginate_by() + 1 return "{0}page{1}/#post-{2...
python
def post_url(self): """ Determine which page this post lives on within the topic and return link to anchor within that page """ topic = self.topic topic_page = topic.post_set.filter(id__lt=self.id).count() / get_paginate_by() + 1 return "{0}page{1}/#post-{2...
[ "def", "post_url", "(", "self", ")", ":", "topic", "=", "self", ".", "topic", "topic_page", "=", "topic", ".", "post_set", ".", "filter", "(", "id__lt", "=", "self", ".", "id", ")", ".", "count", "(", ")", "/", "get_paginate_by", "(", ")", "+", "1"...
Determine which page this post lives on within the topic and return link to anchor within that page
[ "Determine", "which", "page", "this", "post", "lives", "on", "within", "the", "topic", "and", "return", "link", "to", "anchor", "within", "that", "page" ]
train
https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/models.py#L232-L239
laysakura/relshell
relshell/record.py
Record.next
def next(self): """Return a column one by one :raises: StopIteration """ if self._cur_col >= len(self._rec): self._cur_col = 0 raise StopIteration col = self._rec[self._cur_col] self._cur_col += 1 return col
python
def next(self): """Return a column one by one :raises: StopIteration """ if self._cur_col >= len(self._rec): self._cur_col = 0 raise StopIteration col = self._rec[self._cur_col] self._cur_col += 1 return col
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "_cur_col", ">=", "len", "(", "self", ".", "_rec", ")", ":", "self", ".", "_cur_col", "=", "0", "raise", "StopIteration", "col", "=", "self", ".", "_rec", "[", "self", ".", "_cur_col", "]", ...
Return a column one by one :raises: StopIteration
[ "Return", "a", "column", "one", "by", "one" ]
train
https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/record.py#L42-L52
laysakura/relshell
relshell/record.py
Record._chk_type
def _chk_type(recdef, rec): """Checks if type of `rec` matches `recdef` :param recdef: instance of RecordDef :param rec: instance of Record :raises: `TypeError` """ if len(recdef) != len(rec): raise TypeError("Number of columns (%d) is different from ...
python
def _chk_type(recdef, rec): """Checks if type of `rec` matches `recdef` :param recdef: instance of RecordDef :param rec: instance of Record :raises: `TypeError` """ if len(recdef) != len(rec): raise TypeError("Number of columns (%d) is different from ...
[ "def", "_chk_type", "(", "recdef", ",", "rec", ")", ":", "if", "len", "(", "recdef", ")", "!=", "len", "(", "rec", ")", ":", "raise", "TypeError", "(", "\"Number of columns (%d) is different from RecordDef (%d)\"", "%", "(", "len", "(", "rec", ")", ",", "l...
Checks if type of `rec` matches `recdef` :param recdef: instance of RecordDef :param rec: instance of Record :raises: `TypeError`
[ "Checks", "if", "type", "of", "rec", "matches", "recdef", ":", "param", "recdef", ":", "instance", "of", "RecordDef", ":", "param", "rec", ":", "instance", "of", "Record", ":", "raises", ":", "TypeError" ]
train
https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/record.py#L66-L87
edeposit/edeposit.amqp.aleph
src/edeposit/amqp/aleph/datastructures/semanticinfo.py
_parse_summaryRecordSysNumber
def _parse_summaryRecordSysNumber(summaryRecordSysNumber): """ Try to parse vague, not likely machine-readable description and return first token, which contains enough numbers in it. """ def number_of_digits(token): digits = filter(lambda x: x.isdigit(), token) return len(digits) ...
python
def _parse_summaryRecordSysNumber(summaryRecordSysNumber): """ Try to parse vague, not likely machine-readable description and return first token, which contains enough numbers in it. """ def number_of_digits(token): digits = filter(lambda x: x.isdigit(), token) return len(digits) ...
[ "def", "_parse_summaryRecordSysNumber", "(", "summaryRecordSysNumber", ")", ":", "def", "number_of_digits", "(", "token", ")", ":", "digits", "=", "filter", "(", "lambda", "x", ":", "x", ".", "isdigit", "(", ")", ",", "token", ")", "return", "len", "(", "d...
Try to parse vague, not likely machine-readable description and return first token, which contains enough numbers in it.
[ "Try", "to", "parse", "vague", "not", "likely", "machine", "-", "readable", "description", "and", "return", "first", "token", "which", "contains", "enough", "numbers", "in", "it", "." ]
train
https://github.com/edeposit/edeposit.amqp.aleph/blob/360342c0504d5daa2344e864762cdf938d4149c7/src/edeposit/amqp/aleph/datastructures/semanticinfo.py#L19-L39
edeposit/edeposit.amqp.aleph
src/edeposit/amqp/aleph/datastructures/semanticinfo.py
SemanticInfo.from_xml
def from_xml(xml): """ Pick informations from :class:`.MARCXMLRecord` object and use it to build :class:`.SemanticInfo` structure. Args: xml (str/MARCXMLRecord): MarcXML which will be converted to SemanticInfo. In case of str, ``<record>`` tag is required. ...
python
def from_xml(xml): """ Pick informations from :class:`.MARCXMLRecord` object and use it to build :class:`.SemanticInfo` structure. Args: xml (str/MARCXMLRecord): MarcXML which will be converted to SemanticInfo. In case of str, ``<record>`` tag is required. ...
[ "def", "from_xml", "(", "xml", ")", ":", "hasAcquisitionFields", "=", "False", "acquisitionFields", "=", "[", "]", "ISBNAgencyFields", "=", "[", "]", "descriptiveCatFields", "=", "[", "]", "descriptiveCatReviewFields", "=", "[", "]", "subjectCatFields", "=", "["...
Pick informations from :class:`.MARCXMLRecord` object and use it to build :class:`.SemanticInfo` structure. Args: xml (str/MARCXMLRecord): MarcXML which will be converted to SemanticInfo. In case of str, ``<record>`` tag is required. Returns: structure: ...
[ "Pick", "informations", "from", ":", "class", ":", ".", "MARCXMLRecord", "object", "and", "use", "it", "to", "build", ":", "class", ":", ".", "SemanticInfo", "structure", "." ]
train
https://github.com/edeposit/edeposit.amqp.aleph/blob/360342c0504d5daa2344e864762cdf938d4149c7/src/edeposit/amqp/aleph/datastructures/semanticinfo.py#L93-L188
markmuetz/commandify
commandify/commandify.py
commandify
def commandify(use_argcomplete=False, exit=True, *args, **kwargs): '''Turns decorated functions into command line args Finds the main_command and all commands and generates command line args from these.''' parser = CommandifyArgumentParser(*args, **kwargs) parser.setup_arguments() if use_argcom...
python
def commandify(use_argcomplete=False, exit=True, *args, **kwargs): '''Turns decorated functions into command line args Finds the main_command and all commands and generates command line args from these.''' parser = CommandifyArgumentParser(*args, **kwargs) parser.setup_arguments() if use_argcom...
[ "def", "commandify", "(", "use_argcomplete", "=", "False", ",", "exit", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "parser", "=", "CommandifyArgumentParser", "(", "*", "args", ",", "*", "*", "kwargs", ")", "parser", ".", "setup_a...
Turns decorated functions into command line args Finds the main_command and all commands and generates command line args from these.
[ "Turns", "decorated", "functions", "into", "command", "line", "args" ]
train
https://github.com/markmuetz/commandify/blob/2f836caca06fbee80a43ca1ceee22376f63ec4d1/commandify/commandify.py#L245-L265
markmuetz/commandify
commandify/commandify.py
CommandifyArgumentParser._get_command_args
def _get_command_args(self, command, args): '''Work out the command arguments for a given command''' command_args = {} command_argument_names =\ command.__code__.co_varnames[:command.__code__.co_argcount] for varname in command_argument_names: if varname == 'args...
python
def _get_command_args(self, command, args): '''Work out the command arguments for a given command''' command_args = {} command_argument_names =\ command.__code__.co_varnames[:command.__code__.co_argcount] for varname in command_argument_names: if varname == 'args...
[ "def", "_get_command_args", "(", "self", ",", "command", ",", "args", ")", ":", "command_args", "=", "{", "}", "command_argument_names", "=", "command", ".", "__code__", ".", "co_varnames", "[", ":", "command", ".", "__code__", ".", "co_argcount", "]", "for"...
Work out the command arguments for a given command
[ "Work", "out", "the", "command", "arguments", "for", "a", "given", "command" ]
train
https://github.com/markmuetz/commandify/blob/2f836caca06fbee80a43ca1ceee22376f63ec4d1/commandify/commandify.py#L229-L242
b3j0f/annotation
b3j0f/annotation/call.py
types
def types(*args, **kwargs): """Quick alias for the Types Annotation with only args and kwargs parameters. :param tuple args: may contain rtype. :param dict kwargs: may contain ptypes. """ rtype = first(args) return Types(rtype=rtype, ptypes=kwargs)
python
def types(*args, **kwargs): """Quick alias for the Types Annotation with only args and kwargs parameters. :param tuple args: may contain rtype. :param dict kwargs: may contain ptypes. """ rtype = first(args) return Types(rtype=rtype, ptypes=kwargs)
[ "def", "types", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "rtype", "=", "first", "(", "args", ")", "return", "Types", "(", "rtype", "=", "rtype", ",", "ptypes", "=", "kwargs", ")" ]
Quick alias for the Types Annotation with only args and kwargs parameters. :param tuple args: may contain rtype. :param dict kwargs: may contain ptypes.
[ "Quick", "alias", "for", "the", "Types", "Annotation", "with", "only", "args", "and", "kwargs", "parameters", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/call.py#L251-L261
b3j0f/annotation
b3j0f/annotation/call.py
example_exc_handler
def example_exc_handler(tries_remaining, exception, delay): """Example exception handler; prints a warning to stderr. tries_remaining: The number of tries remaining. exception: The exception instance which was raised. """ print >> stderr, "Caught '{0}', {1} tries remaining, \ sleeping for {2} ...
python
def example_exc_handler(tries_remaining, exception, delay): """Example exception handler; prints a warning to stderr. tries_remaining: The number of tries remaining. exception: The exception instance which was raised. """ print >> stderr, "Caught '{0}', {1} tries remaining, \ sleeping for {2} ...
[ "def", "example_exc_handler", "(", "tries_remaining", ",", "exception", ",", "delay", ")", ":", "print", ">>", "stderr", ",", "\"Caught '{0}', {1} tries remaining, \\\n sleeping for {2} seconds\"", ".", "format", "(", "exception", ",", "tries_remaining", ",", "delay", ...
Example exception handler; prints a warning to stderr. tries_remaining: The number of tries remaining. exception: The exception instance which was raised.
[ "Example", "exception", "handler", ";", "prints", "a", "warning", "to", "stderr", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/call.py#L356-L364
b3j0f/annotation
b3j0f/annotation/call.py
Retries._checkretry
def _checkretry(self, mydelay, condition, tries_remaining, data): """Check if input parameters allow to retries function execution. :param float mydelay: waiting delay between two execution. :param int condition: condition to check with this condition. :param int tries_remaining: tries ...
python
def _checkretry(self, mydelay, condition, tries_remaining, data): """Check if input parameters allow to retries function execution. :param float mydelay: waiting delay between two execution. :param int condition: condition to check with this condition. :param int tries_remaining: tries ...
[ "def", "_checkretry", "(", "self", ",", "mydelay", ",", "condition", ",", "tries_remaining", ",", "data", ")", ":", "result", "=", "mydelay", "if", "self", ".", "condition", "&", "condition", "and", "tries_remaining", ">", "0", ":", "# hook data with tries_rem...
Check if input parameters allow to retries function execution. :param float mydelay: waiting delay between two execution. :param int condition: condition to check with this condition. :param int tries_remaining: tries remaining. :param data: data to hook.
[ "Check", "if", "input", "parameters", "allow", "to", "retries", "function", "execution", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/call.py#L465-L491
b3j0f/annotation
b3j0f/annotation/call.py
Memoize._getkey
def _getkey(self, args, kwargs): """Get hash key from args and kwargs. args and kwargs must be hashable. :param tuple args: called vargs. :param dict kwargs: called keywords. :return: hash(tuple(args) + tuple((key, val) for key in sorted(kwargs)). :rtype: int.""" ...
python
def _getkey(self, args, kwargs): """Get hash key from args and kwargs. args and kwargs must be hashable. :param tuple args: called vargs. :param dict kwargs: called keywords. :return: hash(tuple(args) + tuple((key, val) for key in sorted(kwargs)). :rtype: int.""" ...
[ "def", "_getkey", "(", "self", ",", "args", ",", "kwargs", ")", ":", "values", "=", "list", "(", "args", ")", "keys", "=", "sorted", "(", "list", "(", "kwargs", ")", ")", "for", "key", "in", "keys", ":", "values", ".", "append", "(", "(", "key", ...
Get hash key from args and kwargs. args and kwargs must be hashable. :param tuple args: called vargs. :param dict kwargs: called keywords. :return: hash(tuple(args) + tuple((key, val) for key in sorted(kwargs)). :rtype: int.
[ "Get", "hash", "key", "from", "args", "and", "kwargs", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/call.py#L513-L532
b3j0f/annotation
b3j0f/annotation/call.py
Memoize.getparams
def getparams(self, result): """Get result parameters. :param result: cached result. :raises: ValueError if result is not cached. :return: args and kwargs registered with input result. :rtype: tuple""" for key in self._cache: if self._cache[key][2] == result...
python
def getparams(self, result): """Get result parameters. :param result: cached result. :raises: ValueError if result is not cached. :return: args and kwargs registered with input result. :rtype: tuple""" for key in self._cache: if self._cache[key][2] == result...
[ "def", "getparams", "(", "self", ",", "result", ")", ":", "for", "key", "in", "self", ".", "_cache", ":", "if", "self", ".", "_cache", "[", "key", "]", "[", "2", "]", "==", "result", ":", "args", ",", "kwargs", ",", "_", "=", "self", ".", "_cac...
Get result parameters. :param result: cached result. :raises: ValueError if result is not cached. :return: args and kwargs registered with input result. :rtype: tuple
[ "Get", "result", "parameters", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/call.py#L555-L569
EventTeam/beliefs
src/beliefs/cells/bools.py
BoolCell.coerce
def coerce(value): """ Coerces a Bool, None, or int into Bit/Propositional form """ if isinstance(value, BoolCell): return value elif isinstance(value, Cell): raise CellConstructionFailure("Cannot convert %s to BoolCell" % \ type(value)...
python
def coerce(value): """ Coerces a Bool, None, or int into Bit/Propositional form """ if isinstance(value, BoolCell): return value elif isinstance(value, Cell): raise CellConstructionFailure("Cannot convert %s to BoolCell" % \ type(value)...
[ "def", "coerce", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "BoolCell", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "Cell", ")", ":", "raise", "CellConstructionFailure", "(", "\"Cannot convert %s to BoolCell\"", "%...
Coerces a Bool, None, or int into Bit/Propositional form
[ "Coerces", "a", "Bool", "None", "or", "int", "into", "Bit", "/", "Propositional", "form" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/bools.py#L25-L42
EventTeam/beliefs
src/beliefs/cells/bools.py
BoolCell.is_entailed_by
def is_entailed_by(self, other): """ If the other is as or more specific than self""" other = BoolCell.coerce(other) if self.value == U or other.value == self.value: return True return False
python
def is_entailed_by(self, other): """ If the other is as or more specific than self""" other = BoolCell.coerce(other) if self.value == U or other.value == self.value: return True return False
[ "def", "is_entailed_by", "(", "self", ",", "other", ")", ":", "other", "=", "BoolCell", ".", "coerce", "(", "other", ")", "if", "self", ".", "value", "==", "U", "or", "other", ".", "value", "==", "self", ".", "value", ":", "return", "True", "return",...
If the other is as or more specific than self
[ "If", "the", "other", "is", "as", "or", "more", "specific", "than", "self" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/bools.py#L44-L49
EventTeam/beliefs
src/beliefs/cells/bools.py
BoolCell.entails
def entails(self, other): """ Inverse is_entailed_by """ other = BoolCell.coerce(other) return other.is_entailed_by(self)
python
def entails(self, other): """ Inverse is_entailed_by """ other = BoolCell.coerce(other) return other.is_entailed_by(self)
[ "def", "entails", "(", "self", ",", "other", ")", ":", "other", "=", "BoolCell", ".", "coerce", "(", "other", ")", "return", "other", ".", "is_entailed_by", "(", "self", ")" ]
Inverse is_entailed_by
[ "Inverse", "is_entailed_by" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/bools.py#L51-L54
EventTeam/beliefs
src/beliefs/cells/bools.py
BoolCell.merge
def merge(self, other): """ Merges two BoolCells """ other = BoolCell.coerce(other) if self.is_equal(other): # pick among dependencies return self elif other.is_entailed_by(self): return self elif self.is_entailed_by(other): ...
python
def merge(self, other): """ Merges two BoolCells """ other = BoolCell.coerce(other) if self.is_equal(other): # pick among dependencies return self elif other.is_entailed_by(self): return self elif self.is_entailed_by(other): ...
[ "def", "merge", "(", "self", ",", "other", ")", ":", "other", "=", "BoolCell", ".", "coerce", "(", "other", ")", "if", "self", ".", "is_equal", "(", "other", ")", ":", "# pick among dependencies", "return", "self", "elif", "other", ".", "is_entailed_by", ...
Merges two BoolCells
[ "Merges", "two", "BoolCells" ]
train
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/bools.py#L82-L98
BenjaminSchubert/NitPycker
nitpycker/runner.py
ParallelRunner._makeResult
def _makeResult(self): """ instantiates the result class reporters """ return [reporter(self.stream, self.descriptions, self.verbosity) for reporter in self.resultclass]
python
def _makeResult(self): """ instantiates the result class reporters """ return [reporter(self.stream, self.descriptions, self.verbosity) for reporter in self.resultclass]
[ "def", "_makeResult", "(", "self", ")", ":", "return", "[", "reporter", "(", "self", ".", "stream", ",", "self", ".", "descriptions", ",", "self", ".", "verbosity", ")", "for", "reporter", "in", "self", ".", "resultclass", "]" ]
instantiates the result class reporters
[ "instantiates", "the", "result", "class", "reporters" ]
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/runner.py#L108-L110
BenjaminSchubert/NitPycker
nitpycker/runner.py
ParallelRunner.module_can_run_parallel
def module_can_run_parallel(test_module: unittest.TestSuite) -> bool: """ Checks if a given module of tests can be run in parallel or not :param test_module: the module to run :return: True if the module can be run on parallel, False otherwise """ for test_class in test_...
python
def module_can_run_parallel(test_module: unittest.TestSuite) -> bool: """ Checks if a given module of tests can be run in parallel or not :param test_module: the module to run :return: True if the module can be run on parallel, False otherwise """ for test_class in test_...
[ "def", "module_can_run_parallel", "(", "test_module", ":", "unittest", ".", "TestSuite", ")", "->", "bool", ":", "for", "test_class", "in", "test_module", ":", "# if the test is already failed, we just don't filter it", "# and let the test runner deal with it later.", "if", "...
Checks if a given module of tests can be run in parallel or not :param test_module: the module to run :return: True if the module can be run on parallel, False otherwise
[ "Checks", "if", "a", "given", "module", "of", "tests", "can", "be", "run", "in", "parallel", "or", "not" ]
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/runner.py#L113-L135
BenjaminSchubert/NitPycker
nitpycker/runner.py
ParallelRunner.class_can_run_parallel
def class_can_run_parallel(test_class: unittest.TestSuite) -> bool: """ Checks if a given class of tests can be run in parallel or not :param test_class: the class to run :return: True if te class can be run in parallel, False otherwise """ for test_case in test_class: ...
python
def class_can_run_parallel(test_class: unittest.TestSuite) -> bool: """ Checks if a given class of tests can be run in parallel or not :param test_class: the class to run :return: True if te class can be run in parallel, False otherwise """ for test_case in test_class: ...
[ "def", "class_can_run_parallel", "(", "test_class", ":", "unittest", ".", "TestSuite", ")", "->", "bool", ":", "for", "test_case", "in", "test_class", ":", "return", "not", "getattr", "(", "test_case", ",", "\"__no_parallel__\"", ",", "False", ")" ]
Checks if a given class of tests can be run in parallel or not :param test_class: the class to run :return: True if te class can be run in parallel, False otherwise
[ "Checks", "if", "a", "given", "class", "of", "tests", "can", "be", "run", "in", "parallel", "or", "not" ]
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/runner.py#L138-L146
BenjaminSchubert/NitPycker
nitpycker/runner.py
ParallelRunner.print_summary
def print_summary(self, result, time_taken): """ Prints the test summary, how many tests failed, how long it took, etc :param result: result class to use to print summary :param time_taken: the time all tests took to run """ if hasattr(result, "separator2"): ...
python
def print_summary(self, result, time_taken): """ Prints the test summary, how many tests failed, how long it took, etc :param result: result class to use to print summary :param time_taken: the time all tests took to run """ if hasattr(result, "separator2"): ...
[ "def", "print_summary", "(", "self", ",", "result", ",", "time_taken", ")", ":", "if", "hasattr", "(", "result", ",", "\"separator2\"", ")", ":", "self", ".", "stream", ".", "writeln", "(", "result", ".", "separator2", ")", "self", ".", "stream", ".", ...
Prints the test summary, how many tests failed, how long it took, etc :param result: result class to use to print summary :param time_taken: the time all tests took to run
[ "Prints", "the", "test", "summary", "how", "many", "tests", "failed", "how", "long", "it", "took", "etc" ]
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/runner.py#L182-L217
BenjaminSchubert/NitPycker
nitpycker/runner.py
ParallelRunner.run
def run(self, test: unittest.TestSuite): """ Given a TestSuite, will create one process per test case whenever possible and run them concurrently. Will then wait for the result and return them :param test: the TestSuite to run :return: a summary of the test run """ ...
python
def run(self, test: unittest.TestSuite): """ Given a TestSuite, will create one process per test case whenever possible and run them concurrently. Will then wait for the result and return them :param test: the TestSuite to run :return: a summary of the test run """ ...
[ "def", "run", "(", "self", ",", "test", ":", "unittest", ".", "TestSuite", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "process", "=", "[", "]", "resource_manager", "=", "multiprocessing", ".", "Manager", "(", ")", "results_queue", "=", ...
Given a TestSuite, will create one process per test case whenever possible and run them concurrently. Will then wait for the result and return them :param test: the TestSuite to run :return: a summary of the test run
[ "Given", "a", "TestSuite", "will", "create", "one", "process", "per", "test", "case", "whenever", "possible", "and", "run", "them", "concurrently", ".", "Will", "then", "wait", "for", "the", "result", "and", "return", "them" ]
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/runner.py#L219-L261
foliant-docs/foliantcontrib.init
setup.py
get_templates
def get_templates(path: Path) -> List[str]: '''List all files in ``templates`` directory, including all subdirectories. The resulting list contains UNIX-like relative paths starting with ``templates``. ''' result = [] for item in path.glob('**/*'): if item.is_file() and not item.name.star...
python
def get_templates(path: Path) -> List[str]: '''List all files in ``templates`` directory, including all subdirectories. The resulting list contains UNIX-like relative paths starting with ``templates``. ''' result = [] for item in path.glob('**/*'): if item.is_file() and not item.name.star...
[ "def", "get_templates", "(", "path", ":", "Path", ")", "->", "List", "[", "str", "]", ":", "result", "=", "[", "]", "for", "item", "in", "path", ".", "glob", "(", "'**/*'", ")", ":", "if", "item", ".", "is_file", "(", ")", "and", "not", "item", ...
List all files in ``templates`` directory, including all subdirectories. The resulting list contains UNIX-like relative paths starting with ``templates``.
[ "List", "all", "files", "in", "templates", "directory", "including", "all", "subdirectories", "." ]
train
https://github.com/foliant-docs/foliantcontrib.init/blob/39aa38949b6270a750c800b79b4e71dd827f28d8/setup.py#L14-L26
openvax/sercol
sercol/collection.py
Collection.clone_with_new_elements
def clone_with_new_elements( self, new_elements, drop_keywords=set([]), rename_dict={}, extra_kwargs={}): """ Create another Collection of the same class and with same state but possibly different entries. Extra parameters to control wh...
python
def clone_with_new_elements( self, new_elements, drop_keywords=set([]), rename_dict={}, extra_kwargs={}): """ Create another Collection of the same class and with same state but possibly different entries. Extra parameters to control wh...
[ "def", "clone_with_new_elements", "(", "self", ",", "new_elements", ",", "drop_keywords", "=", "set", "(", "[", "]", ")", ",", "rename_dict", "=", "{", "}", ",", "extra_kwargs", "=", "{", "}", ")", ":", "kwargs", "=", "dict", "(", "elements", "=", "new...
Create another Collection of the same class and with same state but possibly different entries. Extra parameters to control which keyword arguments get passed to the initializer are necessary since derived classes have different constructors than the base class.
[ "Create", "another", "Collection", "of", "the", "same", "class", "and", "with", "same", "state", "but", "possibly", "different", "entries", ".", "Extra", "parameters", "to", "control", "which", "keyword", "arguments", "get", "passed", "to", "the", "initializer",...
train
https://github.com/openvax/sercol/blob/e66a8e8c3c0b21e53eb8f73be4d23409fab311ae/sercol/collection.py#L74-L96
openvax/sercol
sercol/collection.py
Collection.source
def source(self): """ Returns the single source name for a variant collection if it is unique, otherwise raises an error. """ if len(self.sources) == 0: raise ValueError("No source associated with %s" % self.__class__.__name__) elif len(self.sources) > 1: ...
python
def source(self): """ Returns the single source name for a variant collection if it is unique, otherwise raises an error. """ if len(self.sources) == 0: raise ValueError("No source associated with %s" % self.__class__.__name__) elif len(self.sources) > 1: ...
[ "def", "source", "(", "self", ")", ":", "if", "len", "(", "self", ".", "sources", ")", "==", "0", ":", "raise", "ValueError", "(", "\"No source associated with %s\"", "%", "self", ".", "__class__", ".", "__name__", ")", "elif", "len", "(", "self", ".", ...
Returns the single source name for a variant collection if it is unique, otherwise raises an error.
[ "Returns", "the", "single", "source", "name", "for", "a", "variant", "collection", "if", "it", "is", "unique", "otherwise", "raises", "an", "error", "." ]
train
https://github.com/openvax/sercol/blob/e66a8e8c3c0b21e53eb8f73be4d23409fab311ae/sercol/collection.py#L99-L108
openvax/sercol
sercol/collection.py
Collection.filenames
def filenames(self): """ Assuming sources are paths to VCF or MAF files, trim their directory path and return just the file names. """ return [os.path.basename(source) for source in self.sources if source]
python
def filenames(self): """ Assuming sources are paths to VCF or MAF files, trim their directory path and return just the file names. """ return [os.path.basename(source) for source in self.sources if source]
[ "def", "filenames", "(", "self", ")", ":", "return", "[", "os", ".", "path", ".", "basename", "(", "source", ")", "for", "source", "in", "self", ".", "sources", "if", "source", "]" ]
Assuming sources are paths to VCF or MAF files, trim their directory path and return just the file names.
[ "Assuming", "sources", "are", "paths", "to", "VCF", "or", "MAF", "files", "trim", "their", "directory", "path", "and", "return", "just", "the", "file", "names", "." ]
train
https://github.com/openvax/sercol/blob/e66a8e8c3c0b21e53eb8f73be4d23409fab311ae/sercol/collection.py#L119-L124
openvax/sercol
sercol/collection.py
Collection.short_string
def short_string(self): """ Compact string representation which doesn't print any of the collection elements. """ source_str = "" if self.sources: source_str = " from '%s'" % ",".join(self.sources) return "<%s%s with %d elements>" % ( self....
python
def short_string(self): """ Compact string representation which doesn't print any of the collection elements. """ source_str = "" if self.sources: source_str = " from '%s'" % ",".join(self.sources) return "<%s%s with %d elements>" % ( self....
[ "def", "short_string", "(", "self", ")", ":", "source_str", "=", "\"\"", "if", "self", ".", "sources", ":", "source_str", "=", "\" from '%s'\"", "%", "\",\"", ".", "join", "(", "self", ".", "sources", ")", "return", "\"<%s%s with %d elements>\"", "%", "(", ...
Compact string representation which doesn't print any of the collection elements.
[ "Compact", "string", "representation", "which", "doesn", "t", "print", "any", "of", "the", "collection", "elements", "." ]
train
https://github.com/openvax/sercol/blob/e66a8e8c3c0b21e53eb8f73be4d23409fab311ae/sercol/collection.py#L134-L145
openvax/sercol
sercol/collection.py
Collection.groupby
def groupby(self, key_fn): """ Parameters ---------- key_fn : function Takes an effect or variant, returns a grouping key. """ result_dict = defaultdict(list) for x in self: result_dict[key_fn(x)].append(x) # convert result lists ...
python
def groupby(self, key_fn): """ Parameters ---------- key_fn : function Takes an effect or variant, returns a grouping key. """ result_dict = defaultdict(list) for x in self: result_dict[key_fn(x)].append(x) # convert result lists ...
[ "def", "groupby", "(", "self", ",", "key_fn", ")", ":", "result_dict", "=", "defaultdict", "(", "list", ")", "for", "x", "in", "self", ":", "result_dict", "[", "key_fn", "(", "x", ")", "]", ".", "append", "(", "x", ")", "# convert result lists into same ...
Parameters ---------- key_fn : function Takes an effect or variant, returns a grouping key.
[ "Parameters", "----------", "key_fn", ":", "function", "Takes", "an", "effect", "or", "variant", "returns", "a", "grouping", "key", "." ]
train
https://github.com/openvax/sercol/blob/e66a8e8c3c0b21e53eb8f73be4d23409fab311ae/sercol/collection.py#L195-L212
openvax/sercol
sercol/collection.py
Collection.multi_groupby
def multi_groupby(self, key_fn): """ Like a groupby but expect the key_fn to return multiple keys for each element. """ result_dict = defaultdict(list) for x in self: for key in key_fn(x): result_dict[key].append(x) # convert result l...
python
def multi_groupby(self, key_fn): """ Like a groupby but expect the key_fn to return multiple keys for each element. """ result_dict = defaultdict(list) for x in self: for key in key_fn(x): result_dict[key].append(x) # convert result l...
[ "def", "multi_groupby", "(", "self", ",", "key_fn", ")", ":", "result_dict", "=", "defaultdict", "(", "list", ")", "for", "x", "in", "self", ":", "for", "key", "in", "key_fn", "(", "x", ")", ":", "result_dict", "[", "key", "]", ".", "append", "(", ...
Like a groupby but expect the key_fn to return multiple keys for each element.
[ "Like", "a", "groupby", "but", "expect", "the", "key_fn", "to", "return", "multiple", "keys", "for", "each", "element", "." ]
train
https://github.com/openvax/sercol/blob/e66a8e8c3c0b21e53eb8f73be4d23409fab311ae/sercol/collection.py#L214-L230
openvax/sercol
sercol/collection.py
Collection.filter_above_threshold
def filter_above_threshold( self, key_fn, value_dict, threshold, default_value=0.0): """The code for filtering by gene or transcript expression was pretty much identical aside from which identifier you pull off an effect. So, factored o...
python
def filter_above_threshold( self, key_fn, value_dict, threshold, default_value=0.0): """The code for filtering by gene or transcript expression was pretty much identical aside from which identifier you pull off an effect. So, factored o...
[ "def", "filter_above_threshold", "(", "self", ",", "key_fn", ",", "value_dict", ",", "threshold", ",", "default_value", "=", "0.0", ")", ":", "def", "filter_fn", "(", "x", ")", ":", "key", "=", "key_fn", "(", "x", ")", "value", "=", "value_dict", ".", ...
The code for filtering by gene or transcript expression was pretty much identical aside from which identifier you pull off an effect. So, factored out the common operations for filtering an effect collection into this helper method. Parameters ---------- key_fn : callabl...
[ "The", "code", "for", "filtering", "by", "gene", "or", "transcript", "expression", "was", "pretty", "much", "identical", "aside", "from", "which", "identifier", "you", "pull", "off", "an", "effect", ".", "So", "factored", "out", "the", "common", "operations", ...
train
https://github.com/openvax/sercol/blob/e66a8e8c3c0b21e53eb8f73be4d23409fab311ae/sercol/collection.py#L232-L262
openvax/sercol
sercol/collection.py
Collection.filter_any_above_threshold
def filter_any_above_threshold( self, multi_key_fn, value_dict, threshold, default_value=0.0): """Like filter_above_threshold but `multi_key_fn` returns multiple keys and the element is kept if any of them have a value above the given t...
python
def filter_any_above_threshold( self, multi_key_fn, value_dict, threshold, default_value=0.0): """Like filter_above_threshold but `multi_key_fn` returns multiple keys and the element is kept if any of them have a value above the given t...
[ "def", "filter_any_above_threshold", "(", "self", ",", "multi_key_fn", ",", "value_dict", ",", "threshold", ",", "default_value", "=", "0.0", ")", ":", "def", "filter_fn", "(", "x", ")", ":", "for", "key", "in", "multi_key_fn", "(", "x", ")", ":", "value",...
Like filter_above_threshold but `multi_key_fn` returns multiple keys and the element is kept if any of them have a value above the given threshold. Parameters ---------- multi_key_fn : callable Given an element of this collection, returns multiple keys in...
[ "Like", "filter_above_threshold", "but", "multi_key_fn", "returns", "multiple", "keys", "and", "the", "element", "is", "kept", "if", "any", "of", "them", "have", "a", "value", "above", "the", "given", "threshold", "." ]
train
https://github.com/openvax/sercol/blob/e66a8e8c3c0b21e53eb8f73be4d23409fab311ae/sercol/collection.py#L264-L296
hapylestat/apputils
apputils/net/curl.py
curl
def curl(url, params=None, auth=None, req_type='GET', data=None, headers=None, timeout=None, use_gzip=True, use_stream=False): """ Make request to web resource :param url: Url to endpoint :param params: list of params after "?" :param auth: authorization tokens :param req_type: column_type of the request ...
python
def curl(url, params=None, auth=None, req_type='GET', data=None, headers=None, timeout=None, use_gzip=True, use_stream=False): """ Make request to web resource :param url: Url to endpoint :param params: list of params after "?" :param auth: authorization tokens :param req_type: column_type of the request ...
[ "def", "curl", "(", "url", ",", "params", "=", "None", ",", "auth", "=", "None", ",", "req_type", "=", "'GET'", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "timeout", "=", "None", ",", "use_gzip", "=", "True", ",", "use_stream", "="...
Make request to web resource :param url: Url to endpoint :param params: list of params after "?" :param auth: authorization tokens :param req_type: column_type of the request :param data: data which need to be posted :param headers: headers which would be posted with request :param timeout: Request timeo...
[ "Make", "request", "to", "web", "resource" ]
train
https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/net/curl.py#L201-L279
msuozzo/Aduro
aduro/events.py
AddEvent.from_str
def from_str(string): """Generate a `AddEvent` object from a string """ match = re.match(r'^ADD (\w+)$', string) if match: return AddEvent(match.group(1)) else: raise EventParseError
python
def from_str(string): """Generate a `AddEvent` object from a string """ match = re.match(r'^ADD (\w+)$', string) if match: return AddEvent(match.group(1)) else: raise EventParseError
[ "def", "from_str", "(", "string", ")", ":", "match", "=", "re", ".", "match", "(", "r'^ADD (\\w+)$'", ",", "string", ")", "if", "match", ":", "return", "AddEvent", "(", "match", ".", "group", "(", "1", ")", ")", "else", ":", "raise", "EventParseError" ...
Generate a `AddEvent` object from a string
[ "Generate", "a", "AddEvent", "object", "from", "a", "string" ]
train
https://github.com/msuozzo/Aduro/blob/338eeb1deeff30c198e721b660ae4daca3660911/aduro/events.py#L69-L76
msuozzo/Aduro
aduro/events.py
SetReadingEvent.from_str
def from_str(string): """Generate a `SetReadingEvent` object from a string """ match = re.match(r'^START READING (\w+) FROM \w+ (\d+)$', string) if match: return SetReadingEvent(match.group(1), int(match.group(2))) else: raise EventParseError
python
def from_str(string): """Generate a `SetReadingEvent` object from a string """ match = re.match(r'^START READING (\w+) FROM \w+ (\d+)$', string) if match: return SetReadingEvent(match.group(1), int(match.group(2))) else: raise EventParseError
[ "def", "from_str", "(", "string", ")", ":", "match", "=", "re", ".", "match", "(", "r'^START READING (\\w+) FROM \\w+ (\\d+)$'", ",", "string", ")", "if", "match", ":", "return", "SetReadingEvent", "(", "match", ".", "group", "(", "1", ")", ",", "int", "("...
Generate a `SetReadingEvent` object from a string
[ "Generate", "a", "SetReadingEvent", "object", "from", "a", "string" ]
train
https://github.com/msuozzo/Aduro/blob/338eeb1deeff30c198e721b660ae4daca3660911/aduro/events.py#L94-L101
msuozzo/Aduro
aduro/events.py
ReadEvent.from_str
def from_str(string): """Generate a `ReadEvent` object from a string """ match = re.match(r'^READ (\w+) FOR (\d+) \w+S$', string) if match: return ReadEvent(match.group(1), int(match.group(2))) else: raise EventParseError
python
def from_str(string): """Generate a `ReadEvent` object from a string """ match = re.match(r'^READ (\w+) FOR (\d+) \w+S$', string) if match: return ReadEvent(match.group(1), int(match.group(2))) else: raise EventParseError
[ "def", "from_str", "(", "string", ")", ":", "match", "=", "re", ".", "match", "(", "r'^READ (\\w+) FOR (\\d+) \\w+S$'", ",", "string", ")", "if", "match", ":", "return", "ReadEvent", "(", "match", ".", "group", "(", "1", ")", ",", "int", "(", "match", ...
Generate a `ReadEvent` object from a string
[ "Generate", "a", "ReadEvent", "object", "from", "a", "string" ]
train
https://github.com/msuozzo/Aduro/blob/338eeb1deeff30c198e721b660ae4daca3660911/aduro/events.py#L121-L128
msuozzo/Aduro
aduro/events.py
SetFinishedEvent.from_str
def from_str(string): """Generate a `SetFinishedEvent` object from a string """ match = re.match(r'^FINISH READING (\w+)$', string) if match: return SetFinishedEvent(match.group(1)) else: raise EventParseError
python
def from_str(string): """Generate a `SetFinishedEvent` object from a string """ match = re.match(r'^FINISH READING (\w+)$', string) if match: return SetFinishedEvent(match.group(1)) else: raise EventParseError
[ "def", "from_str", "(", "string", ")", ":", "match", "=", "re", ".", "match", "(", "r'^FINISH READING (\\w+)$'", ",", "string", ")", "if", "match", ":", "return", "SetFinishedEvent", "(", "match", ".", "group", "(", "1", ")", ")", "else", ":", "raise", ...
Generate a `SetFinishedEvent` object from a string
[ "Generate", "a", "SetFinishedEvent", "object", "from", "a", "string" ]
train
https://github.com/msuozzo/Aduro/blob/338eeb1deeff30c198e721b660ae4daca3660911/aduro/events.py#L144-L151
msuozzo/Aduro
aduro/events.py
UpdateEvent.from_str
def from_str(string): """Generate a `SetFinishedEvent` object from a string """ match = re.match(r'^UPDATE (.+)$', string) if match: parsed_date = dateutil.parser.parse(match.group(1), ignoretz=True) return UpdateEvent(parsed_date) else: raise ...
python
def from_str(string): """Generate a `SetFinishedEvent` object from a string """ match = re.match(r'^UPDATE (.+)$', string) if match: parsed_date = dateutil.parser.parse(match.group(1), ignoretz=True) return UpdateEvent(parsed_date) else: raise ...
[ "def", "from_str", "(", "string", ")", ":", "match", "=", "re", ".", "match", "(", "r'^UPDATE (.+)$'", ",", "string", ")", "if", "match", ":", "parsed_date", "=", "dateutil", ".", "parser", ".", "parse", "(", "match", ".", "group", "(", "1", ")", ","...
Generate a `SetFinishedEvent` object from a string
[ "Generate", "a", "SetFinishedEvent", "object", "from", "a", "string" ]
train
https://github.com/msuozzo/Aduro/blob/338eeb1deeff30c198e721b660ae4daca3660911/aduro/events.py#L165-L173
abe-winter/pg13-py
pg13/table.py
expand_row
def expand_row(table_fields,fields,values): "helper for insert. turn (field_names, values) into the full-width, properly-ordered row" table_fieldnames=[f.name for f in table_fields] reverse_indexes={table_fieldnames.index(f):i for i,f in enumerate(fields)} indexes=[reverse_indexes.get(i) for i in range(len(tabl...
python
def expand_row(table_fields,fields,values): "helper for insert. turn (field_names, values) into the full-width, properly-ordered row" table_fieldnames=[f.name for f in table_fields] reverse_indexes={table_fieldnames.index(f):i for i,f in enumerate(fields)} indexes=[reverse_indexes.get(i) for i in range(len(tabl...
[ "def", "expand_row", "(", "table_fields", ",", "fields", ",", "values", ")", ":", "table_fieldnames", "=", "[", "f", ".", "name", "for", "f", "in", "table_fields", "]", "reverse_indexes", "=", "{", "table_fieldnames", ".", "index", "(", "f", ")", ":", "i...
helper for insert. turn (field_names, values) into the full-width, properly-ordered row
[ "helper", "for", "insert", ".", "turn", "(", "field_names", "values", ")", "into", "the", "full", "-", "width", "properly", "-", "ordered", "row" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/table.py#L13-L18
abe-winter/pg13-py
pg13/table.py
emergency_cast
def emergency_cast(colx, value): """ugly: this is a huge hack. get serious about where this belongs in the architecture. For now, most types rely on being fed in as SubbedLiteral. """ if colx.coltp.type.lower()=='boolean': if isinstance(value,sqparse2.NameX): value = value.name if isinstance(value,bool)...
python
def emergency_cast(colx, value): """ugly: this is a huge hack. get serious about where this belongs in the architecture. For now, most types rely on being fed in as SubbedLiteral. """ if colx.coltp.type.lower()=='boolean': if isinstance(value,sqparse2.NameX): value = value.name if isinstance(value,bool)...
[ "def", "emergency_cast", "(", "colx", ",", "value", ")", ":", "if", "colx", ".", "coltp", ".", "type", ".", "lower", "(", ")", "==", "'boolean'", ":", "if", "isinstance", "(", "value", ",", "sqparse2", ".", "NameX", ")", ":", "value", "=", "value", ...
ugly: this is a huge hack. get serious about where this belongs in the architecture. For now, most types rely on being fed in as SubbedLiteral.
[ "ugly", ":", "this", "is", "a", "huge", "hack", ".", "get", "serious", "about", "where", "this", "belongs", "in", "the", "architecture", ".", "For", "now", "most", "types", "rely", "on", "being", "fed", "in", "as", "SubbedLiteral", "." ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/table.py#L20-L29
abe-winter/pg13-py
pg13/table.py
field_default
def field_default(colx, table_name, tables_dict): "takes sqparse2.ColX, Table" if colx.coltp.type.lower() == 'serial': x = sqparse2.parse('select coalesce(max(%s),-1)+1 from %s' % (colx.name, table_name)) return sqex.run_select(x, tables_dict, Table)[0] elif colx.not_null: raise NotImplementedError('todo:...
python
def field_default(colx, table_name, tables_dict): "takes sqparse2.ColX, Table" if colx.coltp.type.lower() == 'serial': x = sqparse2.parse('select coalesce(max(%s),-1)+1 from %s' % (colx.name, table_name)) return sqex.run_select(x, tables_dict, Table)[0] elif colx.not_null: raise NotImplementedError('todo:...
[ "def", "field_default", "(", "colx", ",", "table_name", ",", "tables_dict", ")", ":", "if", "colx", ".", "coltp", ".", "type", ".", "lower", "(", ")", "==", "'serial'", ":", "x", "=", "sqparse2", ".", "parse", "(", "'select coalesce(max(%s),-1)+1 from %s'", ...
takes sqparse2.ColX, Table
[ "takes", "sqparse2", ".", "ColX", "Table" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/table.py#L31-L37
abe-winter/pg13-py
pg13/table.py
Table.apply_defaults
def apply_defaults(self, row, tables_dict): "apply defaults to missing cols for a row that's being inserted" return [ emergency_cast(colx, field_default(colx, self.name, tables_dict) if v is Missing else v) for colx,v in zip(self.fields,row) ]
python
def apply_defaults(self, row, tables_dict): "apply defaults to missing cols for a row that's being inserted" return [ emergency_cast(colx, field_default(colx, self.name, tables_dict) if v is Missing else v) for colx,v in zip(self.fields,row) ]
[ "def", "apply_defaults", "(", "self", ",", "row", ",", "tables_dict", ")", ":", "return", "[", "emergency_cast", "(", "colx", ",", "field_default", "(", "colx", ",", "self", ".", "name", ",", "tables_dict", ")", "if", "v", "is", "Missing", "else", "v", ...
apply defaults to missing cols for a row that's being inserted
[ "apply", "defaults", "to", "missing", "cols", "for", "a", "row", "that", "s", "being", "inserted" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/table.py#L72-L77
JHowell45/helium-cli
helium/helium_functions/convert_youtube_url.py
convert_youtube_url
def convert_youtube_url(youtube_url, no_controls, autoplay): """Use this function to convert the youtube URL. This function is used for converting the youtube URL so that it can be used correctly with Helium. It means that Helium will know the next video in the playlist. :param youtube_url: the UR...
python
def convert_youtube_url(youtube_url, no_controls, autoplay): """Use this function to convert the youtube URL. This function is used for converting the youtube URL so that it can be used correctly with Helium. It means that Helium will know the next video in the playlist. :param youtube_url: the UR...
[ "def", "convert_youtube_url", "(", "youtube_url", ",", "no_controls", ",", "autoplay", ")", ":", "for", "section", "in", "youtube_url", ".", "split", "(", "'&'", ")", ":", "if", "'list'", "in", "section", ":", "playlist_id", "=", "section", ".", "split", "...
Use this function to convert the youtube URL. This function is used for converting the youtube URL so that it can be used correctly with Helium. It means that Helium will know the next video in the playlist. :param youtube_url: the URL of the youtube playlist video. :type youtube_url: str :par...
[ "Use", "this", "function", "to", "convert", "the", "youtube", "URL", "." ]
train
https://github.com/JHowell45/helium-cli/blob/8decc2f410a17314440eeed411a4b19dd4b4e780/helium/helium_functions/convert_youtube_url.py#L9-L37
thomasvandoren/bugzscout-py
bugzscout/client.py
BugzScout.submit_error
def submit_error(self, description, extra=None, default_message=None): """Send an error to bugzscout. Sends a request to the fogbugz URL for this instance. If a case exists with the **same** description, a new occurrence will be added to that case. It is advisable to remove personal inf...
python
def submit_error(self, description, extra=None, default_message=None): """Send an error to bugzscout. Sends a request to the fogbugz URL for this instance. If a case exists with the **same** description, a new occurrence will be added to that case. It is advisable to remove personal inf...
[ "def", "submit_error", "(", "self", ",", "description", ",", "extra", "=", "None", ",", "default_message", "=", "None", ")", ":", "req_data", "=", "{", "'ScoutUserName'", ":", "self", ".", "user", ",", "'ScoutProject'", ":", "self", ".", "project", ",", ...
Send an error to bugzscout. Sends a request to the fogbugz URL for this instance. If a case exists with the **same** description, a new occurrence will be added to that case. It is advisable to remove personal info from the description for that reason. Account ids, emails, request ids, ...
[ "Send", "an", "error", "to", "bugzscout", "." ]
train
https://github.com/thomasvandoren/bugzscout-py/blob/514528e958a97e0e7b36870037c5c69661511824/bugzscout/client.py#L43-L88
ajk8/microcache
microcache/__init__.py
init_logging
def init_logging(stream=sys.stderr, filepath=None, format='%(asctime).19s [%(levelname)s] %(name)s: %(message)s'): """ Setup logging for the microcache module, but only do it once! :param stream: stream to log to (defaults to sys.stderr) :param filepath: path to a file to log to as wel...
python
def init_logging(stream=sys.stderr, filepath=None, format='%(asctime).19s [%(levelname)s] %(name)s: %(message)s'): """ Setup logging for the microcache module, but only do it once! :param stream: stream to log to (defaults to sys.stderr) :param filepath: path to a file to log to as wel...
[ "def", "init_logging", "(", "stream", "=", "sys", ".", "stderr", ",", "filepath", "=", "None", ",", "format", "=", "'%(asctime).19s [%(levelname)s] %(name)s: %(message)s'", ")", ":", "if", "not", "(", "len", "(", "logger", ".", "handlers", ")", "==", "1", "a...
Setup logging for the microcache module, but only do it once! :param stream: stream to log to (defaults to sys.stderr) :param filepath: path to a file to log to as well (defaults to None) :param format: override the default format with whatever you like
[ "Setup", "logging", "for", "the", "microcache", "module", "but", "only", "do", "it", "once!" ]
train
https://github.com/ajk8/microcache/blob/24876c2c5f8959a806e2701adb7efbf70a87a1ae/microcache/__init__.py#L50-L71
ajk8/microcache
microcache/__init__.py
this
def this(func, cache_obj=CACHE_OBJ, key=None, ttl=None, *args, **kwargs): """ Store the output from the decorated function in the cache and pull it from the cache on future invocations without rerunning. Normally, the value will be stored under a key which takes into account all of the parameters t...
python
def this(func, cache_obj=CACHE_OBJ, key=None, ttl=None, *args, **kwargs): """ Store the output from the decorated function in the cache and pull it from the cache on future invocations without rerunning. Normally, the value will be stored under a key which takes into account all of the parameters t...
[ "def", "this", "(", "func", ",", "cache_obj", "=", "CACHE_OBJ", ",", "key", "=", "None", ",", "ttl", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "key", "=", "key", "or", "(", "func", ".", "__name__", "+", "str", "(", "args...
Store the output from the decorated function in the cache and pull it from the cache on future invocations without rerunning. Normally, the value will be stored under a key which takes into account all of the parameters that are passed into it, thereby caching different invocations separately. If you s...
[ "Store", "the", "output", "from", "the", "decorated", "function", "in", "the", "cache", "and", "pull", "it", "from", "the", "cache", "on", "future", "invocations", "without", "rerunning", "." ]
train
https://github.com/ajk8/microcache/blob/24876c2c5f8959a806e2701adb7efbf70a87a1ae/microcache/__init__.py#L354-L383
ajk8/microcache
microcache/__init__.py
Microcache.has
def has(self, key): """ See if a key is in the cache Returns CACHE_DISABLED if the cache is disabled :param key: key to search for """ if not self.options.enabled: return CACHE_DISABLED ret = key in self._dict.keys() and not self._dict[key].is_expire...
python
def has(self, key): """ See if a key is in the cache Returns CACHE_DISABLED if the cache is disabled :param key: key to search for """ if not self.options.enabled: return CACHE_DISABLED ret = key in self._dict.keys() and not self._dict[key].is_expire...
[ "def", "has", "(", "self", ",", "key", ")", ":", "if", "not", "self", ".", "options", ".", "enabled", ":", "return", "CACHE_DISABLED", "ret", "=", "key", "in", "self", ".", "_dict", ".", "keys", "(", ")", "and", "not", "self", ".", "_dict", "[", ...
See if a key is in the cache Returns CACHE_DISABLED if the cache is disabled :param key: key to search for
[ "See", "if", "a", "key", "is", "in", "the", "cache" ]
train
https://github.com/ajk8/microcache/blob/24876c2c5f8959a806e2701adb7efbf70a87a1ae/microcache/__init__.py#L127-L139
ajk8/microcache
microcache/__init__.py
Microcache.upsert
def upsert(self, key, value, ttl=None): """ Perform an upsert on the cache Returns CACHE_DISABLED if the cache is disabled Returns True on successful operation :param key: key to store the value under :param value: value to cache :param ttl: optional expiry in s...
python
def upsert(self, key, value, ttl=None): """ Perform an upsert on the cache Returns CACHE_DISABLED if the cache is disabled Returns True on successful operation :param key: key to store the value under :param value: value to cache :param ttl: optional expiry in s...
[ "def", "upsert", "(", "self", ",", "key", ",", "value", ",", "ttl", "=", "None", ")", ":", "if", "not", "self", ".", "options", ".", "enabled", ":", "return", "CACHE_DISABLED", "logger", ".", "debug", "(", "'upsert({}, {}, ttl={})'", ".", "format", "(", ...
Perform an upsert on the cache Returns CACHE_DISABLED if the cache is disabled Returns True on successful operation :param key: key to store the value under :param value: value to cache :param ttl: optional expiry in seconds (defaults to None)
[ "Perform", "an", "upsert", "on", "the", "cache" ]
train
https://github.com/ajk8/microcache/blob/24876c2c5f8959a806e2701adb7efbf70a87a1ae/microcache/__init__.py#L141-L156
ajk8/microcache
microcache/__init__.py
Microcache.get
def get(self, key, default=CACHE_MISS): """ Get a value out of the cache Returns CACHE_DISABLED if the cache is disabled :param key: key to search for :param default: value to return if the key is not found (defaults to CACHE_MISS) """ if not self.options.enable...
python
def get(self, key, default=CACHE_MISS): """ Get a value out of the cache Returns CACHE_DISABLED if the cache is disabled :param key: key to search for :param default: value to return if the key is not found (defaults to CACHE_MISS) """ if not self.options.enable...
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "CACHE_MISS", ")", ":", "if", "not", "self", ".", "options", ".", "enabled", ":", "return", "CACHE_DISABLED", "ret", "=", "default", "if", "self", ".", "has", "(", "key", ")", ":", "ret", ...
Get a value out of the cache Returns CACHE_DISABLED if the cache is disabled :param key: key to search for :param default: value to return if the key is not found (defaults to CACHE_MISS)
[ "Get", "a", "value", "out", "of", "the", "cache" ]
train
https://github.com/ajk8/microcache/blob/24876c2c5f8959a806e2701adb7efbf70a87a1ae/microcache/__init__.py#L158-L173
ajk8/microcache
microcache/__init__.py
Microcache.clear
def clear(self, key=None): """ Clear a cache entry, or the entire cache if no key is given Returns CACHE_DISABLED if the cache is disabled Returns True on successful operation :param key: optional key to limit the clear operation to (defaults to None) """ if not...
python
def clear(self, key=None): """ Clear a cache entry, or the entire cache if no key is given Returns CACHE_DISABLED if the cache is disabled Returns True on successful operation :param key: optional key to limit the clear operation to (defaults to None) """ if not...
[ "def", "clear", "(", "self", ",", "key", "=", "None", ")", ":", "if", "not", "self", ".", "options", ".", "enabled", ":", "return", "CACHE_DISABLED", "logger", ".", "debug", "(", "'clear(key={})'", ".", "format", "(", "repr", "(", "key", ")", ")", ")...
Clear a cache entry, or the entire cache if no key is given Returns CACHE_DISABLED if the cache is disabled Returns True on successful operation :param key: optional key to limit the clear operation to (defaults to None)
[ "Clear", "a", "cache", "entry", "or", "the", "entire", "cache", "if", "no", "key", "is", "given" ]
train
https://github.com/ajk8/microcache/blob/24876c2c5f8959a806e2701adb7efbf70a87a1ae/microcache/__init__.py#L175-L194
ajk8/microcache
microcache/__init__.py
Microcache.disable
def disable(self, clear_cache=True): """ Disable the cache and clear its contents :param clear_cache: clear the cache contents as well as disabling (defaults to True) """ logger.debug('disable(clear_cache={})'.format(clear_cache)) if clear_cache: self.clear()...
python
def disable(self, clear_cache=True): """ Disable the cache and clear its contents :param clear_cache: clear the cache contents as well as disabling (defaults to True) """ logger.debug('disable(clear_cache={})'.format(clear_cache)) if clear_cache: self.clear()...
[ "def", "disable", "(", "self", ",", "clear_cache", "=", "True", ")", ":", "logger", ".", "debug", "(", "'disable(clear_cache={})'", ".", "format", "(", "clear_cache", ")", ")", "if", "clear_cache", ":", "self", ".", "clear", "(", ")", "self", ".", "optio...
Disable the cache and clear its contents :param clear_cache: clear the cache contents as well as disabling (defaults to True)
[ "Disable", "the", "cache", "and", "clear", "its", "contents" ]
train
https://github.com/ajk8/microcache/blob/24876c2c5f8959a806e2701adb7efbf70a87a1ae/microcache/__init__.py#L196-L206
ajk8/microcache
microcache/__init__.py
Microcache.enable
def enable(self): """ (Re)enable the cache """ logger.debug('enable()') self.options.enabled = True logger.info('cache enabled')
python
def enable(self): """ (Re)enable the cache """ logger.debug('enable()') self.options.enabled = True logger.info('cache enabled')
[ "def", "enable", "(", "self", ")", ":", "logger", ".", "debug", "(", "'enable()'", ")", "self", ".", "options", ".", "enabled", "=", "True", "logger", ".", "info", "(", "'cache enabled'", ")" ]
(Re)enable the cache
[ "(", "Re", ")", "enable", "the", "cache" ]
train
https://github.com/ajk8/microcache/blob/24876c2c5f8959a806e2701adb7efbf70a87a1ae/microcache/__init__.py#L208-L214
ajk8/microcache
microcache/__init__.py
Microcache.items
def items(self, path_root=None): """ Returns a list of key / value pairs of the non-expired items in the cache, optionally filtered by a root path. :param path_root: path to filter by :return: list(tuple(key, value)) """ keys = list(self._dict.keys()) keys.sort()...
python
def items(self, path_root=None): """ Returns a list of key / value pairs of the non-expired items in the cache, optionally filtered by a root path. :param path_root: path to filter by :return: list(tuple(key, value)) """ keys = list(self._dict.keys()) keys.sort()...
[ "def", "items", "(", "self", ",", "path_root", "=", "None", ")", ":", "keys", "=", "list", "(", "self", ".", "_dict", ".", "keys", "(", ")", ")", "keys", ".", "sort", "(", ")", "ret", "=", "[", "]", "for", "key", "in", "keys", ":", "# filter ou...
Returns a list of key / value pairs of the non-expired items in the cache, optionally filtered by a root path. :param path_root: path to filter by :return: list(tuple(key, value))
[ "Returns", "a", "list", "of", "key", "/", "value", "pairs", "of", "the", "non", "-", "expired", "items", "in", "the", "cache", "optionally", "filtered", "by", "a", "root", "path", "." ]
train
https://github.com/ajk8/microcache/blob/24876c2c5f8959a806e2701adb7efbf70a87a1ae/microcache/__init__.py#L216-L238
ajk8/microcache
microcache/__init__.py
Microcache.temporarily_disabled
def temporarily_disabled(self): """ Temporarily disable the cache (useful for testing) """ old_setting = self.options.enabled self.disable(clear_cache=False) try: yield finally: self.options.enabled = old_setting
python
def temporarily_disabled(self): """ Temporarily disable the cache (useful for testing) """ old_setting = self.options.enabled self.disable(clear_cache=False) try: yield finally: self.options.enabled = old_setting
[ "def", "temporarily_disabled", "(", "self", ")", ":", "old_setting", "=", "self", ".", "options", ".", "enabled", "self", ".", "disable", "(", "clear_cache", "=", "False", ")", "try", ":", "yield", "finally", ":", "self", ".", "options", ".", "enabled", ...
Temporarily disable the cache (useful for testing)
[ "Temporarily", "disable", "the", "cache", "(", "useful", "for", "testing", ")" ]
train
https://github.com/ajk8/microcache/blob/24876c2c5f8959a806e2701adb7efbf70a87a1ae/microcache/__init__.py#L241-L250
ajk8/microcache
microcache/__init__.py
Microcache.temporarily_enabled
def temporarily_enabled(self): """ Temporarily enable the cache (useful for testing) """ old_setting = self.options.enabled self.enable() try: yield finally: self.options.enabled = old_setting
python
def temporarily_enabled(self): """ Temporarily enable the cache (useful for testing) """ old_setting = self.options.enabled self.enable() try: yield finally: self.options.enabled = old_setting
[ "def", "temporarily_enabled", "(", "self", ")", ":", "old_setting", "=", "self", ".", "options", ".", "enabled", "self", ".", "enable", "(", ")", "try", ":", "yield", "finally", ":", "self", ".", "options", ".", "enabled", "=", "old_setting" ]
Temporarily enable the cache (useful for testing)
[ "Temporarily", "enable", "the", "cache", "(", "useful", "for", "testing", ")" ]
train
https://github.com/ajk8/microcache/blob/24876c2c5f8959a806e2701adb7efbf70a87a1ae/microcache/__init__.py#L253-L262
cogniteev/docido-python-sdk
docido_sdk/toolbox/collections_ext.py
chunks
def chunks(it, n): """Split an iterator into chunks with `n` elements each. Examples # n == 2 >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 2) >>> list(x) [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10]] # n == 3 >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, ...
python
def chunks(it, n): """Split an iterator into chunks with `n` elements each. Examples # n == 2 >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 2) >>> list(x) [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10]] # n == 3 >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, ...
[ "def", "chunks", "(", "it", ",", "n", ")", ":", "for", "first", "in", "it", ":", "yield", "[", "first", "]", "+", "list", "(", "itertools", ".", "islice", "(", "it", ",", "n", "-", "1", ")", ")" ]
Split an iterator into chunks with `n` elements each. Examples # n == 2 >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 2) >>> list(x) [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10]] # n == 3 >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 3) ...
[ "Split", "an", "iterator", "into", "chunks", "with", "n", "elements", "each", ".", "Examples", "#", "n", "==", "2", ">>>", "x", "=", "chunks", "(", "iter", "(", "[", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "]", ")", "2", ")", ...
train
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/collections_ext.py#L117-L130
cogniteev/docido-python-sdk
docido_sdk/toolbox/collections_ext.py
flatten_dict
def flatten_dict(d, prefix='', sep='.'): """In place dict flattening. """ def apply_and_resolve_conflicts(dest, item, prefix): for k, v in flatten_dict(item, prefix=prefix, sep=sep).items(): new_key = k i = 2 while new_key in d: new_key = '{key}{se...
python
def flatten_dict(d, prefix='', sep='.'): """In place dict flattening. """ def apply_and_resolve_conflicts(dest, item, prefix): for k, v in flatten_dict(item, prefix=prefix, sep=sep).items(): new_key = k i = 2 while new_key in d: new_key = '{key}{se...
[ "def", "flatten_dict", "(", "d", ",", "prefix", "=", "''", ",", "sep", "=", "'.'", ")", ":", "def", "apply_and_resolve_conflicts", "(", "dest", ",", "item", ",", "prefix", ")", ":", "for", "k", ",", "v", "in", "flatten_dict", "(", "item", ",", "prefi...
In place dict flattening.
[ "In", "place", "dict", "flattening", "." ]
train
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/collections_ext.py#L133-L163
relekang/rmoq
rmoq/backends.py
RmoqStorageBackend.clean_url
def clean_url(url, replacement='_'): """ Cleans the url for protocol prefix and trailing slash and replaces special characters with the given replacement. :param url: The url of the request. :param replacement: A string that is used to replace special characters. """ ...
python
def clean_url(url, replacement='_'): """ Cleans the url for protocol prefix and trailing slash and replaces special characters with the given replacement. :param url: The url of the request. :param replacement: A string that is used to replace special characters. """ ...
[ "def", "clean_url", "(", "url", ",", "replacement", "=", "'_'", ")", ":", "cleaned", "=", "re", ".", "sub", "(", "r'/$'", ",", "''", ",", "re", ".", "sub", "(", "r'https?://'", ",", "''", ",", "url", ")", ")", "for", "character", "in", "'/ _ ? & : ...
Cleans the url for protocol prefix and trailing slash and replaces special characters with the given replacement. :param url: The url of the request. :param replacement: A string that is used to replace special characters.
[ "Cleans", "the", "url", "for", "protocol", "prefix", "and", "trailing", "slash", "and", "replaces", "special", "characters", "with", "the", "given", "replacement", "." ]
train
https://github.com/relekang/rmoq/blob/61fd2a221e247b7aca87492f10c3bc3894536260/rmoq/backends.py#L42-L53
relekang/rmoq
rmoq/backends.py
FileStorageBackend.get_filename
def get_filename(self, prefix, url): """ Creates a file path on the form: current-working-directory/prefix/cleaned-url.txt :param prefix: The prefix from the .get() and .put() methods. :param url: The url of the request. :return: The created path. """ return '{}....
python
def get_filename(self, prefix, url): """ Creates a file path on the form: current-working-directory/prefix/cleaned-url.txt :param prefix: The prefix from the .get() and .put() methods. :param url: The url of the request. :return: The created path. """ return '{}....
[ "def", "get_filename", "(", "self", ",", "prefix", ",", "url", ")", ":", "return", "'{}.txt'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "prefix", ",", "self", ".", "clean_url", "(", "url", ")", ...
Creates a file path on the form: current-working-directory/prefix/cleaned-url.txt :param prefix: The prefix from the .get() and .put() methods. :param url: The url of the request. :return: The created path.
[ "Creates", "a", "file", "path", "on", "the", "form", ":", "current", "-", "working", "-", "directory", "/", "prefix", "/", "cleaned", "-", "url", ".", "txt" ]
train
https://github.com/relekang/rmoq/blob/61fd2a221e247b7aca87492f10c3bc3894536260/rmoq/backends.py#L77-L85
openpermissions/perch
perch/cli.py
create
def create(resource, previous=None, migrations_path=None): """Create an empty migration for a resource""" if migrations_path: file_path = migrate.create(resource, previous_version=previous, package=migrations_path) else: file_path = migrate.create(resource, previous_version=previous) cl...
python
def create(resource, previous=None, migrations_path=None): """Create an empty migration for a resource""" if migrations_path: file_path = migrate.create(resource, previous_version=previous, package=migrations_path) else: file_path = migrate.create(resource, previous_version=previous) cl...
[ "def", "create", "(", "resource", ",", "previous", "=", "None", ",", "migrations_path", "=", "None", ")", ":", "if", "migrations_path", ":", "file_path", "=", "migrate", ".", "create", "(", "resource", ",", "previous_version", "=", "previous", ",", "package"...
Create an empty migration for a resource
[ "Create", "an", "empty", "migration", "for", "a", "resource" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/cli.py#L38-L45
openpermissions/perch
perch/cli.py
run
def run(migrations_path=None, url=None, port=None): """Run migrations""" logger = logging.getLogger() logger.setLevel(logging.INFO) if url: url = str(url).rstrip('/') options.url_registry_db = url if port: options.db_port = int(port) if migrations_path: migrati...
python
def run(migrations_path=None, url=None, port=None): """Run migrations""" logger = logging.getLogger() logger.setLevel(logging.INFO) if url: url = str(url).rstrip('/') options.url_registry_db = url if port: options.db_port = int(port) if migrations_path: migrati...
[ "def", "run", "(", "migrations_path", "=", "None", ",", "url", "=", "None", ",", "port", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", ")", "logger", ".", "setLevel", "(", "logging", ".", "INFO", ")", "if", "url", ":", "ur...
Run migrations
[ "Run", "migrations" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/cli.py#L51-L69
OpenVolunteeringPlatform/django-ovp-search
ovp_search/signals.py
TiedModelRealtimeSignalProcessor.handle_address_save
def handle_address_save(self, sender, instance, **kwargs): """ Custom handler for address save """ objects = self.find_associated_with_address(instance) for obj in objects: self.handle_save(obj.__class__, obj)
python
def handle_address_save(self, sender, instance, **kwargs): """ Custom handler for address save """ objects = self.find_associated_with_address(instance) for obj in objects: self.handle_save(obj.__class__, obj)
[ "def", "handle_address_save", "(", "self", ",", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "objects", "=", "self", ".", "find_associated_with_address", "(", "instance", ")", "for", "obj", "in", "objects", ":", "self", ".", "handle_save", ...
Custom handler for address save
[ "Custom", "handler", "for", "address", "save" ]
train
https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/signals.py#L63-L67
OpenVolunteeringPlatform/django-ovp-search
ovp_search/signals.py
TiedModelRealtimeSignalProcessor.handle_address_delete
def handle_address_delete(self, sender, instance, **kwargs): """ Custom handler for address delete """ objects = self.find_associated_with_address(instance) # this is not called as django will delete associated project/address # triggering handle_delete for obj in objects: # pragma: no cover ...
python
def handle_address_delete(self, sender, instance, **kwargs): """ Custom handler for address delete """ objects = self.find_associated_with_address(instance) # this is not called as django will delete associated project/address # triggering handle_delete for obj in objects: # pragma: no cover ...
[ "def", "handle_address_delete", "(", "self", ",", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "objects", "=", "self", ".", "find_associated_with_address", "(", "instance", ")", "# this is not called as django will delete associated project/address", "#...
Custom handler for address delete
[ "Custom", "handler", "for", "address", "delete" ]
train
https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/signals.py#L70-L77
OpenVolunteeringPlatform/django-ovp-search
ovp_search/signals.py
TiedModelRealtimeSignalProcessor.handle_job_and_work_save
def handle_job_and_work_save(self, sender, instance, **kwargs): """ Custom handler for job and work save """ self.handle_save(instance.project.__class__, instance.project)
python
def handle_job_and_work_save(self, sender, instance, **kwargs): """ Custom handler for job and work save """ self.handle_save(instance.project.__class__, instance.project)
[ "def", "handle_job_and_work_save", "(", "self", ",", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "self", ".", "handle_save", "(", "instance", ".", "project", ".", "__class__", ",", "instance", ".", "project", ")" ]
Custom handler for job and work save
[ "Custom", "handler", "for", "job", "and", "work", "save" ]
train
https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/signals.py#L79-L81
OpenVolunteeringPlatform/django-ovp-search
ovp_search/signals.py
TiedModelRealtimeSignalProcessor.handle_job_and_work_delete
def handle_job_and_work_delete(self, sender, instance, **kwargs): """ Custom handler for job and work delete """ self.handle_delete(instance.project.__class__, instance.project)
python
def handle_job_and_work_delete(self, sender, instance, **kwargs): """ Custom handler for job and work delete """ self.handle_delete(instance.project.__class__, instance.project)
[ "def", "handle_job_and_work_delete", "(", "self", ",", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "self", ".", "handle_delete", "(", "instance", ".", "project", ".", "__class__", ",", "instance", ".", "project", ")" ]
Custom handler for job and work delete
[ "Custom", "handler", "for", "job", "and", "work", "delete" ]
train
https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/signals.py#L83-L85
OpenVolunteeringPlatform/django-ovp-search
ovp_search/signals.py
TiedModelRealtimeSignalProcessor.handle_profile_save
def handle_profile_save(self, sender, instance, **kwargs): """ Custom handler for user profile save """ self.handle_save(instance.user.__class__, instance.user)
python
def handle_profile_save(self, sender, instance, **kwargs): """ Custom handler for user profile save """ self.handle_save(instance.user.__class__, instance.user)
[ "def", "handle_profile_save", "(", "self", ",", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "self", ".", "handle_save", "(", "instance", ".", "user", ".", "__class__", ",", "instance", ".", "user", ")" ]
Custom handler for user profile save
[ "Custom", "handler", "for", "user", "profile", "save" ]
train
https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/signals.py#L87-L89
OpenVolunteeringPlatform/django-ovp-search
ovp_search/signals.py
TiedModelRealtimeSignalProcessor.handle_profile_delete
def handle_profile_delete(self, sender, instance, **kwargs): """ Custom handler for user profile delete """ try: self.handle_save(instance.user.__class__, instance.user) # we call save just as well except (get_profile_model().DoesNotExist): pass
python
def handle_profile_delete(self, sender, instance, **kwargs): """ Custom handler for user profile delete """ try: self.handle_save(instance.user.__class__, instance.user) # we call save just as well except (get_profile_model().DoesNotExist): pass
[ "def", "handle_profile_delete", "(", "self", ",", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "handle_save", "(", "instance", ".", "user", ".", "__class__", ",", "instance", ".", "user", ")", "# we call save just ...
Custom handler for user profile delete
[ "Custom", "handler", "for", "user", "profile", "delete" ]
train
https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/signals.py#L91-L96
OpenVolunteeringPlatform/django-ovp-search
ovp_search/signals.py
TiedModelRealtimeSignalProcessor.handle_m2m
def handle_m2m(self, sender, instance, **kwargs): """ Handle many to many relationships """ self.handle_save(instance.__class__, instance)
python
def handle_m2m(self, sender, instance, **kwargs): """ Handle many to many relationships """ self.handle_save(instance.__class__, instance)
[ "def", "handle_m2m", "(", "self", ",", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "self", ".", "handle_save", "(", "instance", ".", "__class__", ",", "instance", ")" ]
Handle many to many relationships
[ "Handle", "many", "to", "many", "relationships" ]
train
https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/signals.py#L98-L100
OpenVolunteeringPlatform/django-ovp-search
ovp_search/signals.py
TiedModelRealtimeSignalProcessor.handle_m2m_user
def handle_m2m_user(self, sender, instance, **kwargs): """ Handle many to many relationships for user field """ self.handle_save(instance.user.__class__, instance.user)
python
def handle_m2m_user(self, sender, instance, **kwargs): """ Handle many to many relationships for user field """ self.handle_save(instance.user.__class__, instance.user)
[ "def", "handle_m2m_user", "(", "self", ",", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "self", ".", "handle_save", "(", "instance", ".", "user", ".", "__class__", ",", "instance", ".", "user", ")" ]
Handle many to many relationships for user field
[ "Handle", "many", "to", "many", "relationships", "for", "user", "field" ]
train
https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/signals.py#L102-L104
OpenVolunteeringPlatform/django-ovp-search
ovp_search/signals.py
TiedModelRealtimeSignalProcessor.find_associated_with_address
def find_associated_with_address(self, instance): """ Returns list with projects and organizations associated with given address """ objects = [] objects += list(Project.objects.filter(address=instance)) objects += list(Organization.objects.filter(address=instance)) return objects
python
def find_associated_with_address(self, instance): """ Returns list with projects and organizations associated with given address """ objects = [] objects += list(Project.objects.filter(address=instance)) objects += list(Organization.objects.filter(address=instance)) return objects
[ "def", "find_associated_with_address", "(", "self", ",", "instance", ")", ":", "objects", "=", "[", "]", "objects", "+=", "list", "(", "Project", ".", "objects", ".", "filter", "(", "address", "=", "instance", ")", ")", "objects", "+=", "list", "(", "Org...
Returns list with projects and organizations associated with given address
[ "Returns", "list", "with", "projects", "and", "organizations", "associated", "with", "given", "address" ]
train
https://github.com/OpenVolunteeringPlatform/django-ovp-search/blob/003ceecc0a87be31fe8195f65367c52631f72b57/ovp_search/signals.py#L106-L112
cogniteev/docido-python-sdk
docido_sdk/toolbox/google_ext.py
refresh_token
def refresh_token(token, session=None): """Refresh Google OAuth token. :param OAuthToken token: the token to refresh :param requests.Session session: Optional `requests` session to use. """ session = session or HTTP_SESSION refresh_data = dict( refresh_token=token.refresh_t...
python
def refresh_token(token, session=None): """Refresh Google OAuth token. :param OAuthToken token: the token to refresh :param requests.Session session: Optional `requests` session to use. """ session = session or HTTP_SESSION refresh_data = dict( refresh_token=token.refresh_t...
[ "def", "refresh_token", "(", "token", ",", "session", "=", "None", ")", ":", "session", "=", "session", "or", "HTTP_SESSION", "refresh_data", "=", "dict", "(", "refresh_token", "=", "token", ".", "refresh_token", ",", "client_id", "=", "token", ".", "consume...
Refresh Google OAuth token. :param OAuthToken token: the token to refresh :param requests.Session session: Optional `requests` session to use.
[ "Refresh", "Google", "OAuth", "token", "." ]
train
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/google_ext.py#L22-L51
cogniteev/docido-python-sdk
docido_sdk/toolbox/google_ext.py
token_info
def token_info(token, refresh=True, refresh_cb=None, session=None): """ :param OAuthToken token :param bool refresh: whether to attempt to refresh the OAuth token if it expired. default is `True`. :param refresh_cb: If specified, a callable object which is given the new token i...
python
def token_info(token, refresh=True, refresh_cb=None, session=None): """ :param OAuthToken token :param bool refresh: whether to attempt to refresh the OAuth token if it expired. default is `True`. :param refresh_cb: If specified, a callable object which is given the new token i...
[ "def", "token_info", "(", "token", ",", "refresh", "=", "True", ",", "refresh_cb", "=", "None", ",", "session", "=", "None", ")", ":", "session", "=", "session", "or", "HTTP_SESSION", "params", "=", "dict", "(", "access_token", "=", "token", ".", "access...
:param OAuthToken token :param bool refresh: whether to attempt to refresh the OAuth token if it expired. default is `True`. :param refresh_cb: If specified, a callable object which is given the new token in parameter if it has been refreshed. :param requests.Session session: ...
[ ":", "param", "OAuthToken", "token" ]
train
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/google_ext.py#L62-L103
calvinku96/labreporthelper
labreporthelper/table.py
make_tex_table
def make_tex_table(inputlist, outputfile, close=False, fmt=None, **kwargs): """ Parse table from inputlist Args: inputlist: list List to parse outputfile: file .tex file to write fmt: dictionary key: integer colu...
python
def make_tex_table(inputlist, outputfile, close=False, fmt=None, **kwargs): """ Parse table from inputlist Args: inputlist: list List to parse outputfile: file .tex file to write fmt: dictionary key: integer colu...
[ "def", "make_tex_table", "(", "inputlist", ",", "outputfile", ",", "close", "=", "False", ",", "fmt", "=", "None", ",", "*", "*", "kwargs", ")", ":", "output_str", "=", "\"\"", "if", "fmt", "is", "None", ":", "fmt", "=", "{", "}", "for", "row", "in...
Parse table from inputlist Args: inputlist: list List to parse outputfile: file .tex file to write fmt: dictionary key: integer column index starting with 0 values: string format string. eg "{:g}" **kwar...
[ "Parse", "table", "from", "inputlist" ]
train
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/table.py#L7-L50
cogniteev/docido-python-sdk
docido_sdk/toolbox/logger_ext.py
set_root_logger_from_verbosity
def set_root_logger_from_verbosity(verbosity=0): """Configure root logger according to both application settings and verbosity level. """ kwargs = {} if verbosity == 1: kwargs.update(level=logging.INFO) elif verbosity > 1: kwargs.update(level=logging.DEBUG) set_root_logger(*...
python
def set_root_logger_from_verbosity(verbosity=0): """Configure root logger according to both application settings and verbosity level. """ kwargs = {} if verbosity == 1: kwargs.update(level=logging.INFO) elif verbosity > 1: kwargs.update(level=logging.DEBUG) set_root_logger(*...
[ "def", "set_root_logger_from_verbosity", "(", "verbosity", "=", "0", ")", ":", "kwargs", "=", "{", "}", "if", "verbosity", "==", "1", ":", "kwargs", ".", "update", "(", "level", "=", "logging", ".", "INFO", ")", "elif", "verbosity", ">", "1", ":", "kwa...
Configure root logger according to both application settings and verbosity level.
[ "Configure", "root", "logger", "according", "to", "both", "application", "settings", "and", "verbosity", "level", "." ]
train
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/logger_ext.py#L6-L16
cogniteev/docido-python-sdk
docido_sdk/toolbox/logger_ext.py
set_root_logger
def set_root_logger(config=None, **kwargs): """ :param dict config: Override application global settings. :param dict kwargs: Additional arguments given to :py:method:`logging.basicConfig` """ config = config or app_config logging_config = config.get('logging') or {} kwargs.setd...
python
def set_root_logger(config=None, **kwargs): """ :param dict config: Override application global settings. :param dict kwargs: Additional arguments given to :py:method:`logging.basicConfig` """ config = config or app_config logging_config = config.get('logging') or {} kwargs.setd...
[ "def", "set_root_logger", "(", "config", "=", "None", ",", "*", "*", "kwargs", ")", ":", "config", "=", "config", "or", "app_config", "logging_config", "=", "config", ".", "get", "(", "'logging'", ")", "or", "{", "}", "kwargs", ".", "setdefault", "(", ...
:param dict config: Override application global settings. :param dict kwargs: Additional arguments given to :py:method:`logging.basicConfig`
[ ":", "param", "dict", "config", ":", "Override", "application", "global", "settings", "." ]
train
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/logger_ext.py#L19-L31
cogniteev/docido-python-sdk
docido_sdk/toolbox/logger_ext.py
set_loggers_from_config
def set_loggers_from_config(config=None): """Set loggers configuration according to the `logging` section of Docido configuration file. :param nameddict config: overrides Docido configuration """ config = config or app_config.logging for lname, lconfig in config.get('loggers', {}).iterite...
python
def set_loggers_from_config(config=None): """Set loggers configuration according to the `logging` section of Docido configuration file. :param nameddict config: overrides Docido configuration """ config = config or app_config.logging for lname, lconfig in config.get('loggers', {}).iterite...
[ "def", "set_loggers_from_config", "(", "config", "=", "None", ")", ":", "config", "=", "config", "or", "app_config", ".", "logging", "for", "lname", ",", "lconfig", "in", "config", ".", "get", "(", "'loggers'", ",", "{", "}", ")", ".", "iteritems", "(", ...
Set loggers configuration according to the `logging` section of Docido configuration file. :param nameddict config: overrides Docido configuration
[ "Set", "loggers", "configuration", "according", "to", "the", "logging", "section", "of", "Docido", "configuration", "file", "." ]
train
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/logger_ext.py#L34-L47
Sean1708/HipPy
hippy/parser.py
Parser.data
def data(self): """Return parsed data structure.""" if self._data is None: # reset after possible parsing failure self.__init__(self.tokens) return self._parse() else: return self._data
python
def data(self): """Return parsed data structure.""" if self._data is None: # reset after possible parsing failure self.__init__(self.tokens) return self._parse() else: return self._data
[ "def", "data", "(", "self", ")", ":", "if", "self", ".", "_data", "is", "None", ":", "# reset after possible parsing failure", "self", ".", "__init__", "(", "self", ".", "tokens", ")", "return", "self", ".", "_parse", "(", ")", "else", ":", "return", "se...
Return parsed data structure.
[ "Return", "parsed", "data", "structure", "." ]
train
https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L47-L54
Sean1708/HipPy
hippy/parser.py
Parser._increment
def _increment(self, n=1): """Move forward n tokens in the stream.""" if self._cur_position >= self.num_tokens-1: self._cur_positon = self.num_tokens - 1 self._finished = True else: self._cur_position += n
python
def _increment(self, n=1): """Move forward n tokens in the stream.""" if self._cur_position >= self.num_tokens-1: self._cur_positon = self.num_tokens - 1 self._finished = True else: self._cur_position += n
[ "def", "_increment", "(", "self", ",", "n", "=", "1", ")", ":", "if", "self", ".", "_cur_position", ">=", "self", ".", "num_tokens", "-", "1", ":", "self", ".", "_cur_positon", "=", "self", ".", "num_tokens", "-", "1", "self", ".", "_finished", "=", ...
Move forward n tokens in the stream.
[ "Move", "forward", "n", "tokens", "in", "the", "stream", "." ]
train
https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L71-L77
Sean1708/HipPy
hippy/parser.py
Parser._skip_whitespace
def _skip_whitespace(self): """Increment over whitespace, counting characters.""" i = 0 while self._cur_token['type'] is TT.ws and not self._finished: self._increment() i += 1 return i
python
def _skip_whitespace(self): """Increment over whitespace, counting characters.""" i = 0 while self._cur_token['type'] is TT.ws and not self._finished: self._increment() i += 1 return i
[ "def", "_skip_whitespace", "(", "self", ")", ":", "i", "=", "0", "while", "self", ".", "_cur_token", "[", "'type'", "]", "is", "TT", ".", "ws", "and", "not", "self", ".", "_finished", ":", "self", ".", "_increment", "(", ")", "i", "+=", "1", "retur...
Increment over whitespace, counting characters.
[ "Increment", "over", "whitespace", "counting", "characters", "." ]
train
https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L79-L86
Sean1708/HipPy
hippy/parser.py
Parser._skip_newlines
def _skip_newlines(self): """Increment over newlines.""" while self._cur_token['type'] is TT.lbreak and not self._finished: self._increment()
python
def _skip_newlines(self): """Increment over newlines.""" while self._cur_token['type'] is TT.lbreak and not self._finished: self._increment()
[ "def", "_skip_newlines", "(", "self", ")", ":", "while", "self", ".", "_cur_token", "[", "'type'", "]", "is", "TT", ".", "lbreak", "and", "not", "self", ".", "_finished", ":", "self", ".", "_increment", "(", ")" ]
Increment over newlines.
[ "Increment", "over", "newlines", "." ]
train
https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L88-L91
Sean1708/HipPy
hippy/parser.py
Parser._parse
def _parse(self): """Parse the token stream into a nice dictionary data structure.""" while self._cur_token['type'] in (TT.ws, TT.lbreak): self._skip_whitespace() self._skip_newlines() self._data = self._parse_value() return self._data
python
def _parse(self): """Parse the token stream into a nice dictionary data structure.""" while self._cur_token['type'] in (TT.ws, TT.lbreak): self._skip_whitespace() self._skip_newlines() self._data = self._parse_value() return self._data
[ "def", "_parse", "(", "self", ")", ":", "while", "self", ".", "_cur_token", "[", "'type'", "]", "in", "(", "TT", ".", "ws", ",", "TT", ".", "lbreak", ")", ":", "self", ".", "_skip_whitespace", "(", ")", "self", ".", "_skip_newlines", "(", ")", "sel...
Parse the token stream into a nice dictionary data structure.
[ "Parse", "the", "token", "stream", "into", "a", "nice", "dictionary", "data", "structure", "." ]
train
https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L93-L101
Sean1708/HipPy
hippy/parser.py
Parser._parse_value
def _parse_value(self): """Parse the value of a key-value pair.""" indent = 0 while self._cur_token['type'] is TT.ws: indent = self._skip_whitespace() self._skip_newlines() if self._cur_token['type'] is TT.id: return self._parse_key(indent) el...
python
def _parse_value(self): """Parse the value of a key-value pair.""" indent = 0 while self._cur_token['type'] is TT.ws: indent = self._skip_whitespace() self._skip_newlines() if self._cur_token['type'] is TT.id: return self._parse_key(indent) el...
[ "def", "_parse_value", "(", "self", ")", ":", "indent", "=", "0", "while", "self", ".", "_cur_token", "[", "'type'", "]", "is", "TT", ".", "ws", ":", "indent", "=", "self", ".", "_skip_whitespace", "(", ")", "self", ".", "_skip_newlines", "(", ")", "...
Parse the value of a key-value pair.
[ "Parse", "the", "value", "of", "a", "key", "-", "value", "pair", "." ]
train
https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L103-L121
Sean1708/HipPy
hippy/parser.py
Parser._parse_key
def _parse_key(self, indent): """Parse a series of key-value pairs.""" data = {} new_indent = indent while not self._finished and new_indent == indent: self._skip_whitespace() cur_token = self._cur_token if cur_token['type'] is TT.id: ...
python
def _parse_key(self, indent): """Parse a series of key-value pairs.""" data = {} new_indent = indent while not self._finished and new_indent == indent: self._skip_whitespace() cur_token = self._cur_token if cur_token['type'] is TT.id: ...
[ "def", "_parse_key", "(", "self", ",", "indent", ")", ":", "data", "=", "{", "}", "new_indent", "=", "indent", "while", "not", "self", ".", "_finished", "and", "new_indent", "==", "indent", ":", "self", ".", "_skip_whitespace", "(", ")", "cur_token", "="...
Parse a series of key-value pairs.
[ "Parse", "a", "series", "of", "key", "-", "value", "pairs", "." ]
train
https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L123-L172
Sean1708/HipPy
hippy/parser.py
Parser._parse_object_list
def _parse_object_list(self): """Parse a list of data structures.""" array = [] indent = 0 while not self._finished: self._skip_newlines() if self._cur_token['type'] is TT.ws: while self._cur_token['type'] is TT.ws: indent = se...
python
def _parse_object_list(self): """Parse a list of data structures.""" array = [] indent = 0 while not self._finished: self._skip_newlines() if self._cur_token['type'] is TT.ws: while self._cur_token['type'] is TT.ws: indent = se...
[ "def", "_parse_object_list", "(", "self", ")", ":", "array", "=", "[", "]", "indent", "=", "0", "while", "not", "self", ".", "_finished", ":", "self", ".", "_skip_newlines", "(", ")", "if", "self", ".", "_cur_token", "[", "'type'", "]", "is", "TT", "...
Parse a list of data structures.
[ "Parse", "a", "list", "of", "data", "structures", "." ]
train
https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L174-L194
Sean1708/HipPy
hippy/parser.py
Parser._parse_literal_list
def _parse_literal_list(self, indent): """Parse a list of literals.""" if self._cur_token['type'] not in self._literals: raise Exception( "Parser failed, _parse_literal_list was called on non-literal" " {} on line {}.".format( repr(self._cu...
python
def _parse_literal_list(self, indent): """Parse a list of literals.""" if self._cur_token['type'] not in self._literals: raise Exception( "Parser failed, _parse_literal_list was called on non-literal" " {} on line {}.".format( repr(self._cu...
[ "def", "_parse_literal_list", "(", "self", ",", "indent", ")", ":", "if", "self", ".", "_cur_token", "[", "'type'", "]", "not", "in", "self", ".", "_literals", ":", "raise", "Exception", "(", "\"Parser failed, _parse_literal_list was called on non-literal\"", "\" {}...
Parse a list of literals.
[ "Parse", "a", "list", "of", "literals", "." ]
train
https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L196-L237