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
ironfroggy/django-better-cache
bettercache/utils.py
CachingMixin.set_cache
def set_cache(self, request, response): """ caches the response supresses and logs exceptions""" try: cache_key = self.cache_key(request) #presumably this is to deal with requests with attr functions that won't pickle if hasattr(response, 'render') and callable(respo...
python
def set_cache(self, request, response): """ caches the response supresses and logs exceptions""" try: cache_key = self.cache_key(request) #presumably this is to deal with requests with attr functions that won't pickle if hasattr(response, 'render') and callable(respo...
[ "def", "set_cache", "(", "self", ",", "request", ",", "response", ")", ":", "try", ":", "cache_key", "=", "self", ".", "cache_key", "(", "request", ")", "#presumably this is to deal with requests with attr functions that won't pickle", "if", "hasattr", "(", "response"...
caches the response supresses and logs exceptions
[ "caches", "the", "response", "supresses", "and", "logs", "exceptions" ]
train
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L111-L122
ironfroggy/django-better-cache
bettercache/utils.py
CachingMixin.get_cache
def get_cache(self, request): """ Attempts to get a response from cache, returns a tuple of the response and whether it's expired If there is no cached response return (None, None,) """ # try and get the cached GET response cache_key = self.cache_key(request) cached_...
python
def get_cache(self, request): """ Attempts to get a response from cache, returns a tuple of the response and whether it's expired If there is no cached response return (None, None,) """ # try and get the cached GET response cache_key = self.cache_key(request) cached_...
[ "def", "get_cache", "(", "self", ",", "request", ")", ":", "# try and get the cached GET response", "cache_key", "=", "self", ".", "cache_key", "(", "request", ")", "cached_response", "=", "cache", ".", "get", "(", "cache_key", ",", "None", ")", "# if it wasn't ...
Attempts to get a response from cache, returns a tuple of the response and whether it's expired If there is no cached response return (None, None,)
[ "Attempts", "to", "get", "a", "response", "from", "cache", "returns", "a", "tuple", "of", "the", "response", "and", "whether", "it", "s", "expired", "If", "there", "is", "no", "cached", "response", "return", "(", "None", "None", ")" ]
train
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L124-L140
ironfroggy/django-better-cache
bettercache/utils.py
CachingMixin.cache_key
def cache_key(self, request, method=None): """ the cache key is the absolute uri and the request method """ if method is None: method = request.method return "bettercache_page:%s:%s" %(request.build_absolute_uri(), method)
python
def cache_key(self, request, method=None): """ the cache key is the absolute uri and the request method """ if method is None: method = request.method return "bettercache_page:%s:%s" %(request.build_absolute_uri(), method)
[ "def", "cache_key", "(", "self", ",", "request", ",", "method", "=", "None", ")", ":", "if", "method", "is", "None", ":", "method", "=", "request", ".", "method", "return", "\"bettercache_page:%s:%s\"", "%", "(", "request", ".", "build_absolute_uri", "(", ...
the cache key is the absolute uri and the request method
[ "the", "cache", "key", "is", "the", "absolute", "uri", "and", "the", "request", "method" ]
train
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L142-L147
ironfroggy/django-better-cache
bettercache/utils.py
CachingMixin.send_task
def send_task(self, request, response): """send off a celery task for the current page and recache""" # TODO is this too messy? from bettercache.tasks import GeneratePage try: GeneratePage.apply_async((strip_wsgi(request),)) except: logger.error("failed t...
python
def send_task(self, request, response): """send off a celery task for the current page and recache""" # TODO is this too messy? from bettercache.tasks import GeneratePage try: GeneratePage.apply_async((strip_wsgi(request),)) except: logger.error("failed t...
[ "def", "send_task", "(", "self", ",", "request", ",", "response", ")", ":", "# TODO is this too messy?", "from", "bettercache", ".", "tasks", "import", "GeneratePage", "try", ":", "GeneratePage", ".", "apply_async", "(", "(", "strip_wsgi", "(", "request", ")", ...
send off a celery task for the current page and recache
[ "send", "off", "a", "celery", "task", "for", "the", "current", "page", "and", "recache" ]
train
https://github.com/ironfroggy/django-better-cache/blob/5350e8c646cef1c1ca74eab176f856ddd9eaf5c3/bettercache/utils.py#L149-L158
elifesciences/elife-article
elifearticle/utils.py
entity_to_unicode
def entity_to_unicode(string): """ Quick convert unicode HTML entities to unicode characters using a regular expression replacement """ # Selected character replacements that have been seen replacements = [] replacements.append((r"α", u"\u03b1")) replacements.append((r"β", u"\...
python
def entity_to_unicode(string): """ Quick convert unicode HTML entities to unicode characters using a regular expression replacement """ # Selected character replacements that have been seen replacements = [] replacements.append((r"α", u"\u03b1")) replacements.append((r"β", u"\...
[ "def", "entity_to_unicode", "(", "string", ")", ":", "# Selected character replacements that have been seen", "replacements", "=", "[", "]", "replacements", ".", "append", "(", "(", "r\"α\"", ",", "u\"\\u03b1\"", ")", ")", "replacements", ".", "append", "(", "...
Quick convert unicode HTML entities to unicode characters using a regular expression replacement
[ "Quick", "convert", "unicode", "HTML", "entities", "to", "unicode", "characters", "using", "a", "regular", "expression", "replacement" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L37-L59
elifesciences/elife-article
elifearticle/utils.py
remove_tag
def remove_tag(tag_name, string): """ Remove open and close tags - the tags themselves only - using a non-greedy angle bracket pattern match """ if not string: return string pattern = re.compile('</?' + tag_name + '.*?>') string = pattern.sub('', string) return string
python
def remove_tag(tag_name, string): """ Remove open and close tags - the tags themselves only - using a non-greedy angle bracket pattern match """ if not string: return string pattern = re.compile('</?' + tag_name + '.*?>') string = pattern.sub('', string) return string
[ "def", "remove_tag", "(", "tag_name", ",", "string", ")", ":", "if", "not", "string", ":", "return", "string", "pattern", "=", "re", ".", "compile", "(", "'</?'", "+", "tag_name", "+", "'.*?>'", ")", "string", "=", "pattern", ".", "sub", "(", "''", "...
Remove open and close tags - the tags themselves only - using a non-greedy angle bracket pattern match
[ "Remove", "open", "and", "close", "tags", "-", "the", "tags", "themselves", "only", "-", "using", "a", "non", "-", "greedy", "angle", "bracket", "pattern", "match" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L61-L70
elifesciences/elife-article
elifearticle/utils.py
replace_tags
def replace_tags(string, from_tag='i', to_tag='italic'): """ Replace tags such as <i> to <italic> <sup> and <sub> are allowed and do not need to be replaced This does not validate markup """ string = string.replace('<' + from_tag + '>', '<' + to_tag + '>') string = string.replace('</' + from...
python
def replace_tags(string, from_tag='i', to_tag='italic'): """ Replace tags such as <i> to <italic> <sup> and <sub> are allowed and do not need to be replaced This does not validate markup """ string = string.replace('<' + from_tag + '>', '<' + to_tag + '>') string = string.replace('</' + from...
[ "def", "replace_tags", "(", "string", ",", "from_tag", "=", "'i'", ",", "to_tag", "=", "'italic'", ")", ":", "string", "=", "string", ".", "replace", "(", "'<'", "+", "from_tag", "+", "'>'", ",", "'<'", "+", "to_tag", "+", "'>'", ")", "string", "=", ...
Replace tags such as <i> to <italic> <sup> and <sub> are allowed and do not need to be replaced This does not validate markup
[ "Replace", "tags", "such", "as", "<i", ">", "to", "<italic", ">", "<sup", ">", "and", "<sub", ">", "are", "allowed", "and", "do", "not", "need", "to", "be", "replaced", "This", "does", "not", "validate", "markup" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L72-L80
elifesciences/elife-article
elifearticle/utils.py
version_from_xml_filename
def version_from_xml_filename(filename): "extract the numeric version from the xml filename" try: filename_parts = filename.split(os.sep)[-1].split('-') except AttributeError: return None if len(filename_parts) == 3: try: return int(filename_parts[-1].lstrip('v').rstr...
python
def version_from_xml_filename(filename): "extract the numeric version from the xml filename" try: filename_parts = filename.split(os.sep)[-1].split('-') except AttributeError: return None if len(filename_parts) == 3: try: return int(filename_parts[-1].lstrip('v').rstr...
[ "def", "version_from_xml_filename", "(", "filename", ")", ":", "try", ":", "filename_parts", "=", "filename", ".", "split", "(", "os", ".", "sep", ")", "[", "-", "1", "]", ".", "split", "(", "'-'", ")", "except", "AttributeError", ":", "return", "None", ...
extract the numeric version from the xml filename
[ "extract", "the", "numeric", "version", "from", "the", "xml", "filename" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L93-L105
elifesciences/elife-article
elifearticle/utils.py
get_last_commit_to_master
def get_last_commit_to_master(repo_path="."): """ returns the last commit on the master branch. It would be more ideal to get the commit from the branch we are currently on, but as this is a check mostly to help with production issues, returning the commit from master will be sufficient. """ las...
python
def get_last_commit_to_master(repo_path="."): """ returns the last commit on the master branch. It would be more ideal to get the commit from the branch we are currently on, but as this is a check mostly to help with production issues, returning the commit from master will be sufficient. """ las...
[ "def", "get_last_commit_to_master", "(", "repo_path", "=", "\".\"", ")", ":", "last_commit", "=", "None", "repo", "=", "None", "try", ":", "repo", "=", "Repo", "(", "repo_path", ")", "except", "(", "InvalidGitRepositoryError", ",", "NoSuchPathError", ")", ":",...
returns the last commit on the master branch. It would be more ideal to get the commit from the branch we are currently on, but as this is a check mostly to help with production issues, returning the commit from master will be sufficient.
[ "returns", "the", "last", "commit", "on", "the", "master", "branch", ".", "It", "would", "be", "more", "ideal", "to", "get", "the", "commit", "from", "the", "branch", "we", "are", "currently", "on", "but", "as", "this", "is", "a", "check", "mostly", "t...
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L107-L125
elifesciences/elife-article
elifearticle/utils.py
calculate_journal_volume
def calculate_journal_volume(pub_date, year): """ volume value is based on the pub date year pub_date is a python time object """ try: volume = str(pub_date.tm_year - year + 1) except TypeError: volume = None except AttributeError: volume = None return volume
python
def calculate_journal_volume(pub_date, year): """ volume value is based on the pub date year pub_date is a python time object """ try: volume = str(pub_date.tm_year - year + 1) except TypeError: volume = None except AttributeError: volume = None return volume
[ "def", "calculate_journal_volume", "(", "pub_date", ",", "year", ")", ":", "try", ":", "volume", "=", "str", "(", "pub_date", ".", "tm_year", "-", "year", "+", "1", ")", "except", "TypeError", ":", "volume", "=", "None", "except", "AttributeError", ":", ...
volume value is based on the pub date year pub_date is a python time object
[ "volume", "value", "is", "based", "on", "the", "pub", "date", "year", "pub_date", "is", "a", "python", "time", "object" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L127-L138
elifesciences/elife-article
elifearticle/utils.py
author_name_from_json
def author_name_from_json(author_json): "concatenate an author name from json data" author_name = None if author_json.get('type'): if author_json.get('type') == 'group' and author_json.get('name'): author_name = author_json.get('name') elif author_json.get('type') == 'person' and...
python
def author_name_from_json(author_json): "concatenate an author name from json data" author_name = None if author_json.get('type'): if author_json.get('type') == 'group' and author_json.get('name'): author_name = author_json.get('name') elif author_json.get('type') == 'person' and...
[ "def", "author_name_from_json", "(", "author_json", ")", ":", "author_name", "=", "None", "if", "author_json", ".", "get", "(", "'type'", ")", ":", "if", "author_json", ".", "get", "(", "'type'", ")", "==", "'group'", "and", "author_json", ".", "get", "(",...
concatenate an author name from json data
[ "concatenate", "an", "author", "name", "from", "json", "data" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L140-L149
elifesciences/elife-article
elifearticle/utils.py
text_from_affiliation_elements
def text_from_affiliation_elements(department, institution, city, country): "format an author affiliation from details" return ', '.join(element for element in [department, institution, city, country] if element)
python
def text_from_affiliation_elements(department, institution, city, country): "format an author affiliation from details" return ', '.join(element for element in [department, institution, city, country] if element)
[ "def", "text_from_affiliation_elements", "(", "department", ",", "institution", ",", "city", ",", "country", ")", ":", "return", "', '", ".", "join", "(", "element", "for", "element", "in", "[", "department", ",", "institution", ",", "city", ",", "country", ...
format an author affiliation from details
[ "format", "an", "author", "affiliation", "from", "details" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/utils.py#L151-L153
LaoLiulaoliu/pgwrapper
pgwrapper/pgwrapper.py
PGWrapper.select
def select(self, table, args='*', condition=None, control=None): """.. :py:method:: select General select form of select Usage:: >>> select('hospital', 'id, city', control='limit 1') select id, city from hospital limit 1; >>> select('hospital', 'id', ...
python
def select(self, table, args='*', condition=None, control=None): """.. :py:method:: select General select form of select Usage:: >>> select('hospital', 'id, city', control='limit 1') select id, city from hospital limit 1; >>> select('hospital', 'id', ...
[ "def", "select", "(", "self", ",", "table", ",", "args", "=", "'*'", ",", "condition", "=", "None", ",", "control", "=", "None", ")", ":", "sql", "=", "'select {} from {}'", ".", "format", "(", "args", ",", "table", ")", "sql", "+=", "self", ".", "...
.. :py:method:: select General select form of select Usage:: >>> select('hospital', 'id, city', control='limit 1') select id, city from hospital limit 1; >>> select('hospital', 'id', 'address is null') select id from hospital where address is null...
[ "..", ":", "py", ":", "method", "::", "select" ]
train
https://github.com/LaoLiulaoliu/pgwrapper/blob/063a164713b79bfadb56a01c4ae19911f508d01e/pgwrapper/pgwrapper.py#L24-L41
LaoLiulaoliu/pgwrapper
pgwrapper/pgwrapper.py
PGWrapper.update
def update(self, table, kwargs, condition=None): """.. :py:method:: update All module update can user this function. condition only support string and dictionary. Usage:: >>> update('dept', {'name': 'design', 'quantity': 3}, {'id': 'we4d'}) update dept ...
python
def update(self, table, kwargs, condition=None): """.. :py:method:: update All module update can user this function. condition only support string and dictionary. Usage:: >>> update('dept', {'name': 'design', 'quantity': 3}, {'id': 'we4d'}) update dept ...
[ "def", "update", "(", "self", ",", "table", ",", "kwargs", ",", "condition", "=", "None", ")", ":", "sql", "=", "\"update {} set {}\"", "equations", "=", "[", "]", "values", "=", "[", "]", "for", "k", ",", "v", "in", "kwargs", ".", "iteritems", "(", ...
.. :py:method:: update All module update can user this function. condition only support string and dictionary. Usage:: >>> update('dept', {'name': 'design', 'quantity': 3}, {'id': 'we4d'}) update dept set name='design', quantity=3 where id='we4d'; ...
[ "..", ":", "py", ":", "method", "::", "update" ]
train
https://github.com/LaoLiulaoliu/pgwrapper/blob/063a164713b79bfadb56a01c4ae19911f508d01e/pgwrapper/pgwrapper.py#L44-L75
LaoLiulaoliu/pgwrapper
pgwrapper/pgwrapper.py
PGWrapper.insert
def insert(self, table, kwargs, execute=True): """.. :py:method:: Usage:: >>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'}) insert into hospital (id, province) values ('12de3wrv', 'shanghai'); :param string table: table name :param dict kwargs:...
python
def insert(self, table, kwargs, execute=True): """.. :py:method:: Usage:: >>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'}) insert into hospital (id, province) values ('12de3wrv', 'shanghai'); :param string table: table name :param dict kwargs:...
[ "def", "insert", "(", "self", ",", "table", ",", "kwargs", ",", "execute", "=", "True", ")", ":", "sql", "=", "\"insert into \"", "+", "table", "+", "\" ({}) values ({});\"", "keys", ",", "values", "=", "[", "]", ",", "[", "]", "[", "(", "keys", ".",...
.. :py:method:: Usage:: >>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'}) insert into hospital (id, province) values ('12de3wrv', 'shanghai'); :param string table: table name :param dict kwargs: name and value :param bool execute: if not execut...
[ "..", ":", "py", ":", "method", "::" ]
train
https://github.com/LaoLiulaoliu/pgwrapper/blob/063a164713b79bfadb56a01c4ae19911f508d01e/pgwrapper/pgwrapper.py#L78-L99
LaoLiulaoliu/pgwrapper
pgwrapper/pgwrapper.py
PGWrapper.delete
def delete(self, table, condition): """.. :py:method:: Usage:: >>> delete('hospital', {'id': '12de3wrv'}) delete from hospital where id='12de3wrv'; """ sql = "delete from {}".format(table) sql += self.parse_condition(condition) + ";" super(PGWra...
python
def delete(self, table, condition): """.. :py:method:: Usage:: >>> delete('hospital', {'id': '12de3wrv'}) delete from hospital where id='12de3wrv'; """ sql = "delete from {}".format(table) sql += self.parse_condition(condition) + ";" super(PGWra...
[ "def", "delete", "(", "self", ",", "table", ",", "condition", ")", ":", "sql", "=", "\"delete from {}\"", ".", "format", "(", "table", ")", "sql", "+=", "self", ".", "parse_condition", "(", "condition", ")", "+", "\";\"", "super", "(", "PGWrapper", ",", ...
.. :py:method:: Usage:: >>> delete('hospital', {'id': '12de3wrv'}) delete from hospital where id='12de3wrv';
[ "..", ":", "py", ":", "method", "::" ]
train
https://github.com/LaoLiulaoliu/pgwrapper/blob/063a164713b79bfadb56a01c4ae19911f508d01e/pgwrapper/pgwrapper.py#L102-L113
LaoLiulaoliu/pgwrapper
pgwrapper/pgwrapper.py
PGWrapper.insert_inexistence
def insert_inexistence(self, table, kwargs, condition): """.. :py:method:: Usage:: >>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'}, {'id': '12de3wrv'}) insert into hospital (id, province) select '12de3wrv', 'shanghai' where not exists (select 1 from hospital w...
python
def insert_inexistence(self, table, kwargs, condition): """.. :py:method:: Usage:: >>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'}, {'id': '12de3wrv'}) insert into hospital (id, province) select '12de3wrv', 'shanghai' where not exists (select 1 from hospital w...
[ "def", "insert_inexistence", "(", "self", ",", "table", ",", "kwargs", ",", "condition", ")", ":", "sql", "=", "\"insert into \"", "+", "table", "+", "\" ({}) \"", "select", "=", "\"select {} \"", "condition", "=", "\"where not exists (select 1 from \"", "+", "tab...
.. :py:method:: Usage:: >>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'}, {'id': '12de3wrv'}) insert into hospital (id, province) select '12de3wrv', 'shanghai' where not exists (select 1 from hospital where id='12de3wrv' limit 1);
[ "..", ":", "py", ":", "method", "::" ]
train
https://github.com/LaoLiulaoliu/pgwrapper/blob/063a164713b79bfadb56a01c4ae19911f508d01e/pgwrapper/pgwrapper.py#L116-L131
LaoLiulaoliu/pgwrapper
pgwrapper/pgwrapper.py
PGWrapper.parse_condition
def parse_condition(self, condition): """.. :py:method:: parse the condition, support string and dictonary """ if isinstance(condition, bytes): sql = " where {}".format(condition) elif isinstance(condition, dict): conditions = [] for k, v ...
python
def parse_condition(self, condition): """.. :py:method:: parse the condition, support string and dictonary """ if isinstance(condition, bytes): sql = " where {}".format(condition) elif isinstance(condition, dict): conditions = [] for k, v ...
[ "def", "parse_condition", "(", "self", ",", "condition", ")", ":", "if", "isinstance", "(", "condition", ",", "bytes", ")", ":", "sql", "=", "\" where {}\"", ".", "format", "(", "condition", ")", "elif", "isinstance", "(", "condition", ",", "dict", ")", ...
.. :py:method:: parse the condition, support string and dictonary
[ "..", ":", "py", ":", "method", "::" ]
train
https://github.com/LaoLiulaoliu/pgwrapper/blob/063a164713b79bfadb56a01c4ae19911f508d01e/pgwrapper/pgwrapper.py#L134-L151
LaoLiulaoliu/pgwrapper
pgwrapper/pgwrapper.py
PGWrapper.select_join
def select_join(self, table, field, join_table, join_field): """.. :py:method:: Usage:: >>> select_join('hospital', 'id', 'department', 'hospid') select hospital.id from hospital left join department on hospital.id=department.hospid where department.hospid is null; """...
python
def select_join(self, table, field, join_table, join_field): """.. :py:method:: Usage:: >>> select_join('hospital', 'id', 'department', 'hospid') select hospital.id from hospital left join department on hospital.id=department.hospid where department.hospid is null; """...
[ "def", "select_join", "(", "self", ",", "table", ",", "field", ",", "join_table", ",", "join_field", ")", ":", "sql", "=", "\"select {table}.{field} from {table} left join {join_table} \"", "\"on {table}.{field}={join_table}.{join_field} \"", "\"where {join_table}.{join_field} is...
.. :py:method:: Usage:: >>> select_join('hospital', 'id', 'department', 'hospid') select hospital.id from hospital left join department on hospital.id=department.hospid where department.hospid is null;
[ "..", ":", "py", ":", "method", "::" ]
train
https://github.com/LaoLiulaoliu/pgwrapper/blob/063a164713b79bfadb56a01c4ae19911f508d01e/pgwrapper/pgwrapper.py#L155-L170
LaoLiulaoliu/pgwrapper
pgwrapper/pgwrapper.py
PGWrapper.joint
def joint(self, table, fields, join_table, join_fields, condition_field, condition_join_field, join_method='left_join'): """.. :py:method:: Usage:: >>> joint('user', 'name, id_number', 'medical_card', 'number', 'id', 'user_id', 'i...
python
def joint(self, table, fields, join_table, join_fields, condition_field, condition_join_field, join_method='left_join'): """.. :py:method:: Usage:: >>> joint('user', 'name, id_number', 'medical_card', 'number', 'id', 'user_id', 'i...
[ "def", "joint", "(", "self", ",", "table", ",", "fields", ",", "join_table", ",", "join_fields", ",", "condition_field", ",", "condition_join_field", ",", "join_method", "=", "'left_join'", ")", ":", "import", "string", "fields", "=", "map", "(", "string", "...
.. :py:method:: Usage:: >>> joint('user', 'name, id_number', 'medical_card', 'number', 'id', 'user_id', 'inner_join') select u.name, u.id_number, v.number from user as u inner join medical_card as v on u.id=v.user_id;
[ "..", ":", "py", ":", "method", "::" ]
train
https://github.com/LaoLiulaoliu/pgwrapper/blob/063a164713b79bfadb56a01c4ae19911f508d01e/pgwrapper/pgwrapper.py#L173-L200
cdeboever3/cdpybio
cdpybio/mutect.py
read_variants
def read_variants(fns, remove=['DBSNP'], keep_only=True, min_tumor_f=0.1, min_tumor_cov=14, min_normal_cov=8): """Read muTect results from the list of files fns Parameters ---------- fns : list List of MuTect output files. Returns ------- variant...
python
def read_variants(fns, remove=['DBSNP'], keep_only=True, min_tumor_f=0.1, min_tumor_cov=14, min_normal_cov=8): """Read muTect results from the list of files fns Parameters ---------- fns : list List of MuTect output files. Returns ------- variant...
[ "def", "read_variants", "(", "fns", ",", "remove", "=", "[", "'DBSNP'", "]", ",", "keep_only", "=", "True", ",", "min_tumor_f", "=", "0.1", ",", "min_tumor_cov", "=", "14", ",", "min_normal_cov", "=", "8", ")", ":", "variants", "=", "[", "]", "for", ...
Read muTect results from the list of files fns Parameters ---------- fns : list List of MuTect output files. Returns ------- variants : pandas.DataFrame Pandas DataFrame summarizing variant calling results. remove : list List of site types for column "dbsnp_site" t...
[ "Read", "muTect", "results", "from", "the", "list", "of", "files", "fns" ]
train
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/mutect.py#L4-L77
cdeboever3/cdpybio
cdpybio/mutect.py
mutect_to_bed
def mutect_to_bed(df): """Convert MuTect results (read into dataframe) to BedTool object Parameters ---------- df : pandas.DataFrame Pandas DataFrame with MuTect results. Returns ------- bt : pybedtools.BedTool BedTool with variants. """ s = (df.contig.astype(str) ...
python
def mutect_to_bed(df): """Convert MuTect results (read into dataframe) to BedTool object Parameters ---------- df : pandas.DataFrame Pandas DataFrame with MuTect results. Returns ------- bt : pybedtools.BedTool BedTool with variants. """ s = (df.contig.astype(str) ...
[ "def", "mutect_to_bed", "(", "df", ")", ":", "s", "=", "(", "df", ".", "contig", ".", "astype", "(", "str", ")", "+", "'\\t'", "+", "(", "df", ".", "position", "-", "1", ")", ".", "astype", "(", "int", ")", ".", "astype", "(", "str", ")", "+"...
Convert MuTect results (read into dataframe) to BedTool object Parameters ---------- df : pandas.DataFrame Pandas DataFrame with MuTect results. Returns ------- bt : pybedtools.BedTool BedTool with variants.
[ "Convert", "MuTect", "results", "(", "read", "into", "dataframe", ")", "to", "BedTool", "object" ]
train
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/mutect.py#L79-L99
honzamach/pynspect
pynspect/compilers.py
compile_ip_v4
def compile_ip_v4(rule): """ Compiler helper method: attempt to compile constant into object representing IPv4 address to enable relations and thus simple comparisons using Python operators. """ if isinstance(rule.value, ipranges.Range): return rule return IPV4Rule(ipranges.from_str_...
python
def compile_ip_v4(rule): """ Compiler helper method: attempt to compile constant into object representing IPv4 address to enable relations and thus simple comparisons using Python operators. """ if isinstance(rule.value, ipranges.Range): return rule return IPV4Rule(ipranges.from_str_...
[ "def", "compile_ip_v4", "(", "rule", ")", ":", "if", "isinstance", "(", "rule", ".", "value", ",", "ipranges", ".", "Range", ")", ":", "return", "rule", "return", "IPV4Rule", "(", "ipranges", ".", "from_str_v4", "(", "rule", ".", "value", ")", ")" ]
Compiler helper method: attempt to compile constant into object representing IPv4 address to enable relations and thus simple comparisons using Python operators.
[ "Compiler", "helper", "method", ":", "attempt", "to", "compile", "constant", "into", "object", "representing", "IPv4", "address", "to", "enable", "relations", "and", "thus", "simple", "comparisons", "using", "Python", "operators", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L51-L59
honzamach/pynspect
pynspect/compilers.py
compile_ip_v6
def compile_ip_v6(rule): """ Compiler helper method: attempt to compile constant into object representing IPv6 address to enable relations and thus simple comparisons using Python operators. """ if isinstance(rule.value, ipranges.Range): return rule return IPV6Rule(ipranges.from_str_...
python
def compile_ip_v6(rule): """ Compiler helper method: attempt to compile constant into object representing IPv6 address to enable relations and thus simple comparisons using Python operators. """ if isinstance(rule.value, ipranges.Range): return rule return IPV6Rule(ipranges.from_str_...
[ "def", "compile_ip_v6", "(", "rule", ")", ":", "if", "isinstance", "(", "rule", ".", "value", ",", "ipranges", ".", "Range", ")", ":", "return", "rule", "return", "IPV6Rule", "(", "ipranges", ".", "from_str_v6", "(", "rule", ".", "value", ")", ")" ]
Compiler helper method: attempt to compile constant into object representing IPv6 address to enable relations and thus simple comparisons using Python operators.
[ "Compiler", "helper", "method", ":", "attempt", "to", "compile", "constant", "into", "object", "representing", "IPv6", "address", "to", "enable", "relations", "and", "thus", "simple", "comparisons", "using", "Python", "operators", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L61-L69
honzamach/pynspect
pynspect/compilers.py
compile_datetime
def compile_datetime(rule): """ Compiler helper method: attempt to compile constant into object representing datetime object to enable relations and thus simple comparisons using Python operators. """ if isinstance(rule.value, datetime.datetime): return rule try: # Try numeri...
python
def compile_datetime(rule): """ Compiler helper method: attempt to compile constant into object representing datetime object to enable relations and thus simple comparisons using Python operators. """ if isinstance(rule.value, datetime.datetime): return rule try: # Try numeri...
[ "def", "compile_datetime", "(", "rule", ")", ":", "if", "isinstance", "(", "rule", ".", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "rule", "try", ":", "# Try numeric type", "return", "DatetimeRule", "(", "datetime", ".", "datetime", ".", ...
Compiler helper method: attempt to compile constant into object representing datetime object to enable relations and thus simple comparisons using Python operators.
[ "Compiler", "helper", "method", ":", "attempt", "to", "compile", "constant", "into", "object", "representing", "datetime", "object", "to", "enable", "relations", "and", "thus", "simple", "comparisons", "using", "Python", "operators", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L71-L94
honzamach/pynspect
pynspect/compilers.py
compile_timedelta
def compile_timedelta(rule): """ Compiler helper method: attempt to compile constant into object representing timedelta object to enable math operations and relations with datetime objects using Python operators. """ if isinstance(rule.value, datetime.timedelta): return rule try: ...
python
def compile_timedelta(rule): """ Compiler helper method: attempt to compile constant into object representing timedelta object to enable math operations and relations with datetime objects using Python operators. """ if isinstance(rule.value, datetime.timedelta): return rule try: ...
[ "def", "compile_timedelta", "(", "rule", ")", ":", "if", "isinstance", "(", "rule", ".", "value", ",", "datetime", ".", "timedelta", ")", ":", "return", "rule", "try", ":", "# Try numeric type", "return", "TimedeltaRule", "(", "datetime", ".", "timedelta", "...
Compiler helper method: attempt to compile constant into object representing timedelta object to enable math operations and relations with datetime objects using Python operators.
[ "Compiler", "helper", "method", ":", "attempt", "to", "compile", "constant", "into", "object", "representing", "timedelta", "object", "to", "enable", "math", "operations", "and", "relations", "with", "datetime", "objects", "using", "Python", "operators", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L96-L114
honzamach/pynspect
pynspect/compilers.py
compile_timeoper
def compile_timeoper(rule): """ Compiler helper method: attempt to compile constant into object representing datetime or timedelta object to enable relations and thus simple comparisons using Python operators. """ if isinstance(rule.value, (datetime.datetime, datetime.timedelta)): return...
python
def compile_timeoper(rule): """ Compiler helper method: attempt to compile constant into object representing datetime or timedelta object to enable relations and thus simple comparisons using Python operators. """ if isinstance(rule.value, (datetime.datetime, datetime.timedelta)): return...
[ "def", "compile_timeoper", "(", "rule", ")", ":", "if", "isinstance", "(", "rule", ".", "value", ",", "(", "datetime", ".", "datetime", ",", "datetime", ".", "timedelta", ")", ")", ":", "return", "rule", "if", "isinstance", "(", "rule", ",", "NumberRule"...
Compiler helper method: attempt to compile constant into object representing datetime or timedelta object to enable relations and thus simple comparisons using Python operators.
[ "Compiler", "helper", "method", ":", "attempt", "to", "compile", "constant", "into", "object", "representing", "datetime", "or", "timedelta", "object", "to", "enable", "relations", "and", "thus", "simple", "comparisons", "using", "Python", "operators", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L116-L135
honzamach/pynspect
pynspect/compilers.py
ConversionRule.traverse
def traverse(self, traverser, **kwargs): """ Implementation of mandatory interface for traversing the whole rule tree. This method will call the ``traverse`` method of child rule tree and then perform arbitrary conversion of the result before returning it back. The optional ``kwa...
python
def traverse(self, traverser, **kwargs): """ Implementation of mandatory interface for traversing the whole rule tree. This method will call the ``traverse`` method of child rule tree and then perform arbitrary conversion of the result before returning it back. The optional ``kwa...
[ "def", "traverse", "(", "self", ",", "traverser", ",", "*", "*", "kwargs", ")", ":", "result", "=", "self", ".", "rule", ".", "traverse", "(", "traverser", ",", "*", "*", "kwargs", ")", "return", "self", ".", "conversion", "(", "result", ")" ]
Implementation of mandatory interface for traversing the whole rule tree. This method will call the ``traverse`` method of child rule tree and then perform arbitrary conversion of the result before returning it back. The optional ``kwargs`` are passed down to traverser callback as additional ...
[ "Implementation", "of", "mandatory", "interface", "for", "traversing", "the", "whole", "rule", "tree", ".", "This", "method", "will", "call", "the", "traverse", "method", "of", "child", "rule", "tree", "and", "then", "perform", "arbitrary", "conversion", "of", ...
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L186-L198
honzamach/pynspect
pynspect/compilers.py
IDEAFilterCompiler.register_variable_compilation
def register_variable_compilation(self, path, compilation_cbk, listclass): """ Register given compilation method for variable on given path. :param str path: JPath for given variable. :param callable compilation_cbk: Compilation callback to be called. :param class listclass: Lis...
python
def register_variable_compilation(self, path, compilation_cbk, listclass): """ Register given compilation method for variable on given path. :param str path: JPath for given variable. :param callable compilation_cbk: Compilation callback to be called. :param class listclass: Lis...
[ "def", "register_variable_compilation", "(", "self", ",", "path", ",", "compilation_cbk", ",", "listclass", ")", ":", "self", ".", "compilations_variable", "[", "path", "]", "=", "{", "'callback'", ":", "compilation_cbk", ",", "'listclass'", ":", "listclass", "}...
Register given compilation method for variable on given path. :param str path: JPath for given variable. :param callable compilation_cbk: Compilation callback to be called. :param class listclass: List class to use for lists.
[ "Register", "given", "compilation", "method", "for", "variable", "on", "given", "path", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L248-L259
honzamach/pynspect
pynspect/compilers.py
IDEAFilterCompiler.register_function_compilation
def register_function_compilation(self, func, compilation_cbk, listclass): """ Register given compilation method for given function. :param str path: Function name. :param callable compilation_cbk: Compilation callback to be called. :param class listclass: List class to use for ...
python
def register_function_compilation(self, func, compilation_cbk, listclass): """ Register given compilation method for given function. :param str path: Function name. :param callable compilation_cbk: Compilation callback to be called. :param class listclass: List class to use for ...
[ "def", "register_function_compilation", "(", "self", ",", "func", ",", "compilation_cbk", ",", "listclass", ")", ":", "self", ".", "compilations_function", "[", "func", "]", "=", "{", "'callback'", ":", "compilation_cbk", ",", "'listclass'", ":", "listclass", "}...
Register given compilation method for given function. :param str path: Function name. :param callable compilation_cbk: Compilation callback to be called. :param class listclass: List class to use for lists.
[ "Register", "given", "compilation", "method", "for", "given", "function", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L261-L272
honzamach/pynspect
pynspect/compilers.py
IDEAFilterCompiler._cor_compile
def _cor_compile(rule, var, val, result_class, key, compilation_list): """ Actual compilation worker method. """ compilation = compilation_list.get(key, None) if compilation: if isinstance(val, ListRule): result = [] for itemv in val.va...
python
def _cor_compile(rule, var, val, result_class, key, compilation_list): """ Actual compilation worker method. """ compilation = compilation_list.get(key, None) if compilation: if isinstance(val, ListRule): result = [] for itemv in val.va...
[ "def", "_cor_compile", "(", "rule", ",", "var", ",", "val", ",", "result_class", ",", "key", ",", "compilation_list", ")", ":", "compilation", "=", "compilation_list", ".", "get", "(", "key", ",", "None", ")", "if", "compilation", ":", "if", "isinstance", ...
Actual compilation worker method.
[ "Actual", "compilation", "worker", "method", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L277-L291
honzamach/pynspect
pynspect/compilers.py
IDEAFilterCompiler._compile_operation_rule
def _compile_operation_rule(self, rule, left, right, result_class): """ Compile given operation rule, when possible for given compination of operation operands. """ # Make sure variables always have constant with correct datatype on the # opposite side of operation. ...
python
def _compile_operation_rule(self, rule, left, right, result_class): """ Compile given operation rule, when possible for given compination of operation operands. """ # Make sure variables always have constant with correct datatype on the # opposite side of operation. ...
[ "def", "_compile_operation_rule", "(", "self", ",", "rule", ",", "left", ",", "right", ",", "result_class", ")", ":", "# Make sure variables always have constant with correct datatype on the", "# opposite side of operation.", "if", "isinstance", "(", "left", ",", "VariableR...
Compile given operation rule, when possible for given compination of operation operands.
[ "Compile", "given", "operation", "rule", "when", "possible", "for", "given", "compination", "of", "operation", "operands", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L293-L342
honzamach/pynspect
pynspect/compilers.py
IDEAFilterCompiler._calculate_operation_math
def _calculate_operation_math(self, rule, left, right): """ Perform compilation of given math operation by actually calculating given math expression. """ # Attempt to keep integer data type for the result, when possible. if isinstance(left, IntegerRule) and isinstance(r...
python
def _calculate_operation_math(self, rule, left, right): """ Perform compilation of given math operation by actually calculating given math expression. """ # Attempt to keep integer data type for the result, when possible. if isinstance(left, IntegerRule) and isinstance(r...
[ "def", "_calculate_operation_math", "(", "self", ",", "rule", ",", "left", ",", "right", ")", ":", "# Attempt to keep integer data type for the result, when possible.", "if", "isinstance", "(", "left", ",", "IntegerRule", ")", "and", "isinstance", "(", "right", ",", ...
Perform compilation of given math operation by actually calculating given math expression.
[ "Perform", "compilation", "of", "given", "math", "operation", "by", "actually", "calculating", "given", "math", "expression", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L344-L365
honzamach/pynspect
pynspect/compilers.py
IDEAFilterCompiler.integer
def integer(self, rule, **kwargs): """ Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.integer` interface. """ rule.value = int(rule.value) return rule
python
def integer(self, rule, **kwargs): """ Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.integer` interface. """ rule.value = int(rule.value) return rule
[ "def", "integer", "(", "self", ",", "rule", ",", "*", "*", "kwargs", ")", ":", "rule", ".", "value", "=", "int", "(", "rule", ".", "value", ")", "return", "rule" ]
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.integer` interface.
[ "Implementation", "of", ":", "py", ":", "func", ":", "pynspect", ".", "traversers", ".", "RuleTreeTraverser", ".", "integer", "interface", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L399-L404
honzamach/pynspect
pynspect/compilers.py
IDEAFilterCompiler.float
def float(self, rule, **kwargs): """ Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.float` interface. """ rule.value = float(rule.value) return rule
python
def float(self, rule, **kwargs): """ Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.float` interface. """ rule.value = float(rule.value) return rule
[ "def", "float", "(", "self", ",", "rule", ",", "*", "*", "kwargs", ")", ":", "rule", ".", "value", "=", "float", "(", "rule", ".", "value", ")", "return", "rule" ]
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.float` interface.
[ "Implementation", "of", ":", "py", ":", "func", ":", "pynspect", ".", "traversers", ".", "RuleTreeTraverser", ".", "float", "interface", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L406-L411
honzamach/pynspect
pynspect/compilers.py
IDEAFilterCompiler.binary_operation_logical
def binary_operation_logical(self, rule, left, right, **kwargs): """ Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_logical` interface. """ return LogicalBinOpRule(rule.operation, left, right)
python
def binary_operation_logical(self, rule, left, right, **kwargs): """ Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_logical` interface. """ return LogicalBinOpRule(rule.operation, left, right)
[ "def", "binary_operation_logical", "(", "self", ",", "rule", ",", "left", ",", "right", ",", "*", "*", "kwargs", ")", ":", "return", "LogicalBinOpRule", "(", "rule", ".", "operation", ",", "left", ",", "right", ")" ]
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_logical` interface.
[ "Implementation", "of", ":", "py", ":", "func", ":", "pynspect", ".", "traversers", ".", "RuleTreeTraverser", ".", "binary_operation_logical", "interface", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L431-L435
honzamach/pynspect
pynspect/compilers.py
IDEAFilterCompiler.binary_operation_comparison
def binary_operation_comparison(self, rule, left, right, **kwargs): """ Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_comparison` interface. """ return self._compile_operation_rule( rule, left, right, Co...
python
def binary_operation_comparison(self, rule, left, right, **kwargs): """ Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_comparison` interface. """ return self._compile_operation_rule( rule, left, right, Co...
[ "def", "binary_operation_comparison", "(", "self", ",", "rule", ",", "left", ",", "right", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_compile_operation_rule", "(", "rule", ",", "left", ",", "right", ",", "ComparisonBinOpRule", ")" ]
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_comparison` interface.
[ "Implementation", "of", ":", "py", ":", "func", ":", "pynspect", ".", "traversers", ".", "RuleTreeTraverser", ".", "binary_operation_comparison", "interface", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L437-L446
honzamach/pynspect
pynspect/compilers.py
IDEAFilterCompiler.binary_operation_math
def binary_operation_math(self, rule, left, right, **kwargs): """ Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_math` interface. """ if isinstance(left, NumberRule) and isinstance(right, NumberRule): return self._calculate_operation_math(r...
python
def binary_operation_math(self, rule, left, right, **kwargs): """ Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_math` interface. """ if isinstance(left, NumberRule) and isinstance(right, NumberRule): return self._calculate_operation_math(r...
[ "def", "binary_operation_math", "(", "self", ",", "rule", ",", "left", ",", "right", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "left", ",", "NumberRule", ")", "and", "isinstance", "(", "right", ",", "NumberRule", ")", ":", "return", "...
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_math` interface.
[ "Implementation", "of", ":", "py", ":", "func", ":", "pynspect", ".", "traversers", ".", "RuleTreeTraverser", ".", "binary_operation_math", "interface", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/compilers.py#L448-L459
pyvec/pyvodb
pyvodb/load.py
get_db
def get_db(directory, engine=None): """Get a database :param directory: The root data directory :param engine: a pre-created SQLAlchemy engine (default: in-memory SQLite) """ if engine is None: engine = create_engine('sqlite://') tables.metadata.create_all(engine) Session = sessionm...
python
def get_db(directory, engine=None): """Get a database :param directory: The root data directory :param engine: a pre-created SQLAlchemy engine (default: in-memory SQLite) """ if engine is None: engine = create_engine('sqlite://') tables.metadata.create_all(engine) Session = sessionm...
[ "def", "get_db", "(", "directory", ",", "engine", "=", "None", ")", ":", "if", "engine", "is", "None", ":", "engine", "=", "create_engine", "(", "'sqlite://'", ")", "tables", ".", "metadata", ".", "create_all", "(", "engine", ")", "Session", "=", "sessio...
Get a database :param directory: The root data directory :param engine: a pre-created SQLAlchemy engine (default: in-memory SQLite)
[ "Get", "a", "database" ]
train
https://github.com/pyvec/pyvodb/blob/07183333df26eb12c5c2b98802cde3fb3a6c1339/pyvodb/load.py#L22-L35
pyvec/pyvodb
pyvodb/load.py
load_from_dict
def load_from_dict(db, data, metadata): """Load data from a dict (as loaded from directory of YAMLs) into database """ # The ORM overhead is too high for this kind of bulk load, # so drop down to SQLAlchemy Core. # This tries to do minimize the number of SQL commands by loading entire # tables a...
python
def load_from_dict(db, data, metadata): """Load data from a dict (as loaded from directory of YAMLs) into database """ # The ORM overhead is too high for this kind of bulk load, # so drop down to SQLAlchemy Core. # This tries to do minimize the number of SQL commands by loading entire # tables a...
[ "def", "load_from_dict", "(", "db", ",", "data", ",", "metadata", ")", ":", "# The ORM overhead is too high for this kind of bulk load,", "# so drop down to SQLAlchemy Core.", "# This tries to do minimize the number of SQL commands by loading entire", "# tables at once", "if", "metadat...
Load data from a dict (as loaded from directory of YAMLs) into database
[ "Load", "data", "from", "a", "dict", "(", "as", "loaded", "from", "directory", "of", "YAMLs", ")", "into", "database" ]
train
https://github.com/pyvec/pyvodb/blob/07183333df26eb12c5c2b98802cde3fb3a6c1339/pyvodb/load.py#L73-L227
legnaleurc/wcpan.listen
wcpan/listen/helper.py
bind_sockets
def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=_DEFAULT_BACKLOG, flags=None, reuse_port=False): """Creates listening sockets bound to the given port and address. Returns a list of socket objects (multiple sockets are returned if the given address maps to multiple IP ...
python
def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=_DEFAULT_BACKLOG, flags=None, reuse_port=False): """Creates listening sockets bound to the given port and address. Returns a list of socket objects (multiple sockets are returned if the given address maps to multiple IP ...
[ "def", "bind_sockets", "(", "port", ",", "address", "=", "None", ",", "family", "=", "socket", ".", "AF_UNSPEC", ",", "backlog", "=", "_DEFAULT_BACKLOG", ",", "flags", "=", "None", ",", "reuse_port", "=", "False", ")", ":", "if", "reuse_port", "and", "no...
Creates listening sockets bound to the given port and address. Returns a list of socket objects (multiple sockets are returned if the given address maps to multiple IP addresses, which is most common for mixed IPv4 and IPv6 use). Address may be either an IP address or hostname. If it's a hostname, ...
[ "Creates", "listening", "sockets", "bound", "to", "the", "given", "port", "and", "address", "." ]
train
https://github.com/legnaleurc/wcpan.listen/blob/9c11e92ec5db588fc181543ad723b6eef0741db1/wcpan/listen/helper.py#L99-L185
legnaleurc/wcpan.listen
wcpan/listen/helper.py
bind_unix_socket
def bind_unix_socket(file_, mode=0o600, backlog=_DEFAULT_BACKLOG): """Creates a listening unix socket. If a socket with the given name already exists, it will be deleted. If any other file with that name exists, an exception will be raised. Returns a socket object (not a list of socket objects lik...
python
def bind_unix_socket(file_, mode=0o600, backlog=_DEFAULT_BACKLOG): """Creates a listening unix socket. If a socket with the given name already exists, it will be deleted. If any other file with that name exists, an exception will be raised. Returns a socket object (not a list of socket objects lik...
[ "def", "bind_unix_socket", "(", "file_", ",", "mode", "=", "0o600", ",", "backlog", "=", "_DEFAULT_BACKLOG", ")", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_UNIX", ",", "socket", ".", "SOCK_STREAM", ")", "sock", ".", "setsockopt", ...
Creates a listening unix socket. If a socket with the given name already exists, it will be deleted. If any other file with that name exists, an exception will be raised. Returns a socket object (not a list of socket objects like `bind_sockets`)
[ "Creates", "a", "listening", "unix", "socket", "." ]
train
https://github.com/legnaleurc/wcpan.listen/blob/9c11e92ec5db588fc181543ad723b6eef0741db1/wcpan/listen/helper.py#L188-L214
noobermin/lspreader
lspreader/pmovie.py
firsthash
def firsthash(frame, removedupes=False): ''' Hashes the first time step. Only will work as long as the hash can fit in a uint64. Parameters: ----------- frame : first frame. Keywords: --------- removedups: specify duplicates for the given frame. Returns a dictionary of...
python
def firsthash(frame, removedupes=False): ''' Hashes the first time step. Only will work as long as the hash can fit in a uint64. Parameters: ----------- frame : first frame. Keywords: --------- removedups: specify duplicates for the given frame. Returns a dictionary of...
[ "def", "firsthash", "(", "frame", ",", "removedupes", "=", "False", ")", ":", "#hashes must have i8 available", "#overwise, we'll have overflow", "def", "avgdiff", "(", "d", ")", ":", "d", "=", "np", ".", "sort", "(", "d", ")", "d", "=", "d", "[", "1", "...
Hashes the first time step. Only will work as long as the hash can fit in a uint64. Parameters: ----------- frame : first frame. Keywords: --------- removedups: specify duplicates for the given frame. Returns a dictionary of everything needed to generate hashes from the ge...
[ "Hashes", "the", "first", "time", "step", ".", "Only", "will", "work", "as", "long", "as", "the", "hash", "can", "fit", "in", "a", "uint64", "." ]
train
https://github.com/noobermin/lspreader/blob/903b9d6427513b07986ffacf76cbca54e18d8be6/lspreader/pmovie.py#L14-L67
noobermin/lspreader
lspreader/pmovie.py
genhash
def genhash(frame,**kw): ''' Generate the hashes for the given frame for a specification given in the dictionary d returned from firsthash. Parameters: ----------- frame : frame to hash. Keywords: --------- d : hash specification generated from firsthash. new ...
python
def genhash(frame,**kw): ''' Generate the hashes for the given frame for a specification given in the dictionary d returned from firsthash. Parameters: ----------- frame : frame to hash. Keywords: --------- d : hash specification generated from firsthash. new ...
[ "def", "genhash", "(", "frame", ",", "*", "*", "kw", ")", ":", "getkw", "=", "mk_getkw", "(", "kw", ",", "genhash_defaults", ",", "prefer_passed", "=", "True", ")", "dims", "=", "getkw", "(", "'dims'", ")", "dupes", "=", "getkw", "(", "'dupes'", ")",...
Generate the hashes for the given frame for a specification given in the dictionary d returned from firsthash. Parameters: ----------- frame : frame to hash. Keywords: --------- d : hash specification generated from firsthash. new : use new hashing, which isn't rea...
[ "Generate", "the", "hashes", "for", "the", "given", "frame", "for", "a", "specification", "given", "in", "the", "dictionary", "d", "returned", "from", "firsthash", "." ]
train
https://github.com/noobermin/lspreader/blob/903b9d6427513b07986ffacf76cbca54e18d8be6/lspreader/pmovie.py#L87-L130
noobermin/lspreader
lspreader/pmovie.py
addhash
def addhash(frame,**kw): ''' helper function to add hashes to the given frame given in the dictionary d returned from firsthash. Parameters: ----------- frame : frame to hash. Keywords: --------- same as genhash Returns frame with added hashes, although it will be add...
python
def addhash(frame,**kw): ''' helper function to add hashes to the given frame given in the dictionary d returned from firsthash. Parameters: ----------- frame : frame to hash. Keywords: --------- same as genhash Returns frame with added hashes, although it will be add...
[ "def", "addhash", "(", "frame", ",", "*", "*", "kw", ")", ":", "hashes", "=", "genhash", "(", "frame", ",", "*", "*", "kw", ")", "frame", "[", "'data'", "]", "=", "rfn", ".", "rec_append_fields", "(", "frame", "[", "'data'", "]", ",", "'hash'", "...
helper function to add hashes to the given frame given in the dictionary d returned from firsthash. Parameters: ----------- frame : frame to hash. Keywords: --------- same as genhash Returns frame with added hashes, although it will be added in place.
[ "helper", "function", "to", "add", "hashes", "to", "the", "given", "frame", "given", "in", "the", "dictionary", "d", "returned", "from", "firsthash", "." ]
train
https://github.com/noobermin/lspreader/blob/903b9d6427513b07986ffacf76cbca54e18d8be6/lspreader/pmovie.py#L132-L151
noobermin/lspreader
lspreader/pmovie.py
sortframe
def sortframe(frame): ''' sorts particles for a frame ''' d = frame['data']; sortedargs = np.lexsort([d['xi'],d['yi'],d['zi']]) d = d[sortedargs]; frame['data']=d; return frame;
python
def sortframe(frame): ''' sorts particles for a frame ''' d = frame['data']; sortedargs = np.lexsort([d['xi'],d['yi'],d['zi']]) d = d[sortedargs]; frame['data']=d; return frame;
[ "def", "sortframe", "(", "frame", ")", ":", "d", "=", "frame", "[", "'data'", "]", "sortedargs", "=", "np", ".", "lexsort", "(", "[", "d", "[", "'xi'", "]", ",", "d", "[", "'yi'", "]", ",", "d", "[", "'zi'", "]", "]", ")", "d", "=", "d", "[...
sorts particles for a frame
[ "sorts", "particles", "for", "a", "frame" ]
train
https://github.com/noobermin/lspreader/blob/903b9d6427513b07986ffacf76cbca54e18d8be6/lspreader/pmovie.py#L153-L161
noobermin/lspreader
lspreader/pmovie.py
read_and_hash
def read_and_hash(fname, **kw): ''' Read and and addhash each frame. ''' return [addhash(frame, **kw) for frame in read(fname, **kw)];
python
def read_and_hash(fname, **kw): ''' Read and and addhash each frame. ''' return [addhash(frame, **kw) for frame in read(fname, **kw)];
[ "def", "read_and_hash", "(", "fname", ",", "*", "*", "kw", ")", ":", "return", "[", "addhash", "(", "frame", ",", "*", "*", "kw", ")", "for", "frame", "in", "read", "(", "fname", ",", "*", "*", "kw", ")", "]" ]
Read and and addhash each frame.
[ "Read", "and", "and", "addhash", "each", "frame", "." ]
train
https://github.com/noobermin/lspreader/blob/903b9d6427513b07986ffacf76cbca54e18d8be6/lspreader/pmovie.py#L163-L167
noobermin/lspreader
lspreader/pmovie.py
filter_hashes_from_file
def filter_hashes_from_file(fname, f, **kw): ''' Obtain good hashes from a .p4 file with the dict hashd and a function that returns good hashes. Any keywords will be sent to read_and_hash. Parameters: ----------- fname -- filename of file. f -- function that returns a list of good ...
python
def filter_hashes_from_file(fname, f, **kw): ''' Obtain good hashes from a .p4 file with the dict hashd and a function that returns good hashes. Any keywords will be sent to read_and_hash. Parameters: ----------- fname -- filename of file. f -- function that returns a list of good ...
[ "def", "filter_hashes_from_file", "(", "fname", ",", "f", ",", "*", "*", "kw", ")", ":", "return", "np", ".", "concatenate", "(", "[", "frame", "[", "'data'", "]", "[", "'hash'", "]", "[", "f", "(", "frame", ")", "]", "for", "frame", "in", "read_an...
Obtain good hashes from a .p4 file with the dict hashd and a function that returns good hashes. Any keywords will be sent to read_and_hash. Parameters: ----------- fname -- filename of file. f -- function that returns a list of good hashes.
[ "Obtain", "good", "hashes", "from", "a", ".", "p4", "file", "with", "the", "dict", "hashd", "and", "a", "function", "that", "returns", "good", "hashes", ".", "Any", "keywords", "will", "be", "sent", "to", "read_and_hash", "." ]
train
https://github.com/noobermin/lspreader/blob/903b9d6427513b07986ffacf76cbca54e18d8be6/lspreader/pmovie.py#L169-L184
shi-cong/PYSTUDY
PYSTUDY/html_parserlib.py
LinksParser.links
def links(self): """ 解析页面上所有的链接并返回一个生成器 """ ass = self.xpath('//a') for a in ass: text = a.xpath('./text()').extract_first() url = a.xpath('./@href').extract_first() link = Link(text, url) yield link
python
def links(self): """ 解析页面上所有的链接并返回一个生成器 """ ass = self.xpath('//a') for a in ass: text = a.xpath('./text()').extract_first() url = a.xpath('./@href').extract_first() link = Link(text, url) yield link
[ "def", "links", "(", "self", ")", ":", "ass", "=", "self", ".", "xpath", "(", "'//a'", ")", "for", "a", "in", "ass", ":", "text", "=", "a", ".", "xpath", "(", "'./text()'", ")", ".", "extract_first", "(", ")", "url", "=", "a", ".", "xpath", "("...
解析页面上所有的链接并返回一个生成器
[ "解析页面上所有的链接并返回一个生成器" ]
train
https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/html_parserlib.py#L32-L41
shi-cong/PYSTUDY
PYSTUDY/html_parserlib.py
ReParser.replace
def replace(self, re_text, replace_str, text): """ 正则表达式替换 :param re_text: 正则表达式 :param replace_str: 替换字符串 :param text: 搜索文档 :return: 替换后的字符串 """ return re.sub(re_text, replace_str, text)
python
def replace(self, re_text, replace_str, text): """ 正则表达式替换 :param re_text: 正则表达式 :param replace_str: 替换字符串 :param text: 搜索文档 :return: 替换后的字符串 """ return re.sub(re_text, replace_str, text)
[ "def", "replace", "(", "self", ",", "re_text", ",", "replace_str", ",", "text", ")", ":", "return", "re", ".", "sub", "(", "re_text", ",", "replace_str", ",", "text", ")" ]
正则表达式替换 :param re_text: 正则表达式 :param replace_str: 替换字符串 :param text: 搜索文档 :return: 替换后的字符串
[ "正则表达式替换", ":", "param", "re_text", ":", "正则表达式", ":", "param", "replace_str", ":", "替换字符串", ":", "param", "text", ":", "搜索文档", ":", "return", ":", "替换后的字符串" ]
train
https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/html_parserlib.py#L53-L61
cuescience/goat
goat/matcher.py
GoatMatcher.check_match
def check_match(self, step) -> list: """Like matchers.CFParseMatcher.check_match but also add the implicit parameters from the context """ args = [] match = super().check_match(step) if match is None: return None for arg in match: args.app...
python
def check_match(self, step) -> list: """Like matchers.CFParseMatcher.check_match but also add the implicit parameters from the context """ args = [] match = super().check_match(step) if match is None: return None for arg in match: args.app...
[ "def", "check_match", "(", "self", ",", "step", ")", "->", "list", ":", "args", "=", "[", "]", "match", "=", "super", "(", ")", ".", "check_match", "(", "step", ")", "if", "match", "is", "None", ":", "return", "None", "for", "arg", "in", "match", ...
Like matchers.CFParseMatcher.check_match but also add the implicit parameters from the context
[ "Like", "matchers", ".", "CFParseMatcher", ".", "check_match", "but", "also", "add", "the", "implicit", "parameters", "from", "the", "context" ]
train
https://github.com/cuescience/goat/blob/d76f44b9ec5dc40ad33abca50830c0d7492ef152/goat/matcher.py#L52-L67
cuescience/goat
goat/matcher.py
GoatMatcher.convert
def convert(self, pattern: str) -> str: """Convert the goat step string to CFParse String""" parameters = OrderedDict() for parameter in self.signature.parameters.values(): annotation = self.convert_type_to_parse_type(parameter) parameters[parameter.name] = "{%s:%s}" % (p...
python
def convert(self, pattern: str) -> str: """Convert the goat step string to CFParse String""" parameters = OrderedDict() for parameter in self.signature.parameters.values(): annotation = self.convert_type_to_parse_type(parameter) parameters[parameter.name] = "{%s:%s}" % (p...
[ "def", "convert", "(", "self", ",", "pattern", ":", "str", ")", "->", "str", ":", "parameters", "=", "OrderedDict", "(", ")", "for", "parameter", "in", "self", ".", "signature", ".", "parameters", ".", "values", "(", ")", ":", "annotation", "=", "self"...
Convert the goat step string to CFParse String
[ "Convert", "the", "goat", "step", "string", "to", "CFParse", "String" ]
train
https://github.com/cuescience/goat/blob/d76f44b9ec5dc40ad33abca50830c0d7492ef152/goat/matcher.py#L76-L91
BioMapOrg/biomap-utils
biomap/utils/xml.py
xml_to_json
def xml_to_json(root, tag_prefix=None, on_tag={}): ''' Parses a XML element to JSON format. This is a relatively generic function parsing a XML element to JSON format. It does not guarantee any specific formal behaviour but is empirically known to "work well" with respect to the author's needs....
python
def xml_to_json(root, tag_prefix=None, on_tag={}): ''' Parses a XML element to JSON format. This is a relatively generic function parsing a XML element to JSON format. It does not guarantee any specific formal behaviour but is empirically known to "work well" with respect to the author's needs....
[ "def", "xml_to_json", "(", "root", ",", "tag_prefix", "=", "None", ",", "on_tag", "=", "{", "}", ")", ":", "def", "get_key", "(", "tag", ")", ":", "if", "tag_prefix", "is", "not", "None", ":", "return", "tag", ".", "split", "(", "tag_prefix", ")", ...
Parses a XML element to JSON format. This is a relatively generic function parsing a XML element to JSON format. It does not guarantee any specific formal behaviour but is empirically known to "work well" with respect to the author's needs. External verification of the returned results by the user ...
[ "Parses", "a", "XML", "element", "to", "JSON", "format", "." ]
train
https://github.com/BioMapOrg/biomap-utils/blob/270c5c5fc6361094a5e2f93fc2ad84c2fe9b6ce5/biomap/utils/xml.py#L1-L75
mayfield/shellish
shellish/rendering/vtml.py
beststr
def beststr(*strings): """ Test if the output device can handle the desired strings. The options should be sorted by preference. Eg. beststr(unicode, ascii). """ for x in strings: try: x.encode(sys.stdout.encoding) except UnicodeEncodeError: pass else: ...
python
def beststr(*strings): """ Test if the output device can handle the desired strings. The options should be sorted by preference. Eg. beststr(unicode, ascii). """ for x in strings: try: x.encode(sys.stdout.encoding) except UnicodeEncodeError: pass else: ...
[ "def", "beststr", "(", "*", "strings", ")", ":", "for", "x", "in", "strings", ":", "try", ":", "x", ".", "encode", "(", "sys", ".", "stdout", ".", "encoding", ")", "except", "UnicodeEncodeError", ":", "pass", "else", ":", "return", "x", "raise", "Val...
Test if the output device can handle the desired strings. The options should be sorted by preference. Eg. beststr(unicode, ascii).
[ "Test", "if", "the", "output", "device", "can", "handle", "the", "desired", "strings", ".", "The", "options", "should", "be", "sorted", "by", "preference", ".", "Eg", ".", "beststr", "(", "unicode", "ascii", ")", "." ]
train
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/rendering/vtml.py#L37-L47
mayfield/shellish
shellish/rendering/vtml.py
_add_slice
def _add_slice(seq, slc): """ Our textwrap routine deals in slices. This function will concat contiguous slices as an optimization so lookup performance is faster. It expects a sequence (probably a list) to add slice to or will extend the last slice of the sequence if it ends where the new slice begins...
python
def _add_slice(seq, slc): """ Our textwrap routine deals in slices. This function will concat contiguous slices as an optimization so lookup performance is faster. It expects a sequence (probably a list) to add slice to or will extend the last slice of the sequence if it ends where the new slice begins...
[ "def", "_add_slice", "(", "seq", ",", "slc", ")", ":", "if", "seq", "and", "seq", "[", "-", "1", "]", ".", "stop", "==", "slc", ".", "start", ":", "seq", "[", "-", "1", "]", "=", "slice", "(", "seq", "[", "-", "1", "]", ".", "start", ",", ...
Our textwrap routine deals in slices. This function will concat contiguous slices as an optimization so lookup performance is faster. It expects a sequence (probably a list) to add slice to or will extend the last slice of the sequence if it ends where the new slice begins.
[ "Our", "textwrap", "routine", "deals", "in", "slices", ".", "This", "function", "will", "concat", "contiguous", "slices", "as", "an", "optimization", "so", "lookup", "performance", "is", "faster", ".", "It", "expects", "a", "sequence", "(", "probably", "a", ...
train
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/rendering/vtml.py#L62-L70
mayfield/shellish
shellish/rendering/vtml.py
_textwrap_slices
def _textwrap_slices(text, width, strip_leading_indent=False): """ Nearly identical to textwrap.wrap except this routine is a tad bit safer in its algo that textwrap. I ran into some issues with textwrap output that make it unusable to this usecase as a baseline text wrapper. Further this utility retur...
python
def _textwrap_slices(text, width, strip_leading_indent=False): """ Nearly identical to textwrap.wrap except this routine is a tad bit safer in its algo that textwrap. I ran into some issues with textwrap output that make it unusable to this usecase as a baseline text wrapper. Further this utility retur...
[ "def", "_textwrap_slices", "(", "text", ",", "width", ",", "strip_leading_indent", "=", "False", ")", ":", "if", "not", "isinstance", "(", "text", ",", "str", ")", ":", "raise", "TypeError", "(", "\"Expected `str` type\"", ")", "chunks", "=", "(", "x", "fo...
Nearly identical to textwrap.wrap except this routine is a tad bit safer in its algo that textwrap. I ran into some issues with textwrap output that make it unusable to this usecase as a baseline text wrapper. Further this utility returns slices instead of strings. So the slices can be used to extract...
[ "Nearly", "identical", "to", "textwrap", ".", "wrap", "except", "this", "routine", "is", "a", "tad", "bit", "safer", "in", "its", "algo", "that", "textwrap", ".", "I", "ran", "into", "some", "issues", "with", "textwrap", "output", "that", "make", "it", "...
train
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/rendering/vtml.py#L73-L149
mayfield/shellish
shellish/rendering/vtml.py
vtmlrender
def vtmlrender(vtmarkup, plain=None, strict=False, vtmlparser=VTMLParser()): """ Look for vt100 markup and render vt opcodes into a VTMLBuffer. """ if isinstance(vtmarkup, VTMLBuffer): return vtmarkup.plain() if plain else vtmarkup try: vtmlparser.feed(vtmarkup) vtmlparser.close() ...
python
def vtmlrender(vtmarkup, plain=None, strict=False, vtmlparser=VTMLParser()): """ Look for vt100 markup and render vt opcodes into a VTMLBuffer. """ if isinstance(vtmarkup, VTMLBuffer): return vtmarkup.plain() if plain else vtmarkup try: vtmlparser.feed(vtmarkup) vtmlparser.close() ...
[ "def", "vtmlrender", "(", "vtmarkup", ",", "plain", "=", "None", ",", "strict", "=", "False", ",", "vtmlparser", "=", "VTMLParser", "(", ")", ")", ":", "if", "isinstance", "(", "vtmarkup", ",", "VTMLBuffer", ")", ":", "return", "vtmarkup", ".", "plain", ...
Look for vt100 markup and render vt opcodes into a VTMLBuffer.
[ "Look", "for", "vt100", "markup", "and", "render", "vt", "opcodes", "into", "a", "VTMLBuffer", "." ]
train
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/rendering/vtml.py#L554-L571
mayfield/shellish
shellish/rendering/vtml.py
vtmlprint
def vtmlprint(*values, plain=None, strict=None, **options): """ Follow normal print() signature but look for vt100 codes for richer output. """ print(*[vtmlrender(x, plain=plain, strict=strict) for x in values], **options)
python
def vtmlprint(*values, plain=None, strict=None, **options): """ Follow normal print() signature but look for vt100 codes for richer output. """ print(*[vtmlrender(x, plain=plain, strict=strict) for x in values], **options)
[ "def", "vtmlprint", "(", "*", "values", ",", "plain", "=", "None", ",", "strict", "=", "None", ",", "*", "*", "options", ")", ":", "print", "(", "*", "[", "vtmlrender", "(", "x", ",", "plain", "=", "plain", ",", "strict", "=", "strict", ")", "for...
Follow normal print() signature but look for vt100 codes for richer output.
[ "Follow", "normal", "print", "()", "signature", "but", "look", "for", "vt100", "codes", "for", "richer", "output", "." ]
train
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/rendering/vtml.py#L574-L578
mayfield/shellish
shellish/rendering/vtml.py
VTMLParser.feed
def feed(self, data): """ We need to prevent insertion of some special HTML characters (entity refs and maybe more). It's hard to prevent the state machine from blowing up with them in the data, so we temporarily replacing them with a reserved unicode value based on the PAU private spac...
python
def feed(self, data): """ We need to prevent insertion of some special HTML characters (entity refs and maybe more). It's hard to prevent the state machine from blowing up with them in the data, so we temporarily replacing them with a reserved unicode value based on the PAU private spac...
[ "def", "feed", "(", "self", ",", "data", ")", ":", "assert", "not", "self", ".", "closed", "for", "mark", ",", "special", "in", "self", ".", "escape_map", ":", "assert", "mark", "not", "in", "data", "data", "=", "data", ".", "replace", "(", "special"...
We need to prevent insertion of some special HTML characters (entity refs and maybe more). It's hard to prevent the state machine from blowing up with them in the data, so we temporarily replacing them with a reserved unicode value based on the PAU private space.
[ "We", "need", "to", "prevent", "insertion", "of", "some", "special", "HTML", "characters", "(", "entity", "refs", "and", "maybe", "more", ")", ".", "It", "s", "hard", "to", "prevent", "the", "state", "machine", "from", "blowing", "up", "with", "them", "i...
train
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/rendering/vtml.py#L163-L172
BetterWorks/djschema
djschema/introspection.py
DatabaseIntrospection.get_constraints
def get_constraints(self, cursor, table_name): """ Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Loop over the key table, collecting things as constraints # This will get PKs, FKs, and uniques, but not ...
python
def get_constraints(self, cursor, table_name): """ Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Loop over the key table, collecting things as constraints # This will get PKs, FKs, and uniques, but not ...
[ "def", "get_constraints", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "constraints", "=", "{", "}", "# Loop over the key table, collecting things as constraints", "# This will get PKs, FKs, and uniques, but not CHECK", "cursor", ".", "execute", "(", "\"\"\"\n ...
Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
[ "Retrieves", "any", "constraints", "or", "keys", "(", "unique", "pk", "fk", "check", "index", ")", "across", "one", "or", "more", "columns", "." ]
train
https://github.com/BetterWorks/djschema/blob/b9cbe89310754d7a30ec69d842d9014e9877645b/djschema/introspection.py#L147-L240
tBaxter/tango-shared-core
build/lib/tango_shared/utils/sanetize.py
clean_text
def clean_text(value, topic=False): """ Replaces "profane" words with more suitable ones. Uses bleach to strip all but whitelisted html. Converts bbcode to Markdown """ for x in PROFANITY_REPLACEMENTS: value = value.replace(x[0], x[1]) for bbset in BBCODE_REPLACEMENTS: p = r...
python
def clean_text(value, topic=False): """ Replaces "profane" words with more suitable ones. Uses bleach to strip all but whitelisted html. Converts bbcode to Markdown """ for x in PROFANITY_REPLACEMENTS: value = value.replace(x[0], x[1]) for bbset in BBCODE_REPLACEMENTS: p = r...
[ "def", "clean_text", "(", "value", ",", "topic", "=", "False", ")", ":", "for", "x", "in", "PROFANITY_REPLACEMENTS", ":", "value", "=", "value", ".", "replace", "(", "x", "[", "0", "]", ",", "x", "[", "1", "]", ")", "for", "bbset", "in", "BBCODE_RE...
Replaces "profane" words with more suitable ones. Uses bleach to strip all but whitelisted html. Converts bbcode to Markdown
[ "Replaces", "profane", "words", "with", "more", "suitable", "ones", ".", "Uses", "bleach", "to", "strip", "all", "but", "whitelisted", "html", ".", "Converts", "bbcode", "to", "Markdown" ]
train
https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/utils/sanetize.py#L133-L150
tBaxter/tango-shared-core
build/lib/tango_shared/utils/sanetize.py
is_email_simple
def is_email_simple(value): """Return True if value looks like an email address.""" # An @ must be in the middle of the value. if '@' not in value or value.startswith('@') or value.endswith('@'): return False try: p1, p2 = value.split('@') except ValueErro...
python
def is_email_simple(value): """Return True if value looks like an email address.""" # An @ must be in the middle of the value. if '@' not in value or value.startswith('@') or value.endswith('@'): return False try: p1, p2 = value.split('@') except ValueErro...
[ "def", "is_email_simple", "(", "value", ")", ":", "# An @ must be in the middle of the value.", "if", "'@'", "not", "in", "value", "or", "value", ".", "startswith", "(", "'@'", ")", "or", "value", ".", "endswith", "(", "'@'", ")", ":", "return", "False", "tr...
Return True if value looks like an email address.
[ "Return", "True", "if", "value", "looks", "like", "an", "email", "address", "." ]
train
https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/utils/sanetize.py#L153-L166
tBaxter/tango-shared-core
build/lib/tango_shared/utils/sanetize.py
convert_links
def convert_links(text, trim_url_limit=None, nofollow=False, autoescape=False): """ Finds URLs in text and attempts to handle correctly. Heavily based on django.utils.html.urlize With the additions of attempting to embed media links, particularly images. Works on http://, https://, www. links, and ...
python
def convert_links(text, trim_url_limit=None, nofollow=False, autoescape=False): """ Finds URLs in text and attempts to handle correctly. Heavily based on django.utils.html.urlize With the additions of attempting to embed media links, particularly images. Works on http://, https://, www. links, and ...
[ "def", "convert_links", "(", "text", ",", "trim_url_limit", "=", "None", ",", "nofollow", "=", "False", ",", "autoescape", "=", "False", ")", ":", "safe_input", "=", "isinstance", "(", "text", ",", "SafeData", ")", "words", "=", "word_split_re", ".", "spli...
Finds URLs in text and attempts to handle correctly. Heavily based on django.utils.html.urlize With the additions of attempting to embed media links, particularly images. Works on http://, https://, www. links, and also on links ending in one of the original seven gTLDs (.com, .edu, .gov, .int, .mil, ....
[ "Finds", "URLs", "in", "text", "and", "attempts", "to", "handle", "correctly", ".", "Heavily", "based", "on", "django", ".", "utils", ".", "html", ".", "urlize", "With", "the", "additions", "of", "attempting", "to", "embed", "media", "links", "particularly",...
train
https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/utils/sanetize.py#L169-L254
tBaxter/tango-shared-core
build/lib/tango_shared/utils/sanetize.py
format_text
def format_text(value): """ Takes cleaned text and creates HTML-formatted, web-friendly version. - converts links to images and video to actual media objects. - Make raw links clickable (and truncated, if necessary). - Converts smilies and markdown to valid HTML. _ Bleaches output (again) to cat...
python
def format_text(value): """ Takes cleaned text and creates HTML-formatted, web-friendly version. - converts links to images and video to actual media objects. - Make raw links clickable (and truncated, if necessary). - Converts smilies and markdown to valid HTML. _ Bleaches output (again) to cat...
[ "def", "format_text", "(", "value", ")", ":", "# convert media links", "value", "=", "convert_links", "(", "value", ")", "value", "=", "urlizetrunc", "(", "value", ",", "30", ")", "for", "x", "in", "EMOTICON_REPLACEMENTS", ":", "value", "=", "value", ".", ...
Takes cleaned text and creates HTML-formatted, web-friendly version. - converts links to images and video to actual media objects. - Make raw links clickable (and truncated, if necessary). - Converts smilies and markdown to valid HTML. _ Bleaches output (again) to catch any stray HTML inserted by markdo...
[ "Takes", "cleaned", "text", "and", "creates", "HTML", "-", "formatted", "web", "-", "friendly", "version", ".", "-", "converts", "links", "to", "images", "and", "video", "to", "actual", "media", "objects", ".", "-", "Make", "raw", "links", "clickable", "("...
train
https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/utils/sanetize.py#L257-L278
shreyaspotnis/rampage
rampage/widgets/RampViewer.py
RampViewer.loadSettings
def loadSettings(self): """Load window state from self.settings""" self.settings.beginGroup('rampviewer') geometry = self.settings.value('geometry').toByteArray() self.settings.endGroup() self.restoreGeometry(geometry)
python
def loadSettings(self): """Load window state from self.settings""" self.settings.beginGroup('rampviewer') geometry = self.settings.value('geometry').toByteArray() self.settings.endGroup() self.restoreGeometry(geometry)
[ "def", "loadSettings", "(", "self", ")", ":", "self", ".", "settings", ".", "beginGroup", "(", "'rampviewer'", ")", "geometry", "=", "self", ".", "settings", ".", "value", "(", "'geometry'", ")", ".", "toByteArray", "(", ")", "self", ".", "settings", "."...
Load window state from self.settings
[ "Load", "window", "state", "from", "self", ".", "settings" ]
train
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/widgets/RampViewer.py#L96-L102
shreyaspotnis/rampage
rampage/widgets/RampViewer.py
RampViewer.saveSettings
def saveSettings(self): """Save window state to self.settings.""" self.settings.beginGroup('rampviewer') self.settings.setValue('geometry', self.saveGeometry()) self.settings.endGroup()
python
def saveSettings(self): """Save window state to self.settings.""" self.settings.beginGroup('rampviewer') self.settings.setValue('geometry', self.saveGeometry()) self.settings.endGroup()
[ "def", "saveSettings", "(", "self", ")", ":", "self", ".", "settings", ".", "beginGroup", "(", "'rampviewer'", ")", "self", ".", "settings", ".", "setValue", "(", "'geometry'", ",", "self", ".", "saveGeometry", "(", ")", ")", "self", ".", "settings", "."...
Save window state to self.settings.
[ "Save", "window", "state", "to", "self", ".", "settings", "." ]
train
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/widgets/RampViewer.py#L105-L109
mrstephenneal/dirutility
dirutility/multiprocess.py
pool_process
def pool_process(func, iterable, cpus=cpu_count(), return_vals=False, cpu_reduction=0, progress_bar=False): """ Multiprocessing helper function for performing looped operation using multiple processors. :param func: Function to call :param iterable: Iterable object to perform each function on :para...
python
def pool_process(func, iterable, cpus=cpu_count(), return_vals=False, cpu_reduction=0, progress_bar=False): """ Multiprocessing helper function for performing looped operation using multiple processors. :param func: Function to call :param iterable: Iterable object to perform each function on :para...
[ "def", "pool_process", "(", "func", ",", "iterable", ",", "cpus", "=", "cpu_count", "(", ")", ",", "return_vals", "=", "False", ",", "cpu_reduction", "=", "0", ",", "progress_bar", "=", "False", ")", ":", "with", "Pool", "(", "cpus", "-", "abs", "(", ...
Multiprocessing helper function for performing looped operation using multiple processors. :param func: Function to call :param iterable: Iterable object to perform each function on :param cpus: Number of cpu cores, defaults to system's cpu count :param return_vals: Bool, returns output values when Tru...
[ "Multiprocessing", "helper", "function", "for", "performing", "looped", "operation", "using", "multiple", "processors", "." ]
train
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/multiprocess.py#L6-L38
mrstephenneal/dirutility
dirutility/multiprocess.py
PoolProcess.map
def map(self): """Perform a function on every item in an iterable.""" with Pool(self.cpu_count) as pool: pool.map(self._func, self._iterable) pool.close() return True
python
def map(self): """Perform a function on every item in an iterable.""" with Pool(self.cpu_count) as pool: pool.map(self._func, self._iterable) pool.close() return True
[ "def", "map", "(", "self", ")", ":", "with", "Pool", "(", "self", ".", "cpu_count", ")", "as", "pool", ":", "pool", ".", "map", "(", "self", ".", "_func", ",", "self", ".", "_iterable", ")", "pool", ".", "close", "(", ")", "return", "True" ]
Perform a function on every item in an iterable.
[ "Perform", "a", "function", "on", "every", "item", "in", "an", "iterable", "." ]
train
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/multiprocess.py#L58-L63
mrstephenneal/dirutility
dirutility/multiprocess.py
PoolProcess.map_return
def map_return(self): """Perform a function on every item and return a list of yield values.""" with Pool(self.cpu_count) as pool: vals = pool.map(self._func, self._iterable) pool.close() return vals
python
def map_return(self): """Perform a function on every item and return a list of yield values.""" with Pool(self.cpu_count) as pool: vals = pool.map(self._func, self._iterable) pool.close() return vals
[ "def", "map_return", "(", "self", ")", ":", "with", "Pool", "(", "self", ".", "cpu_count", ")", "as", "pool", ":", "vals", "=", "pool", ".", "map", "(", "self", ".", "_func", ",", "self", ".", "_iterable", ")", "pool", ".", "close", "(", ")", "re...
Perform a function on every item and return a list of yield values.
[ "Perform", "a", "function", "on", "every", "item", "and", "return", "a", "list", "of", "yield", "values", "." ]
train
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/multiprocess.py#L65-L70
mrstephenneal/dirutility
dirutility/multiprocess.py
PoolProcess.map_tqdm
def map_tqdm(self): """ Perform a function on every item while displaying a progress bar. :return: A list of yielded values """ with Pool(self.cpu_count) as pool: vals = [v for v in tqdm(pool.imap_unordered(self._func, self._iterable), total=len(self._iterable))] ...
python
def map_tqdm(self): """ Perform a function on every item while displaying a progress bar. :return: A list of yielded values """ with Pool(self.cpu_count) as pool: vals = [v for v in tqdm(pool.imap_unordered(self._func, self._iterable), total=len(self._iterable))] ...
[ "def", "map_tqdm", "(", "self", ")", ":", "with", "Pool", "(", "self", ".", "cpu_count", ")", "as", "pool", ":", "vals", "=", "[", "v", "for", "v", "in", "tqdm", "(", "pool", ".", "imap_unordered", "(", "self", ".", "_func", ",", "self", ".", "_i...
Perform a function on every item while displaying a progress bar. :return: A list of yielded values
[ "Perform", "a", "function", "on", "every", "item", "while", "displaying", "a", "progress", "bar", "." ]
train
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/multiprocess.py#L72-L81
PonteIneptique/collatinus-python
pycollatinus/modele.py
Modele.clone
def clone(self, d): """ Crée une Désinence copiée sur la désinence d. :param d: Desinence à copier :type d: Desinence :return: Désinence copiée sur la désinence d. :rtype: Desinence """ return Desinence(d.grq(), d.morphoNum(), d.numRad(), self)
python
def clone(self, d): """ Crée une Désinence copiée sur la désinence d. :param d: Desinence à copier :type d: Desinence :return: Désinence copiée sur la désinence d. :rtype: Desinence """ return Desinence(d.grq(), d.morphoNum(), d.numRad(), self)
[ "def", "clone", "(", "self", ",", "d", ")", ":", "return", "Desinence", "(", "d", ".", "grq", "(", ")", ",", "d", ".", "morphoNum", "(", ")", ",", "d", ".", "numRad", "(", ")", ",", "self", ")" ]
Crée une Désinence copiée sur la désinence d. :param d: Desinence à copier :type d: Desinence :return: Désinence copiée sur la désinence d. :rtype: Desinence
[ "Crée", "une", "Désinence", "copiée", "sur", "la", "désinence", "d", "." ]
train
https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/modele.py#L160-L168
PonteIneptique/collatinus-python
pycollatinus/modele.py
Modele.desinences
def desinences(self, d=None): """ Renvoie la liste des désinence de morpho d du modèle. :param d: Identifant de morphologie :type d: int :return: Liste des désinence de morpho d du modèle ou toutes les désinences du modèle (Applaties en python, doute sur original) :rtype: list o...
python
def desinences(self, d=None): """ Renvoie la liste des désinence de morpho d du modèle. :param d: Identifant de morphologie :type d: int :return: Liste des désinence de morpho d du modèle ou toutes les désinences du modèle (Applaties en python, doute sur original) :rtype: list o...
[ "def", "desinences", "(", "self", ",", "d", "=", "None", ")", ":", "if", "d", ":", "return", "self", ".", "_desinences", "[", "d", "]", "return", "[", "x", "for", "morpho_values", "in", "self", ".", "_desinences", ".", "values", "(", ")", "for", "x...
Renvoie la liste des désinence de morpho d du modèle. :param d: Identifant de morphologie :type d: int :return: Liste des désinence de morpho d du modèle ou toutes les désinences du modèle (Applaties en python, doute sur original) :rtype: list of Desinence
[ "Renvoie", "la", "liste", "des", "désinence", "de", "morpho", "d", "du", "modèle", "." ]
train
https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/modele.py#L180-L190
PonteIneptique/collatinus-python
pycollatinus/modele.py
Modele.estUn
def estUn(self, m): """ Renvoie True si le modèle se nomme m, si l'un de ses ancêtre se nomme m :param m: Nom de modele :type m: str :return: si le modèle se nomme m, si l'un de ses ancêtre se nomme m :rtype: bool """ if self._gr == m: return True ...
python
def estUn(self, m): """ Renvoie True si le modèle se nomme m, si l'un de ses ancêtre se nomme m :param m: Nom de modele :type m: str :return: si le modèle se nomme m, si l'un de ses ancêtre se nomme m :rtype: bool """ if self._gr == m: return True ...
[ "def", "estUn", "(", "self", ",", "m", ")", ":", "if", "self", ".", "_gr", "==", "m", ":", "return", "True", "if", "self", ".", "_pere", "is", "not", "None", ":", "return", "self", ".", "_pere", ".", "estUn", "(", "m", ")", "return", "False" ]
Renvoie True si le modèle se nomme m, si l'un de ses ancêtre se nomme m :param m: Nom de modele :type m: str :return: si le modèle se nomme m, si l'un de ses ancêtre se nomme m :rtype: bool
[ "Renvoie", "True", "si", "le", "modèle", "se", "nomme", "m", "si", "l", "un", "de", "ses", "ancêtre", "se", "nomme", "m" ]
train
https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/modele.py#L192-L204
tshlabs/tunic
tunic/core.py
split_by_line
def split_by_line(content): """Split the given content into a list of items by newline. Both \r\n and \n are supported. This is done since it seems that TTY devices on POSIX systems use \r\n for newlines in some instances. If the given content is an empty string or a string of only whitespace,...
python
def split_by_line(content): """Split the given content into a list of items by newline. Both \r\n and \n are supported. This is done since it seems that TTY devices on POSIX systems use \r\n for newlines in some instances. If the given content is an empty string or a string of only whitespace,...
[ "def", "split_by_line", "(", "content", ")", ":", "# Make sure we don't end up splitting a string with", "# just a single trailing \\n or \\r\\n into multiple parts.", "stripped", "=", "content", ".", "strip", "(", ")", "if", "not", "stripped", ":", "return", "[", "]", "i...
Split the given content into a list of items by newline. Both \r\n and \n are supported. This is done since it seems that TTY devices on POSIX systems use \r\n for newlines in some instances. If the given content is an empty string or a string of only whitespace, an empty list will be returned. If...
[ "Split", "the", "given", "content", "into", "a", "list", "of", "items", "by", "newline", "." ]
train
https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/core.py#L67-L96
tshlabs/tunic
tunic/core.py
get_release_id
def get_release_id(version=None): """Get a unique, time-based identifier for a deployment that optionally, also includes some sort of version number or release. If a version is supplied, the release ID will be of the form '$timestamp-$version'. For example: >>> get_release_id(version='1.4.1') ...
python
def get_release_id(version=None): """Get a unique, time-based identifier for a deployment that optionally, also includes some sort of version number or release. If a version is supplied, the release ID will be of the form '$timestamp-$version'. For example: >>> get_release_id(version='1.4.1') ...
[ "def", "get_release_id", "(", "version", "=", "None", ")", ":", "# pylint: disable=invalid-name", "ts", "=", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "RELEASE_DATE_FMT", ")", "if", "version", "is", "None", ":", "return", "ts", "return", "'{...
Get a unique, time-based identifier for a deployment that optionally, also includes some sort of version number or release. If a version is supplied, the release ID will be of the form '$timestamp-$version'. For example: >>> get_release_id(version='1.4.1') '20140214231159-1.4.1' If the ve...
[ "Get", "a", "unique", "time", "-", "based", "identifier", "for", "a", "deployment", "that", "optionally", "also", "includes", "some", "sort", "of", "version", "number", "or", "release", "." ]
train
https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/core.py#L147-L176
tshlabs/tunic
tunic/core.py
try_repeatedly
def try_repeatedly(method, max_retries=None, delay=None): """Execute the given Fabric call, retrying up to a certain number of times. The method is expected to be wrapper around a Fabric :func:`run` or :func:`sudo` call that returns the results of that call. The call will be executed at least once, and...
python
def try_repeatedly(method, max_retries=None, delay=None): """Execute the given Fabric call, retrying up to a certain number of times. The method is expected to be wrapper around a Fabric :func:`run` or :func:`sudo` call that returns the results of that call. The call will be executed at least once, and...
[ "def", "try_repeatedly", "(", "method", ",", "max_retries", "=", "None", ",", "delay", "=", "None", ")", ":", "max_retries", "=", "max_retries", "if", "max_retries", "is", "not", "None", "else", "1", "delay", "=", "delay", "if", "delay", "is", "not", "No...
Execute the given Fabric call, retrying up to a certain number of times. The method is expected to be wrapper around a Fabric :func:`run` or :func:`sudo` call that returns the results of that call. The call will be executed at least once, and up to :code:`max_retries` additional times until the call execut...
[ "Execute", "the", "given", "Fabric", "call", "retrying", "up", "to", "a", "certain", "number", "of", "times", "." ]
train
https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/core.py#L219-L249
tshlabs/tunic
tunic/core.py
ReleaseManager.get_current_release
def get_current_release(self): """Get the release ID of the "current" deployment, None if there is no current deployment. This method performs one network operation. :return: Get the current release ID :rtype: str """ current = self._runner.run("readlink '{0}'"....
python
def get_current_release(self): """Get the release ID of the "current" deployment, None if there is no current deployment. This method performs one network operation. :return: Get the current release ID :rtype: str """ current = self._runner.run("readlink '{0}'"....
[ "def", "get_current_release", "(", "self", ")", ":", "current", "=", "self", ".", "_runner", ".", "run", "(", "\"readlink '{0}'\"", ".", "format", "(", "self", ".", "_current", ")", ")", "if", "current", ".", "failed", ":", "return", "None", "return", "o...
Get the release ID of the "current" deployment, None if there is no current deployment. This method performs one network operation. :return: Get the current release ID :rtype: str
[ "Get", "the", "release", "ID", "of", "the", "current", "deployment", "None", "if", "there", "is", "no", "current", "deployment", "." ]
train
https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/core.py#L304-L316
tshlabs/tunic
tunic/core.py
ReleaseManager.get_previous_release
def get_previous_release(self): """Get the release ID of the deployment immediately before the "current" deployment, ``None`` if no previous release could be determined. This method performs two network operations. :return: The release ID of the release previous to the ...
python
def get_previous_release(self): """Get the release ID of the deployment immediately before the "current" deployment, ``None`` if no previous release could be determined. This method performs two network operations. :return: The release ID of the release previous to the ...
[ "def", "get_previous_release", "(", "self", ")", ":", "releases", "=", "self", ".", "get_releases", "(", ")", "if", "not", "releases", ":", "return", "None", "current", "=", "self", ".", "get_current_release", "(", ")", "if", "not", "current", ":", "return...
Get the release ID of the deployment immediately before the "current" deployment, ``None`` if no previous release could be determined. This method performs two network operations. :return: The release ID of the release previous to the "current" release. :rtype: str
[ "Get", "the", "release", "ID", "of", "the", "deployment", "immediately", "before", "the", "current", "deployment", "None", "if", "no", "previous", "release", "could", "be", "determined", "." ]
train
https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/core.py#L329-L356
tshlabs/tunic
tunic/core.py
ReleaseManager.cleanup
def cleanup(self, keep=5): """Remove all but the ``keep`` most recent releases. If any of the candidates for deletion are pointed to by the 'current' symlink, they will not be deleted. This method performs N + 2 network operations where N is the number of old releases that are ...
python
def cleanup(self, keep=5): """Remove all but the ``keep`` most recent releases. If any of the candidates for deletion are pointed to by the 'current' symlink, they will not be deleted. This method performs N + 2 network operations where N is the number of old releases that are ...
[ "def", "cleanup", "(", "self", ",", "keep", "=", "5", ")", ":", "releases", "=", "self", ".", "get_releases", "(", ")", "current_version", "=", "self", ".", "get_current_release", "(", ")", "to_delete", "=", "[", "version", "for", "version", "in", "relea...
Remove all but the ``keep`` most recent releases. If any of the candidates for deletion are pointed to by the 'current' symlink, they will not be deleted. This method performs N + 2 network operations where N is the number of old releases that are cleaned up. :param int keep: ...
[ "Remove", "all", "but", "the", "keep", "most", "recent", "releases", "." ]
train
https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/core.py#L387-L403
tshlabs/tunic
tunic/core.py
ProjectSetup.setup_directories
def setup_directories(self, use_sudo=True): """Create the minimal required directories for deploying multiple releases of a project. By default, creation of directories is done with the Fabric ``sudo`` function but can optionally use the ``run`` function. This method performs o...
python
def setup_directories(self, use_sudo=True): """Create the minimal required directories for deploying multiple releases of a project. By default, creation of directories is done with the Fabric ``sudo`` function but can optionally use the ``run`` function. This method performs o...
[ "def", "setup_directories", "(", "self", ",", "use_sudo", "=", "True", ")", ":", "runner", "=", "self", ".", "_runner", ".", "sudo", "if", "use_sudo", "else", "self", ".", "_runner", ".", "run", "runner", "(", "\"mkdir -p '{0}'\"", ".", "format", "(", "s...
Create the minimal required directories for deploying multiple releases of a project. By default, creation of directories is done with the Fabric ``sudo`` function but can optionally use the ``run`` function. This method performs one network operation. :param bool use_sudo: If...
[ "Create", "the", "minimal", "required", "directories", "for", "deploying", "multiple", "releases", "of", "a", "project", "." ]
train
https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/core.py#L436-L450
tshlabs/tunic
tunic/core.py
ProjectSetup.set_permissions
def set_permissions( self, owner, file_perms=PERMS_FILE_DEFAULT, dir_perms=PERMS_DIR_DEFAULT, use_sudo=True): """Set the owner and permissions of the code deploy. The owner will be set recursively for the entire code deploy. The directory permissions will be set on only...
python
def set_permissions( self, owner, file_perms=PERMS_FILE_DEFAULT, dir_perms=PERMS_DIR_DEFAULT, use_sudo=True): """Set the owner and permissions of the code deploy. The owner will be set recursively for the entire code deploy. The directory permissions will be set on only...
[ "def", "set_permissions", "(", "self", ",", "owner", ",", "file_perms", "=", "PERMS_FILE_DEFAULT", ",", "dir_perms", "=", "PERMS_DIR_DEFAULT", ",", "use_sudo", "=", "True", ")", ":", "runner", "=", "self", ".", "_runner", ".", "sudo", "if", "use_sudo", "else...
Set the owner and permissions of the code deploy. The owner will be set recursively for the entire code deploy. The directory permissions will be set on only the base of the code deploy and the releases directory. The file permissions will be set recursively for the entire code deploy....
[ "Set", "the", "owner", "and", "permissions", "of", "the", "code", "deploy", "." ]
train
https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/core.py#L452-L500
frigg/frigg-worker
frigg_worker/jobs.py
Job.create_pending_tasks
def create_pending_tasks(self): """ Creates pending task results in a dict on self.result with task string as key. It will also create a list on self.tasks that is used to make sure the serialization of the results creates a correctly ordered list. """ for task in self.se...
python
def create_pending_tasks(self): """ Creates pending task results in a dict on self.result with task string as key. It will also create a list on self.tasks that is used to make sure the serialization of the results creates a correctly ordered list. """ for task in self.se...
[ "def", "create_pending_tasks", "(", "self", ")", ":", "for", "task", "in", "self", ".", "settings", ".", "services", ":", "task", "=", "self", ".", "create_service_command", "(", "task", ")", "self", ".", "service_tasks", ".", "append", "(", "task", ")", ...
Creates pending task results in a dict on self.result with task string as key. It will also create a list on self.tasks that is used to make sure the serialization of the results creates a correctly ordered list.
[ "Creates", "pending", "task", "results", "in", "a", "dict", "on", "self", ".", "result", "with", "task", "string", "as", "key", ".", "It", "will", "also", "create", "a", "list", "on", "self", ".", "tasks", "that", "is", "used", "to", "make", "sure", ...
train
https://github.com/frigg/frigg-worker/blob/8c215cd8f5a27ff9f5a4fedafe93d2ef0fbca86c/frigg_worker/jobs.py#L212-L229
frigg/frigg-worker
frigg_worker/jobs.py
Job.create_pending_after_task
def create_pending_after_task(self): """ Creates pending task results in a dict on self.after_result with task string as key. It will also create a list on self.tasks that is used to make sure the serialization of the results creates a correctly ordered list. """ for task...
python
def create_pending_after_task(self): """ Creates pending task results in a dict on self.after_result with task string as key. It will also create a list on self.tasks that is used to make sure the serialization of the results creates a correctly ordered list. """ for task...
[ "def", "create_pending_after_task", "(", "self", ")", ":", "for", "task", "in", "self", ".", "settings", ".", "tasks", "[", "self", ".", "after_tasks_key", "]", ":", "self", ".", "after_tasks", ".", "append", "(", "task", ")", "self", ".", "after_results",...
Creates pending task results in a dict on self.after_result with task string as key. It will also create a list on self.tasks that is used to make sure the serialization of the results creates a correctly ordered list.
[ "Creates", "pending", "task", "results", "in", "a", "dict", "on", "self", ".", "after_result", "with", "task", "string", "as", "key", ".", "It", "will", "also", "create", "a", "list", "on", "self", ".", "tasks", "that", "is", "used", "to", "make", "sur...
train
https://github.com/frigg/frigg-worker/blob/8c215cd8f5a27ff9f5a4fedafe93d2ef0fbca86c/frigg_worker/jobs.py#L231-L239
scivision/histutils
histutils/camclass.py
Cam.arbanglemap
def arbanglemap(self): ''' here's the center angle of each pixel ( + then - to go from biggest to smallest angle) (e.g. 94.5 deg to 85.5 deg. -- sweeping left to right) ''' # raySpacingDeg = self.arbfov / self.nCutPix maxAng = self.boresightEl + self.arbfov / 2 m...
python
def arbanglemap(self): ''' here's the center angle of each pixel ( + then - to go from biggest to smallest angle) (e.g. 94.5 deg to 85.5 deg. -- sweeping left to right) ''' # raySpacingDeg = self.arbfov / self.nCutPix maxAng = self.boresightEl + self.arbfov / 2 m...
[ "def", "arbanglemap", "(", "self", ")", ":", "# raySpacingDeg = self.arbfov / self.nCutPix", "maxAng", "=", "self", ".", "boresightEl", "+", "self", ".", "arbfov", "/", "2", "minAng", "=", "self", ".", "boresightEl", "-", "self", ".", "arbfov", "/", "2", "an...
here's the center angle of each pixel ( + then - to go from biggest to smallest angle) (e.g. 94.5 deg to 85.5 deg. -- sweeping left to right)
[ "here", "s", "the", "center", "angle", "of", "each", "pixel", "(", "+", "then", "-", "to", "go", "from", "biggest", "to", "smallest", "angle", ")", "(", "e", ".", "g", ".", "94", ".", "5", "deg", "to", "85", ".", "5", "deg", ".", "--", "sweepin...
train
https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/camclass.py#L272-L282
scivision/histutils
histutils/camclass.py
Cam.doorient
def doorient(self): """ NOTE: we need to retrieve values in case no modifications are done. (since we'd get a closed h5py handle) """ assert self.cal1Dfn.is_file( ), 'please specify filename for each camera under [cam]/cal1Dname: in .ini file {}'.format(self.cal1Dfn) ...
python
def doorient(self): """ NOTE: we need to retrieve values in case no modifications are done. (since we'd get a closed h5py handle) """ assert self.cal1Dfn.is_file( ), 'please specify filename for each camera under [cam]/cal1Dname: in .ini file {}'.format(self.cal1Dfn) ...
[ "def", "doorient", "(", "self", ")", ":", "assert", "self", ".", "cal1Dfn", ".", "is_file", "(", ")", ",", "'please specify filename for each camera under [cam]/cal1Dname: in .ini file {}'", ".", "format", "(", "self", ".", "cal1Dfn", ")", "with", "h5py", ".", "F...
NOTE: we need to retrieve values in case no modifications are done. (since we'd get a closed h5py handle)
[ "NOTE", ":", "we", "need", "to", "retrieve", "values", "in", "case", "no", "modifications", "are", "done", ".", "(", "since", "we", "d", "get", "a", "closed", "h5py", "handle", ")" ]
train
https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/camclass.py#L333-L382
webadmin87/midnight
midnight_news/templatetags/midnight_news.py
show_news_line
def show_news_line(slug=None, limit=3, **kwargs): """ Отображает список последних новостей Пример использования:: {% show_news_line 'news_section_slug' 3 class='news-class' %} :param slug: символьный код категории новостей, если не задан фильтрация по категории не происходит :param limit:...
python
def show_news_line(slug=None, limit=3, **kwargs): """ Отображает список последних новостей Пример использования:: {% show_news_line 'news_section_slug' 3 class='news-class' %} :param slug: символьный код категории новостей, если не задан фильтрация по категории не происходит :param limit:...
[ "def", "show_news_line", "(", "slug", "=", "None", ",", "limit", "=", "3", ",", "*", "*", "kwargs", ")", ":", "if", "slug", "is", "None", ":", "section", "=", "None", "q", "=", "News", ".", "objects", ".", "published", "(", ")", "else", ":", "sec...
Отображает список последних новостей Пример использования:: {% show_news_line 'news_section_slug' 3 class='news-class' %} :param slug: символьный код категории новостей, если не задан фильтрация по категории не происходит :param limit: количество выводимых новостей :param kwargs: html атрибут...
[ "Отображает", "список", "последних", "новостей" ]
train
https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_news/templatetags/midnight_news.py#L7-L30
privacee/freelan-configurator
freelan_configurator/freelan_cmd.py
load_config
def load_config(): '''try loading config file from a default directory''' cfg_path = '/usr/local/etc/freelan' cfg_file = 'freelan.cfg' if not os.path.isdir(cfg_path): print("Can not find default freelan config directory.") return cfg_file_path = os.path.join(cfg_path,cfg_file) ...
python
def load_config(): '''try loading config file from a default directory''' cfg_path = '/usr/local/etc/freelan' cfg_file = 'freelan.cfg' if not os.path.isdir(cfg_path): print("Can not find default freelan config directory.") return cfg_file_path = os.path.join(cfg_path,cfg_file) ...
[ "def", "load_config", "(", ")", ":", "cfg_path", "=", "'/usr/local/etc/freelan'", "cfg_file", "=", "'freelan.cfg'", "if", "not", "os", ".", "path", ".", "isdir", "(", "cfg_path", ")", ":", "print", "(", "\"Can not find default freelan config directory.\"", ")", "r...
try loading config file from a default directory
[ "try", "loading", "config", "file", "from", "a", "default", "directory" ]
train
https://github.com/privacee/freelan-configurator/blob/7c070f8958454792f870ef0d195a7f5da36edb5a/freelan_configurator/freelan_cmd.py#L14-L29
privacee/freelan-configurator
freelan_configurator/freelan_cmd.py
write_config
def write_config(cfg): '''try writing config file to a default directory''' cfg_path = '/usr/local/etc/freelan' cfg_file = 'freelan_TEST.cfg' cfg_lines = [] if not isinstance(cfg, FreelanCFG): if not isinstance(cfg, (list, tuple)): print("Freelan write input can not be processe...
python
def write_config(cfg): '''try writing config file to a default directory''' cfg_path = '/usr/local/etc/freelan' cfg_file = 'freelan_TEST.cfg' cfg_lines = [] if not isinstance(cfg, FreelanCFG): if not isinstance(cfg, (list, tuple)): print("Freelan write input can not be processe...
[ "def", "write_config", "(", "cfg", ")", ":", "cfg_path", "=", "'/usr/local/etc/freelan'", "cfg_file", "=", "'freelan_TEST.cfg'", "cfg_lines", "=", "[", "]", "if", "not", "isinstance", "(", "cfg", ",", "FreelanCFG", ")", ":", "if", "not", "isinstance", "(", "...
try writing config file to a default directory
[ "try", "writing", "config", "file", "to", "a", "default", "directory" ]
train
https://github.com/privacee/freelan-configurator/blob/7c070f8958454792f870ef0d195a7f5da36edb5a/freelan_configurator/freelan_cmd.py#L76-L106
DecBayComp/RWA-python
rwa/sequence.py
SequenceHandling.poke_array
def poke_array(self, store, name, elemtype, elements, container, visited, _stack): """abstract method""" raise NotImplementedError
python
def poke_array(self, store, name, elemtype, elements, container, visited, _stack): """abstract method""" raise NotImplementedError
[ "def", "poke_array", "(", "self", ",", "store", ",", "name", ",", "elemtype", ",", "elements", ",", "container", ",", "visited", ",", "_stack", ")", ":", "raise", "NotImplementedError" ]
abstract method
[ "abstract", "method" ]
train
https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/sequence.py#L89-L91
pyvec/pyvodb
pyvodb/cli/videometadata.py
cfgdump
def cfgdump(path, config): """Create output directory path and output there the config.yaml file.""" dump = yaml_dump(config) if not os.path.exists(path): os.makedirs(path) with open(os.path.join(path, 'config.yaml'), 'w') as outf: outf.write(dump) print(dump)
python
def cfgdump(path, config): """Create output directory path and output there the config.yaml file.""" dump = yaml_dump(config) if not os.path.exists(path): os.makedirs(path) with open(os.path.join(path, 'config.yaml'), 'w') as outf: outf.write(dump) print(dump)
[ "def", "cfgdump", "(", "path", ",", "config", ")", ":", "dump", "=", "yaml_dump", "(", "config", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "with", "open", "(", "os", ".", ...
Create output directory path and output there the config.yaml file.
[ "Create", "output", "directory", "path", "and", "output", "there", "the", "config", ".", "yaml", "file", "." ]
train
https://github.com/pyvec/pyvodb/blob/07183333df26eb12c5c2b98802cde3fb3a6c1339/pyvodb/cli/videometadata.py#L11-L18
pyvec/pyvodb
pyvodb/cli/videometadata.py
videometadata
def videometadata(ctx, city, date, outpath): """Generate metadata for video records. city: The meetup series. \b date: The date. May be: - YYYY-MM-DD or YY-MM-DD (e.g. 2015-08-27) - YYYY-MM or YY-MM (e.g. 2015-08) - MM (e.g. 08): the given month in the current year - pN...
python
def videometadata(ctx, city, date, outpath): """Generate metadata for video records. city: The meetup series. \b date: The date. May be: - YYYY-MM-DD or YY-MM-DD (e.g. 2015-08-27) - YYYY-MM or YY-MM (e.g. 2015-08) - MM (e.g. 08): the given month in the current year - pN...
[ "def", "videometadata", "(", "ctx", ",", "city", ",", "date", ",", "outpath", ")", ":", "db", "=", "ctx", ".", "obj", "[", "'db'", "]", "today", "=", "ctx", ".", "obj", "[", "'now'", "]", ".", "date", "(", ")", "event", "=", "cliutil", ".", "ge...
Generate metadata for video records. city: The meetup series. \b date: The date. May be: - YYYY-MM-DD or YY-MM-DD (e.g. 2015-08-27) - YYYY-MM or YY-MM (e.g. 2015-08) - MM (e.g. 08): the given month in the current year - pN (e.g. p1): show the N-th last meetup
[ "Generate", "metadata", "for", "video", "records", "." ]
train
https://github.com/pyvec/pyvodb/blob/07183333df26eb12c5c2b98802cde3fb3a6c1339/pyvodb/cli/videometadata.py#L26-L73
briancappello/flask-sqlalchemy-bundle
flask_sqlalchemy_bundle/meta/model_meta_options.py
MetaOption.get_value
def get_value(self, meta, base_model_meta, mcs_args: McsArgs): """ :param meta: the class Meta (if any) from the user's model (NOTE: this will be a plain object, NOT an instance of ModelMetaOptions) :param base_model_meta: the ModelMetaOptions (if any) from the base class...
python
def get_value(self, meta, base_model_meta, mcs_args: McsArgs): """ :param meta: the class Meta (if any) from the user's model (NOTE: this will be a plain object, NOT an instance of ModelMetaOptions) :param base_model_meta: the ModelMetaOptions (if any) from the base class...
[ "def", "get_value", "(", "self", ",", "meta", ",", "base_model_meta", ",", "mcs_args", ":", "McsArgs", ")", ":", "value", "=", "self", ".", "default", "if", "self", ".", "inherit", "and", "base_model_meta", "is", "not", "None", ":", "value", "=", "getatt...
:param meta: the class Meta (if any) from the user's model (NOTE: this will be a plain object, NOT an instance of ModelMetaOptions) :param base_model_meta: the ModelMetaOptions (if any) from the base class of the user's model :param mcs_args: the McsArgs for the user's model clas...
[ ":", "param", "meta", ":", "the", "class", "Meta", "(", "if", "any", ")", "from", "the", "user", "s", "model", "(", "NOTE", ":", "this", "will", "be", "a", "plain", "object", "NOT", "an", "instance", "of", "ModelMetaOptions", ")", ":", "param", "base...
train
https://github.com/briancappello/flask-sqlalchemy-bundle/blob/8150896787907ef0001839b5a6ef303edccb9b6c/flask_sqlalchemy_bundle/meta/model_meta_options.py#L21-L34
anjos/rrbob
rr/database.py
split_data
def split_data(data, subset, splits): '''Returns the data for a given protocol ''' return dict([(k, data[k][splits[subset]]) for k in data])
python
def split_data(data, subset, splits): '''Returns the data for a given protocol ''' return dict([(k, data[k][splits[subset]]) for k in data])
[ "def", "split_data", "(", "data", ",", "subset", ",", "splits", ")", ":", "return", "dict", "(", "[", "(", "k", ",", "data", "[", "k", "]", "[", "splits", "[", "subset", "]", "]", ")", "for", "k", "in", "data", "]", ")" ]
Returns the data for a given protocol
[ "Returns", "the", "data", "for", "a", "given", "protocol" ]
train
https://github.com/anjos/rrbob/blob/d32d35bab2aa2698d3caa923fd02afb6d67f3235/rr/database.py#L37-L41
anjos/rrbob
rr/database.py
get
def get(protocol, subset, classes=CLASSES, variables=VARIABLES): '''Returns the data subset given a particular protocol Parameters protocol (string): one of the valid protocols supported by this interface subset (string): one of 'train' or 'test' classes (list of string): a list of strings containi...
python
def get(protocol, subset, classes=CLASSES, variables=VARIABLES): '''Returns the data subset given a particular protocol Parameters protocol (string): one of the valid protocols supported by this interface subset (string): one of 'train' or 'test' classes (list of string): a list of strings containi...
[ "def", "get", "(", "protocol", ",", "subset", ",", "classes", "=", "CLASSES", ",", "variables", "=", "VARIABLES", ")", ":", "retval", "=", "split_data", "(", "bob", ".", "db", ".", "iris", ".", "data", "(", ")", ",", "subset", ",", "PROTOCOLS", "[", ...
Returns the data subset given a particular protocol Parameters protocol (string): one of the valid protocols supported by this interface subset (string): one of 'train' or 'test' classes (list of string): a list of strings containing the names of the classes from which you want to have the data...
[ "Returns", "the", "data", "subset", "given", "a", "particular", "protocol" ]
train
https://github.com/anjos/rrbob/blob/d32d35bab2aa2698d3caa923fd02afb6d67f3235/rr/database.py#L44-L78
mayfield/shellish
shellish/completer.py
ActionCompleter.silent_parse_args
def silent_parse_args(self, command, args): """ Silently attempt to parse args. If there is a failure then we ignore the effects. Using an in-place namespace object ensures we capture as many of the valid arguments as possible when the argparse system would otherwise throw away the res...
python
def silent_parse_args(self, command, args): """ Silently attempt to parse args. If there is a failure then we ignore the effects. Using an in-place namespace object ensures we capture as many of the valid arguments as possible when the argparse system would otherwise throw away the res...
[ "def", "silent_parse_args", "(", "self", ",", "command", ",", "args", ")", ":", "args_ns", "=", "argparse", ".", "Namespace", "(", ")", "stderr_save", "=", "argparse", ".", "_sys", ".", "stderr", "stdout_save", "=", "argparse", ".", "_sys", ".", "stdout", ...
Silently attempt to parse args. If there is a failure then we ignore the effects. Using an in-place namespace object ensures we capture as many of the valid arguments as possible when the argparse system would otherwise throw away the results.
[ "Silently", "attempt", "to", "parse", "args", ".", "If", "there", "is", "a", "failure", "then", "we", "ignore", "the", "effects", ".", "Using", "an", "in", "-", "place", "namespace", "object", "ensures", "we", "capture", "as", "many", "of", "the", "valid...
train
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/completer.py#L53-L70
mayfield/shellish
shellish/completer.py
ActionCompleter.parse_nargs
def parse_nargs(self, nargs): """ Nargs is essentially a multi-type encoding. We have to parse it to understand how many values this action may consume. """ self.max_args = self.min_args = 0 if nargs is None: self.max_args = self.min_args = 1 elif nargs == argparse.O...
python
def parse_nargs(self, nargs): """ Nargs is essentially a multi-type encoding. We have to parse it to understand how many values this action may consume. """ self.max_args = self.min_args = 0 if nargs is None: self.max_args = self.min_args = 1 elif nargs == argparse.O...
[ "def", "parse_nargs", "(", "self", ",", "nargs", ")", ":", "self", ".", "max_args", "=", "self", ".", "min_args", "=", "0", "if", "nargs", "is", "None", ":", "self", ".", "max_args", "=", "self", ".", "min_args", "=", "1", "elif", "nargs", "==", "a...
Nargs is essentially a multi-type encoding. We have to parse it to understand how many values this action may consume.
[ "Nargs", "is", "essentially", "a", "multi", "-", "type", "encoding", ".", "We", "have", "to", "parse", "it", "to", "understand", "how", "many", "values", "this", "action", "may", "consume", "." ]
train
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/completer.py#L72-L86
mayfield/shellish
shellish/completer.py
ActionCompleter.consume
def consume(self, args): """ Consume the arguments we support. The args are modified inline. The return value is the number of args eaten. """ consumable = args[:self.max_args] self.consumed = len(consumable) del args[:self.consumed] return self.consumed
python
def consume(self, args): """ Consume the arguments we support. The args are modified inline. The return value is the number of args eaten. """ consumable = args[:self.max_args] self.consumed = len(consumable) del args[:self.consumed] return self.consumed
[ "def", "consume", "(", "self", ",", "args", ")", ":", "consumable", "=", "args", "[", ":", "self", ".", "max_args", "]", "self", ".", "consumed", "=", "len", "(", "consumable", ")", "del", "args", "[", ":", "self", ".", "consumed", "]", "return", "...
Consume the arguments we support. The args are modified inline. The return value is the number of args eaten.
[ "Consume", "the", "arguments", "we", "support", ".", "The", "args", "are", "modified", "inline", ".", "The", "return", "value", "is", "the", "number", "of", "args", "eaten", "." ]
train
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/completer.py#L88-L94
mayfield/shellish
shellish/completer.py
ActionCompleter.about_action
def about_action(self): """ Simple string describing the action. """ name = self.action.metavar or self.action.dest type_name = self.action.type.__name__ if self.action.type else '' if self.action.help or type_name: extra = ' (%s)' % (self.action.help or 'type: %s' % type_nam...
python
def about_action(self): """ Simple string describing the action. """ name = self.action.metavar or self.action.dest type_name = self.action.type.__name__ if self.action.type else '' if self.action.help or type_name: extra = ' (%s)' % (self.action.help or 'type: %s' % type_nam...
[ "def", "about_action", "(", "self", ")", ":", "name", "=", "self", ".", "action", ".", "metavar", "or", "self", ".", "action", ".", "dest", "type_name", "=", "self", ".", "action", ".", "type", ".", "__name__", "if", "self", ".", "action", ".", "type...
Simple string describing the action.
[ "Simple", "string", "describing", "the", "action", "." ]
train
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/completer.py#L108-L116
mayfield/shellish
shellish/completer.py
ActionCompleter.file_complete
def file_complete(self, prefix, args): """ Look in the local filesystem for valid file choices. """ path = os.path.expanduser(prefix) dirname, name = os.path.split(path) if not dirname: dirname = '.' try: dirs = os.listdir(dirname) except FileNotFo...
python
def file_complete(self, prefix, args): """ Look in the local filesystem for valid file choices. """ path = os.path.expanduser(prefix) dirname, name = os.path.split(path) if not dirname: dirname = '.' try: dirs = os.listdir(dirname) except FileNotFo...
[ "def", "file_complete", "(", "self", ",", "prefix", ",", "args", ")", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "prefix", ")", "dirname", ",", "name", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "not", "dirname"...
Look in the local filesystem for valid file choices.
[ "Look", "in", "the", "local", "filesystem", "for", "valid", "file", "choices", "." ]
train
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/completer.py#L121-L145
openp2pdesign/makerlabs
makerlabs/hackerspaces_org.py
get_single_lab
def get_single_lab(lab_slug, open_cage_api_key): """Gets data from a single lab from hackerspaces.org.""" wiki = MediaWiki(hackerspaces_org_api_url) wiki_response = wiki.call( {'action': 'query', 'titles': lab_slug, 'prop': 'revisions', 'rvprop': 'content'}) # If we d...
python
def get_single_lab(lab_slug, open_cage_api_key): """Gets data from a single lab from hackerspaces.org.""" wiki = MediaWiki(hackerspaces_org_api_url) wiki_response = wiki.call( {'action': 'query', 'titles': lab_slug, 'prop': 'revisions', 'rvprop': 'content'}) # If we d...
[ "def", "get_single_lab", "(", "lab_slug", ",", "open_cage_api_key", ")", ":", "wiki", "=", "MediaWiki", "(", "hackerspaces_org_api_url", ")", "wiki_response", "=", "wiki", ".", "call", "(", "{", "'action'", ":", "'query'", ",", "'titles'", ":", "lab_slug", ","...
Gets data from a single lab from hackerspaces.org.
[ "Gets", "data", "from", "a", "single", "lab", "from", "hackerspaces", ".", "org", "." ]
train
https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/hackerspaces_org.py#L32-L142